SemaOverload.cpp revision 569c3166874324c24011f8ade6978421f0d39b3c
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 "Lookup.h" 16#include "SemaInit.h" 17#include "clang/Basic/Diagnostic.h" 18#include "clang/Lex/Preprocessor.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/CXXInheritance.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/TypeOrdering.h" 24#include "clang/Basic/PartialDiagnostic.h" 25#include "llvm/ADT/SmallPtrSet.h" 26#include "llvm/ADT/STLExtras.h" 27#include <algorithm> 28 29namespace clang { 30 31/// GetConversionCategory - Retrieve the implicit conversion 32/// category corresponding to the given implicit conversion kind. 33ImplicitConversionCategory 34GetConversionCategory(ImplicitConversionKind Kind) { 35 static const ImplicitConversionCategory 36 Category[(int)ICK_Num_Conversion_Kinds] = { 37 ICC_Identity, 38 ICC_Lvalue_Transformation, 39 ICC_Lvalue_Transformation, 40 ICC_Lvalue_Transformation, 41 ICC_Identity, 42 ICC_Qualification_Adjustment, 43 ICC_Promotion, 44 ICC_Promotion, 45 ICC_Promotion, 46 ICC_Conversion, 47 ICC_Conversion, 48 ICC_Conversion, 49 ICC_Conversion, 50 ICC_Conversion, 51 ICC_Conversion, 52 ICC_Conversion, 53 ICC_Conversion, 54 ICC_Conversion, 55 ICC_Conversion, 56 ICC_Conversion, 57 ICC_Conversion 58 }; 59 return Category[(int)Kind]; 60} 61 62/// GetConversionRank - Retrieve the implicit conversion rank 63/// corresponding to the given implicit conversion kind. 64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 65 static const ImplicitConversionRank 66 Rank[(int)ICK_Num_Conversion_Kinds] = { 67 ICR_Exact_Match, 68 ICR_Exact_Match, 69 ICR_Exact_Match, 70 ICR_Exact_Match, 71 ICR_Exact_Match, 72 ICR_Exact_Match, 73 ICR_Promotion, 74 ICR_Promotion, 75 ICR_Promotion, 76 ICR_Conversion, 77 ICR_Conversion, 78 ICR_Conversion, 79 ICR_Conversion, 80 ICR_Conversion, 81 ICR_Conversion, 82 ICR_Conversion, 83 ICR_Conversion, 84 ICR_Conversion, 85 ICR_Conversion, 86 ICR_Conversion, 87 ICR_Complex_Real_Conversion 88 }; 89 return Rank[(int)Kind]; 90} 91 92/// GetImplicitConversionName - Return the name of this kind of 93/// implicit conversion. 94const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 95 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 96 "No conversion", 97 "Lvalue-to-rvalue", 98 "Array-to-pointer", 99 "Function-to-pointer", 100 "Noreturn adjustment", 101 "Qualification", 102 "Integral promotion", 103 "Floating point promotion", 104 "Complex promotion", 105 "Integral conversion", 106 "Floating conversion", 107 "Complex conversion", 108 "Floating-integral conversion", 109 "Pointer conversion", 110 "Pointer-to-member conversion", 111 "Boolean conversion", 112 "Compatible-types conversion", 113 "Derived-to-base conversion", 114 "Vector conversion", 115 "Vector splat", 116 "Complex-real conversion" 117 }; 118 return Name[Kind]; 119} 120 121/// StandardConversionSequence - Set the standard conversion 122/// sequence to the identity conversion. 123void StandardConversionSequence::setAsIdentityConversion() { 124 First = ICK_Identity; 125 Second = ICK_Identity; 126 Third = ICK_Identity; 127 DeprecatedStringLiteralToCharPtr = false; 128 ReferenceBinding = false; 129 DirectBinding = false; 130 RRefBinding = false; 131 CopyConstructor = 0; 132} 133 134/// getRank - Retrieve the rank of this standard conversion sequence 135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 136/// implicit conversions. 137ImplicitConversionRank StandardConversionSequence::getRank() const { 138 ImplicitConversionRank Rank = ICR_Exact_Match; 139 if (GetConversionRank(First) > Rank) 140 Rank = GetConversionRank(First); 141 if (GetConversionRank(Second) > Rank) 142 Rank = GetConversionRank(Second); 143 if (GetConversionRank(Third) > Rank) 144 Rank = GetConversionRank(Third); 145 return Rank; 146} 147 148/// isPointerConversionToBool - Determines whether this conversion is 149/// a conversion of a pointer or pointer-to-member to bool. This is 150/// used as part of the ranking of standard conversion sequences 151/// (C++ 13.3.3.2p4). 152bool StandardConversionSequence::isPointerConversionToBool() const { 153 // Note that FromType has not necessarily been transformed by the 154 // array-to-pointer or function-to-pointer implicit conversions, so 155 // check for their presence as well as checking whether FromType is 156 // a pointer. 157 if (getToType(1)->isBooleanType() && 158 (getFromType()->isPointerType() || 159 getFromType()->isObjCObjectPointerType() || 160 getFromType()->isBlockPointerType() || 161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 162 return true; 163 164 return false; 165} 166 167/// isPointerConversionToVoidPointer - Determines whether this 168/// conversion is a conversion of a pointer to a void pointer. This is 169/// used as part of the ranking of standard conversion sequences (C++ 170/// 13.3.3.2p4). 171bool 172StandardConversionSequence:: 173isPointerConversionToVoidPointer(ASTContext& Context) const { 174 QualType FromType = getFromType(); 175 QualType ToType = getToType(1); 176 177 // Note that FromType has not necessarily been transformed by the 178 // array-to-pointer implicit conversion, so check for its presence 179 // and redo the conversion to get a pointer. 180 if (First == ICK_Array_To_Pointer) 181 FromType = Context.getArrayDecayedType(FromType); 182 183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType()) 184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 185 return ToPtrType->getPointeeType()->isVoidType(); 186 187 return false; 188} 189 190/// DebugPrint - Print this standard conversion sequence to standard 191/// error. Useful for debugging overloading issues. 192void StandardConversionSequence::DebugPrint() const { 193 llvm::raw_ostream &OS = llvm::errs(); 194 bool PrintedSomething = false; 195 if (First != ICK_Identity) { 196 OS << GetImplicitConversionName(First); 197 PrintedSomething = true; 198 } 199 200 if (Second != ICK_Identity) { 201 if (PrintedSomething) { 202 OS << " -> "; 203 } 204 OS << GetImplicitConversionName(Second); 205 206 if (CopyConstructor) { 207 OS << " (by copy constructor)"; 208 } else if (DirectBinding) { 209 OS << " (direct reference binding)"; 210 } else if (ReferenceBinding) { 211 OS << " (reference binding)"; 212 } 213 PrintedSomething = true; 214 } 215 216 if (Third != ICK_Identity) { 217 if (PrintedSomething) { 218 OS << " -> "; 219 } 220 OS << GetImplicitConversionName(Third); 221 PrintedSomething = true; 222 } 223 224 if (!PrintedSomething) { 225 OS << "No conversions required"; 226 } 227} 228 229/// DebugPrint - Print this user-defined conversion sequence to standard 230/// error. Useful for debugging overloading issues. 231void UserDefinedConversionSequence::DebugPrint() const { 232 llvm::raw_ostream &OS = llvm::errs(); 233 if (Before.First || Before.Second || Before.Third) { 234 Before.DebugPrint(); 235 OS << " -> "; 236 } 237 OS << '\'' << ConversionFunction << '\''; 238 if (After.First || After.Second || After.Third) { 239 OS << " -> "; 240 After.DebugPrint(); 241 } 242} 243 244/// DebugPrint - Print this implicit conversion sequence to standard 245/// error. Useful for debugging overloading issues. 246void ImplicitConversionSequence::DebugPrint() const { 247 llvm::raw_ostream &OS = llvm::errs(); 248 switch (ConversionKind) { 249 case StandardConversion: 250 OS << "Standard conversion: "; 251 Standard.DebugPrint(); 252 break; 253 case UserDefinedConversion: 254 OS << "User-defined conversion: "; 255 UserDefined.DebugPrint(); 256 break; 257 case EllipsisConversion: 258 OS << "Ellipsis conversion"; 259 break; 260 case AmbiguousConversion: 261 OS << "Ambiguous conversion"; 262 break; 263 case BadConversion: 264 OS << "Bad conversion"; 265 break; 266 } 267 268 OS << "\n"; 269} 270 271void AmbiguousConversionSequence::construct() { 272 new (&conversions()) ConversionSet(); 273} 274 275void AmbiguousConversionSequence::destruct() { 276 conversions().~ConversionSet(); 277} 278 279void 280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 281 FromTypePtr = O.FromTypePtr; 282 ToTypePtr = O.ToTypePtr; 283 new (&conversions()) ConversionSet(O.conversions()); 284} 285 286namespace { 287 // Structure used by OverloadCandidate::DeductionFailureInfo to store 288 // template parameter and template argument information. 289 struct DFIParamWithArguments { 290 TemplateParameter Param; 291 TemplateArgument FirstArg; 292 TemplateArgument SecondArg; 293 }; 294} 295 296/// \brief Convert from Sema's representation of template deduction information 297/// to the form used in overload-candidate information. 298OverloadCandidate::DeductionFailureInfo 299static MakeDeductionFailureInfo(ASTContext &Context, 300 Sema::TemplateDeductionResult TDK, 301 Sema::TemplateDeductionInfo &Info) { 302 OverloadCandidate::DeductionFailureInfo Result; 303 Result.Result = static_cast<unsigned>(TDK); 304 Result.Data = 0; 305 switch (TDK) { 306 case Sema::TDK_Success: 307 case Sema::TDK_InstantiationDepth: 308 case Sema::TDK_TooManyArguments: 309 case Sema::TDK_TooFewArguments: 310 break; 311 312 case Sema::TDK_Incomplete: 313 case Sema::TDK_InvalidExplicitArguments: 314 Result.Data = Info.Param.getOpaqueValue(); 315 break; 316 317 case Sema::TDK_Inconsistent: 318 case Sema::TDK_Underqualified: { 319 // FIXME: Should allocate from normal heap so that we can free this later. 320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 321 Saved->Param = Info.Param; 322 Saved->FirstArg = Info.FirstArg; 323 Saved->SecondArg = Info.SecondArg; 324 Result.Data = Saved; 325 break; 326 } 327 328 case Sema::TDK_SubstitutionFailure: 329 Result.Data = Info.take(); 330 break; 331 332 case Sema::TDK_NonDeducedMismatch: 333 case Sema::TDK_FailedOverloadResolution: 334 break; 335 } 336 337 return Result; 338} 339 340void OverloadCandidate::DeductionFailureInfo::Destroy() { 341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 342 case Sema::TDK_Success: 343 case Sema::TDK_InstantiationDepth: 344 case Sema::TDK_Incomplete: 345 case Sema::TDK_TooManyArguments: 346 case Sema::TDK_TooFewArguments: 347 case Sema::TDK_InvalidExplicitArguments: 348 break; 349 350 case Sema::TDK_Inconsistent: 351 case Sema::TDK_Underqualified: 352 // FIXME: Destroy the data? 353 Data = 0; 354 break; 355 356 case Sema::TDK_SubstitutionFailure: 357 // FIXME: Destroy the template arugment list? 358 Data = 0; 359 break; 360 361 // Unhandled 362 case Sema::TDK_NonDeducedMismatch: 363 case Sema::TDK_FailedOverloadResolution: 364 break; 365 } 366} 367 368TemplateParameter 369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 371 case Sema::TDK_Success: 372 case Sema::TDK_InstantiationDepth: 373 case Sema::TDK_TooManyArguments: 374 case Sema::TDK_TooFewArguments: 375 case Sema::TDK_SubstitutionFailure: 376 return TemplateParameter(); 377 378 case Sema::TDK_Incomplete: 379 case Sema::TDK_InvalidExplicitArguments: 380 return TemplateParameter::getFromOpaqueValue(Data); 381 382 case Sema::TDK_Inconsistent: 383 case Sema::TDK_Underqualified: 384 return static_cast<DFIParamWithArguments*>(Data)->Param; 385 386 // Unhandled 387 case Sema::TDK_NonDeducedMismatch: 388 case Sema::TDK_FailedOverloadResolution: 389 break; 390 } 391 392 return TemplateParameter(); 393} 394 395TemplateArgumentList * 396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 398 case Sema::TDK_Success: 399 case Sema::TDK_InstantiationDepth: 400 case Sema::TDK_TooManyArguments: 401 case Sema::TDK_TooFewArguments: 402 case Sema::TDK_Incomplete: 403 case Sema::TDK_InvalidExplicitArguments: 404 case Sema::TDK_Inconsistent: 405 case Sema::TDK_Underqualified: 406 return 0; 407 408 case Sema::TDK_SubstitutionFailure: 409 return static_cast<TemplateArgumentList*>(Data); 410 411 // Unhandled 412 case Sema::TDK_NonDeducedMismatch: 413 case Sema::TDK_FailedOverloadResolution: 414 break; 415 } 416 417 return 0; 418} 419 420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 422 case Sema::TDK_Success: 423 case Sema::TDK_InstantiationDepth: 424 case Sema::TDK_Incomplete: 425 case Sema::TDK_TooManyArguments: 426 case Sema::TDK_TooFewArguments: 427 case Sema::TDK_InvalidExplicitArguments: 428 case Sema::TDK_SubstitutionFailure: 429 return 0; 430 431 case Sema::TDK_Inconsistent: 432 case Sema::TDK_Underqualified: 433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 434 435 // Unhandled 436 case Sema::TDK_NonDeducedMismatch: 437 case Sema::TDK_FailedOverloadResolution: 438 break; 439 } 440 441 return 0; 442} 443 444const TemplateArgument * 445OverloadCandidate::DeductionFailureInfo::getSecondArg() { 446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 447 case Sema::TDK_Success: 448 case Sema::TDK_InstantiationDepth: 449 case Sema::TDK_Incomplete: 450 case Sema::TDK_TooManyArguments: 451 case Sema::TDK_TooFewArguments: 452 case Sema::TDK_InvalidExplicitArguments: 453 case Sema::TDK_SubstitutionFailure: 454 return 0; 455 456 case Sema::TDK_Inconsistent: 457 case Sema::TDK_Underqualified: 458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 459 460 // Unhandled 461 case Sema::TDK_NonDeducedMismatch: 462 case Sema::TDK_FailedOverloadResolution: 463 break; 464 } 465 466 return 0; 467} 468 469void OverloadCandidateSet::clear() { 470 inherited::clear(); 471 Functions.clear(); 472} 473 474// IsOverload - Determine whether the given New declaration is an 475// overload of the declarations in Old. This routine returns false if 476// New and Old cannot be overloaded, e.g., if New has the same 477// signature as some function in Old (C++ 1.3.10) or if the Old 478// declarations aren't functions (or function templates) at all. When 479// it does return false, MatchedDecl will point to the decl that New 480// cannot be overloaded with. This decl may be a UsingShadowDecl on 481// top of the underlying declaration. 482// 483// Example: Given the following input: 484// 485// void f(int, float); // #1 486// void f(int, int); // #2 487// int f(int, int); // #3 488// 489// When we process #1, there is no previous declaration of "f", 490// so IsOverload will not be used. 491// 492// When we process #2, Old contains only the FunctionDecl for #1. By 493// comparing the parameter types, we see that #1 and #2 are overloaded 494// (since they have different signatures), so this routine returns 495// false; MatchedDecl is unchanged. 496// 497// When we process #3, Old is an overload set containing #1 and #2. We 498// compare the signatures of #3 to #1 (they're overloaded, so we do 499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 500// identical (return types of functions are not part of the 501// signature), IsOverload returns false and MatchedDecl will be set to 502// point to the FunctionDecl for #2. 503// 504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 505// into a class by a using declaration. The rules for whether to hide 506// shadow declarations ignore some properties which otherwise figure 507// into a function template's signature. 508Sema::OverloadKind 509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 510 NamedDecl *&Match, bool NewIsUsingDecl) { 511 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 512 I != E; ++I) { 513 NamedDecl *OldD = *I; 514 515 bool OldIsUsingDecl = false; 516 if (isa<UsingShadowDecl>(OldD)) { 517 OldIsUsingDecl = true; 518 519 // We can always introduce two using declarations into the same 520 // context, even if they have identical signatures. 521 if (NewIsUsingDecl) continue; 522 523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 524 } 525 526 // If either declaration was introduced by a using declaration, 527 // we'll need to use slightly different rules for matching. 528 // Essentially, these rules are the normal rules, except that 529 // function templates hide function templates with different 530 // return types or template parameter lists. 531 bool UseMemberUsingDeclRules = 532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 533 534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 536 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 538 continue; 539 } 540 541 Match = *I; 542 return Ovl_Match; 543 } 544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 546 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 548 continue; 549 } 550 551 Match = *I; 552 return Ovl_Match; 553 } 554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) { 555 // We can overload with these, which can show up when doing 556 // redeclaration checks for UsingDecls. 557 assert(Old.getLookupKind() == LookupUsingDeclName); 558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 559 // Optimistically assume that an unresolved using decl will 560 // overload; if it doesn't, we'll have to diagnose during 561 // template instantiation. 562 } else { 563 // (C++ 13p1): 564 // Only function declarations can be overloaded; object and type 565 // declarations cannot be overloaded. 566 Match = *I; 567 return Ovl_NonFunction; 568 } 569 } 570 571 return Ovl_Overload; 572} 573 574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 575 bool UseUsingDeclRules) { 576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 578 579 // C++ [temp.fct]p2: 580 // A function template can be overloaded with other function templates 581 // and with normal (non-template) functions. 582 if ((OldTemplate == 0) != (NewTemplate == 0)) 583 return true; 584 585 // Is the function New an overload of the function Old? 586 QualType OldQType = Context.getCanonicalType(Old->getType()); 587 QualType NewQType = Context.getCanonicalType(New->getType()); 588 589 // Compare the signatures (C++ 1.3.10) of the two functions to 590 // determine whether they are overloads. If we find any mismatch 591 // in the signature, they are overloads. 592 593 // If either of these functions is a K&R-style function (no 594 // prototype), then we consider them to have matching signatures. 595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 596 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 597 return false; 598 599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 601 602 // The signature of a function includes the types of its 603 // parameters (C++ 1.3.10), which includes the presence or absence 604 // of the ellipsis; see C++ DR 357). 605 if (OldQType != NewQType && 606 (OldType->getNumArgs() != NewType->getNumArgs() || 607 OldType->isVariadic() != NewType->isVariadic() || 608 !FunctionArgTypesAreEqual(OldType, NewType))) 609 return true; 610 611 // C++ [temp.over.link]p4: 612 // The signature of a function template consists of its function 613 // signature, its return type and its template parameter list. The names 614 // of the template parameters are significant only for establishing the 615 // relationship between the template parameters and the rest of the 616 // signature. 617 // 618 // We check the return type and template parameter lists for function 619 // templates first; the remaining checks follow. 620 // 621 // However, we don't consider either of these when deciding whether 622 // a member introduced by a shadow declaration is hidden. 623 if (!UseUsingDeclRules && NewTemplate && 624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 625 OldTemplate->getTemplateParameters(), 626 false, TPL_TemplateMatch) || 627 OldType->getResultType() != NewType->getResultType())) 628 return true; 629 630 // If the function is a class member, its signature includes the 631 // cv-qualifiers (if any) on the function itself. 632 // 633 // As part of this, also check whether one of the member functions 634 // is static, in which case they are not overloads (C++ 635 // 13.1p2). While not part of the definition of the signature, 636 // this check is important to determine whether these functions 637 // can be overloaded. 638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 640 if (OldMethod && NewMethod && 641 !OldMethod->isStatic() && !NewMethod->isStatic() && 642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers()) 643 return true; 644 645 // The signatures match; this is not an overload. 646 return false; 647} 648 649/// TryImplicitConversion - Attempt to perform an implicit conversion 650/// from the given expression (Expr) to the given type (ToType). This 651/// function returns an implicit conversion sequence that can be used 652/// to perform the initialization. Given 653/// 654/// void f(float f); 655/// void g(int i) { f(i); } 656/// 657/// this routine would produce an implicit conversion sequence to 658/// describe the initialization of f from i, which will be a standard 659/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 660/// 4.1) followed by a floating-integral conversion (C++ 4.9). 661// 662/// Note that this routine only determines how the conversion can be 663/// performed; it does not actually perform the conversion. As such, 664/// it will not produce any diagnostics if no conversion is available, 665/// but will instead return an implicit conversion sequence of kind 666/// "BadConversion". 667/// 668/// If @p SuppressUserConversions, then user-defined conversions are 669/// not permitted. 670/// If @p AllowExplicit, then explicit user-defined conversions are 671/// permitted. 672ImplicitConversionSequence 673Sema::TryImplicitConversion(Expr* From, QualType ToType, 674 bool SuppressUserConversions, 675 bool AllowExplicit, 676 bool InOverloadResolution) { 677 ImplicitConversionSequence ICS; 678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) { 679 ICS.setStandard(); 680 return ICS; 681 } 682 683 if (!getLangOptions().CPlusPlus) { 684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 685 return ICS; 686 } 687 688 if (SuppressUserConversions) { 689 // C++ [over.ics.user]p4: 690 // A conversion of an expression of class type to the same class 691 // type is given Exact Match rank, and a conversion of an 692 // expression of class type to a base class of that type is 693 // given Conversion rank, in spite of the fact that a copy/move 694 // constructor (i.e., a user-defined conversion function) is 695 // called for those cases. 696 QualType FromType = From->getType(); 697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() || 698 !(Context.hasSameUnqualifiedType(FromType, ToType) || 699 IsDerivedFrom(FromType, ToType))) { 700 // We're not in the case above, so there is no conversion that 701 // we can perform. 702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 703 return ICS; 704 } 705 706 ICS.setStandard(); 707 ICS.Standard.setAsIdentityConversion(); 708 ICS.Standard.setFromType(FromType); 709 ICS.Standard.setAllToTypes(ToType); 710 711 // We don't actually check at this point whether there is a valid 712 // copy/move constructor, since overloading just assumes that it 713 // exists. When we actually perform initialization, we'll find the 714 // appropriate constructor to copy the returned object, if needed. 715 ICS.Standard.CopyConstructor = 0; 716 717 // Determine whether this is considered a derived-to-base conversion. 718 if (!Context.hasSameUnqualifiedType(FromType, ToType)) 719 ICS.Standard.Second = ICK_Derived_To_Base; 720 721 return ICS; 722 } 723 724 // Attempt user-defined conversion. 725 OverloadCandidateSet Conversions(From->getExprLoc()); 726 OverloadingResult UserDefResult 727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions, 728 AllowExplicit); 729 730 if (UserDefResult == OR_Success) { 731 ICS.setUserDefined(); 732 // C++ [over.ics.user]p4: 733 // A conversion of an expression of class type to the same class 734 // type is given Exact Match rank, and a conversion of an 735 // expression of class type to a base class of that type is 736 // given Conversion rank, in spite of the fact that a copy 737 // constructor (i.e., a user-defined conversion function) is 738 // called for those cases. 739 if (CXXConstructorDecl *Constructor 740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 741 QualType FromCanon 742 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 744 if (Constructor->isCopyConstructor() && 745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) { 746 // Turn this into a "standard" conversion sequence, so that it 747 // gets ranked with standard conversion sequences. 748 ICS.setStandard(); 749 ICS.Standard.setAsIdentityConversion(); 750 ICS.Standard.setFromType(From->getType()); 751 ICS.Standard.setAllToTypes(ToType); 752 ICS.Standard.CopyConstructor = Constructor; 753 if (ToCanon != FromCanon) 754 ICS.Standard.Second = ICK_Derived_To_Base; 755 } 756 } 757 758 // C++ [over.best.ics]p4: 759 // However, when considering the argument of a user-defined 760 // conversion function that is a candidate by 13.3.1.3 when 761 // invoked for the copying of the temporary in the second step 762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 763 // 13.3.1.6 in all cases, only standard conversion sequences and 764 // ellipsis conversion sequences are allowed. 765 if (SuppressUserConversions && ICS.isUserDefined()) { 766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 767 } 768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 769 ICS.setAmbiguous(); 770 ICS.Ambiguous.setFromType(From->getType()); 771 ICS.Ambiguous.setToType(ToType); 772 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 773 Cand != Conversions.end(); ++Cand) 774 if (Cand->Viable) 775 ICS.Ambiguous.addConversion(Cand->Function); 776 } else { 777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 778 } 779 780 return ICS; 781} 782 783/// PerformImplicitConversion - Perform an implicit conversion of the 784/// expression From to the type ToType. Returns true if there was an 785/// error, false otherwise. The expression From is replaced with the 786/// converted expression. Flavor is the kind of conversion we're 787/// performing, used in the error message. If @p AllowExplicit, 788/// explicit user-defined conversions are permitted. 789bool 790Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 791 AssignmentAction Action, bool AllowExplicit) { 792 ImplicitConversionSequence ICS; 793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 794} 795 796bool 797Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 798 AssignmentAction Action, bool AllowExplicit, 799 ImplicitConversionSequence& ICS) { 800 ICS = TryImplicitConversion(From, ToType, 801 /*SuppressUserConversions=*/false, 802 AllowExplicit, 803 /*InOverloadResolution=*/false); 804 return PerformImplicitConversion(From, ToType, ICS, Action); 805} 806 807/// \brief Determine whether the conversion from FromType to ToType is a valid 808/// conversion that strips "noreturn" off the nested function type. 809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType, 810 QualType ToType, QualType &ResultTy) { 811 if (Context.hasSameUnqualifiedType(FromType, ToType)) 812 return false; 813 814 // Strip the noreturn off the type we're converting from; noreturn can 815 // safely be removed. 816 FromType = Context.getNoReturnType(FromType, false); 817 if (!Context.hasSameUnqualifiedType(FromType, ToType)) 818 return false; 819 820 ResultTy = FromType; 821 return true; 822} 823 824/// \brief Determine whether the conversion from FromType to ToType is a valid 825/// vector conversion. 826/// 827/// \param ICK Will be set to the vector conversion kind, if this is a vector 828/// conversion. 829static bool IsVectorConversion(ASTContext &Context, QualType FromType, 830 QualType ToType, ImplicitConversionKind &ICK) { 831 // We need at least one of these types to be a vector type to have a vector 832 // conversion. 833 if (!ToType->isVectorType() && !FromType->isVectorType()) 834 return false; 835 836 // Identical types require no conversions. 837 if (Context.hasSameUnqualifiedType(FromType, ToType)) 838 return false; 839 840 // There are no conversions between extended vector types, only identity. 841 if (ToType->isExtVectorType()) { 842 // There are no conversions between extended vector types other than the 843 // identity conversion. 844 if (FromType->isExtVectorType()) 845 return false; 846 847 // Vector splat from any arithmetic type to a vector. 848 if (FromType->isArithmeticType()) { 849 ICK = ICK_Vector_Splat; 850 return true; 851 } 852 } 853 854 // We can perform the conversion between vector types in the following cases: 855 // 1)vector types are equivalent AltiVec and GCC vector types 856 // 2)lax vector conversions are permitted and the vector types are of the 857 // same size 858 if (ToType->isVectorType() && FromType->isVectorType()) { 859 if (Context.areCompatibleVectorTypes(FromType, ToType) || 860 Context.getLangOptions().LaxVectorConversions && 861 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType))) { 862 ICK = ICK_Vector_Conversion; 863 return true; 864 } 865 } 866 867 return false; 868} 869 870/// IsStandardConversion - Determines whether there is a standard 871/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 872/// expression From to the type ToType. Standard conversion sequences 873/// only consider non-class types; for conversions that involve class 874/// types, use TryImplicitConversion. If a conversion exists, SCS will 875/// contain the standard conversion sequence required to perform this 876/// conversion and this routine will return true. Otherwise, this 877/// routine will return false and the value of SCS is unspecified. 878bool 879Sema::IsStandardConversion(Expr* From, QualType ToType, 880 bool InOverloadResolution, 881 StandardConversionSequence &SCS) { 882 QualType FromType = From->getType(); 883 884 // Standard conversions (C++ [conv]) 885 SCS.setAsIdentityConversion(); 886 SCS.DeprecatedStringLiteralToCharPtr = false; 887 SCS.IncompatibleObjC = false; 888 SCS.setFromType(FromType); 889 SCS.CopyConstructor = 0; 890 891 // There are no standard conversions for class types in C++, so 892 // abort early. When overloading in C, however, we do permit 893 if (FromType->isRecordType() || ToType->isRecordType()) { 894 if (getLangOptions().CPlusPlus) 895 return false; 896 897 // When we're overloading in C, we allow, as standard conversions, 898 } 899 900 // The first conversion can be an lvalue-to-rvalue conversion, 901 // array-to-pointer conversion, or function-to-pointer conversion 902 // (C++ 4p1). 903 904 if (FromType == Context.OverloadTy) { 905 DeclAccessPair AccessPair; 906 if (FunctionDecl *Fn 907 = ResolveAddressOfOverloadedFunction(From, ToType, false, 908 AccessPair)) { 909 // We were able to resolve the address of the overloaded function, 910 // so we can convert to the type of that function. 911 FromType = Fn->getType(); 912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 913 if (!Method->isStatic()) { 914 Type *ClassType 915 = Context.getTypeDeclType(Method->getParent()).getTypePtr(); 916 FromType = Context.getMemberPointerType(FromType, ClassType); 917 } 918 } 919 920 // If the "from" expression takes the address of the overloaded 921 // function, update the type of the resulting expression accordingly. 922 if (FromType->getAs<FunctionType>()) 923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens())) 924 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 925 FromType = Context.getPointerType(FromType); 926 927 // Check that we've computed the proper type after overload resolution. 928 assert(Context.hasSameType(FromType, 929 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 930 } else { 931 return false; 932 } 933 } 934 // Lvalue-to-rvalue conversion (C++ 4.1): 935 // An lvalue (3.10) of a non-function, non-array type T can be 936 // converted to an rvalue. 937 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context); 938 if (argIsLvalue == Expr::LV_Valid && 939 !FromType->isFunctionType() && !FromType->isArrayType() && 940 Context.getCanonicalType(FromType) != Context.OverloadTy) { 941 SCS.First = ICK_Lvalue_To_Rvalue; 942 943 // If T is a non-class type, the type of the rvalue is the 944 // cv-unqualified version of T. Otherwise, the type of the rvalue 945 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 946 // just strip the qualifiers because they don't matter. 947 FromType = FromType.getUnqualifiedType(); 948 } else if (FromType->isArrayType()) { 949 // Array-to-pointer conversion (C++ 4.2) 950 SCS.First = ICK_Array_To_Pointer; 951 952 // An lvalue or rvalue of type "array of N T" or "array of unknown 953 // bound of T" can be converted to an rvalue of type "pointer to 954 // T" (C++ 4.2p1). 955 FromType = Context.getArrayDecayedType(FromType); 956 957 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) { 958 // This conversion is deprecated. (C++ D.4). 959 SCS.DeprecatedStringLiteralToCharPtr = true; 960 961 // For the purpose of ranking in overload resolution 962 // (13.3.3.1.1), this conversion is considered an 963 // array-to-pointer conversion followed by a qualification 964 // conversion (4.4). (C++ 4.2p2) 965 SCS.Second = ICK_Identity; 966 SCS.Third = ICK_Qualification; 967 SCS.setAllToTypes(FromType); 968 return true; 969 } 970 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 971 // Function-to-pointer conversion (C++ 4.3). 972 SCS.First = ICK_Function_To_Pointer; 973 974 // An lvalue of function type T can be converted to an rvalue of 975 // type "pointer to T." The result is a pointer to the 976 // function. (C++ 4.3p1). 977 FromType = Context.getPointerType(FromType); 978 } else { 979 // We don't require any conversions for the first step. 980 SCS.First = ICK_Identity; 981 } 982 SCS.setToType(0, FromType); 983 984 // The second conversion can be an integral promotion, floating 985 // point promotion, integral conversion, floating point conversion, 986 // floating-integral conversion, pointer conversion, 987 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 988 // For overloading in C, this can also be a "compatible-type" 989 // conversion. 990 bool IncompatibleObjC = false; 991 ImplicitConversionKind SecondICK = ICK_Identity; 992 if (Context.hasSameUnqualifiedType(FromType, ToType)) { 993 // The unqualified versions of the types are the same: there's no 994 // conversion to do. 995 SCS.Second = ICK_Identity; 996 } else if (IsIntegralPromotion(From, FromType, ToType)) { 997 // Integral promotion (C++ 4.5). 998 SCS.Second = ICK_Integral_Promotion; 999 FromType = ToType.getUnqualifiedType(); 1000 } else if (IsFloatingPointPromotion(FromType, ToType)) { 1001 // Floating point promotion (C++ 4.6). 1002 SCS.Second = ICK_Floating_Promotion; 1003 FromType = ToType.getUnqualifiedType(); 1004 } else if (IsComplexPromotion(FromType, ToType)) { 1005 // Complex promotion (Clang extension) 1006 SCS.Second = ICK_Complex_Promotion; 1007 FromType = ToType.getUnqualifiedType(); 1008 } else if (FromType->isIntegralOrEnumerationType() && 1009 ToType->isIntegralType(Context)) { 1010 // Integral conversions (C++ 4.7). 1011 SCS.Second = ICK_Integral_Conversion; 1012 FromType = ToType.getUnqualifiedType(); 1013 } else if (FromType->isComplexType() && ToType->isComplexType()) { 1014 // Complex conversions (C99 6.3.1.6) 1015 SCS.Second = ICK_Complex_Conversion; 1016 FromType = ToType.getUnqualifiedType(); 1017 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) || 1018 (ToType->isComplexType() && FromType->isArithmeticType())) { 1019 // Complex-real conversions (C99 6.3.1.7) 1020 SCS.Second = ICK_Complex_Real; 1021 FromType = ToType.getUnqualifiedType(); 1022 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1023 // Floating point conversions (C++ 4.8). 1024 SCS.Second = ICK_Floating_Conversion; 1025 FromType = ToType.getUnqualifiedType(); 1026 } else if ((FromType->isRealFloatingType() && 1027 ToType->isIntegralType(Context) && !ToType->isBooleanType()) || 1028 (FromType->isIntegralOrEnumerationType() && 1029 ToType->isRealFloatingType())) { 1030 // Floating-integral conversions (C++ 4.9). 1031 SCS.Second = ICK_Floating_Integral; 1032 FromType = ToType.getUnqualifiedType(); 1033 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1034 FromType, IncompatibleObjC)) { 1035 // Pointer conversions (C++ 4.10). 1036 SCS.Second = ICK_Pointer_Conversion; 1037 SCS.IncompatibleObjC = IncompatibleObjC; 1038 } else if (IsMemberPointerConversion(From, FromType, ToType, 1039 InOverloadResolution, FromType)) { 1040 // Pointer to member conversions (4.11). 1041 SCS.Second = ICK_Pointer_Member; 1042 } else if (ToType->isBooleanType() && 1043 (FromType->isArithmeticType() || 1044 FromType->isEnumeralType() || 1045 FromType->isAnyPointerType() || 1046 FromType->isBlockPointerType() || 1047 FromType->isMemberPointerType() || 1048 FromType->isNullPtrType())) { 1049 // Boolean conversions (C++ 4.12). 1050 SCS.Second = ICK_Boolean_Conversion; 1051 FromType = Context.BoolTy; 1052 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) { 1053 SCS.Second = SecondICK; 1054 FromType = ToType.getUnqualifiedType(); 1055 } else if (!getLangOptions().CPlusPlus && 1056 Context.typesAreCompatible(ToType, FromType)) { 1057 // Compatible conversions (Clang extension for C function overloading) 1058 SCS.Second = ICK_Compatible_Conversion; 1059 FromType = ToType.getUnqualifiedType(); 1060 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) { 1061 // Treat a conversion that strips "noreturn" as an identity conversion. 1062 SCS.Second = ICK_NoReturn_Adjustment; 1063 } else { 1064 // No second conversion required. 1065 SCS.Second = ICK_Identity; 1066 } 1067 SCS.setToType(1, FromType); 1068 1069 QualType CanonFrom; 1070 QualType CanonTo; 1071 // The third conversion can be a qualification conversion (C++ 4p1). 1072 if (IsQualificationConversion(FromType, ToType)) { 1073 SCS.Third = ICK_Qualification; 1074 FromType = ToType; 1075 CanonFrom = Context.getCanonicalType(FromType); 1076 CanonTo = Context.getCanonicalType(ToType); 1077 } else { 1078 // No conversion required 1079 SCS.Third = ICK_Identity; 1080 1081 // C++ [over.best.ics]p6: 1082 // [...] Any difference in top-level cv-qualification is 1083 // subsumed by the initialization itself and does not constitute 1084 // a conversion. [...] 1085 CanonFrom = Context.getCanonicalType(FromType); 1086 CanonTo = Context.getCanonicalType(ToType); 1087 if (CanonFrom.getLocalUnqualifiedType() 1088 == CanonTo.getLocalUnqualifiedType() && 1089 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1090 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) { 1091 FromType = ToType; 1092 CanonFrom = CanonTo; 1093 } 1094 } 1095 SCS.setToType(2, FromType); 1096 1097 // If we have not converted the argument type to the parameter type, 1098 // this is a bad conversion sequence. 1099 if (CanonFrom != CanonTo) 1100 return false; 1101 1102 return true; 1103} 1104 1105/// IsIntegralPromotion - Determines whether the conversion from the 1106/// expression From (whose potentially-adjusted type is FromType) to 1107/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1108/// sets PromotedType to the promoted type. 1109bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1110 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1111 // All integers are built-in. 1112 if (!To) { 1113 return false; 1114 } 1115 1116 // An rvalue of type char, signed char, unsigned char, short int, or 1117 // unsigned short int can be converted to an rvalue of type int if 1118 // int can represent all the values of the source type; otherwise, 1119 // the source rvalue can be converted to an rvalue of type unsigned 1120 // int (C++ 4.5p1). 1121 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1122 !FromType->isEnumeralType()) { 1123 if (// We can promote any signed, promotable integer type to an int 1124 (FromType->isSignedIntegerType() || 1125 // We can promote any unsigned integer type whose size is 1126 // less than int to an int. 1127 (!FromType->isSignedIntegerType() && 1128 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1129 return To->getKind() == BuiltinType::Int; 1130 } 1131 1132 return To->getKind() == BuiltinType::UInt; 1133 } 1134 1135 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 1136 // can be converted to an rvalue of the first of the following types 1137 // that can represent all the values of its underlying type: int, 1138 // unsigned int, long, or unsigned long (C++ 4.5p2). 1139 1140 // We pre-calculate the promotion type for enum types. 1141 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) 1142 if (ToType->isIntegerType()) 1143 return Context.hasSameUnqualifiedType(ToType, 1144 FromEnumType->getDecl()->getPromotionType()); 1145 1146 if (FromType->isWideCharType() && ToType->isIntegerType()) { 1147 // Determine whether the type we're converting from is signed or 1148 // unsigned. 1149 bool FromIsSigned; 1150 uint64_t FromSize = Context.getTypeSize(FromType); 1151 1152 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 1153 FromIsSigned = true; 1154 1155 // The types we'll try to promote to, in the appropriate 1156 // order. Try each of these types. 1157 QualType PromoteTypes[6] = { 1158 Context.IntTy, Context.UnsignedIntTy, 1159 Context.LongTy, Context.UnsignedLongTy , 1160 Context.LongLongTy, Context.UnsignedLongLongTy 1161 }; 1162 for (int Idx = 0; Idx < 6; ++Idx) { 1163 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1164 if (FromSize < ToSize || 1165 (FromSize == ToSize && 1166 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1167 // We found the type that we can promote to. If this is the 1168 // type we wanted, we have a promotion. Otherwise, no 1169 // promotion. 1170 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1171 } 1172 } 1173 } 1174 1175 // An rvalue for an integral bit-field (9.6) can be converted to an 1176 // rvalue of type int if int can represent all the values of the 1177 // bit-field; otherwise, it can be converted to unsigned int if 1178 // unsigned int can represent all the values of the bit-field. If 1179 // the bit-field is larger yet, no integral promotion applies to 1180 // it. If the bit-field has an enumerated type, it is treated as any 1181 // other value of that type for promotion purposes (C++ 4.5p3). 1182 // FIXME: We should delay checking of bit-fields until we actually perform the 1183 // conversion. 1184 using llvm::APSInt; 1185 if (From) 1186 if (FieldDecl *MemberDecl = From->getBitField()) { 1187 APSInt BitWidth; 1188 if (FromType->isIntegralType(Context) && 1189 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1190 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1191 ToSize = Context.getTypeSize(ToType); 1192 1193 // Are we promoting to an int from a bitfield that fits in an int? 1194 if (BitWidth < ToSize || 1195 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1196 return To->getKind() == BuiltinType::Int; 1197 } 1198 1199 // Are we promoting to an unsigned int from an unsigned bitfield 1200 // that fits into an unsigned int? 1201 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1202 return To->getKind() == BuiltinType::UInt; 1203 } 1204 1205 return false; 1206 } 1207 } 1208 1209 // An rvalue of type bool can be converted to an rvalue of type int, 1210 // with false becoming zero and true becoming one (C++ 4.5p4). 1211 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1212 return true; 1213 } 1214 1215 return false; 1216} 1217 1218/// IsFloatingPointPromotion - Determines whether the conversion from 1219/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1220/// returns true and sets PromotedType to the promoted type. 1221bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1222 /// An rvalue of type float can be converted to an rvalue of type 1223 /// double. (C++ 4.6p1). 1224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1226 if (FromBuiltin->getKind() == BuiltinType::Float && 1227 ToBuiltin->getKind() == BuiltinType::Double) 1228 return true; 1229 1230 // C99 6.3.1.5p1: 1231 // When a float is promoted to double or long double, or a 1232 // double is promoted to long double [...]. 1233 if (!getLangOptions().CPlusPlus && 1234 (FromBuiltin->getKind() == BuiltinType::Float || 1235 FromBuiltin->getKind() == BuiltinType::Double) && 1236 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1237 return true; 1238 } 1239 1240 return false; 1241} 1242 1243/// \brief Determine if a conversion is a complex promotion. 1244/// 1245/// A complex promotion is defined as a complex -> complex conversion 1246/// where the conversion between the underlying real types is a 1247/// floating-point or integral promotion. 1248bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1249 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1250 if (!FromComplex) 1251 return false; 1252 1253 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1254 if (!ToComplex) 1255 return false; 1256 1257 return IsFloatingPointPromotion(FromComplex->getElementType(), 1258 ToComplex->getElementType()) || 1259 IsIntegralPromotion(0, FromComplex->getElementType(), 1260 ToComplex->getElementType()); 1261} 1262 1263/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1264/// the pointer type FromPtr to a pointer to type ToPointee, with the 1265/// same type qualifiers as FromPtr has on its pointee type. ToType, 1266/// if non-empty, will be a pointer to ToType that may or may not have 1267/// the right set of qualifiers on its pointee. 1268static QualType 1269BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr, 1270 QualType ToPointee, QualType ToType, 1271 ASTContext &Context) { 1272 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType()); 1273 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1274 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1275 1276 // Exact qualifier match -> return the pointer type we're converting to. 1277 if (CanonToPointee.getLocalQualifiers() == Quals) { 1278 // ToType is exactly what we need. Return it. 1279 if (!ToType.isNull()) 1280 return ToType.getUnqualifiedType(); 1281 1282 // Build a pointer to ToPointee. It has the right qualifiers 1283 // already. 1284 return Context.getPointerType(ToPointee); 1285 } 1286 1287 // Just build a canonical type that has the right qualifiers. 1288 return Context.getPointerType( 1289 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), 1290 Quals)); 1291} 1292 1293/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from 1294/// the FromType, which is an objective-c pointer, to ToType, which may or may 1295/// not have the right set of qualifiers. 1296static QualType 1297BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType, 1298 QualType ToType, 1299 ASTContext &Context) { 1300 QualType CanonFromType = Context.getCanonicalType(FromType); 1301 QualType CanonToType = Context.getCanonicalType(ToType); 1302 Qualifiers Quals = CanonFromType.getQualifiers(); 1303 1304 // Exact qualifier match -> return the pointer type we're converting to. 1305 if (CanonToType.getLocalQualifiers() == Quals) 1306 return ToType; 1307 1308 // Just build a canonical type that has the right qualifiers. 1309 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals); 1310} 1311 1312static bool isNullPointerConstantForConversion(Expr *Expr, 1313 bool InOverloadResolution, 1314 ASTContext &Context) { 1315 // Handle value-dependent integral null pointer constants correctly. 1316 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1317 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1318 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1319 return !InOverloadResolution; 1320 1321 return Expr->isNullPointerConstant(Context, 1322 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1323 : Expr::NPC_ValueDependentIsNull); 1324} 1325 1326/// IsPointerConversion - Determines whether the conversion of the 1327/// expression From, which has the (possibly adjusted) type FromType, 1328/// can be converted to the type ToType via a pointer conversion (C++ 1329/// 4.10). If so, returns true and places the converted type (that 1330/// might differ from ToType in its cv-qualifiers at some level) into 1331/// ConvertedType. 1332/// 1333/// This routine also supports conversions to and from block pointers 1334/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1335/// pointers to interfaces. FIXME: Once we've determined the 1336/// appropriate overloading rules for Objective-C, we may want to 1337/// split the Objective-C checks into a different routine; however, 1338/// GCC seems to consider all of these conversions to be pointer 1339/// conversions, so for now they live here. IncompatibleObjC will be 1340/// set if the conversion is an allowed Objective-C conversion that 1341/// should result in a warning. 1342bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1343 bool InOverloadResolution, 1344 QualType& ConvertedType, 1345 bool &IncompatibleObjC) { 1346 IncompatibleObjC = false; 1347 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC)) 1348 return true; 1349 1350 // Conversion from a null pointer constant to any Objective-C pointer type. 1351 if (ToType->isObjCObjectPointerType() && 1352 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1353 ConvertedType = ToType; 1354 return true; 1355 } 1356 1357 // Blocks: Block pointers can be converted to void*. 1358 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1359 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1360 ConvertedType = ToType; 1361 return true; 1362 } 1363 // Blocks: A null pointer constant can be converted to a block 1364 // pointer type. 1365 if (ToType->isBlockPointerType() && 1366 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1367 ConvertedType = ToType; 1368 return true; 1369 } 1370 1371 // If the left-hand-side is nullptr_t, the right side can be a null 1372 // pointer constant. 1373 if (ToType->isNullPtrType() && 1374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1375 ConvertedType = ToType; 1376 return true; 1377 } 1378 1379 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1380 if (!ToTypePtr) 1381 return false; 1382 1383 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1384 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1385 ConvertedType = ToType; 1386 return true; 1387 } 1388 1389 // Beyond this point, both types need to be pointers 1390 // , including objective-c pointers. 1391 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1392 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) { 1393 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType, 1394 ToType, Context); 1395 return true; 1396 1397 } 1398 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1399 if (!FromTypePtr) 1400 return false; 1401 1402 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1403 1404 // An rvalue of type "pointer to cv T," where T is an object type, 1405 // can be converted to an rvalue of type "pointer to cv void" (C++ 1406 // 4.10p2). 1407 if (FromPointeeType->isIncompleteOrObjectType() && 1408 ToPointeeType->isVoidType()) { 1409 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1410 ToPointeeType, 1411 ToType, Context); 1412 return true; 1413 } 1414 1415 // When we're overloading in C, we allow a special kind of pointer 1416 // conversion for compatible-but-not-identical pointee types. 1417 if (!getLangOptions().CPlusPlus && 1418 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1420 ToPointeeType, 1421 ToType, Context); 1422 return true; 1423 } 1424 1425 // C++ [conv.ptr]p3: 1426 // 1427 // An rvalue of type "pointer to cv D," where D is a class type, 1428 // can be converted to an rvalue of type "pointer to cv B," where 1429 // B is a base class (clause 10) of D. If B is an inaccessible 1430 // (clause 11) or ambiguous (10.2) base class of D, a program that 1431 // necessitates this conversion is ill-formed. The result of the 1432 // conversion is a pointer to the base class sub-object of the 1433 // derived class object. The null pointer value is converted to 1434 // the null pointer value of the destination type. 1435 // 1436 // Note that we do not check for ambiguity or inaccessibility 1437 // here. That is handled by CheckPointerConversion. 1438 if (getLangOptions().CPlusPlus && 1439 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 1440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 1441 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) && 1442 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 1443 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1444 ToPointeeType, 1445 ToType, Context); 1446 return true; 1447 } 1448 1449 return false; 1450} 1451 1452/// isObjCPointerConversion - Determines whether this is an 1453/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 1454/// with the same arguments and return values. 1455bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 1456 QualType& ConvertedType, 1457 bool &IncompatibleObjC) { 1458 if (!getLangOptions().ObjC1) 1459 return false; 1460 1461 // First, we handle all conversions on ObjC object pointer types. 1462 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>(); 1463 const ObjCObjectPointerType *FromObjCPtr = 1464 FromType->getAs<ObjCObjectPointerType>(); 1465 1466 if (ToObjCPtr && FromObjCPtr) { 1467 // Objective C++: We're able to convert between "id" or "Class" and a 1468 // pointer to any interface (in both directions). 1469 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 1470 ConvertedType = ToType; 1471 return true; 1472 } 1473 // Conversions with Objective-C's id<...>. 1474 if ((FromObjCPtr->isObjCQualifiedIdType() || 1475 ToObjCPtr->isObjCQualifiedIdType()) && 1476 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 1477 /*compare=*/false)) { 1478 ConvertedType = ToType; 1479 return true; 1480 } 1481 // Objective C++: We're able to convert from a pointer to an 1482 // interface to a pointer to a different interface. 1483 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 1484 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 1485 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 1486 if (getLangOptions().CPlusPlus && LHS && RHS && 1487 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 1488 FromObjCPtr->getPointeeType())) 1489 return false; 1490 ConvertedType = ToType; 1491 return true; 1492 } 1493 1494 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 1495 // Okay: this is some kind of implicit downcast of Objective-C 1496 // interfaces, which is permitted. However, we're going to 1497 // complain about it. 1498 IncompatibleObjC = true; 1499 ConvertedType = FromType; 1500 return true; 1501 } 1502 } 1503 // Beyond this point, both types need to be C pointers or block pointers. 1504 QualType ToPointeeType; 1505 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 1506 ToPointeeType = ToCPtr->getPointeeType(); 1507 else if (const BlockPointerType *ToBlockPtr = 1508 ToType->getAs<BlockPointerType>()) { 1509 // Objective C++: We're able to convert from a pointer to any object 1510 // to a block pointer type. 1511 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 1512 ConvertedType = ToType; 1513 return true; 1514 } 1515 ToPointeeType = ToBlockPtr->getPointeeType(); 1516 } 1517 else if (FromType->getAs<BlockPointerType>() && 1518 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 1519 // Objective C++: We're able to convert from a block pointer type to a 1520 // pointer to any object. 1521 ConvertedType = ToType; 1522 return true; 1523 } 1524 else 1525 return false; 1526 1527 QualType FromPointeeType; 1528 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 1529 FromPointeeType = FromCPtr->getPointeeType(); 1530 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>()) 1531 FromPointeeType = FromBlockPtr->getPointeeType(); 1532 else 1533 return false; 1534 1535 // If we have pointers to pointers, recursively check whether this 1536 // is an Objective-C conversion. 1537 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 1538 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1539 IncompatibleObjC)) { 1540 // We always complain about this conversion. 1541 IncompatibleObjC = true; 1542 ConvertedType = ToType; 1543 return true; 1544 } 1545 // Allow conversion of pointee being objective-c pointer to another one; 1546 // as in I* to id. 1547 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 1548 ToPointeeType->getAs<ObjCObjectPointerType>() && 1549 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1550 IncompatibleObjC)) { 1551 ConvertedType = ToType; 1552 return true; 1553 } 1554 1555 // If we have pointers to functions or blocks, check whether the only 1556 // differences in the argument and result types are in Objective-C 1557 // pointer conversions. If so, we permit the conversion (but 1558 // complain about it). 1559 const FunctionProtoType *FromFunctionType 1560 = FromPointeeType->getAs<FunctionProtoType>(); 1561 const FunctionProtoType *ToFunctionType 1562 = ToPointeeType->getAs<FunctionProtoType>(); 1563 if (FromFunctionType && ToFunctionType) { 1564 // If the function types are exactly the same, this isn't an 1565 // Objective-C pointer conversion. 1566 if (Context.getCanonicalType(FromPointeeType) 1567 == Context.getCanonicalType(ToPointeeType)) 1568 return false; 1569 1570 // Perform the quick checks that will tell us whether these 1571 // function types are obviously different. 1572 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 1573 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 1574 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 1575 return false; 1576 1577 bool HasObjCConversion = false; 1578 if (Context.getCanonicalType(FromFunctionType->getResultType()) 1579 == Context.getCanonicalType(ToFunctionType->getResultType())) { 1580 // Okay, the types match exactly. Nothing to do. 1581 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 1582 ToFunctionType->getResultType(), 1583 ConvertedType, IncompatibleObjC)) { 1584 // Okay, we have an Objective-C pointer conversion. 1585 HasObjCConversion = true; 1586 } else { 1587 // Function types are too different. Abort. 1588 return false; 1589 } 1590 1591 // Check argument types. 1592 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 1593 ArgIdx != NumArgs; ++ArgIdx) { 1594 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 1595 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 1596 if (Context.getCanonicalType(FromArgType) 1597 == Context.getCanonicalType(ToArgType)) { 1598 // Okay, the types match exactly. Nothing to do. 1599 } else if (isObjCPointerConversion(FromArgType, ToArgType, 1600 ConvertedType, IncompatibleObjC)) { 1601 // Okay, we have an Objective-C pointer conversion. 1602 HasObjCConversion = true; 1603 } else { 1604 // Argument types are too different. Abort. 1605 return false; 1606 } 1607 } 1608 1609 if (HasObjCConversion) { 1610 // We had an Objective-C conversion. Allow this pointer 1611 // conversion, but complain about it. 1612 ConvertedType = ToType; 1613 IncompatibleObjC = true; 1614 return true; 1615 } 1616 } 1617 1618 return false; 1619} 1620 1621/// FunctionArgTypesAreEqual - This routine checks two function proto types 1622/// for equlity of their argument types. Caller has already checked that 1623/// they have same number of arguments. This routine assumes that Objective-C 1624/// pointer types which only differ in their protocol qualifiers are equal. 1625bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType, 1626 FunctionProtoType* NewType){ 1627 if (!getLangOptions().ObjC1) 1628 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 1629 NewType->arg_type_begin()); 1630 1631 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 1632 N = NewType->arg_type_begin(), 1633 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 1634 QualType ToType = (*O); 1635 QualType FromType = (*N); 1636 if (ToType != FromType) { 1637 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 1638 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 1639 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 1640 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 1641 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 1642 PTFr->getPointeeType()->isObjCQualifiedClassType())) 1643 continue; 1644 } 1645 else if (const ObjCObjectPointerType *PTTo = 1646 ToType->getAs<ObjCObjectPointerType>()) { 1647 if (const ObjCObjectPointerType *PTFr = 1648 FromType->getAs<ObjCObjectPointerType>()) 1649 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl()) 1650 continue; 1651 } 1652 return false; 1653 } 1654 } 1655 return true; 1656} 1657 1658/// CheckPointerConversion - Check the pointer conversion from the 1659/// expression From to the type ToType. This routine checks for 1660/// ambiguous or inaccessible derived-to-base pointer 1661/// conversions for which IsPointerConversion has already returned 1662/// true. It returns true and produces a diagnostic if there was an 1663/// error, or returns false otherwise. 1664bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 1665 CastExpr::CastKind &Kind, 1666 CXXCastPath& BasePath, 1667 bool IgnoreBaseAccess) { 1668 QualType FromType = From->getType(); 1669 1670 if (CXXBoolLiteralExpr* LitBool 1671 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens())) 1672 if (LitBool->getValue() == false) 1673 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false) 1674 << ToType; 1675 1676 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) 1677 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 1678 QualType FromPointeeType = FromPtrType->getPointeeType(), 1679 ToPointeeType = ToPtrType->getPointeeType(); 1680 1681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 1682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 1683 // We must have a derived-to-base conversion. Check an 1684 // ambiguous or inaccessible conversion. 1685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 1686 From->getExprLoc(), 1687 From->getSourceRange(), &BasePath, 1688 IgnoreBaseAccess)) 1689 return true; 1690 1691 // The conversion was successful. 1692 Kind = CastExpr::CK_DerivedToBase; 1693 } 1694 } 1695 if (const ObjCObjectPointerType *FromPtrType = 1696 FromType->getAs<ObjCObjectPointerType>()) 1697 if (const ObjCObjectPointerType *ToPtrType = 1698 ToType->getAs<ObjCObjectPointerType>()) { 1699 // Objective-C++ conversions are always okay. 1700 // FIXME: We should have a different class of conversions for the 1701 // Objective-C++ implicit conversions. 1702 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 1703 return false; 1704 1705 } 1706 return false; 1707} 1708 1709/// IsMemberPointerConversion - Determines whether the conversion of the 1710/// expression From, which has the (possibly adjusted) type FromType, can be 1711/// converted to the type ToType via a member pointer conversion (C++ 4.11). 1712/// If so, returns true and places the converted type (that might differ from 1713/// ToType in its cv-qualifiers at some level) into ConvertedType. 1714bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 1715 QualType ToType, 1716 bool InOverloadResolution, 1717 QualType &ConvertedType) { 1718 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 1719 if (!ToTypePtr) 1720 return false; 1721 1722 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 1723 if (From->isNullPointerConstant(Context, 1724 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1725 : Expr::NPC_ValueDependentIsNull)) { 1726 ConvertedType = ToType; 1727 return true; 1728 } 1729 1730 // Otherwise, both types have to be member pointers. 1731 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 1732 if (!FromTypePtr) 1733 return false; 1734 1735 // A pointer to member of B can be converted to a pointer to member of D, 1736 // where D is derived from B (C++ 4.11p2). 1737 QualType FromClass(FromTypePtr->getClass(), 0); 1738 QualType ToClass(ToTypePtr->getClass(), 0); 1739 // FIXME: What happens when these are dependent? Is this function even called? 1740 1741 if (IsDerivedFrom(ToClass, FromClass)) { 1742 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 1743 ToClass.getTypePtr()); 1744 return true; 1745 } 1746 1747 return false; 1748} 1749 1750/// CheckMemberPointerConversion - Check the member pointer conversion from the 1751/// expression From to the type ToType. This routine checks for ambiguous or 1752/// virtual or inaccessible base-to-derived member pointer conversions 1753/// for which IsMemberPointerConversion has already returned true. It returns 1754/// true and produces a diagnostic if there was an error, or returns false 1755/// otherwise. 1756bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 1757 CastExpr::CastKind &Kind, 1758 CXXCastPath &BasePath, 1759 bool IgnoreBaseAccess) { 1760 QualType FromType = From->getType(); 1761 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 1762 if (!FromPtrType) { 1763 // This must be a null pointer to member pointer conversion 1764 assert(From->isNullPointerConstant(Context, 1765 Expr::NPC_ValueDependentIsNull) && 1766 "Expr must be null pointer constant!"); 1767 Kind = CastExpr::CK_NullToMemberPointer; 1768 return false; 1769 } 1770 1771 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 1772 assert(ToPtrType && "No member pointer cast has a target type " 1773 "that is not a member pointer."); 1774 1775 QualType FromClass = QualType(FromPtrType->getClass(), 0); 1776 QualType ToClass = QualType(ToPtrType->getClass(), 0); 1777 1778 // FIXME: What about dependent types? 1779 assert(FromClass->isRecordType() && "Pointer into non-class."); 1780 assert(ToClass->isRecordType() && "Pointer into non-class."); 1781 1782 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1783 /*DetectVirtual=*/true); 1784 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 1785 assert(DerivationOkay && 1786 "Should not have been called if derivation isn't OK."); 1787 (void)DerivationOkay; 1788 1789 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 1790 getUnqualifiedType())) { 1791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1792 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 1793 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 1794 return true; 1795 } 1796 1797 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1798 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 1799 << FromClass << ToClass << QualType(VBase, 0) 1800 << From->getSourceRange(); 1801 return true; 1802 } 1803 1804 if (!IgnoreBaseAccess) 1805 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 1806 Paths.front(), 1807 diag::err_downcast_from_inaccessible_base); 1808 1809 // Must be a base to derived member conversion. 1810 BuildBasePathArray(Paths, BasePath); 1811 Kind = CastExpr::CK_BaseToDerivedMemberPointer; 1812 return false; 1813} 1814 1815/// IsQualificationConversion - Determines whether the conversion from 1816/// an rvalue of type FromType to ToType is a qualification conversion 1817/// (C++ 4.4). 1818bool 1819Sema::IsQualificationConversion(QualType FromType, QualType ToType) { 1820 FromType = Context.getCanonicalType(FromType); 1821 ToType = Context.getCanonicalType(ToType); 1822 1823 // If FromType and ToType are the same type, this is not a 1824 // qualification conversion. 1825 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 1826 return false; 1827 1828 // (C++ 4.4p4): 1829 // A conversion can add cv-qualifiers at levels other than the first 1830 // in multi-level pointers, subject to the following rules: [...] 1831 bool PreviousToQualsIncludeConst = true; 1832 bool UnwrappedAnyPointer = false; 1833 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 1834 // Within each iteration of the loop, we check the qualifiers to 1835 // determine if this still looks like a qualification 1836 // conversion. Then, if all is well, we unwrap one more level of 1837 // pointers or pointers-to-members and do it all again 1838 // until there are no more pointers or pointers-to-members left to 1839 // unwrap. 1840 UnwrappedAnyPointer = true; 1841 1842 // -- for every j > 0, if const is in cv 1,j then const is in cv 1843 // 2,j, and similarly for volatile. 1844 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 1845 return false; 1846 1847 // -- if the cv 1,j and cv 2,j are different, then const is in 1848 // every cv for 0 < k < j. 1849 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 1850 && !PreviousToQualsIncludeConst) 1851 return false; 1852 1853 // Keep track of whether all prior cv-qualifiers in the "to" type 1854 // include const. 1855 PreviousToQualsIncludeConst 1856 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 1857 } 1858 1859 // We are left with FromType and ToType being the pointee types 1860 // after unwrapping the original FromType and ToType the same number 1861 // of types. If we unwrapped any pointers, and if FromType and 1862 // ToType have the same unqualified type (since we checked 1863 // qualifiers above), then this is a qualification conversion. 1864 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 1865} 1866 1867/// Determines whether there is a user-defined conversion sequence 1868/// (C++ [over.ics.user]) that converts expression From to the type 1869/// ToType. If such a conversion exists, User will contain the 1870/// user-defined conversion sequence that performs such a conversion 1871/// and this routine will return true. Otherwise, this routine returns 1872/// false and User is unspecified. 1873/// 1874/// \param AllowExplicit true if the conversion should consider C++0x 1875/// "explicit" conversion functions as well as non-explicit conversion 1876/// functions (C++0x [class.conv.fct]p2). 1877OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 1878 UserDefinedConversionSequence& User, 1879 OverloadCandidateSet& CandidateSet, 1880 bool AllowExplicit) { 1881 // Whether we will only visit constructors. 1882 bool ConstructorsOnly = false; 1883 1884 // If the type we are conversion to is a class type, enumerate its 1885 // constructors. 1886 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 1887 // C++ [over.match.ctor]p1: 1888 // When objects of class type are direct-initialized (8.5), or 1889 // copy-initialized from an expression of the same or a 1890 // derived class type (8.5), overload resolution selects the 1891 // constructor. [...] For copy-initialization, the candidate 1892 // functions are all the converting constructors (12.3.1) of 1893 // that class. The argument list is the expression-list within 1894 // the parentheses of the initializer. 1895 if (Context.hasSameUnqualifiedType(ToType, From->getType()) || 1896 (From->getType()->getAs<RecordType>() && 1897 IsDerivedFrom(From->getType(), ToType))) 1898 ConstructorsOnly = true; 1899 1900 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) { 1901 // We're not going to find any constructors. 1902 } else if (CXXRecordDecl *ToRecordDecl 1903 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 1904 DeclContext::lookup_iterator Con, ConEnd; 1905 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl); 1906 Con != ConEnd; ++Con) { 1907 NamedDecl *D = *Con; 1908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 1909 1910 // Find the constructor (which may be a template). 1911 CXXConstructorDecl *Constructor = 0; 1912 FunctionTemplateDecl *ConstructorTmpl 1913 = dyn_cast<FunctionTemplateDecl>(D); 1914 if (ConstructorTmpl) 1915 Constructor 1916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 1917 else 1918 Constructor = cast<CXXConstructorDecl>(D); 1919 1920 if (!Constructor->isInvalidDecl() && 1921 Constructor->isConvertingConstructor(AllowExplicit)) { 1922 if (ConstructorTmpl) 1923 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 1924 /*ExplicitArgs*/ 0, 1925 &From, 1, CandidateSet, 1926 /*SuppressUserConversions=*/!ConstructorsOnly); 1927 else 1928 // Allow one user-defined conversion when user specifies a 1929 // From->ToType conversion via an static cast (c-style, etc). 1930 AddOverloadCandidate(Constructor, FoundDecl, 1931 &From, 1, CandidateSet, 1932 /*SuppressUserConversions=*/!ConstructorsOnly); 1933 } 1934 } 1935 } 1936 } 1937 1938 // Enumerate conversion functions, if we're allowed to. 1939 if (ConstructorsOnly) { 1940 } else if (RequireCompleteType(From->getLocStart(), From->getType(), 1941 PDiag(0) << From->getSourceRange())) { 1942 // No conversion functions from incomplete types. 1943 } else if (const RecordType *FromRecordType 1944 = From->getType()->getAs<RecordType>()) { 1945 if (CXXRecordDecl *FromRecordDecl 1946 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 1947 // Add all of the conversion functions as candidates. 1948 const UnresolvedSetImpl *Conversions 1949 = FromRecordDecl->getVisibleConversionFunctions(); 1950 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1951 E = Conversions->end(); I != E; ++I) { 1952 DeclAccessPair FoundDecl = I.getPair(); 1953 NamedDecl *D = FoundDecl.getDecl(); 1954 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 1955 if (isa<UsingShadowDecl>(D)) 1956 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1957 1958 CXXConversionDecl *Conv; 1959 FunctionTemplateDecl *ConvTemplate; 1960 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 1961 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 1962 else 1963 Conv = cast<CXXConversionDecl>(D); 1964 1965 if (AllowExplicit || !Conv->isExplicit()) { 1966 if (ConvTemplate) 1967 AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 1968 ActingContext, From, ToType, 1969 CandidateSet); 1970 else 1971 AddConversionCandidate(Conv, FoundDecl, ActingContext, 1972 From, ToType, CandidateSet); 1973 } 1974 } 1975 } 1976 } 1977 1978 OverloadCandidateSet::iterator Best; 1979 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) { 1980 case OR_Success: 1981 // Record the standard conversion we used and the conversion function. 1982 if (CXXConstructorDecl *Constructor 1983 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 1984 // C++ [over.ics.user]p1: 1985 // If the user-defined conversion is specified by a 1986 // constructor (12.3.1), the initial standard conversion 1987 // sequence converts the source type to the type required by 1988 // the argument of the constructor. 1989 // 1990 QualType ThisType = Constructor->getThisType(Context); 1991 if (Best->Conversions[0].isEllipsis()) 1992 User.EllipsisConversion = true; 1993 else { 1994 User.Before = Best->Conversions[0].Standard; 1995 User.EllipsisConversion = false; 1996 } 1997 User.ConversionFunction = Constructor; 1998 User.After.setAsIdentityConversion(); 1999 User.After.setFromType( 2000 ThisType->getAs<PointerType>()->getPointeeType()); 2001 User.After.setAllToTypes(ToType); 2002 return OR_Success; 2003 } else if (CXXConversionDecl *Conversion 2004 = dyn_cast<CXXConversionDecl>(Best->Function)) { 2005 // C++ [over.ics.user]p1: 2006 // 2007 // [...] If the user-defined conversion is specified by a 2008 // conversion function (12.3.2), the initial standard 2009 // conversion sequence converts the source type to the 2010 // implicit object parameter of the conversion function. 2011 User.Before = Best->Conversions[0].Standard; 2012 User.ConversionFunction = Conversion; 2013 User.EllipsisConversion = false; 2014 2015 // C++ [over.ics.user]p2: 2016 // The second standard conversion sequence converts the 2017 // result of the user-defined conversion to the target type 2018 // for the sequence. Since an implicit conversion sequence 2019 // is an initialization, the special rules for 2020 // initialization by user-defined conversion apply when 2021 // selecting the best user-defined conversion for a 2022 // user-defined conversion sequence (see 13.3.3 and 2023 // 13.3.3.1). 2024 User.After = Best->FinalConversion; 2025 return OR_Success; 2026 } else { 2027 assert(false && "Not a constructor or conversion function?"); 2028 return OR_No_Viable_Function; 2029 } 2030 2031 case OR_No_Viable_Function: 2032 return OR_No_Viable_Function; 2033 case OR_Deleted: 2034 // No conversion here! We're done. 2035 return OR_Deleted; 2036 2037 case OR_Ambiguous: 2038 return OR_Ambiguous; 2039 } 2040 2041 return OR_No_Viable_Function; 2042} 2043 2044bool 2045Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 2046 ImplicitConversionSequence ICS; 2047 OverloadCandidateSet CandidateSet(From->getExprLoc()); 2048 OverloadingResult OvResult = 2049 IsUserDefinedConversion(From, ToType, ICS.UserDefined, 2050 CandidateSet, false); 2051 if (OvResult == OR_Ambiguous) 2052 Diag(From->getSourceRange().getBegin(), 2053 diag::err_typecheck_ambiguous_condition) 2054 << From->getType() << ToType << From->getSourceRange(); 2055 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 2056 Diag(From->getSourceRange().getBegin(), 2057 diag::err_typecheck_nonviable_condition) 2058 << From->getType() << ToType << From->getSourceRange(); 2059 else 2060 return false; 2061 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1); 2062 return true; 2063} 2064 2065/// CompareImplicitConversionSequences - Compare two implicit 2066/// conversion sequences to determine whether one is better than the 2067/// other or if they are indistinguishable (C++ 13.3.3.2). 2068ImplicitConversionSequence::CompareKind 2069Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 2070 const ImplicitConversionSequence& ICS2) 2071{ 2072 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 2073 // conversion sequences (as defined in 13.3.3.1) 2074 // -- a standard conversion sequence (13.3.3.1.1) is a better 2075 // conversion sequence than a user-defined conversion sequence or 2076 // an ellipsis conversion sequence, and 2077 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 2078 // conversion sequence than an ellipsis conversion sequence 2079 // (13.3.3.1.3). 2080 // 2081 // C++0x [over.best.ics]p10: 2082 // For the purpose of ranking implicit conversion sequences as 2083 // described in 13.3.3.2, the ambiguous conversion sequence is 2084 // treated as a user-defined sequence that is indistinguishable 2085 // from any other user-defined conversion sequence. 2086 if (ICS1.getKindRank() < ICS2.getKindRank()) 2087 return ImplicitConversionSequence::Better; 2088 else if (ICS2.getKindRank() < ICS1.getKindRank()) 2089 return ImplicitConversionSequence::Worse; 2090 2091 // The following checks require both conversion sequences to be of 2092 // the same kind. 2093 if (ICS1.getKind() != ICS2.getKind()) 2094 return ImplicitConversionSequence::Indistinguishable; 2095 2096 // Two implicit conversion sequences of the same form are 2097 // indistinguishable conversion sequences unless one of the 2098 // following rules apply: (C++ 13.3.3.2p3): 2099 if (ICS1.isStandard()) 2100 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 2101 else if (ICS1.isUserDefined()) { 2102 // User-defined conversion sequence U1 is a better conversion 2103 // sequence than another user-defined conversion sequence U2 if 2104 // they contain the same user-defined conversion function or 2105 // constructor and if the second standard conversion sequence of 2106 // U1 is better than the second standard conversion sequence of 2107 // U2 (C++ 13.3.3.2p3). 2108 if (ICS1.UserDefined.ConversionFunction == 2109 ICS2.UserDefined.ConversionFunction) 2110 return CompareStandardConversionSequences(ICS1.UserDefined.After, 2111 ICS2.UserDefined.After); 2112 } 2113 2114 return ImplicitConversionSequence::Indistinguishable; 2115} 2116 2117static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 2118 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 2119 Qualifiers Quals; 2120 T1 = Context.getUnqualifiedArrayType(T1, Quals); 2121 T2 = Context.getUnqualifiedArrayType(T2, Quals); 2122 } 2123 2124 return Context.hasSameUnqualifiedType(T1, T2); 2125} 2126 2127// Per 13.3.3.2p3, compare the given standard conversion sequences to 2128// determine if one is a proper subset of the other. 2129static ImplicitConversionSequence::CompareKind 2130compareStandardConversionSubsets(ASTContext &Context, 2131 const StandardConversionSequence& SCS1, 2132 const StandardConversionSequence& SCS2) { 2133 ImplicitConversionSequence::CompareKind Result 2134 = ImplicitConversionSequence::Indistinguishable; 2135 2136 // the identity conversion sequence is considered to be a subsequence of 2137 // any non-identity conversion sequence 2138 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) { 2139 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 2140 return ImplicitConversionSequence::Better; 2141 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 2142 return ImplicitConversionSequence::Worse; 2143 } 2144 2145 if (SCS1.Second != SCS2.Second) { 2146 if (SCS1.Second == ICK_Identity) 2147 Result = ImplicitConversionSequence::Better; 2148 else if (SCS2.Second == ICK_Identity) 2149 Result = ImplicitConversionSequence::Worse; 2150 else 2151 return ImplicitConversionSequence::Indistinguishable; 2152 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 2153 return ImplicitConversionSequence::Indistinguishable; 2154 2155 if (SCS1.Third == SCS2.Third) { 2156 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 2157 : ImplicitConversionSequence::Indistinguishable; 2158 } 2159 2160 if (SCS1.Third == ICK_Identity) 2161 return Result == ImplicitConversionSequence::Worse 2162 ? ImplicitConversionSequence::Indistinguishable 2163 : ImplicitConversionSequence::Better; 2164 2165 if (SCS2.Third == ICK_Identity) 2166 return Result == ImplicitConversionSequence::Better 2167 ? ImplicitConversionSequence::Indistinguishable 2168 : ImplicitConversionSequence::Worse; 2169 2170 return ImplicitConversionSequence::Indistinguishable; 2171} 2172 2173/// CompareStandardConversionSequences - Compare two standard 2174/// conversion sequences to determine whether one is better than the 2175/// other or if they are indistinguishable (C++ 13.3.3.2p3). 2176ImplicitConversionSequence::CompareKind 2177Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 2178 const StandardConversionSequence& SCS2) 2179{ 2180 // Standard conversion sequence S1 is a better conversion sequence 2181 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 2182 2183 // -- S1 is a proper subsequence of S2 (comparing the conversion 2184 // sequences in the canonical form defined by 13.3.3.1.1, 2185 // excluding any Lvalue Transformation; the identity conversion 2186 // sequence is considered to be a subsequence of any 2187 // non-identity conversion sequence) or, if not that, 2188 if (ImplicitConversionSequence::CompareKind CK 2189 = compareStandardConversionSubsets(Context, SCS1, SCS2)) 2190 return CK; 2191 2192 // -- the rank of S1 is better than the rank of S2 (by the rules 2193 // defined below), or, if not that, 2194 ImplicitConversionRank Rank1 = SCS1.getRank(); 2195 ImplicitConversionRank Rank2 = SCS2.getRank(); 2196 if (Rank1 < Rank2) 2197 return ImplicitConversionSequence::Better; 2198 else if (Rank2 < Rank1) 2199 return ImplicitConversionSequence::Worse; 2200 2201 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 2202 // are indistinguishable unless one of the following rules 2203 // applies: 2204 2205 // A conversion that is not a conversion of a pointer, or 2206 // pointer to member, to bool is better than another conversion 2207 // that is such a conversion. 2208 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 2209 return SCS2.isPointerConversionToBool() 2210 ? ImplicitConversionSequence::Better 2211 : ImplicitConversionSequence::Worse; 2212 2213 // C++ [over.ics.rank]p4b2: 2214 // 2215 // If class B is derived directly or indirectly from class A, 2216 // conversion of B* to A* is better than conversion of B* to 2217 // void*, and conversion of A* to void* is better than conversion 2218 // of B* to void*. 2219 bool SCS1ConvertsToVoid 2220 = SCS1.isPointerConversionToVoidPointer(Context); 2221 bool SCS2ConvertsToVoid 2222 = SCS2.isPointerConversionToVoidPointer(Context); 2223 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 2224 // Exactly one of the conversion sequences is a conversion to 2225 // a void pointer; it's the worse conversion. 2226 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 2227 : ImplicitConversionSequence::Worse; 2228 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 2229 // Neither conversion sequence converts to a void pointer; compare 2230 // their derived-to-base conversions. 2231 if (ImplicitConversionSequence::CompareKind DerivedCK 2232 = CompareDerivedToBaseConversions(SCS1, SCS2)) 2233 return DerivedCK; 2234 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 2235 // Both conversion sequences are conversions to void 2236 // pointers. Compare the source types to determine if there's an 2237 // inheritance relationship in their sources. 2238 QualType FromType1 = SCS1.getFromType(); 2239 QualType FromType2 = SCS2.getFromType(); 2240 2241 // Adjust the types we're converting from via the array-to-pointer 2242 // conversion, if we need to. 2243 if (SCS1.First == ICK_Array_To_Pointer) 2244 FromType1 = Context.getArrayDecayedType(FromType1); 2245 if (SCS2.First == ICK_Array_To_Pointer) 2246 FromType2 = Context.getArrayDecayedType(FromType2); 2247 2248 QualType FromPointee1 2249 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2250 QualType FromPointee2 2251 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2252 2253 if (IsDerivedFrom(FromPointee2, FromPointee1)) 2254 return ImplicitConversionSequence::Better; 2255 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 2256 return ImplicitConversionSequence::Worse; 2257 2258 // Objective-C++: If one interface is more specific than the 2259 // other, it is the better one. 2260 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>(); 2261 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>(); 2262 if (FromIface1 && FromIface1) { 2263 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 2264 return ImplicitConversionSequence::Better; 2265 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 2266 return ImplicitConversionSequence::Worse; 2267 } 2268 } 2269 2270 // Compare based on qualification conversions (C++ 13.3.3.2p3, 2271 // bullet 3). 2272 if (ImplicitConversionSequence::CompareKind QualCK 2273 = CompareQualificationConversions(SCS1, SCS2)) 2274 return QualCK; 2275 2276 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 2277 // C++0x [over.ics.rank]p3b4: 2278 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 2279 // implicit object parameter of a non-static member function declared 2280 // without a ref-qualifier, and S1 binds an rvalue reference to an 2281 // rvalue and S2 binds an lvalue reference. 2282 // FIXME: We don't know if we're dealing with the implicit object parameter, 2283 // or if the member function in this case has a ref qualifier. 2284 // (Of course, we don't have ref qualifiers yet.) 2285 if (SCS1.RRefBinding != SCS2.RRefBinding) 2286 return SCS1.RRefBinding ? ImplicitConversionSequence::Better 2287 : ImplicitConversionSequence::Worse; 2288 2289 // C++ [over.ics.rank]p3b4: 2290 // -- S1 and S2 are reference bindings (8.5.3), and the types to 2291 // which the references refer are the same type except for 2292 // top-level cv-qualifiers, and the type to which the reference 2293 // initialized by S2 refers is more cv-qualified than the type 2294 // to which the reference initialized by S1 refers. 2295 QualType T1 = SCS1.getToType(2); 2296 QualType T2 = SCS2.getToType(2); 2297 T1 = Context.getCanonicalType(T1); 2298 T2 = Context.getCanonicalType(T2); 2299 Qualifiers T1Quals, T2Quals; 2300 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 2301 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 2302 if (UnqualT1 == UnqualT2) { 2303 // If the type is an array type, promote the element qualifiers to the type 2304 // for comparison. 2305 if (isa<ArrayType>(T1) && T1Quals) 2306 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 2307 if (isa<ArrayType>(T2) && T2Quals) 2308 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 2309 if (T2.isMoreQualifiedThan(T1)) 2310 return ImplicitConversionSequence::Better; 2311 else if (T1.isMoreQualifiedThan(T2)) 2312 return ImplicitConversionSequence::Worse; 2313 } 2314 } 2315 2316 return ImplicitConversionSequence::Indistinguishable; 2317} 2318 2319/// CompareQualificationConversions - Compares two standard conversion 2320/// sequences to determine whether they can be ranked based on their 2321/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 2322ImplicitConversionSequence::CompareKind 2323Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 2324 const StandardConversionSequence& SCS2) { 2325 // C++ 13.3.3.2p3: 2326 // -- S1 and S2 differ only in their qualification conversion and 2327 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 2328 // cv-qualification signature of type T1 is a proper subset of 2329 // the cv-qualification signature of type T2, and S1 is not the 2330 // deprecated string literal array-to-pointer conversion (4.2). 2331 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 2332 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 2333 return ImplicitConversionSequence::Indistinguishable; 2334 2335 // FIXME: the example in the standard doesn't use a qualification 2336 // conversion (!) 2337 QualType T1 = SCS1.getToType(2); 2338 QualType T2 = SCS2.getToType(2); 2339 T1 = Context.getCanonicalType(T1); 2340 T2 = Context.getCanonicalType(T2); 2341 Qualifiers T1Quals, T2Quals; 2342 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 2343 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 2344 2345 // If the types are the same, we won't learn anything by unwrapped 2346 // them. 2347 if (UnqualT1 == UnqualT2) 2348 return ImplicitConversionSequence::Indistinguishable; 2349 2350 // If the type is an array type, promote the element qualifiers to the type 2351 // for comparison. 2352 if (isa<ArrayType>(T1) && T1Quals) 2353 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 2354 if (isa<ArrayType>(T2) && T2Quals) 2355 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 2356 2357 ImplicitConversionSequence::CompareKind Result 2358 = ImplicitConversionSequence::Indistinguishable; 2359 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 2360 // Within each iteration of the loop, we check the qualifiers to 2361 // determine if this still looks like a qualification 2362 // conversion. Then, if all is well, we unwrap one more level of 2363 // pointers or pointers-to-members and do it all again 2364 // until there are no more pointers or pointers-to-members left 2365 // to unwrap. This essentially mimics what 2366 // IsQualificationConversion does, but here we're checking for a 2367 // strict subset of qualifiers. 2368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 2369 // The qualifiers are the same, so this doesn't tell us anything 2370 // about how the sequences rank. 2371 ; 2372 else if (T2.isMoreQualifiedThan(T1)) { 2373 // T1 has fewer qualifiers, so it could be the better sequence. 2374 if (Result == ImplicitConversionSequence::Worse) 2375 // Neither has qualifiers that are a subset of the other's 2376 // qualifiers. 2377 return ImplicitConversionSequence::Indistinguishable; 2378 2379 Result = ImplicitConversionSequence::Better; 2380 } else if (T1.isMoreQualifiedThan(T2)) { 2381 // T2 has fewer qualifiers, so it could be the better sequence. 2382 if (Result == ImplicitConversionSequence::Better) 2383 // Neither has qualifiers that are a subset of the other's 2384 // qualifiers. 2385 return ImplicitConversionSequence::Indistinguishable; 2386 2387 Result = ImplicitConversionSequence::Worse; 2388 } else { 2389 // Qualifiers are disjoint. 2390 return ImplicitConversionSequence::Indistinguishable; 2391 } 2392 2393 // If the types after this point are equivalent, we're done. 2394 if (Context.hasSameUnqualifiedType(T1, T2)) 2395 break; 2396 } 2397 2398 // Check that the winning standard conversion sequence isn't using 2399 // the deprecated string literal array to pointer conversion. 2400 switch (Result) { 2401 case ImplicitConversionSequence::Better: 2402 if (SCS1.DeprecatedStringLiteralToCharPtr) 2403 Result = ImplicitConversionSequence::Indistinguishable; 2404 break; 2405 2406 case ImplicitConversionSequence::Indistinguishable: 2407 break; 2408 2409 case ImplicitConversionSequence::Worse: 2410 if (SCS2.DeprecatedStringLiteralToCharPtr) 2411 Result = ImplicitConversionSequence::Indistinguishable; 2412 break; 2413 } 2414 2415 return Result; 2416} 2417 2418/// CompareDerivedToBaseConversions - Compares two standard conversion 2419/// sequences to determine whether they can be ranked based on their 2420/// various kinds of derived-to-base conversions (C++ 2421/// [over.ics.rank]p4b3). As part of these checks, we also look at 2422/// conversions between Objective-C interface types. 2423ImplicitConversionSequence::CompareKind 2424Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 2425 const StandardConversionSequence& SCS2) { 2426 QualType FromType1 = SCS1.getFromType(); 2427 QualType ToType1 = SCS1.getToType(1); 2428 QualType FromType2 = SCS2.getFromType(); 2429 QualType ToType2 = SCS2.getToType(1); 2430 2431 // Adjust the types we're converting from via the array-to-pointer 2432 // conversion, if we need to. 2433 if (SCS1.First == ICK_Array_To_Pointer) 2434 FromType1 = Context.getArrayDecayedType(FromType1); 2435 if (SCS2.First == ICK_Array_To_Pointer) 2436 FromType2 = Context.getArrayDecayedType(FromType2); 2437 2438 // Canonicalize all of the types. 2439 FromType1 = Context.getCanonicalType(FromType1); 2440 ToType1 = Context.getCanonicalType(ToType1); 2441 FromType2 = Context.getCanonicalType(FromType2); 2442 ToType2 = Context.getCanonicalType(ToType2); 2443 2444 // C++ [over.ics.rank]p4b3: 2445 // 2446 // If class B is derived directly or indirectly from class A and 2447 // class C is derived directly or indirectly from B, 2448 // 2449 // For Objective-C, we let A, B, and C also be Objective-C 2450 // interfaces. 2451 2452 // Compare based on pointer conversions. 2453 if (SCS1.Second == ICK_Pointer_Conversion && 2454 SCS2.Second == ICK_Pointer_Conversion && 2455 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 2456 FromType1->isPointerType() && FromType2->isPointerType() && 2457 ToType1->isPointerType() && ToType2->isPointerType()) { 2458 QualType FromPointee1 2459 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2460 QualType ToPointee1 2461 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2462 QualType FromPointee2 2463 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2464 QualType ToPointee2 2465 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2466 2467 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>(); 2468 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>(); 2469 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>(); 2470 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>(); 2471 2472 // -- conversion of C* to B* is better than conversion of C* to A*, 2473 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 2474 if (IsDerivedFrom(ToPointee1, ToPointee2)) 2475 return ImplicitConversionSequence::Better; 2476 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 2477 return ImplicitConversionSequence::Worse; 2478 2479 if (ToIface1 && ToIface2) { 2480 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 2481 return ImplicitConversionSequence::Better; 2482 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 2483 return ImplicitConversionSequence::Worse; 2484 } 2485 } 2486 2487 // -- conversion of B* to A* is better than conversion of C* to A*, 2488 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 2489 if (IsDerivedFrom(FromPointee2, FromPointee1)) 2490 return ImplicitConversionSequence::Better; 2491 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 2492 return ImplicitConversionSequence::Worse; 2493 2494 if (FromIface1 && FromIface2) { 2495 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 2496 return ImplicitConversionSequence::Better; 2497 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 2498 return ImplicitConversionSequence::Worse; 2499 } 2500 } 2501 } 2502 2503 // Ranking of member-pointer types. 2504 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 2505 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 2506 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 2507 const MemberPointerType * FromMemPointer1 = 2508 FromType1->getAs<MemberPointerType>(); 2509 const MemberPointerType * ToMemPointer1 = 2510 ToType1->getAs<MemberPointerType>(); 2511 const MemberPointerType * FromMemPointer2 = 2512 FromType2->getAs<MemberPointerType>(); 2513 const MemberPointerType * ToMemPointer2 = 2514 ToType2->getAs<MemberPointerType>(); 2515 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 2516 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 2517 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 2518 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 2519 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 2520 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 2521 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 2522 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 2523 // conversion of A::* to B::* is better than conversion of A::* to C::*, 2524 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 2525 if (IsDerivedFrom(ToPointee1, ToPointee2)) 2526 return ImplicitConversionSequence::Worse; 2527 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 2528 return ImplicitConversionSequence::Better; 2529 } 2530 // conversion of B::* to C::* is better than conversion of A::* to C::* 2531 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 2532 if (IsDerivedFrom(FromPointee1, FromPointee2)) 2533 return ImplicitConversionSequence::Better; 2534 else if (IsDerivedFrom(FromPointee2, FromPointee1)) 2535 return ImplicitConversionSequence::Worse; 2536 } 2537 } 2538 2539 if (SCS1.Second == ICK_Derived_To_Base) { 2540 // -- conversion of C to B is better than conversion of C to A, 2541 // -- binding of an expression of type C to a reference of type 2542 // B& is better than binding an expression of type C to a 2543 // reference of type A&, 2544 if (Context.hasSameUnqualifiedType(FromType1, FromType2) && 2545 !Context.hasSameUnqualifiedType(ToType1, ToType2)) { 2546 if (IsDerivedFrom(ToType1, ToType2)) 2547 return ImplicitConversionSequence::Better; 2548 else if (IsDerivedFrom(ToType2, ToType1)) 2549 return ImplicitConversionSequence::Worse; 2550 } 2551 2552 // -- conversion of B to A is better than conversion of C to A. 2553 // -- binding of an expression of type B to a reference of type 2554 // A& is better than binding an expression of type C to a 2555 // reference of type A&, 2556 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) && 2557 Context.hasSameUnqualifiedType(ToType1, ToType2)) { 2558 if (IsDerivedFrom(FromType2, FromType1)) 2559 return ImplicitConversionSequence::Better; 2560 else if (IsDerivedFrom(FromType1, FromType2)) 2561 return ImplicitConversionSequence::Worse; 2562 } 2563 } 2564 2565 return ImplicitConversionSequence::Indistinguishable; 2566} 2567 2568/// CompareReferenceRelationship - Compare the two types T1 and T2 to 2569/// determine whether they are reference-related, 2570/// reference-compatible, reference-compatible with added 2571/// qualification, or incompatible, for use in C++ initialization by 2572/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 2573/// type, and the first type (T1) is the pointee type of the reference 2574/// type being initialized. 2575Sema::ReferenceCompareResult 2576Sema::CompareReferenceRelationship(SourceLocation Loc, 2577 QualType OrigT1, QualType OrigT2, 2578 bool &DerivedToBase, 2579 bool &ObjCConversion) { 2580 assert(!OrigT1->isReferenceType() && 2581 "T1 must be the pointee type of the reference type"); 2582 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 2583 2584 QualType T1 = Context.getCanonicalType(OrigT1); 2585 QualType T2 = Context.getCanonicalType(OrigT2); 2586 Qualifiers T1Quals, T2Quals; 2587 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 2588 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 2589 2590 // C++ [dcl.init.ref]p4: 2591 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 2592 // reference-related to "cv2 T2" if T1 is the same type as T2, or 2593 // T1 is a base class of T2. 2594 DerivedToBase = false; 2595 ObjCConversion = false; 2596 if (UnqualT1 == UnqualT2) { 2597 // Nothing to do. 2598 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) && 2599 IsDerivedFrom(UnqualT2, UnqualT1)) 2600 DerivedToBase = true; 2601 else if (UnqualT1->isObjCObjectOrInterfaceType() && 2602 UnqualT2->isObjCObjectOrInterfaceType() && 2603 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 2604 ObjCConversion = true; 2605 else 2606 return Ref_Incompatible; 2607 2608 // At this point, we know that T1 and T2 are reference-related (at 2609 // least). 2610 2611 // If the type is an array type, promote the element qualifiers to the type 2612 // for comparison. 2613 if (isa<ArrayType>(T1) && T1Quals) 2614 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 2615 if (isa<ArrayType>(T2) && T2Quals) 2616 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 2617 2618 // C++ [dcl.init.ref]p4: 2619 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 2620 // reference-related to T2 and cv1 is the same cv-qualification 2621 // as, or greater cv-qualification than, cv2. For purposes of 2622 // overload resolution, cases for which cv1 is greater 2623 // cv-qualification than cv2 are identified as 2624 // reference-compatible with added qualification (see 13.3.3.2). 2625 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers()) 2626 return Ref_Compatible; 2627 else if (T1.isMoreQualifiedThan(T2)) 2628 return Ref_Compatible_With_Added_Qualification; 2629 else 2630 return Ref_Related; 2631} 2632 2633/// \brief Look for a user-defined conversion to an lvalue reference-compatible 2634/// with DeclType. Return true if something definite is found. 2635static bool 2636FindConversionToLValue(Sema &S, ImplicitConversionSequence &ICS, 2637 QualType DeclType, SourceLocation DeclLoc, 2638 Expr *Init, QualType T2, bool AllowExplicit) { 2639 assert(T2->isRecordType() && "Can only find conversions of record types."); 2640 CXXRecordDecl *T2RecordDecl 2641 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 2642 2643 OverloadCandidateSet CandidateSet(DeclLoc); 2644 const UnresolvedSetImpl *Conversions 2645 = T2RecordDecl->getVisibleConversionFunctions(); 2646 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2647 E = Conversions->end(); I != E; ++I) { 2648 NamedDecl *D = *I; 2649 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2650 if (isa<UsingShadowDecl>(D)) 2651 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2652 2653 FunctionTemplateDecl *ConvTemplate 2654 = dyn_cast<FunctionTemplateDecl>(D); 2655 CXXConversionDecl *Conv; 2656 if (ConvTemplate) 2657 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2658 else 2659 Conv = cast<CXXConversionDecl>(D); 2660 2661 // If the conversion function doesn't return a reference type, 2662 // it can't be considered for this conversion. An rvalue reference 2663 // is only acceptable if its referencee is a function type. 2664 const ReferenceType *RefType = 2665 Conv->getConversionType()->getAs<ReferenceType>(); 2666 if (RefType && (RefType->isLValueReferenceType() || 2667 RefType->getPointeeType()->isFunctionType()) && 2668 (AllowExplicit || !Conv->isExplicit())) { 2669 if (ConvTemplate) 2670 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 2671 Init, DeclType, CandidateSet); 2672 else 2673 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 2674 DeclType, CandidateSet); 2675 } 2676 } 2677 2678 OverloadCandidateSet::iterator Best; 2679 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) { 2680 case OR_Success: 2681 // C++ [over.ics.ref]p1: 2682 // 2683 // [...] If the parameter binds directly to the result of 2684 // applying a conversion function to the argument 2685 // expression, the implicit conversion sequence is a 2686 // user-defined conversion sequence (13.3.3.1.2), with the 2687 // second standard conversion sequence either an identity 2688 // conversion or, if the conversion function returns an 2689 // entity of a type that is a derived class of the parameter 2690 // type, a derived-to-base Conversion. 2691 if (!Best->FinalConversion.DirectBinding) 2692 return false; 2693 2694 ICS.setUserDefined(); 2695 ICS.UserDefined.Before = Best->Conversions[0].Standard; 2696 ICS.UserDefined.After = Best->FinalConversion; 2697 ICS.UserDefined.ConversionFunction = Best->Function; 2698 ICS.UserDefined.EllipsisConversion = false; 2699 assert(ICS.UserDefined.After.ReferenceBinding && 2700 ICS.UserDefined.After.DirectBinding && 2701 "Expected a direct reference binding!"); 2702 return true; 2703 2704 case OR_Ambiguous: 2705 ICS.setAmbiguous(); 2706 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2707 Cand != CandidateSet.end(); ++Cand) 2708 if (Cand->Viable) 2709 ICS.Ambiguous.addConversion(Cand->Function); 2710 return true; 2711 2712 case OR_No_Viable_Function: 2713 case OR_Deleted: 2714 // There was no suitable conversion, or we found a deleted 2715 // conversion; continue with other checks. 2716 return false; 2717 } 2718 2719 return false; 2720} 2721 2722/// \brief Compute an implicit conversion sequence for reference 2723/// initialization. 2724static ImplicitConversionSequence 2725TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType, 2726 SourceLocation DeclLoc, 2727 bool SuppressUserConversions, 2728 bool AllowExplicit) { 2729 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 2730 2731 // Most paths end in a failed conversion. 2732 ImplicitConversionSequence ICS; 2733 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 2734 2735 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 2736 QualType T2 = Init->getType(); 2737 2738 // If the initializer is the address of an overloaded function, try 2739 // to resolve the overloaded function. If all goes well, T2 is the 2740 // type of the resulting function. 2741 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2742 DeclAccessPair Found; 2743 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 2744 false, Found)) 2745 T2 = Fn->getType(); 2746 } 2747 2748 // Compute some basic properties of the types and the initializer. 2749 bool isRValRef = DeclType->isRValueReferenceType(); 2750 bool DerivedToBase = false; 2751 bool ObjCConversion = false; 2752 Expr::Classification InitCategory = Init->Classify(S.Context); 2753 Sema::ReferenceCompareResult RefRelationship 2754 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 2755 ObjCConversion); 2756 2757 2758 // C++0x [dcl.init.ref]p5: 2759 // A reference to type "cv1 T1" is initialized by an expression 2760 // of type "cv2 T2" as follows: 2761 2762 // -- If reference is an lvalue reference and the initializer expression 2763 // The next bullet point (T1 is a function) is pretty much equivalent to this 2764 // one, so it's handled here. 2765 if (!isRValRef || T1->isFunctionType()) { 2766 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 2767 // reference-compatible with "cv2 T2," or 2768 // 2769 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 2770 if (InitCategory.isLValue() && 2771 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2772 // C++ [over.ics.ref]p1: 2773 // When a parameter of reference type binds directly (8.5.3) 2774 // to an argument expression, the implicit conversion sequence 2775 // is the identity conversion, unless the argument expression 2776 // has a type that is a derived class of the parameter type, 2777 // in which case the implicit conversion sequence is a 2778 // derived-to-base Conversion (13.3.3.1). 2779 ICS.setStandard(); 2780 ICS.Standard.First = ICK_Identity; 2781 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 2782 : ObjCConversion? ICK_Compatible_Conversion 2783 : ICK_Identity; 2784 ICS.Standard.Third = ICK_Identity; 2785 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 2786 ICS.Standard.setToType(0, T2); 2787 ICS.Standard.setToType(1, T1); 2788 ICS.Standard.setToType(2, T1); 2789 ICS.Standard.ReferenceBinding = true; 2790 ICS.Standard.DirectBinding = true; 2791 ICS.Standard.RRefBinding = isRValRef; 2792 ICS.Standard.CopyConstructor = 0; 2793 2794 // Nothing more to do: the inaccessibility/ambiguity check for 2795 // derived-to-base conversions is suppressed when we're 2796 // computing the implicit conversion sequence (C++ 2797 // [over.best.ics]p2). 2798 return ICS; 2799 } 2800 2801 // -- has a class type (i.e., T2 is a class type), where T1 is 2802 // not reference-related to T2, and can be implicitly 2803 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 2804 // is reference-compatible with "cv3 T3" 92) (this 2805 // conversion is selected by enumerating the applicable 2806 // conversion functions (13.3.1.6) and choosing the best 2807 // one through overload resolution (13.3)), 2808 if (!SuppressUserConversions && T2->isRecordType() && 2809 !S.RequireCompleteType(DeclLoc, T2, 0) && 2810 RefRelationship == Sema::Ref_Incompatible) { 2811 if (FindConversionToLValue(S, ICS, DeclType, DeclLoc, 2812 Init, T2, AllowExplicit)) 2813 return ICS; 2814 } 2815 } 2816 2817 // -- Otherwise, the reference shall be an lvalue reference to a 2818 // non-volatile const type (i.e., cv1 shall be const), or the reference 2819 // shall be an rvalue reference and the initializer expression shall be 2820 // an rvalue or have a function type. 2821 // 2822 // We actually handle one oddity of C++ [over.ics.ref] at this 2823 // point, which is that, due to p2 (which short-circuits reference 2824 // binding by only attempting a simple conversion for non-direct 2825 // bindings) and p3's strange wording, we allow a const volatile 2826 // reference to bind to an rvalue. Hence the check for the presence 2827 // of "const" rather than checking for "const" being the only 2828 // qualifier. 2829 // This is also the point where rvalue references and lvalue inits no longer 2830 // go together. 2831 if ((!isRValRef && !T1.isConstQualified()) || 2832 (isRValRef && InitCategory.isLValue())) 2833 return ICS; 2834 2835 // -- If T1 is a function type, then 2836 // -- if T2 is the same type as T1, the reference is bound to the 2837 // initializer expression lvalue; 2838 // -- if T2 is a class type and the initializer expression can be 2839 // implicitly converted to an lvalue of type T1 [...], the 2840 // reference is bound to the function lvalue that is the result 2841 // of the conversion; 2842 // This is the same as for the lvalue case above, so it was handled there. 2843 // -- otherwise, the program is ill-formed. 2844 // This is the one difference to the lvalue case. 2845 if (T1->isFunctionType()) 2846 return ICS; 2847 2848 // -- Otherwise, if T2 is a class type and 2849 // -- the initializer expression is an rvalue and "cv1 T1" 2850 // is reference-compatible with "cv2 T2," or 2851 // 2852 // -- T1 is not reference-related to T2 and the initializer 2853 // expression can be implicitly converted to an rvalue 2854 // of type "cv3 T3" (this conversion is selected by 2855 // enumerating the applicable conversion functions 2856 // (13.3.1.6) and choosing the best one through overload 2857 // resolution (13.3)), 2858 // 2859 // then the reference is bound to the initializer 2860 // expression rvalue in the first case and to the object 2861 // that is the result of the conversion in the second case 2862 // (or, in either case, to the appropriate base class 2863 // subobject of the object). 2864 // 2865 // We're only checking the first case here, which is a direct 2866 // binding in C++0x but not in C++03. 2867 if (InitCategory.isRValue() && T2->isRecordType() && 2868 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2869 ICS.setStandard(); 2870 ICS.Standard.First = ICK_Identity; 2871 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 2872 : ObjCConversion? ICK_Compatible_Conversion 2873 : ICK_Identity; 2874 ICS.Standard.Third = ICK_Identity; 2875 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 2876 ICS.Standard.setToType(0, T2); 2877 ICS.Standard.setToType(1, T1); 2878 ICS.Standard.setToType(2, T1); 2879 ICS.Standard.ReferenceBinding = true; 2880 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x; 2881 ICS.Standard.RRefBinding = isRValRef; 2882 ICS.Standard.CopyConstructor = 0; 2883 return ICS; 2884 } 2885 2886 // -- Otherwise, a temporary of type "cv1 T1" is created and 2887 // initialized from the initializer expression using the 2888 // rules for a non-reference copy initialization (8.5). The 2889 // reference is then bound to the temporary. If T1 is 2890 // reference-related to T2, cv1 must be the same 2891 // cv-qualification as, or greater cv-qualification than, 2892 // cv2; otherwise, the program is ill-formed. 2893 if (RefRelationship == Sema::Ref_Related) { 2894 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 2895 // we would be reference-compatible or reference-compatible with 2896 // added qualification. But that wasn't the case, so the reference 2897 // initialization fails. 2898 return ICS; 2899 } 2900 2901 // If at least one of the types is a class type, the types are not 2902 // related, and we aren't allowed any user conversions, the 2903 // reference binding fails. This case is important for breaking 2904 // recursion, since TryImplicitConversion below will attempt to 2905 // create a temporary through the use of a copy constructor. 2906 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 2907 (T1->isRecordType() || T2->isRecordType())) 2908 return ICS; 2909 2910 // C++ [over.ics.ref]p2: 2911 // When a parameter of reference type is not bound directly to 2912 // an argument expression, the conversion sequence is the one 2913 // required to convert the argument expression to the 2914 // underlying type of the reference according to 2915 // 13.3.3.1. Conceptually, this conversion sequence corresponds 2916 // to copy-initializing a temporary of the underlying type with 2917 // the argument expression. Any difference in top-level 2918 // cv-qualification is subsumed by the initialization itself 2919 // and does not constitute a conversion. 2920 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions, 2921 /*AllowExplicit=*/false, 2922 /*InOverloadResolution=*/false); 2923 2924 // Of course, that's still a reference binding. 2925 if (ICS.isStandard()) { 2926 ICS.Standard.ReferenceBinding = true; 2927 ICS.Standard.RRefBinding = isRValRef; 2928 } else if (ICS.isUserDefined()) { 2929 ICS.UserDefined.After.ReferenceBinding = true; 2930 ICS.UserDefined.After.RRefBinding = isRValRef; 2931 } 2932 return ICS; 2933} 2934 2935/// TryCopyInitialization - Try to copy-initialize a value of type 2936/// ToType from the expression From. Return the implicit conversion 2937/// sequence required to pass this argument, which may be a bad 2938/// conversion sequence (meaning that the argument cannot be passed to 2939/// a parameter of this type). If @p SuppressUserConversions, then we 2940/// do not permit any user-defined conversion sequences. 2941static ImplicitConversionSequence 2942TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 2943 bool SuppressUserConversions, 2944 bool InOverloadResolution) { 2945 if (ToType->isReferenceType()) 2946 return TryReferenceInit(S, From, ToType, 2947 /*FIXME:*/From->getLocStart(), 2948 SuppressUserConversions, 2949 /*AllowExplicit=*/false); 2950 2951 return S.TryImplicitConversion(From, ToType, 2952 SuppressUserConversions, 2953 /*AllowExplicit=*/false, 2954 InOverloadResolution); 2955} 2956 2957/// TryObjectArgumentInitialization - Try to initialize the object 2958/// parameter of the given member function (@c Method) from the 2959/// expression @p From. 2960ImplicitConversionSequence 2961Sema::TryObjectArgumentInitialization(QualType OrigFromType, 2962 CXXMethodDecl *Method, 2963 CXXRecordDecl *ActingContext) { 2964 QualType ClassType = Context.getTypeDeclType(ActingContext); 2965 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 2966 // const volatile object. 2967 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 2968 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 2969 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals); 2970 2971 // Set up the conversion sequence as a "bad" conversion, to allow us 2972 // to exit early. 2973 ImplicitConversionSequence ICS; 2974 2975 // We need to have an object of class type. 2976 QualType FromType = OrigFromType; 2977 if (const PointerType *PT = FromType->getAs<PointerType>()) 2978 FromType = PT->getPointeeType(); 2979 2980 assert(FromType->isRecordType()); 2981 2982 // The implicit object parameter is has the type "reference to cv X", 2983 // where X is the class of which the function is a member 2984 // (C++ [over.match.funcs]p4). However, when finding an implicit 2985 // conversion sequence for the argument, we are not allowed to 2986 // create temporaries or perform user-defined conversions 2987 // (C++ [over.match.funcs]p5). We perform a simplified version of 2988 // reference binding here, that allows class rvalues to bind to 2989 // non-constant references. 2990 2991 // First check the qualifiers. We don't care about lvalue-vs-rvalue 2992 // with the implicit object parameter (C++ [over.match.funcs]p5). 2993 QualType FromTypeCanon = Context.getCanonicalType(FromType); 2994 if (ImplicitParamType.getCVRQualifiers() 2995 != FromTypeCanon.getLocalCVRQualifiers() && 2996 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 2997 ICS.setBad(BadConversionSequence::bad_qualifiers, 2998 OrigFromType, ImplicitParamType); 2999 return ICS; 3000 } 3001 3002 // Check that we have either the same type or a derived type. It 3003 // affects the conversion rank. 3004 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 3005 ImplicitConversionKind SecondKind; 3006 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 3007 SecondKind = ICK_Identity; 3008 } else if (IsDerivedFrom(FromType, ClassType)) 3009 SecondKind = ICK_Derived_To_Base; 3010 else { 3011 ICS.setBad(BadConversionSequence::unrelated_class, 3012 FromType, ImplicitParamType); 3013 return ICS; 3014 } 3015 3016 // Success. Mark this as a reference binding. 3017 ICS.setStandard(); 3018 ICS.Standard.setAsIdentityConversion(); 3019 ICS.Standard.Second = SecondKind; 3020 ICS.Standard.setFromType(FromType); 3021 ICS.Standard.setAllToTypes(ImplicitParamType); 3022 ICS.Standard.ReferenceBinding = true; 3023 ICS.Standard.DirectBinding = true; 3024 ICS.Standard.RRefBinding = false; 3025 return ICS; 3026} 3027 3028/// PerformObjectArgumentInitialization - Perform initialization of 3029/// the implicit object parameter for the given Method with the given 3030/// expression. 3031bool 3032Sema::PerformObjectArgumentInitialization(Expr *&From, 3033 NestedNameSpecifier *Qualifier, 3034 NamedDecl *FoundDecl, 3035 CXXMethodDecl *Method) { 3036 QualType FromRecordType, DestType; 3037 QualType ImplicitParamRecordType = 3038 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 3039 3040 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 3041 FromRecordType = PT->getPointeeType(); 3042 DestType = Method->getThisType(Context); 3043 } else { 3044 FromRecordType = From->getType(); 3045 DestType = ImplicitParamRecordType; 3046 } 3047 3048 // Note that we always use the true parent context when performing 3049 // the actual argument initialization. 3050 ImplicitConversionSequence ICS 3051 = TryObjectArgumentInitialization(From->getType(), Method, 3052 Method->getParent()); 3053 if (ICS.isBad()) 3054 return Diag(From->getSourceRange().getBegin(), 3055 diag::err_implicit_object_parameter_init) 3056 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 3057 3058 if (ICS.Standard.Second == ICK_Derived_To_Base) 3059 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 3060 3061 if (!Context.hasSameType(From->getType(), DestType)) 3062 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp, 3063 From->getType()->isPointerType() ? 3064 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue); 3065 return false; 3066} 3067 3068/// TryContextuallyConvertToBool - Attempt to contextually convert the 3069/// expression From to bool (C++0x [conv]p3). 3070ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) { 3071 // FIXME: This is pretty broken. 3072 return TryImplicitConversion(From, Context.BoolTy, 3073 // FIXME: Are these flags correct? 3074 /*SuppressUserConversions=*/false, 3075 /*AllowExplicit=*/true, 3076 /*InOverloadResolution=*/false); 3077} 3078 3079/// PerformContextuallyConvertToBool - Perform a contextual conversion 3080/// of the expression From to bool (C++0x [conv]p3). 3081bool Sema::PerformContextuallyConvertToBool(Expr *&From) { 3082 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From); 3083 if (!ICS.isBad()) 3084 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 3085 3086 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 3087 return Diag(From->getSourceRange().getBegin(), 3088 diag::err_typecheck_bool_condition) 3089 << From->getType() << From->getSourceRange(); 3090 return true; 3091} 3092 3093/// TryContextuallyConvertToObjCId - Attempt to contextually convert the 3094/// expression From to 'id'. 3095ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) { 3096 QualType Ty = Context.getObjCIdType(); 3097 return TryImplicitConversion(From, Ty, 3098 // FIXME: Are these flags correct? 3099 /*SuppressUserConversions=*/false, 3100 /*AllowExplicit=*/true, 3101 /*InOverloadResolution=*/false); 3102} 3103 3104/// PerformContextuallyConvertToObjCId - Perform a contextual conversion 3105/// of the expression From to 'id'. 3106bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) { 3107 QualType Ty = Context.getObjCIdType(); 3108 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From); 3109 if (!ICS.isBad()) 3110 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 3111 return true; 3112} 3113 3114/// \brief Attempt to convert the given expression to an integral or 3115/// enumeration type. 3116/// 3117/// This routine will attempt to convert an expression of class type to an 3118/// integral or enumeration type, if that class type only has a single 3119/// conversion to an integral or enumeration type. 3120/// 3121/// \param Loc The source location of the construct that requires the 3122/// conversion. 3123/// 3124/// \param FromE The expression we're converting from. 3125/// 3126/// \param NotIntDiag The diagnostic to be emitted if the expression does not 3127/// have integral or enumeration type. 3128/// 3129/// \param IncompleteDiag The diagnostic to be emitted if the expression has 3130/// incomplete class type. 3131/// 3132/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 3133/// explicit conversion function (because no implicit conversion functions 3134/// were available). This is a recovery mode. 3135/// 3136/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 3137/// showing which conversion was picked. 3138/// 3139/// \param AmbigDiag The diagnostic to be emitted if there is more than one 3140/// conversion function that could convert to integral or enumeration type. 3141/// 3142/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 3143/// usable conversion function. 3144/// 3145/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 3146/// function, which may be an extension in this case. 3147/// 3148/// \returns The expression, converted to an integral or enumeration type if 3149/// successful. 3150Sema::OwningExprResult 3151Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE, 3152 const PartialDiagnostic &NotIntDiag, 3153 const PartialDiagnostic &IncompleteDiag, 3154 const PartialDiagnostic &ExplicitConvDiag, 3155 const PartialDiagnostic &ExplicitConvNote, 3156 const PartialDiagnostic &AmbigDiag, 3157 const PartialDiagnostic &AmbigNote, 3158 const PartialDiagnostic &ConvDiag) { 3159 Expr *From = static_cast<Expr *>(FromE.get()); 3160 3161 // We can't perform any more checking for type-dependent expressions. 3162 if (From->isTypeDependent()) 3163 return move(FromE); 3164 3165 // If the expression already has integral or enumeration type, we're golden. 3166 QualType T = From->getType(); 3167 if (T->isIntegralOrEnumerationType()) 3168 return move(FromE); 3169 3170 // FIXME: Check for missing '()' if T is a function type? 3171 3172 // If we don't have a class type in C++, there's no way we can get an 3173 // expression of integral or enumeration type. 3174 const RecordType *RecordTy = T->getAs<RecordType>(); 3175 if (!RecordTy || !getLangOptions().CPlusPlus) { 3176 Diag(Loc, NotIntDiag) 3177 << T << From->getSourceRange(); 3178 return move(FromE); 3179 } 3180 3181 // We must have a complete class type. 3182 if (RequireCompleteType(Loc, T, IncompleteDiag)) 3183 return move(FromE); 3184 3185 // Look for a conversion to an integral or enumeration type. 3186 UnresolvedSet<4> ViableConversions; 3187 UnresolvedSet<4> ExplicitConversions; 3188 const UnresolvedSetImpl *Conversions 3189 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 3190 3191 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3192 E = Conversions->end(); 3193 I != E; 3194 ++I) { 3195 if (CXXConversionDecl *Conversion 3196 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) 3197 if (Conversion->getConversionType().getNonReferenceType() 3198 ->isIntegralOrEnumerationType()) { 3199 if (Conversion->isExplicit()) 3200 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 3201 else 3202 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 3203 } 3204 } 3205 3206 switch (ViableConversions.size()) { 3207 case 0: 3208 if (ExplicitConversions.size() == 1) { 3209 DeclAccessPair Found = ExplicitConversions[0]; 3210 CXXConversionDecl *Conversion 3211 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3212 3213 // The user probably meant to invoke the given explicit 3214 // conversion; use it. 3215 QualType ConvTy 3216 = Conversion->getConversionType().getNonReferenceType(); 3217 std::string TypeStr; 3218 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy); 3219 3220 Diag(Loc, ExplicitConvDiag) 3221 << T << ConvTy 3222 << FixItHint::CreateInsertion(From->getLocStart(), 3223 "static_cast<" + TypeStr + ">(") 3224 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 3225 ")"); 3226 Diag(Conversion->getLocation(), ExplicitConvNote) 3227 << ConvTy->isEnumeralType() << ConvTy; 3228 3229 // If we aren't in a SFINAE context, build a call to the 3230 // explicit conversion function. 3231 if (isSFINAEContext()) 3232 return ExprError(); 3233 3234 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3235 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion); 3236 FromE = Owned(From); 3237 } 3238 3239 // We'll complain below about a non-integral condition type. 3240 break; 3241 3242 case 1: { 3243 // Apply this conversion. 3244 DeclAccessPair Found = ViableConversions[0]; 3245 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3246 3247 CXXConversionDecl *Conversion 3248 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3249 QualType ConvTy 3250 = Conversion->getConversionType().getNonReferenceType(); 3251 if (ConvDiag.getDiagID()) { 3252 if (isSFINAEContext()) 3253 return ExprError(); 3254 3255 Diag(Loc, ConvDiag) 3256 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange(); 3257 } 3258 3259 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, 3260 cast<CXXConversionDecl>(Found->getUnderlyingDecl())); 3261 FromE = Owned(From); 3262 break; 3263 } 3264 3265 default: 3266 Diag(Loc, AmbigDiag) 3267 << T << From->getSourceRange(); 3268 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 3269 CXXConversionDecl *Conv 3270 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 3271 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 3272 Diag(Conv->getLocation(), AmbigNote) 3273 << ConvTy->isEnumeralType() << ConvTy; 3274 } 3275 return move(FromE); 3276 } 3277 3278 if (!From->getType()->isIntegralOrEnumerationType()) 3279 Diag(Loc, NotIntDiag) 3280 << From->getType() << From->getSourceRange(); 3281 3282 return move(FromE); 3283} 3284 3285/// AddOverloadCandidate - Adds the given function to the set of 3286/// candidate functions, using the given function call arguments. If 3287/// @p SuppressUserConversions, then don't allow user-defined 3288/// conversions via constructors or conversion operators. 3289/// 3290/// \para PartialOverloading true if we are performing "partial" overloading 3291/// based on an incomplete set of function arguments. This feature is used by 3292/// code completion. 3293void 3294Sema::AddOverloadCandidate(FunctionDecl *Function, 3295 DeclAccessPair FoundDecl, 3296 Expr **Args, unsigned NumArgs, 3297 OverloadCandidateSet& CandidateSet, 3298 bool SuppressUserConversions, 3299 bool PartialOverloading) { 3300 const FunctionProtoType* Proto 3301 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 3302 assert(Proto && "Functions without a prototype cannot be overloaded"); 3303 assert(!Function->getDescribedFunctionTemplate() && 3304 "Use AddTemplateOverloadCandidate for function templates"); 3305 3306 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 3307 if (!isa<CXXConstructorDecl>(Method)) { 3308 // If we get here, it's because we're calling a member function 3309 // that is named without a member access expression (e.g., 3310 // "this->f") that was either written explicitly or created 3311 // implicitly. This can happen with a qualified call to a member 3312 // function, e.g., X::f(). We use an empty type for the implied 3313 // object argument (C++ [over.call.func]p3), and the acting context 3314 // is irrelevant. 3315 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 3316 QualType(), Args, NumArgs, CandidateSet, 3317 SuppressUserConversions); 3318 return; 3319 } 3320 // We treat a constructor like a non-member function, since its object 3321 // argument doesn't participate in overload resolution. 3322 } 3323 3324 if (!CandidateSet.isNewCandidate(Function)) 3325 return; 3326 3327 // Overload resolution is always an unevaluated context. 3328 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 3329 3330 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 3331 // C++ [class.copy]p3: 3332 // A member function template is never instantiated to perform the copy 3333 // of a class object to an object of its class type. 3334 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 3335 if (NumArgs == 1 && 3336 Constructor->isCopyConstructorLikeSpecialization() && 3337 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 3338 IsDerivedFrom(Args[0]->getType(), ClassType))) 3339 return; 3340 } 3341 3342 // Add this candidate 3343 CandidateSet.push_back(OverloadCandidate()); 3344 OverloadCandidate& Candidate = CandidateSet.back(); 3345 Candidate.FoundDecl = FoundDecl; 3346 Candidate.Function = Function; 3347 Candidate.Viable = true; 3348 Candidate.IsSurrogate = false; 3349 Candidate.IgnoreObjectArgument = false; 3350 3351 unsigned NumArgsInProto = Proto->getNumArgs(); 3352 3353 // (C++ 13.3.2p2): A candidate function having fewer than m 3354 // parameters is viable only if it has an ellipsis in its parameter 3355 // list (8.3.5). 3356 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 3357 !Proto->isVariadic()) { 3358 Candidate.Viable = false; 3359 Candidate.FailureKind = ovl_fail_too_many_arguments; 3360 return; 3361 } 3362 3363 // (C++ 13.3.2p2): A candidate function having more than m parameters 3364 // is viable only if the (m+1)st parameter has a default argument 3365 // (8.3.6). For the purposes of overload resolution, the 3366 // parameter list is truncated on the right, so that there are 3367 // exactly m parameters. 3368 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 3369 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 3370 // Not enough arguments. 3371 Candidate.Viable = false; 3372 Candidate.FailureKind = ovl_fail_too_few_arguments; 3373 return; 3374 } 3375 3376 // Determine the implicit conversion sequences for each of the 3377 // arguments. 3378 Candidate.Conversions.resize(NumArgs); 3379 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3380 if (ArgIdx < NumArgsInProto) { 3381 // (C++ 13.3.2p3): for F to be a viable function, there shall 3382 // exist for each argument an implicit conversion sequence 3383 // (13.3.3.1) that converts that argument to the corresponding 3384 // parameter of F. 3385 QualType ParamType = Proto->getArgType(ArgIdx); 3386 Candidate.Conversions[ArgIdx] 3387 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3388 SuppressUserConversions, 3389 /*InOverloadResolution=*/true); 3390 if (Candidate.Conversions[ArgIdx].isBad()) { 3391 Candidate.Viable = false; 3392 Candidate.FailureKind = ovl_fail_bad_conversion; 3393 break; 3394 } 3395 } else { 3396 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3397 // argument for which there is no corresponding parameter is 3398 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3399 Candidate.Conversions[ArgIdx].setEllipsis(); 3400 } 3401 } 3402} 3403 3404/// \brief Add all of the function declarations in the given function set to 3405/// the overload canddiate set. 3406void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 3407 Expr **Args, unsigned NumArgs, 3408 OverloadCandidateSet& CandidateSet, 3409 bool SuppressUserConversions) { 3410 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 3411 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 3412 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3413 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 3414 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 3415 cast<CXXMethodDecl>(FD)->getParent(), 3416 Args[0]->getType(), Args + 1, NumArgs - 1, 3417 CandidateSet, SuppressUserConversions); 3418 else 3419 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet, 3420 SuppressUserConversions); 3421 } else { 3422 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 3423 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 3424 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 3425 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 3426 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 3427 /*FIXME: explicit args */ 0, 3428 Args[0]->getType(), Args + 1, NumArgs - 1, 3429 CandidateSet, 3430 SuppressUserConversions); 3431 else 3432 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 3433 /*FIXME: explicit args */ 0, 3434 Args, NumArgs, CandidateSet, 3435 SuppressUserConversions); 3436 } 3437 } 3438} 3439 3440/// AddMethodCandidate - Adds a named decl (which is some kind of 3441/// method) as a method candidate to the given overload set. 3442void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 3443 QualType ObjectType, 3444 Expr **Args, unsigned NumArgs, 3445 OverloadCandidateSet& CandidateSet, 3446 bool SuppressUserConversions) { 3447 NamedDecl *Decl = FoundDecl.getDecl(); 3448 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 3449 3450 if (isa<UsingShadowDecl>(Decl)) 3451 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 3452 3453 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 3454 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 3455 "Expected a member function template"); 3456 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 3457 /*ExplicitArgs*/ 0, 3458 ObjectType, Args, NumArgs, 3459 CandidateSet, 3460 SuppressUserConversions); 3461 } else { 3462 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 3463 ObjectType, Args, NumArgs, 3464 CandidateSet, SuppressUserConversions); 3465 } 3466} 3467 3468/// AddMethodCandidate - Adds the given C++ member function to the set 3469/// of candidate functions, using the given function call arguments 3470/// and the object argument (@c Object). For example, in a call 3471/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 3472/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 3473/// allow user-defined conversions via constructors or conversion 3474/// operators. 3475void 3476Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 3477 CXXRecordDecl *ActingContext, QualType ObjectType, 3478 Expr **Args, unsigned NumArgs, 3479 OverloadCandidateSet& CandidateSet, 3480 bool SuppressUserConversions) { 3481 const FunctionProtoType* Proto 3482 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 3483 assert(Proto && "Methods without a prototype cannot be overloaded"); 3484 assert(!isa<CXXConstructorDecl>(Method) && 3485 "Use AddOverloadCandidate for constructors"); 3486 3487 if (!CandidateSet.isNewCandidate(Method)) 3488 return; 3489 3490 // Overload resolution is always an unevaluated context. 3491 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 3492 3493 // Add this candidate 3494 CandidateSet.push_back(OverloadCandidate()); 3495 OverloadCandidate& Candidate = CandidateSet.back(); 3496 Candidate.FoundDecl = FoundDecl; 3497 Candidate.Function = Method; 3498 Candidate.IsSurrogate = false; 3499 Candidate.IgnoreObjectArgument = false; 3500 3501 unsigned NumArgsInProto = Proto->getNumArgs(); 3502 3503 // (C++ 13.3.2p2): A candidate function having fewer than m 3504 // parameters is viable only if it has an ellipsis in its parameter 3505 // list (8.3.5). 3506 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 3507 Candidate.Viable = false; 3508 Candidate.FailureKind = ovl_fail_too_many_arguments; 3509 return; 3510 } 3511 3512 // (C++ 13.3.2p2): A candidate function having more than m parameters 3513 // is viable only if the (m+1)st parameter has a default argument 3514 // (8.3.6). For the purposes of overload resolution, the 3515 // parameter list is truncated on the right, so that there are 3516 // exactly m parameters. 3517 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 3518 if (NumArgs < MinRequiredArgs) { 3519 // Not enough arguments. 3520 Candidate.Viable = false; 3521 Candidate.FailureKind = ovl_fail_too_few_arguments; 3522 return; 3523 } 3524 3525 Candidate.Viable = true; 3526 Candidate.Conversions.resize(NumArgs + 1); 3527 3528 if (Method->isStatic() || ObjectType.isNull()) 3529 // The implicit object argument is ignored. 3530 Candidate.IgnoreObjectArgument = true; 3531 else { 3532 // Determine the implicit conversion sequence for the object 3533 // parameter. 3534 Candidate.Conversions[0] 3535 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext); 3536 if (Candidate.Conversions[0].isBad()) { 3537 Candidate.Viable = false; 3538 Candidate.FailureKind = ovl_fail_bad_conversion; 3539 return; 3540 } 3541 } 3542 3543 // Determine the implicit conversion sequences for each of the 3544 // arguments. 3545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3546 if (ArgIdx < NumArgsInProto) { 3547 // (C++ 13.3.2p3): for F to be a viable function, there shall 3548 // exist for each argument an implicit conversion sequence 3549 // (13.3.3.1) that converts that argument to the corresponding 3550 // parameter of F. 3551 QualType ParamType = Proto->getArgType(ArgIdx); 3552 Candidate.Conversions[ArgIdx + 1] 3553 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3554 SuppressUserConversions, 3555 /*InOverloadResolution=*/true); 3556 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 3557 Candidate.Viable = false; 3558 Candidate.FailureKind = ovl_fail_bad_conversion; 3559 break; 3560 } 3561 } else { 3562 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3563 // argument for which there is no corresponding parameter is 3564 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3565 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 3566 } 3567 } 3568} 3569 3570/// \brief Add a C++ member function template as a candidate to the candidate 3571/// set, using template argument deduction to produce an appropriate member 3572/// function template specialization. 3573void 3574Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3575 DeclAccessPair FoundDecl, 3576 CXXRecordDecl *ActingContext, 3577 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3578 QualType ObjectType, 3579 Expr **Args, unsigned NumArgs, 3580 OverloadCandidateSet& CandidateSet, 3581 bool SuppressUserConversions) { 3582 if (!CandidateSet.isNewCandidate(MethodTmpl)) 3583 return; 3584 3585 // C++ [over.match.funcs]p7: 3586 // In each case where a candidate is a function template, candidate 3587 // function template specializations are generated using template argument 3588 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 3589 // candidate functions in the usual way.113) A given name can refer to one 3590 // or more function templates and also to a set of overloaded non-template 3591 // functions. In such a case, the candidate functions generated from each 3592 // function template are combined with the set of non-template candidate 3593 // functions. 3594 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3595 FunctionDecl *Specialization = 0; 3596 if (TemplateDeductionResult Result 3597 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 3598 Args, NumArgs, Specialization, Info)) { 3599 CandidateSet.push_back(OverloadCandidate()); 3600 OverloadCandidate &Candidate = CandidateSet.back(); 3601 Candidate.FoundDecl = FoundDecl; 3602 Candidate.Function = MethodTmpl->getTemplatedDecl(); 3603 Candidate.Viable = false; 3604 Candidate.FailureKind = ovl_fail_bad_deduction; 3605 Candidate.IsSurrogate = false; 3606 Candidate.IgnoreObjectArgument = false; 3607 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3608 Info); 3609 return; 3610 } 3611 3612 // Add the function template specialization produced by template argument 3613 // deduction as a candidate. 3614 assert(Specialization && "Missing member function template specialization?"); 3615 assert(isa<CXXMethodDecl>(Specialization) && 3616 "Specialization is not a member function?"); 3617 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 3618 ActingContext, ObjectType, Args, NumArgs, 3619 CandidateSet, SuppressUserConversions); 3620} 3621 3622/// \brief Add a C++ function template specialization as a candidate 3623/// in the candidate set, using template argument deduction to produce 3624/// an appropriate function template specialization. 3625void 3626Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 3627 DeclAccessPair FoundDecl, 3628 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3629 Expr **Args, unsigned NumArgs, 3630 OverloadCandidateSet& CandidateSet, 3631 bool SuppressUserConversions) { 3632 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 3633 return; 3634 3635 // C++ [over.match.funcs]p7: 3636 // In each case where a candidate is a function template, candidate 3637 // function template specializations are generated using template argument 3638 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 3639 // candidate functions in the usual way.113) A given name can refer to one 3640 // or more function templates and also to a set of overloaded non-template 3641 // functions. In such a case, the candidate functions generated from each 3642 // function template are combined with the set of non-template candidate 3643 // functions. 3644 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3645 FunctionDecl *Specialization = 0; 3646 if (TemplateDeductionResult Result 3647 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 3648 Args, NumArgs, Specialization, Info)) { 3649 CandidateSet.push_back(OverloadCandidate()); 3650 OverloadCandidate &Candidate = CandidateSet.back(); 3651 Candidate.FoundDecl = FoundDecl; 3652 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 3653 Candidate.Viable = false; 3654 Candidate.FailureKind = ovl_fail_bad_deduction; 3655 Candidate.IsSurrogate = false; 3656 Candidate.IgnoreObjectArgument = false; 3657 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3658 Info); 3659 return; 3660 } 3661 3662 // Add the function template specialization produced by template argument 3663 // deduction as a candidate. 3664 assert(Specialization && "Missing function template specialization?"); 3665 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet, 3666 SuppressUserConversions); 3667} 3668 3669/// AddConversionCandidate - Add a C++ conversion function as a 3670/// candidate in the candidate set (C++ [over.match.conv], 3671/// C++ [over.match.copy]). From is the expression we're converting from, 3672/// and ToType is the type that we're eventually trying to convert to 3673/// (which may or may not be the same type as the type that the 3674/// conversion function produces). 3675void 3676Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 3677 DeclAccessPair FoundDecl, 3678 CXXRecordDecl *ActingContext, 3679 Expr *From, QualType ToType, 3680 OverloadCandidateSet& CandidateSet) { 3681 assert(!Conversion->getDescribedFunctionTemplate() && 3682 "Conversion function templates use AddTemplateConversionCandidate"); 3683 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 3684 if (!CandidateSet.isNewCandidate(Conversion)) 3685 return; 3686 3687 // Overload resolution is always an unevaluated context. 3688 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 3689 3690 // Add this candidate 3691 CandidateSet.push_back(OverloadCandidate()); 3692 OverloadCandidate& Candidate = CandidateSet.back(); 3693 Candidate.FoundDecl = FoundDecl; 3694 Candidate.Function = Conversion; 3695 Candidate.IsSurrogate = false; 3696 Candidate.IgnoreObjectArgument = false; 3697 Candidate.FinalConversion.setAsIdentityConversion(); 3698 Candidate.FinalConversion.setFromType(ConvType); 3699 Candidate.FinalConversion.setAllToTypes(ToType); 3700 3701 // Determine the implicit conversion sequence for the implicit 3702 // object parameter. 3703 Candidate.Viable = true; 3704 Candidate.Conversions.resize(1); 3705 Candidate.Conversions[0] 3706 = TryObjectArgumentInitialization(From->getType(), Conversion, 3707 ActingContext); 3708 // Conversion functions to a different type in the base class is visible in 3709 // the derived class. So, a derived to base conversion should not participate 3710 // in overload resolution. 3711 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base) 3712 Candidate.Conversions[0].Standard.Second = ICK_Identity; 3713 if (Candidate.Conversions[0].isBad()) { 3714 Candidate.Viable = false; 3715 Candidate.FailureKind = ovl_fail_bad_conversion; 3716 return; 3717 } 3718 3719 // We won't go through a user-define type conversion function to convert a 3720 // derived to base as such conversions are given Conversion Rank. They only 3721 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 3722 QualType FromCanon 3723 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 3724 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 3725 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 3726 Candidate.Viable = false; 3727 Candidate.FailureKind = ovl_fail_trivial_conversion; 3728 return; 3729 } 3730 3731 // To determine what the conversion from the result of calling the 3732 // conversion function to the type we're eventually trying to 3733 // convert to (ToType), we need to synthesize a call to the 3734 // conversion function and attempt copy initialization from it. This 3735 // makes sure that we get the right semantics with respect to 3736 // lvalues/rvalues and the type. Fortunately, we can allocate this 3737 // call on the stack and we don't need its arguments to be 3738 // well-formed. 3739 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 3740 From->getLocStart()); 3741 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 3742 Context.getPointerType(Conversion->getType()), 3743 CastExpr::CK_FunctionToPointerDecay, 3744 &ConversionRef, ImplicitCastExpr::RValue); 3745 3746 // Note that it is safe to allocate CallExpr on the stack here because 3747 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 3748 // allocator). 3749 CallExpr Call(Context, &ConversionFn, 0, 0, 3750 Conversion->getConversionType().getNonLValueExprType(Context), 3751 From->getLocStart()); 3752 ImplicitConversionSequence ICS = 3753 TryCopyInitialization(*this, &Call, ToType, 3754 /*SuppressUserConversions=*/true, 3755 /*InOverloadResolution=*/false); 3756 3757 switch (ICS.getKind()) { 3758 case ImplicitConversionSequence::StandardConversion: 3759 Candidate.FinalConversion = ICS.Standard; 3760 3761 // C++ [over.ics.user]p3: 3762 // If the user-defined conversion is specified by a specialization of a 3763 // conversion function template, the second standard conversion sequence 3764 // shall have exact match rank. 3765 if (Conversion->getPrimaryTemplate() && 3766 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 3767 Candidate.Viable = false; 3768 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 3769 } 3770 3771 break; 3772 3773 case ImplicitConversionSequence::BadConversion: 3774 Candidate.Viable = false; 3775 Candidate.FailureKind = ovl_fail_bad_final_conversion; 3776 break; 3777 3778 default: 3779 assert(false && 3780 "Can only end up with a standard conversion sequence or failure"); 3781 } 3782} 3783 3784/// \brief Adds a conversion function template specialization 3785/// candidate to the overload set, using template argument deduction 3786/// to deduce the template arguments of the conversion function 3787/// template from the type that we are converting to (C++ 3788/// [temp.deduct.conv]). 3789void 3790Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 3791 DeclAccessPair FoundDecl, 3792 CXXRecordDecl *ActingDC, 3793 Expr *From, QualType ToType, 3794 OverloadCandidateSet &CandidateSet) { 3795 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 3796 "Only conversion function templates permitted here"); 3797 3798 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 3799 return; 3800 3801 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3802 CXXConversionDecl *Specialization = 0; 3803 if (TemplateDeductionResult Result 3804 = DeduceTemplateArguments(FunctionTemplate, ToType, 3805 Specialization, Info)) { 3806 CandidateSet.push_back(OverloadCandidate()); 3807 OverloadCandidate &Candidate = CandidateSet.back(); 3808 Candidate.FoundDecl = FoundDecl; 3809 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 3810 Candidate.Viable = false; 3811 Candidate.FailureKind = ovl_fail_bad_deduction; 3812 Candidate.IsSurrogate = false; 3813 Candidate.IgnoreObjectArgument = false; 3814 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3815 Info); 3816 return; 3817 } 3818 3819 // Add the conversion function template specialization produced by 3820 // template argument deduction as a candidate. 3821 assert(Specialization && "Missing function template specialization?"); 3822 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 3823 CandidateSet); 3824} 3825 3826/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 3827/// converts the given @c Object to a function pointer via the 3828/// conversion function @c Conversion, and then attempts to call it 3829/// with the given arguments (C++ [over.call.object]p2-4). Proto is 3830/// the type of function that we'll eventually be calling. 3831void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 3832 DeclAccessPair FoundDecl, 3833 CXXRecordDecl *ActingContext, 3834 const FunctionProtoType *Proto, 3835 QualType ObjectType, 3836 Expr **Args, unsigned NumArgs, 3837 OverloadCandidateSet& CandidateSet) { 3838 if (!CandidateSet.isNewCandidate(Conversion)) 3839 return; 3840 3841 // Overload resolution is always an unevaluated context. 3842 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 3843 3844 CandidateSet.push_back(OverloadCandidate()); 3845 OverloadCandidate& Candidate = CandidateSet.back(); 3846 Candidate.FoundDecl = FoundDecl; 3847 Candidate.Function = 0; 3848 Candidate.Surrogate = Conversion; 3849 Candidate.Viable = true; 3850 Candidate.IsSurrogate = true; 3851 Candidate.IgnoreObjectArgument = false; 3852 Candidate.Conversions.resize(NumArgs + 1); 3853 3854 // Determine the implicit conversion sequence for the implicit 3855 // object parameter. 3856 ImplicitConversionSequence ObjectInit 3857 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext); 3858 if (ObjectInit.isBad()) { 3859 Candidate.Viable = false; 3860 Candidate.FailureKind = ovl_fail_bad_conversion; 3861 Candidate.Conversions[0] = ObjectInit; 3862 return; 3863 } 3864 3865 // The first conversion is actually a user-defined conversion whose 3866 // first conversion is ObjectInit's standard conversion (which is 3867 // effectively a reference binding). Record it as such. 3868 Candidate.Conversions[0].setUserDefined(); 3869 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 3870 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 3871 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 3872 Candidate.Conversions[0].UserDefined.After 3873 = Candidate.Conversions[0].UserDefined.Before; 3874 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 3875 3876 // Find the 3877 unsigned NumArgsInProto = Proto->getNumArgs(); 3878 3879 // (C++ 13.3.2p2): A candidate function having fewer than m 3880 // parameters is viable only if it has an ellipsis in its parameter 3881 // list (8.3.5). 3882 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 3883 Candidate.Viable = false; 3884 Candidate.FailureKind = ovl_fail_too_many_arguments; 3885 return; 3886 } 3887 3888 // Function types don't have any default arguments, so just check if 3889 // we have enough arguments. 3890 if (NumArgs < NumArgsInProto) { 3891 // Not enough arguments. 3892 Candidate.Viable = false; 3893 Candidate.FailureKind = ovl_fail_too_few_arguments; 3894 return; 3895 } 3896 3897 // Determine the implicit conversion sequences for each of the 3898 // arguments. 3899 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3900 if (ArgIdx < NumArgsInProto) { 3901 // (C++ 13.3.2p3): for F to be a viable function, there shall 3902 // exist for each argument an implicit conversion sequence 3903 // (13.3.3.1) that converts that argument to the corresponding 3904 // parameter of F. 3905 QualType ParamType = Proto->getArgType(ArgIdx); 3906 Candidate.Conversions[ArgIdx + 1] 3907 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3908 /*SuppressUserConversions=*/false, 3909 /*InOverloadResolution=*/false); 3910 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 3911 Candidate.Viable = false; 3912 Candidate.FailureKind = ovl_fail_bad_conversion; 3913 break; 3914 } 3915 } else { 3916 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3917 // argument for which there is no corresponding parameter is 3918 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3919 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 3920 } 3921 } 3922} 3923 3924/// \brief Add overload candidates for overloaded operators that are 3925/// member functions. 3926/// 3927/// Add the overloaded operator candidates that are member functions 3928/// for the operator Op that was used in an operator expression such 3929/// as "x Op y". , Args/NumArgs provides the operator arguments, and 3930/// CandidateSet will store the added overload candidates. (C++ 3931/// [over.match.oper]). 3932void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 3933 SourceLocation OpLoc, 3934 Expr **Args, unsigned NumArgs, 3935 OverloadCandidateSet& CandidateSet, 3936 SourceRange OpRange) { 3937 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 3938 3939 // C++ [over.match.oper]p3: 3940 // For a unary operator @ with an operand of a type whose 3941 // cv-unqualified version is T1, and for a binary operator @ with 3942 // a left operand of a type whose cv-unqualified version is T1 and 3943 // a right operand of a type whose cv-unqualified version is T2, 3944 // three sets of candidate functions, designated member 3945 // candidates, non-member candidates and built-in candidates, are 3946 // constructed as follows: 3947 QualType T1 = Args[0]->getType(); 3948 QualType T2; 3949 if (NumArgs > 1) 3950 T2 = Args[1]->getType(); 3951 3952 // -- If T1 is a class type, the set of member candidates is the 3953 // result of the qualified lookup of T1::operator@ 3954 // (13.3.1.1.1); otherwise, the set of member candidates is 3955 // empty. 3956 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 3957 // Complete the type if it can be completed. Otherwise, we're done. 3958 if (RequireCompleteType(OpLoc, T1, PDiag())) 3959 return; 3960 3961 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 3962 LookupQualifiedName(Operators, T1Rec->getDecl()); 3963 Operators.suppressDiagnostics(); 3964 3965 for (LookupResult::iterator Oper = Operators.begin(), 3966 OperEnd = Operators.end(); 3967 Oper != OperEnd; 3968 ++Oper) 3969 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 3970 Args + 1, NumArgs - 1, CandidateSet, 3971 /* SuppressUserConversions = */ false); 3972 } 3973} 3974 3975/// AddBuiltinCandidate - Add a candidate for a built-in 3976/// operator. ResultTy and ParamTys are the result and parameter types 3977/// of the built-in candidate, respectively. Args and NumArgs are the 3978/// arguments being passed to the candidate. IsAssignmentOperator 3979/// should be true when this built-in candidate is an assignment 3980/// operator. NumContextualBoolArguments is the number of arguments 3981/// (at the beginning of the argument list) that will be contextually 3982/// converted to bool. 3983void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 3984 Expr **Args, unsigned NumArgs, 3985 OverloadCandidateSet& CandidateSet, 3986 bool IsAssignmentOperator, 3987 unsigned NumContextualBoolArguments) { 3988 // Overload resolution is always an unevaluated context. 3989 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 3990 3991 // Add this candidate 3992 CandidateSet.push_back(OverloadCandidate()); 3993 OverloadCandidate& Candidate = CandidateSet.back(); 3994 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 3995 Candidate.Function = 0; 3996 Candidate.IsSurrogate = false; 3997 Candidate.IgnoreObjectArgument = false; 3998 Candidate.BuiltinTypes.ResultTy = ResultTy; 3999 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4000 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 4001 4002 // Determine the implicit conversion sequences for each of the 4003 // arguments. 4004 Candidate.Viable = true; 4005 Candidate.Conversions.resize(NumArgs); 4006 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4007 // C++ [over.match.oper]p4: 4008 // For the built-in assignment operators, conversions of the 4009 // left operand are restricted as follows: 4010 // -- no temporaries are introduced to hold the left operand, and 4011 // -- no user-defined conversions are applied to the left 4012 // operand to achieve a type match with the left-most 4013 // parameter of a built-in candidate. 4014 // 4015 // We block these conversions by turning off user-defined 4016 // conversions, since that is the only way that initialization of 4017 // a reference to a non-class type can occur from something that 4018 // is not of the same type. 4019 if (ArgIdx < NumContextualBoolArguments) { 4020 assert(ParamTys[ArgIdx] == Context.BoolTy && 4021 "Contextual conversion to bool requires bool type"); 4022 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]); 4023 } else { 4024 Candidate.Conversions[ArgIdx] 4025 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 4026 ArgIdx == 0 && IsAssignmentOperator, 4027 /*InOverloadResolution=*/false); 4028 } 4029 if (Candidate.Conversions[ArgIdx].isBad()) { 4030 Candidate.Viable = false; 4031 Candidate.FailureKind = ovl_fail_bad_conversion; 4032 break; 4033 } 4034 } 4035} 4036 4037/// BuiltinCandidateTypeSet - A set of types that will be used for the 4038/// candidate operator functions for built-in operators (C++ 4039/// [over.built]). The types are separated into pointer types and 4040/// enumeration types. 4041class BuiltinCandidateTypeSet { 4042 /// TypeSet - A set of types. 4043 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 4044 4045 /// PointerTypes - The set of pointer types that will be used in the 4046 /// built-in candidates. 4047 TypeSet PointerTypes; 4048 4049 /// MemberPointerTypes - The set of member pointer types that will be 4050 /// used in the built-in candidates. 4051 TypeSet MemberPointerTypes; 4052 4053 /// EnumerationTypes - The set of enumeration types that will be 4054 /// used in the built-in candidates. 4055 TypeSet EnumerationTypes; 4056 4057 /// \brief The set of vector types that will be used in the built-in 4058 /// candidates. 4059 TypeSet VectorTypes; 4060 4061 /// Sema - The semantic analysis instance where we are building the 4062 /// candidate type set. 4063 Sema &SemaRef; 4064 4065 /// Context - The AST context in which we will build the type sets. 4066 ASTContext &Context; 4067 4068 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4069 const Qualifiers &VisibleQuals); 4070 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 4071 4072public: 4073 /// iterator - Iterates through the types that are part of the set. 4074 typedef TypeSet::iterator iterator; 4075 4076 BuiltinCandidateTypeSet(Sema &SemaRef) 4077 : SemaRef(SemaRef), Context(SemaRef.Context) { } 4078 4079 void AddTypesConvertedFrom(QualType Ty, 4080 SourceLocation Loc, 4081 bool AllowUserConversions, 4082 bool AllowExplicitConversions, 4083 const Qualifiers &VisibleTypeConversionsQuals); 4084 4085 /// pointer_begin - First pointer type found; 4086 iterator pointer_begin() { return PointerTypes.begin(); } 4087 4088 /// pointer_end - Past the last pointer type found; 4089 iterator pointer_end() { return PointerTypes.end(); } 4090 4091 /// member_pointer_begin - First member pointer type found; 4092 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 4093 4094 /// member_pointer_end - Past the last member pointer type found; 4095 iterator member_pointer_end() { return MemberPointerTypes.end(); } 4096 4097 /// enumeration_begin - First enumeration type found; 4098 iterator enumeration_begin() { return EnumerationTypes.begin(); } 4099 4100 /// enumeration_end - Past the last enumeration type found; 4101 iterator enumeration_end() { return EnumerationTypes.end(); } 4102 4103 iterator vector_begin() { return VectorTypes.begin(); } 4104 iterator vector_end() { return VectorTypes.end(); } 4105}; 4106 4107/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 4108/// the set of pointer types along with any more-qualified variants of 4109/// that type. For example, if @p Ty is "int const *", this routine 4110/// will add "int const *", "int const volatile *", "int const 4111/// restrict *", and "int const volatile restrict *" to the set of 4112/// pointer types. Returns true if the add of @p Ty itself succeeded, 4113/// false otherwise. 4114/// 4115/// FIXME: what to do about extended qualifiers? 4116bool 4117BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4118 const Qualifiers &VisibleQuals) { 4119 4120 // Insert this type. 4121 if (!PointerTypes.insert(Ty)) 4122 return false; 4123 4124 const PointerType *PointerTy = Ty->getAs<PointerType>(); 4125 assert(PointerTy && "type was not a pointer type!"); 4126 4127 QualType PointeeTy = PointerTy->getPointeeType(); 4128 // Don't add qualified variants of arrays. For one, they're not allowed 4129 // (the qualifier would sink to the element type), and for another, the 4130 // only overload situation where it matters is subscript or pointer +- int, 4131 // and those shouldn't have qualifier variants anyway. 4132 if (PointeeTy->isArrayType()) 4133 return true; 4134 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4135 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 4136 BaseCVR = Array->getElementType().getCVRQualifiers(); 4137 bool hasVolatile = VisibleQuals.hasVolatile(); 4138 bool hasRestrict = VisibleQuals.hasRestrict(); 4139 4140 // Iterate through all strict supersets of BaseCVR. 4141 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4142 if ((CVR | BaseCVR) != CVR) continue; 4143 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 4144 // in the types. 4145 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 4146 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 4147 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4148 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 4149 } 4150 4151 return true; 4152} 4153 4154/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 4155/// to the set of pointer types along with any more-qualified variants of 4156/// that type. For example, if @p Ty is "int const *", this routine 4157/// will add "int const *", "int const volatile *", "int const 4158/// restrict *", and "int const volatile restrict *" to the set of 4159/// pointer types. Returns true if the add of @p Ty itself succeeded, 4160/// false otherwise. 4161/// 4162/// FIXME: what to do about extended qualifiers? 4163bool 4164BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 4165 QualType Ty) { 4166 // Insert this type. 4167 if (!MemberPointerTypes.insert(Ty)) 4168 return false; 4169 4170 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 4171 assert(PointerTy && "type was not a member pointer type!"); 4172 4173 QualType PointeeTy = PointerTy->getPointeeType(); 4174 // Don't add qualified variants of arrays. For one, they're not allowed 4175 // (the qualifier would sink to the element type), and for another, the 4176 // only overload situation where it matters is subscript or pointer +- int, 4177 // and those shouldn't have qualifier variants anyway. 4178 if (PointeeTy->isArrayType()) 4179 return true; 4180 const Type *ClassTy = PointerTy->getClass(); 4181 4182 // Iterate through all strict supersets of the pointee type's CVR 4183 // qualifiers. 4184 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4185 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4186 if ((CVR | BaseCVR) != CVR) continue; 4187 4188 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4189 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy)); 4190 } 4191 4192 return true; 4193} 4194 4195/// AddTypesConvertedFrom - Add each of the types to which the type @p 4196/// Ty can be implicit converted to the given set of @p Types. We're 4197/// primarily interested in pointer types and enumeration types. We also 4198/// take member pointer types, for the conditional operator. 4199/// AllowUserConversions is true if we should look at the conversion 4200/// functions of a class type, and AllowExplicitConversions if we 4201/// should also include the explicit conversion functions of a class 4202/// type. 4203void 4204BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 4205 SourceLocation Loc, 4206 bool AllowUserConversions, 4207 bool AllowExplicitConversions, 4208 const Qualifiers &VisibleQuals) { 4209 // Only deal with canonical types. 4210 Ty = Context.getCanonicalType(Ty); 4211 4212 // Look through reference types; they aren't part of the type of an 4213 // expression for the purposes of conversions. 4214 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 4215 Ty = RefTy->getPointeeType(); 4216 4217 // We don't care about qualifiers on the type. 4218 Ty = Ty.getLocalUnqualifiedType(); 4219 4220 // If we're dealing with an array type, decay to the pointer. 4221 if (Ty->isArrayType()) 4222 Ty = SemaRef.Context.getArrayDecayedType(Ty); 4223 4224 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) { 4225 QualType PointeeTy = PointerTy->getPointeeType(); 4226 4227 // Insert our type, and its more-qualified variants, into the set 4228 // of types. 4229 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 4230 return; 4231 } else if (Ty->isMemberPointerType()) { 4232 // Member pointers are far easier, since the pointee can't be converted. 4233 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 4234 return; 4235 } else if (Ty->isEnumeralType()) { 4236 EnumerationTypes.insert(Ty); 4237 } else if (Ty->isVectorType()) { 4238 VectorTypes.insert(Ty); 4239 } else if (AllowUserConversions) { 4240 if (const RecordType *TyRec = Ty->getAs<RecordType>()) { 4241 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) { 4242 // No conversion functions in incomplete types. 4243 return; 4244 } 4245 4246 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 4247 const UnresolvedSetImpl *Conversions 4248 = ClassDecl->getVisibleConversionFunctions(); 4249 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4250 E = Conversions->end(); I != E; ++I) { 4251 NamedDecl *D = I.getDecl(); 4252 if (isa<UsingShadowDecl>(D)) 4253 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4254 4255 // Skip conversion function templates; they don't tell us anything 4256 // about which builtin types we can convert to. 4257 if (isa<FunctionTemplateDecl>(D)) 4258 continue; 4259 4260 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 4261 if (AllowExplicitConversions || !Conv->isExplicit()) { 4262 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 4263 VisibleQuals); 4264 } 4265 } 4266 } 4267 } 4268} 4269 4270/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 4271/// the volatile- and non-volatile-qualified assignment operators for the 4272/// given type to the candidate set. 4273static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 4274 QualType T, 4275 Expr **Args, 4276 unsigned NumArgs, 4277 OverloadCandidateSet &CandidateSet) { 4278 QualType ParamTypes[2]; 4279 4280 // T& operator=(T&, T) 4281 ParamTypes[0] = S.Context.getLValueReferenceType(T); 4282 ParamTypes[1] = T; 4283 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4284 /*IsAssignmentOperator=*/true); 4285 4286 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 4287 // volatile T& operator=(volatile T&, T) 4288 ParamTypes[0] 4289 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 4290 ParamTypes[1] = T; 4291 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4292 /*IsAssignmentOperator=*/true); 4293 } 4294} 4295 4296/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 4297/// if any, found in visible type conversion functions found in ArgExpr's type. 4298static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 4299 Qualifiers VRQuals; 4300 const RecordType *TyRec; 4301 if (const MemberPointerType *RHSMPType = 4302 ArgExpr->getType()->getAs<MemberPointerType>()) 4303 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 4304 else 4305 TyRec = ArgExpr->getType()->getAs<RecordType>(); 4306 if (!TyRec) { 4307 // Just to be safe, assume the worst case. 4308 VRQuals.addVolatile(); 4309 VRQuals.addRestrict(); 4310 return VRQuals; 4311 } 4312 4313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 4314 if (!ClassDecl->hasDefinition()) 4315 return VRQuals; 4316 4317 const UnresolvedSetImpl *Conversions = 4318 ClassDecl->getVisibleConversionFunctions(); 4319 4320 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4321 E = Conversions->end(); I != E; ++I) { 4322 NamedDecl *D = I.getDecl(); 4323 if (isa<UsingShadowDecl>(D)) 4324 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4325 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 4326 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 4327 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 4328 CanTy = ResTypeRef->getPointeeType(); 4329 // Need to go down the pointer/mempointer chain and add qualifiers 4330 // as see them. 4331 bool done = false; 4332 while (!done) { 4333 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 4334 CanTy = ResTypePtr->getPointeeType(); 4335 else if (const MemberPointerType *ResTypeMPtr = 4336 CanTy->getAs<MemberPointerType>()) 4337 CanTy = ResTypeMPtr->getPointeeType(); 4338 else 4339 done = true; 4340 if (CanTy.isVolatileQualified()) 4341 VRQuals.addVolatile(); 4342 if (CanTy.isRestrictQualified()) 4343 VRQuals.addRestrict(); 4344 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 4345 return VRQuals; 4346 } 4347 } 4348 } 4349 return VRQuals; 4350} 4351 4352/// AddBuiltinOperatorCandidates - Add the appropriate built-in 4353/// operator overloads to the candidate set (C++ [over.built]), based 4354/// on the operator @p Op and the arguments given. For example, if the 4355/// operator is a binary '+', this routine might add "int 4356/// operator+(int, int)" to cover integer addition. 4357void 4358Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 4359 SourceLocation OpLoc, 4360 Expr **Args, unsigned NumArgs, 4361 OverloadCandidateSet& CandidateSet) { 4362 // The set of "promoted arithmetic types", which are the arithmetic 4363 // types are that preserved by promotion (C++ [over.built]p2). Note 4364 // that the first few of these types are the promoted integral 4365 // types; these types need to be first. 4366 // FIXME: What about complex? 4367 const unsigned FirstIntegralType = 0; 4368 const unsigned LastIntegralType = 13; 4369 const unsigned FirstPromotedIntegralType = 7, 4370 LastPromotedIntegralType = 13; 4371 const unsigned FirstPromotedArithmeticType = 7, 4372 LastPromotedArithmeticType = 16; 4373 const unsigned NumArithmeticTypes = 16; 4374 QualType ArithmeticTypes[NumArithmeticTypes] = { 4375 Context.BoolTy, Context.CharTy, Context.WCharTy, 4376// FIXME: Context.Char16Ty, Context.Char32Ty, 4377 Context.SignedCharTy, Context.ShortTy, 4378 Context.UnsignedCharTy, Context.UnsignedShortTy, 4379 Context.IntTy, Context.LongTy, Context.LongLongTy, 4380 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 4381 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 4382 }; 4383 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy && 4384 "Invalid first promoted integral type"); 4385 assert(ArithmeticTypes[LastPromotedIntegralType - 1] 4386 == Context.UnsignedLongLongTy && 4387 "Invalid last promoted integral type"); 4388 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy && 4389 "Invalid first promoted arithmetic type"); 4390 assert(ArithmeticTypes[LastPromotedArithmeticType - 1] 4391 == Context.LongDoubleTy && 4392 "Invalid last promoted arithmetic type"); 4393 4394 // Find all of the types that the arguments can convert to, but only 4395 // if the operator we're looking at has built-in operator candidates 4396 // that make use of these types. 4397 Qualifiers VisibleTypeConversionsQuals; 4398 VisibleTypeConversionsQuals.addConst(); 4399 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4400 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 4401 4402 BuiltinCandidateTypeSet CandidateTypes(*this); 4403 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4404 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(), 4405 OpLoc, 4406 true, 4407 (Op == OO_Exclaim || 4408 Op == OO_AmpAmp || 4409 Op == OO_PipePipe), 4410 VisibleTypeConversionsQuals); 4411 4412 bool isComparison = false; 4413 switch (Op) { 4414 case OO_None: 4415 case NUM_OVERLOADED_OPERATORS: 4416 assert(false && "Expected an overloaded operator"); 4417 break; 4418 4419 case OO_Star: // '*' is either unary or binary 4420 if (NumArgs == 1) 4421 goto UnaryStar; 4422 else 4423 goto BinaryStar; 4424 break; 4425 4426 case OO_Plus: // '+' is either unary or binary 4427 if (NumArgs == 1) 4428 goto UnaryPlus; 4429 else 4430 goto BinaryPlus; 4431 break; 4432 4433 case OO_Minus: // '-' is either unary or binary 4434 if (NumArgs == 1) 4435 goto UnaryMinus; 4436 else 4437 goto BinaryMinus; 4438 break; 4439 4440 case OO_Amp: // '&' is either unary or binary 4441 if (NumArgs == 1) 4442 goto UnaryAmp; 4443 else 4444 goto BinaryAmp; 4445 4446 case OO_PlusPlus: 4447 case OO_MinusMinus: 4448 // C++ [over.built]p3: 4449 // 4450 // For every pair (T, VQ), where T is an arithmetic type, and VQ 4451 // is either volatile or empty, there exist candidate operator 4452 // functions of the form 4453 // 4454 // VQ T& operator++(VQ T&); 4455 // T operator++(VQ T&, int); 4456 // 4457 // C++ [over.built]p4: 4458 // 4459 // For every pair (T, VQ), where T is an arithmetic type other 4460 // than bool, and VQ is either volatile or empty, there exist 4461 // candidate operator functions of the form 4462 // 4463 // VQ T& operator--(VQ T&); 4464 // T operator--(VQ T&, int); 4465 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 4466 Arith < NumArithmeticTypes; ++Arith) { 4467 QualType ArithTy = ArithmeticTypes[Arith]; 4468 QualType ParamTypes[2] 4469 = { Context.getLValueReferenceType(ArithTy), Context.IntTy }; 4470 4471 // Non-volatile version. 4472 if (NumArgs == 1) 4473 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4474 else 4475 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 4476 // heuristic to reduce number of builtin candidates in the set. 4477 // Add volatile version only if there are conversions to a volatile type. 4478 if (VisibleTypeConversionsQuals.hasVolatile()) { 4479 // Volatile version 4480 ParamTypes[0] 4481 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy)); 4482 if (NumArgs == 1) 4483 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4484 else 4485 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 4486 } 4487 } 4488 4489 // C++ [over.built]p5: 4490 // 4491 // For every pair (T, VQ), where T is a cv-qualified or 4492 // cv-unqualified object type, and VQ is either volatile or 4493 // empty, there exist candidate operator functions of the form 4494 // 4495 // T*VQ& operator++(T*VQ&); 4496 // T*VQ& operator--(T*VQ&); 4497 // T* operator++(T*VQ&, int); 4498 // T* operator--(T*VQ&, int); 4499 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4500 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4501 // Skip pointer types that aren't pointers to object types. 4502 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType()) 4503 continue; 4504 4505 QualType ParamTypes[2] = { 4506 Context.getLValueReferenceType(*Ptr), Context.IntTy 4507 }; 4508 4509 // Without volatile 4510 if (NumArgs == 1) 4511 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4512 else 4513 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4514 4515 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 4516 VisibleTypeConversionsQuals.hasVolatile()) { 4517 // With volatile 4518 ParamTypes[0] 4519 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 4520 if (NumArgs == 1) 4521 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4522 else 4523 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4524 } 4525 } 4526 break; 4527 4528 UnaryStar: 4529 // C++ [over.built]p6: 4530 // For every cv-qualified or cv-unqualified object type T, there 4531 // exist candidate operator functions of the form 4532 // 4533 // T& operator*(T*); 4534 // 4535 // C++ [over.built]p7: 4536 // For every function type T, there exist candidate operator 4537 // functions of the form 4538 // T& operator*(T*); 4539 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4540 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4541 QualType ParamTy = *Ptr; 4542 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType(); 4543 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy), 4544 &ParamTy, Args, 1, CandidateSet); 4545 } 4546 break; 4547 4548 UnaryPlus: 4549 // C++ [over.built]p8: 4550 // For every type T, there exist candidate operator functions of 4551 // the form 4552 // 4553 // T* operator+(T*); 4554 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4555 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4556 QualType ParamTy = *Ptr; 4557 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 4558 } 4559 4560 // Fall through 4561 4562 UnaryMinus: 4563 // C++ [over.built]p9: 4564 // For every promoted arithmetic type T, there exist candidate 4565 // operator functions of the form 4566 // 4567 // T operator+(T); 4568 // T operator-(T); 4569 for (unsigned Arith = FirstPromotedArithmeticType; 4570 Arith < LastPromotedArithmeticType; ++Arith) { 4571 QualType ArithTy = ArithmeticTypes[Arith]; 4572 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 4573 } 4574 4575 // Extension: We also add these operators for vector types. 4576 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(), 4577 VecEnd = CandidateTypes.vector_end(); 4578 Vec != VecEnd; ++Vec) { 4579 QualType VecTy = *Vec; 4580 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 4581 } 4582 break; 4583 4584 case OO_Tilde: 4585 // C++ [over.built]p10: 4586 // For every promoted integral type T, there exist candidate 4587 // operator functions of the form 4588 // 4589 // T operator~(T); 4590 for (unsigned Int = FirstPromotedIntegralType; 4591 Int < LastPromotedIntegralType; ++Int) { 4592 QualType IntTy = ArithmeticTypes[Int]; 4593 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 4594 } 4595 4596 // Extension: We also add this operator for vector types. 4597 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(), 4598 VecEnd = CandidateTypes.vector_end(); 4599 Vec != VecEnd; ++Vec) { 4600 QualType VecTy = *Vec; 4601 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 4602 } 4603 break; 4604 4605 case OO_New: 4606 case OO_Delete: 4607 case OO_Array_New: 4608 case OO_Array_Delete: 4609 case OO_Call: 4610 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 4611 break; 4612 4613 case OO_Comma: 4614 UnaryAmp: 4615 case OO_Arrow: 4616 // C++ [over.match.oper]p3: 4617 // -- For the operator ',', the unary operator '&', or the 4618 // operator '->', the built-in candidates set is empty. 4619 break; 4620 4621 case OO_EqualEqual: 4622 case OO_ExclaimEqual: 4623 // C++ [over.match.oper]p16: 4624 // For every pointer to member type T, there exist candidate operator 4625 // functions of the form 4626 // 4627 // bool operator==(T,T); 4628 // bool operator!=(T,T); 4629 for (BuiltinCandidateTypeSet::iterator 4630 MemPtr = CandidateTypes.member_pointer_begin(), 4631 MemPtrEnd = CandidateTypes.member_pointer_end(); 4632 MemPtr != MemPtrEnd; 4633 ++MemPtr) { 4634 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 4635 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 4636 } 4637 4638 // Fall through 4639 4640 case OO_Less: 4641 case OO_Greater: 4642 case OO_LessEqual: 4643 case OO_GreaterEqual: 4644 // C++ [over.built]p15: 4645 // 4646 // For every pointer or enumeration type T, there exist 4647 // candidate operator functions of the form 4648 // 4649 // bool operator<(T, T); 4650 // bool operator>(T, T); 4651 // bool operator<=(T, T); 4652 // bool operator>=(T, T); 4653 // bool operator==(T, T); 4654 // bool operator!=(T, T); 4655 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4656 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4657 QualType ParamTypes[2] = { *Ptr, *Ptr }; 4658 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 4659 } 4660 for (BuiltinCandidateTypeSet::iterator Enum 4661 = CandidateTypes.enumeration_begin(); 4662 Enum != CandidateTypes.enumeration_end(); ++Enum) { 4663 QualType ParamTypes[2] = { *Enum, *Enum }; 4664 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 4665 } 4666 4667 // Fall through. 4668 isComparison = true; 4669 4670 BinaryPlus: 4671 BinaryMinus: 4672 if (!isComparison) { 4673 // We didn't fall through, so we must have OO_Plus or OO_Minus. 4674 4675 // C++ [over.built]p13: 4676 // 4677 // For every cv-qualified or cv-unqualified object type T 4678 // there exist candidate operator functions of the form 4679 // 4680 // T* operator+(T*, ptrdiff_t); 4681 // T& operator[](T*, ptrdiff_t); [BELOW] 4682 // T* operator-(T*, ptrdiff_t); 4683 // T* operator+(ptrdiff_t, T*); 4684 // T& operator[](ptrdiff_t, T*); [BELOW] 4685 // 4686 // C++ [over.built]p14: 4687 // 4688 // For every T, where T is a pointer to object type, there 4689 // exist candidate operator functions of the form 4690 // 4691 // ptrdiff_t operator-(T, T); 4692 for (BuiltinCandidateTypeSet::iterator Ptr 4693 = CandidateTypes.pointer_begin(); 4694 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4695 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 4696 4697 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 4698 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4699 4700 if (Op == OO_Plus) { 4701 // T* operator+(ptrdiff_t, T*); 4702 ParamTypes[0] = ParamTypes[1]; 4703 ParamTypes[1] = *Ptr; 4704 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4705 } else { 4706 // ptrdiff_t operator-(T, T); 4707 ParamTypes[1] = *Ptr; 4708 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 4709 Args, 2, CandidateSet); 4710 } 4711 } 4712 } 4713 // Fall through 4714 4715 case OO_Slash: 4716 BinaryStar: 4717 Conditional: 4718 // C++ [over.built]p12: 4719 // 4720 // For every pair of promoted arithmetic types L and R, there 4721 // exist candidate operator functions of the form 4722 // 4723 // LR operator*(L, R); 4724 // LR operator/(L, R); 4725 // LR operator+(L, R); 4726 // LR operator-(L, R); 4727 // bool operator<(L, R); 4728 // bool operator>(L, R); 4729 // bool operator<=(L, R); 4730 // bool operator>=(L, R); 4731 // bool operator==(L, R); 4732 // bool operator!=(L, R); 4733 // 4734 // where LR is the result of the usual arithmetic conversions 4735 // between types L and R. 4736 // 4737 // C++ [over.built]p24: 4738 // 4739 // For every pair of promoted arithmetic types L and R, there exist 4740 // candidate operator functions of the form 4741 // 4742 // LR operator?(bool, L, R); 4743 // 4744 // where LR is the result of the usual arithmetic conversions 4745 // between types L and R. 4746 // Our candidates ignore the first parameter. 4747 for (unsigned Left = FirstPromotedArithmeticType; 4748 Left < LastPromotedArithmeticType; ++Left) { 4749 for (unsigned Right = FirstPromotedArithmeticType; 4750 Right < LastPromotedArithmeticType; ++Right) { 4751 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 4752 QualType Result 4753 = isComparison 4754 ? Context.BoolTy 4755 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 4756 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 4757 } 4758 } 4759 4760 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 4761 // conditional operator for vector types. 4762 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(), 4763 Vec1End = CandidateTypes.vector_end(); 4764 Vec1 != Vec1End; ++Vec1) 4765 for (BuiltinCandidateTypeSet::iterator 4766 Vec2 = CandidateTypes.vector_begin(), 4767 Vec2End = CandidateTypes.vector_end(); 4768 Vec2 != Vec2End; ++Vec2) { 4769 QualType LandR[2] = { *Vec1, *Vec2 }; 4770 QualType Result; 4771 if (isComparison) 4772 Result = Context.BoolTy; 4773 else { 4774 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 4775 Result = *Vec1; 4776 else 4777 Result = *Vec2; 4778 } 4779 4780 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 4781 } 4782 4783 break; 4784 4785 case OO_Percent: 4786 BinaryAmp: 4787 case OO_Caret: 4788 case OO_Pipe: 4789 case OO_LessLess: 4790 case OO_GreaterGreater: 4791 // C++ [over.built]p17: 4792 // 4793 // For every pair of promoted integral types L and R, there 4794 // exist candidate operator functions of the form 4795 // 4796 // LR operator%(L, R); 4797 // LR operator&(L, R); 4798 // LR operator^(L, R); 4799 // LR operator|(L, R); 4800 // L operator<<(L, R); 4801 // L operator>>(L, R); 4802 // 4803 // where LR is the result of the usual arithmetic conversions 4804 // between types L and R. 4805 for (unsigned Left = FirstPromotedIntegralType; 4806 Left < LastPromotedIntegralType; ++Left) { 4807 for (unsigned Right = FirstPromotedIntegralType; 4808 Right < LastPromotedIntegralType; ++Right) { 4809 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 4810 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 4811 ? LandR[0] 4812 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 4813 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 4814 } 4815 } 4816 break; 4817 4818 case OO_Equal: 4819 // C++ [over.built]p20: 4820 // 4821 // For every pair (T, VQ), where T is an enumeration or 4822 // pointer to member type and VQ is either volatile or 4823 // empty, there exist candidate operator functions of the form 4824 // 4825 // VQ T& operator=(VQ T&, T); 4826 for (BuiltinCandidateTypeSet::iterator 4827 Enum = CandidateTypes.enumeration_begin(), 4828 EnumEnd = CandidateTypes.enumeration_end(); 4829 Enum != EnumEnd; ++Enum) 4830 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2, 4831 CandidateSet); 4832 for (BuiltinCandidateTypeSet::iterator 4833 MemPtr = CandidateTypes.member_pointer_begin(), 4834 MemPtrEnd = CandidateTypes.member_pointer_end(); 4835 MemPtr != MemPtrEnd; ++MemPtr) 4836 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2, 4837 CandidateSet); 4838 4839 // Fall through. 4840 4841 case OO_PlusEqual: 4842 case OO_MinusEqual: 4843 // C++ [over.built]p19: 4844 // 4845 // For every pair (T, VQ), where T is any type and VQ is either 4846 // volatile or empty, there exist candidate operator functions 4847 // of the form 4848 // 4849 // T*VQ& operator=(T*VQ&, T*); 4850 // 4851 // C++ [over.built]p21: 4852 // 4853 // For every pair (T, VQ), where T is a cv-qualified or 4854 // cv-unqualified object type and VQ is either volatile or 4855 // empty, there exist candidate operator functions of the form 4856 // 4857 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 4858 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 4859 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4860 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4861 QualType ParamTypes[2]; 4862 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 4863 4864 // non-volatile version 4865 ParamTypes[0] = Context.getLValueReferenceType(*Ptr); 4866 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4867 /*IsAssigmentOperator=*/Op == OO_Equal); 4868 4869 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 4870 VisibleTypeConversionsQuals.hasVolatile()) { 4871 // volatile version 4872 ParamTypes[0] 4873 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 4874 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4875 /*IsAssigmentOperator=*/Op == OO_Equal); 4876 } 4877 } 4878 // Fall through. 4879 4880 case OO_StarEqual: 4881 case OO_SlashEqual: 4882 // C++ [over.built]p18: 4883 // 4884 // For every triple (L, VQ, R), where L is an arithmetic type, 4885 // VQ is either volatile or empty, and R is a promoted 4886 // arithmetic type, there exist candidate operator functions of 4887 // the form 4888 // 4889 // VQ L& operator=(VQ L&, R); 4890 // VQ L& operator*=(VQ L&, R); 4891 // VQ L& operator/=(VQ L&, R); 4892 // VQ L& operator+=(VQ L&, R); 4893 // VQ L& operator-=(VQ L&, R); 4894 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 4895 for (unsigned Right = FirstPromotedArithmeticType; 4896 Right < LastPromotedArithmeticType; ++Right) { 4897 QualType ParamTypes[2]; 4898 ParamTypes[1] = ArithmeticTypes[Right]; 4899 4900 // Add this built-in operator as a candidate (VQ is empty). 4901 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 4902 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4903 /*IsAssigmentOperator=*/Op == OO_Equal); 4904 4905 // Add this built-in operator as a candidate (VQ is 'volatile'). 4906 if (VisibleTypeConversionsQuals.hasVolatile()) { 4907 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]); 4908 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 4909 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4910 /*IsAssigmentOperator=*/Op == OO_Equal); 4911 } 4912 } 4913 } 4914 4915 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 4916 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(), 4917 Vec1End = CandidateTypes.vector_end(); 4918 Vec1 != Vec1End; ++Vec1) 4919 for (BuiltinCandidateTypeSet::iterator 4920 Vec2 = CandidateTypes.vector_begin(), 4921 Vec2End = CandidateTypes.vector_end(); 4922 Vec2 != Vec2End; ++Vec2) { 4923 QualType ParamTypes[2]; 4924 ParamTypes[1] = *Vec2; 4925 // Add this built-in operator as a candidate (VQ is empty). 4926 ParamTypes[0] = Context.getLValueReferenceType(*Vec1); 4927 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4928 /*IsAssigmentOperator=*/Op == OO_Equal); 4929 4930 // Add this built-in operator as a candidate (VQ is 'volatile'). 4931 if (VisibleTypeConversionsQuals.hasVolatile()) { 4932 ParamTypes[0] = Context.getVolatileType(*Vec1); 4933 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 4934 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4935 /*IsAssigmentOperator=*/Op == OO_Equal); 4936 } 4937 } 4938 break; 4939 4940 case OO_PercentEqual: 4941 case OO_LessLessEqual: 4942 case OO_GreaterGreaterEqual: 4943 case OO_AmpEqual: 4944 case OO_CaretEqual: 4945 case OO_PipeEqual: 4946 // C++ [over.built]p22: 4947 // 4948 // For every triple (L, VQ, R), where L is an integral type, VQ 4949 // is either volatile or empty, and R is a promoted integral 4950 // type, there exist candidate operator functions of the form 4951 // 4952 // VQ L& operator%=(VQ L&, R); 4953 // VQ L& operator<<=(VQ L&, R); 4954 // VQ L& operator>>=(VQ L&, R); 4955 // VQ L& operator&=(VQ L&, R); 4956 // VQ L& operator^=(VQ L&, R); 4957 // VQ L& operator|=(VQ L&, R); 4958 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 4959 for (unsigned Right = FirstPromotedIntegralType; 4960 Right < LastPromotedIntegralType; ++Right) { 4961 QualType ParamTypes[2]; 4962 ParamTypes[1] = ArithmeticTypes[Right]; 4963 4964 // Add this built-in operator as a candidate (VQ is empty). 4965 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 4966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 4967 if (VisibleTypeConversionsQuals.hasVolatile()) { 4968 // Add this built-in operator as a candidate (VQ is 'volatile'). 4969 ParamTypes[0] = ArithmeticTypes[Left]; 4970 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]); 4971 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 4972 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 4973 } 4974 } 4975 } 4976 break; 4977 4978 case OO_Exclaim: { 4979 // C++ [over.operator]p23: 4980 // 4981 // There also exist candidate operator functions of the form 4982 // 4983 // bool operator!(bool); 4984 // bool operator&&(bool, bool); [BELOW] 4985 // bool operator||(bool, bool); [BELOW] 4986 QualType ParamTy = Context.BoolTy; 4987 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 4988 /*IsAssignmentOperator=*/false, 4989 /*NumContextualBoolArguments=*/1); 4990 break; 4991 } 4992 4993 case OO_AmpAmp: 4994 case OO_PipePipe: { 4995 // C++ [over.operator]p23: 4996 // 4997 // There also exist candidate operator functions of the form 4998 // 4999 // bool operator!(bool); [ABOVE] 5000 // bool operator&&(bool, bool); 5001 // bool operator||(bool, bool); 5002 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 5003 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 5004 /*IsAssignmentOperator=*/false, 5005 /*NumContextualBoolArguments=*/2); 5006 break; 5007 } 5008 5009 case OO_Subscript: 5010 // C++ [over.built]p13: 5011 // 5012 // For every cv-qualified or cv-unqualified object type T there 5013 // exist candidate operator functions of the form 5014 // 5015 // T* operator+(T*, ptrdiff_t); [ABOVE] 5016 // T& operator[](T*, ptrdiff_t); 5017 // T* operator-(T*, ptrdiff_t); [ABOVE] 5018 // T* operator+(ptrdiff_t, T*); [ABOVE] 5019 // T& operator[](ptrdiff_t, T*); 5020 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 5021 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 5022 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 5023 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType(); 5024 QualType ResultTy = Context.getLValueReferenceType(PointeeType); 5025 5026 // T& operator[](T*, ptrdiff_t) 5027 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5028 5029 // T& operator[](ptrdiff_t, T*); 5030 ParamTypes[0] = ParamTypes[1]; 5031 ParamTypes[1] = *Ptr; 5032 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5033 } 5034 break; 5035 5036 case OO_ArrowStar: 5037 // C++ [over.built]p11: 5038 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 5039 // C1 is the same type as C2 or is a derived class of C2, T is an object 5040 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 5041 // there exist candidate operator functions of the form 5042 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 5043 // where CV12 is the union of CV1 and CV2. 5044 { 5045 for (BuiltinCandidateTypeSet::iterator Ptr = 5046 CandidateTypes.pointer_begin(); 5047 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 5048 QualType C1Ty = (*Ptr); 5049 QualType C1; 5050 QualifierCollector Q1; 5051 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) { 5052 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0); 5053 if (!isa<RecordType>(C1)) 5054 continue; 5055 // heuristic to reduce number of builtin candidates in the set. 5056 // Add volatile/restrict version only if there are conversions to a 5057 // volatile/restrict type. 5058 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 5059 continue; 5060 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 5061 continue; 5062 } 5063 for (BuiltinCandidateTypeSet::iterator 5064 MemPtr = CandidateTypes.member_pointer_begin(), 5065 MemPtrEnd = CandidateTypes.member_pointer_end(); 5066 MemPtr != MemPtrEnd; ++MemPtr) { 5067 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 5068 QualType C2 = QualType(mptr->getClass(), 0); 5069 C2 = C2.getUnqualifiedType(); 5070 if (C1 != C2 && !IsDerivedFrom(C1, C2)) 5071 break; 5072 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 5073 // build CV12 T& 5074 QualType T = mptr->getPointeeType(); 5075 if (!VisibleTypeConversionsQuals.hasVolatile() && 5076 T.isVolatileQualified()) 5077 continue; 5078 if (!VisibleTypeConversionsQuals.hasRestrict() && 5079 T.isRestrictQualified()) 5080 continue; 5081 T = Q1.apply(T); 5082 QualType ResultTy = Context.getLValueReferenceType(T); 5083 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5084 } 5085 } 5086 } 5087 break; 5088 5089 case OO_Conditional: 5090 // Note that we don't consider the first argument, since it has been 5091 // contextually converted to bool long ago. The candidates below are 5092 // therefore added as binary. 5093 // 5094 // C++ [over.built]p24: 5095 // For every type T, where T is a pointer or pointer-to-member type, 5096 // there exist candidate operator functions of the form 5097 // 5098 // T operator?(bool, T, T); 5099 // 5100 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(), 5101 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) { 5102 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5103 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 5104 } 5105 for (BuiltinCandidateTypeSet::iterator Ptr = 5106 CandidateTypes.member_pointer_begin(), 5107 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) { 5108 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5109 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 5110 } 5111 goto Conditional; 5112 } 5113} 5114 5115/// \brief Add function candidates found via argument-dependent lookup 5116/// to the set of overloading candidates. 5117/// 5118/// This routine performs argument-dependent name lookup based on the 5119/// given function name (which may also be an operator name) and adds 5120/// all of the overload candidates found by ADL to the overload 5121/// candidate set (C++ [basic.lookup.argdep]). 5122void 5123Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 5124 bool Operator, 5125 Expr **Args, unsigned NumArgs, 5126 const TemplateArgumentListInfo *ExplicitTemplateArgs, 5127 OverloadCandidateSet& CandidateSet, 5128 bool PartialOverloading) { 5129 ADLResult Fns; 5130 5131 // FIXME: This approach for uniquing ADL results (and removing 5132 // redundant candidates from the set) relies on pointer-equality, 5133 // which means we need to key off the canonical decl. However, 5134 // always going back to the canonical decl might not get us the 5135 // right set of default arguments. What default arguments are 5136 // we supposed to consider on ADL candidates, anyway? 5137 5138 // FIXME: Pass in the explicit template arguments? 5139 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns); 5140 5141 // Erase all of the candidates we already knew about. 5142 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 5143 CandEnd = CandidateSet.end(); 5144 Cand != CandEnd; ++Cand) 5145 if (Cand->Function) { 5146 Fns.erase(Cand->Function); 5147 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 5148 Fns.erase(FunTmpl); 5149 } 5150 5151 // For each of the ADL candidates we found, add it to the overload 5152 // set. 5153 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 5154 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 5155 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 5156 if (ExplicitTemplateArgs) 5157 continue; 5158 5159 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet, 5160 false, PartialOverloading); 5161 } else 5162 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 5163 FoundDecl, ExplicitTemplateArgs, 5164 Args, NumArgs, CandidateSet); 5165 } 5166} 5167 5168/// isBetterOverloadCandidate - Determines whether the first overload 5169/// candidate is a better candidate than the second (C++ 13.3.3p1). 5170bool 5171Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 5172 const OverloadCandidate& Cand2, 5173 SourceLocation Loc) { 5174 // Define viable functions to be better candidates than non-viable 5175 // functions. 5176 if (!Cand2.Viable) 5177 return Cand1.Viable; 5178 else if (!Cand1.Viable) 5179 return false; 5180 5181 // C++ [over.match.best]p1: 5182 // 5183 // -- if F is a static member function, ICS1(F) is defined such 5184 // that ICS1(F) is neither better nor worse than ICS1(G) for 5185 // any function G, and, symmetrically, ICS1(G) is neither 5186 // better nor worse than ICS1(F). 5187 unsigned StartArg = 0; 5188 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 5189 StartArg = 1; 5190 5191 // C++ [over.match.best]p1: 5192 // A viable function F1 is defined to be a better function than another 5193 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 5194 // conversion sequence than ICSi(F2), and then... 5195 unsigned NumArgs = Cand1.Conversions.size(); 5196 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 5197 bool HasBetterConversion = false; 5198 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 5199 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 5200 Cand2.Conversions[ArgIdx])) { 5201 case ImplicitConversionSequence::Better: 5202 // Cand1 has a better conversion sequence. 5203 HasBetterConversion = true; 5204 break; 5205 5206 case ImplicitConversionSequence::Worse: 5207 // Cand1 can't be better than Cand2. 5208 return false; 5209 5210 case ImplicitConversionSequence::Indistinguishable: 5211 // Do nothing. 5212 break; 5213 } 5214 } 5215 5216 // -- for some argument j, ICSj(F1) is a better conversion sequence than 5217 // ICSj(F2), or, if not that, 5218 if (HasBetterConversion) 5219 return true; 5220 5221 // - F1 is a non-template function and F2 is a function template 5222 // specialization, or, if not that, 5223 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 5224 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 5225 return true; 5226 5227 // -- F1 and F2 are function template specializations, and the function 5228 // template for F1 is more specialized than the template for F2 5229 // according to the partial ordering rules described in 14.5.5.2, or, 5230 // if not that, 5231 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 5232 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 5233 if (FunctionTemplateDecl *BetterTemplate 5234 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 5235 Cand2.Function->getPrimaryTemplate(), 5236 Loc, 5237 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 5238 : TPOC_Call)) 5239 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 5240 5241 // -- the context is an initialization by user-defined conversion 5242 // (see 8.5, 13.3.1.5) and the standard conversion sequence 5243 // from the return type of F1 to the destination type (i.e., 5244 // the type of the entity being initialized) is a better 5245 // conversion sequence than the standard conversion sequence 5246 // from the return type of F2 to the destination type. 5247 if (Cand1.Function && Cand2.Function && 5248 isa<CXXConversionDecl>(Cand1.Function) && 5249 isa<CXXConversionDecl>(Cand2.Function)) { 5250 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 5251 Cand2.FinalConversion)) { 5252 case ImplicitConversionSequence::Better: 5253 // Cand1 has a better conversion sequence. 5254 return true; 5255 5256 case ImplicitConversionSequence::Worse: 5257 // Cand1 can't be better than Cand2. 5258 return false; 5259 5260 case ImplicitConversionSequence::Indistinguishable: 5261 // Do nothing 5262 break; 5263 } 5264 } 5265 5266 return false; 5267} 5268 5269/// \brief Computes the best viable function (C++ 13.3.3) 5270/// within an overload candidate set. 5271/// 5272/// \param CandidateSet the set of candidate functions. 5273/// 5274/// \param Loc the location of the function name (or operator symbol) for 5275/// which overload resolution occurs. 5276/// 5277/// \param Best f overload resolution was successful or found a deleted 5278/// function, Best points to the candidate function found. 5279/// 5280/// \returns The result of overload resolution. 5281OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 5282 SourceLocation Loc, 5283 OverloadCandidateSet::iterator& Best) { 5284 // Find the best viable function. 5285 Best = CandidateSet.end(); 5286 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 5287 Cand != CandidateSet.end(); ++Cand) { 5288 if (Cand->Viable) { 5289 if (Best == CandidateSet.end() || 5290 isBetterOverloadCandidate(*Cand, *Best, Loc)) 5291 Best = Cand; 5292 } 5293 } 5294 5295 // If we didn't find any viable functions, abort. 5296 if (Best == CandidateSet.end()) 5297 return OR_No_Viable_Function; 5298 5299 // Make sure that this function is better than every other viable 5300 // function. If not, we have an ambiguity. 5301 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 5302 Cand != CandidateSet.end(); ++Cand) { 5303 if (Cand->Viable && 5304 Cand != Best && 5305 !isBetterOverloadCandidate(*Best, *Cand, Loc)) { 5306 Best = CandidateSet.end(); 5307 return OR_Ambiguous; 5308 } 5309 } 5310 5311 // Best is the best viable function. 5312 if (Best->Function && 5313 (Best->Function->isDeleted() || 5314 Best->Function->getAttr<UnavailableAttr>())) 5315 return OR_Deleted; 5316 5317 // C++ [basic.def.odr]p2: 5318 // An overloaded function is used if it is selected by overload resolution 5319 // when referred to from a potentially-evaluated expression. [Note: this 5320 // covers calls to named functions (5.2.2), operator overloading 5321 // (clause 13), user-defined conversions (12.3.2), allocation function for 5322 // placement new (5.3.4), as well as non-default initialization (8.5). 5323 if (Best->Function) 5324 MarkDeclarationReferenced(Loc, Best->Function); 5325 return OR_Success; 5326} 5327 5328namespace { 5329 5330enum OverloadCandidateKind { 5331 oc_function, 5332 oc_method, 5333 oc_constructor, 5334 oc_function_template, 5335 oc_method_template, 5336 oc_constructor_template, 5337 oc_implicit_default_constructor, 5338 oc_implicit_copy_constructor, 5339 oc_implicit_copy_assignment 5340}; 5341 5342OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 5343 FunctionDecl *Fn, 5344 std::string &Description) { 5345 bool isTemplate = false; 5346 5347 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 5348 isTemplate = true; 5349 Description = S.getTemplateArgumentBindingsText( 5350 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 5351 } 5352 5353 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 5354 if (!Ctor->isImplicit()) 5355 return isTemplate ? oc_constructor_template : oc_constructor; 5356 5357 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor 5358 : oc_implicit_default_constructor; 5359 } 5360 5361 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 5362 // This actually gets spelled 'candidate function' for now, but 5363 // it doesn't hurt to split it out. 5364 if (!Meth->isImplicit()) 5365 return isTemplate ? oc_method_template : oc_method; 5366 5367 assert(Meth->isCopyAssignment() 5368 && "implicit method is not copy assignment operator?"); 5369 return oc_implicit_copy_assignment; 5370 } 5371 5372 return isTemplate ? oc_function_template : oc_function; 5373} 5374 5375} // end anonymous namespace 5376 5377// Notes the location of an overload candidate. 5378void Sema::NoteOverloadCandidate(FunctionDecl *Fn) { 5379 std::string FnDesc; 5380 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 5381 Diag(Fn->getLocation(), diag::note_ovl_candidate) 5382 << (unsigned) K << FnDesc; 5383} 5384 5385/// Diagnoses an ambiguous conversion. The partial diagnostic is the 5386/// "lead" diagnostic; it will be given two arguments, the source and 5387/// target types of the conversion. 5388void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS, 5389 SourceLocation CaretLoc, 5390 const PartialDiagnostic &PDiag) { 5391 Diag(CaretLoc, PDiag) 5392 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType(); 5393 for (AmbiguousConversionSequence::const_iterator 5394 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) { 5395 NoteOverloadCandidate(*I); 5396 } 5397} 5398 5399namespace { 5400 5401void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 5402 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 5403 assert(Conv.isBad()); 5404 assert(Cand->Function && "for now, candidate must be a function"); 5405 FunctionDecl *Fn = Cand->Function; 5406 5407 // There's a conversion slot for the object argument if this is a 5408 // non-constructor method. Note that 'I' corresponds the 5409 // conversion-slot index. 5410 bool isObjectArgument = false; 5411 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 5412 if (I == 0) 5413 isObjectArgument = true; 5414 else 5415 I--; 5416 } 5417 5418 std::string FnDesc; 5419 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 5420 5421 Expr *FromExpr = Conv.Bad.FromExpr; 5422 QualType FromTy = Conv.Bad.getFromType(); 5423 QualType ToTy = Conv.Bad.getToType(); 5424 5425 if (FromTy == S.Context.OverloadTy) { 5426 assert(FromExpr && "overload set argument came from implicit argument?"); 5427 Expr *E = FromExpr->IgnoreParens(); 5428 if (isa<UnaryOperator>(E)) 5429 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 5430 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 5431 5432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 5433 << (unsigned) FnKind << FnDesc 5434 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5435 << ToTy << Name << I+1; 5436 return; 5437 } 5438 5439 // Do some hand-waving analysis to see if the non-viability is due 5440 // to a qualifier mismatch. 5441 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 5442 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 5443 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 5444 CToTy = RT->getPointeeType(); 5445 else { 5446 // TODO: detect and diagnose the full richness of const mismatches. 5447 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 5448 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 5449 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 5450 } 5451 5452 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 5453 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 5454 // It is dumb that we have to do this here. 5455 while (isa<ArrayType>(CFromTy)) 5456 CFromTy = CFromTy->getAs<ArrayType>()->getElementType(); 5457 while (isa<ArrayType>(CToTy)) 5458 CToTy = CFromTy->getAs<ArrayType>()->getElementType(); 5459 5460 Qualifiers FromQs = CFromTy.getQualifiers(); 5461 Qualifiers ToQs = CToTy.getQualifiers(); 5462 5463 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 5464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 5465 << (unsigned) FnKind << FnDesc 5466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5467 << FromTy 5468 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 5469 << (unsigned) isObjectArgument << I+1; 5470 return; 5471 } 5472 5473 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5474 assert(CVR && "unexpected qualifiers mismatch"); 5475 5476 if (isObjectArgument) { 5477 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 5478 << (unsigned) FnKind << FnDesc 5479 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5480 << FromTy << (CVR - 1); 5481 } else { 5482 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 5483 << (unsigned) FnKind << FnDesc 5484 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5485 << FromTy << (CVR - 1) << I+1; 5486 } 5487 return; 5488 } 5489 5490 // Diagnose references or pointers to incomplete types differently, 5491 // since it's far from impossible that the incompleteness triggered 5492 // the failure. 5493 QualType TempFromTy = FromTy.getNonReferenceType(); 5494 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 5495 TempFromTy = PTy->getPointeeType(); 5496 if (TempFromTy->isIncompleteType()) { 5497 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 5498 << (unsigned) FnKind << FnDesc 5499 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5500 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 5501 return; 5502 } 5503 5504 // Diagnose base -> derived pointer conversions. 5505 unsigned BaseToDerivedConversion = 0; 5506 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 5507 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 5508 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 5509 FromPtrTy->getPointeeType()) && 5510 !FromPtrTy->getPointeeType()->isIncompleteType() && 5511 !ToPtrTy->getPointeeType()->isIncompleteType() && 5512 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 5513 FromPtrTy->getPointeeType())) 5514 BaseToDerivedConversion = 1; 5515 } 5516 } else if (const ObjCObjectPointerType *FromPtrTy 5517 = FromTy->getAs<ObjCObjectPointerType>()) { 5518 if (const ObjCObjectPointerType *ToPtrTy 5519 = ToTy->getAs<ObjCObjectPointerType>()) 5520 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 5521 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 5522 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 5523 FromPtrTy->getPointeeType()) && 5524 FromIface->isSuperClassOf(ToIface)) 5525 BaseToDerivedConversion = 2; 5526 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 5527 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 5528 !FromTy->isIncompleteType() && 5529 !ToRefTy->getPointeeType()->isIncompleteType() && 5530 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 5531 BaseToDerivedConversion = 3; 5532 } 5533 5534 if (BaseToDerivedConversion) { 5535 S.Diag(Fn->getLocation(), 5536 diag::note_ovl_candidate_bad_base_to_derived_conv) 5537 << (unsigned) FnKind << FnDesc 5538 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5539 << (BaseToDerivedConversion - 1) 5540 << FromTy << ToTy << I+1; 5541 return; 5542 } 5543 5544 // TODO: specialize more based on the kind of mismatch 5545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv) 5546 << (unsigned) FnKind << FnDesc 5547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5548 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 5549} 5550 5551void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 5552 unsigned NumFormalArgs) { 5553 // TODO: treat calls to a missing default constructor as a special case 5554 5555 FunctionDecl *Fn = Cand->Function; 5556 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 5557 5558 unsigned MinParams = Fn->getMinRequiredArguments(); 5559 5560 // at least / at most / exactly 5561 // FIXME: variadic templates "at most" should account for parameter packs 5562 unsigned mode, modeCount; 5563 if (NumFormalArgs < MinParams) { 5564 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 5565 (Cand->FailureKind == ovl_fail_bad_deduction && 5566 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 5567 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic()) 5568 mode = 0; // "at least" 5569 else 5570 mode = 2; // "exactly" 5571 modeCount = MinParams; 5572 } else { 5573 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 5574 (Cand->FailureKind == ovl_fail_bad_deduction && 5575 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 5576 if (MinParams != FnTy->getNumArgs()) 5577 mode = 1; // "at most" 5578 else 5579 mode = 2; // "exactly" 5580 modeCount = FnTy->getNumArgs(); 5581 } 5582 5583 std::string Description; 5584 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 5585 5586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 5587 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 5588 << modeCount << NumFormalArgs; 5589} 5590 5591/// Diagnose a failed template-argument deduction. 5592void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 5593 Expr **Args, unsigned NumArgs) { 5594 FunctionDecl *Fn = Cand->Function; // pattern 5595 5596 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 5597 NamedDecl *ParamD; 5598 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 5599 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 5600 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 5601 switch (Cand->DeductionFailure.Result) { 5602 case Sema::TDK_Success: 5603 llvm_unreachable("TDK_success while diagnosing bad deduction"); 5604 5605 case Sema::TDK_Incomplete: { 5606 assert(ParamD && "no parameter found for incomplete deduction result"); 5607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 5608 << ParamD->getDeclName(); 5609 return; 5610 } 5611 5612 case Sema::TDK_Underqualified: { 5613 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 5614 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 5615 5616 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 5617 5618 // Param will have been canonicalized, but it should just be a 5619 // qualified version of ParamD, so move the qualifiers to that. 5620 QualifierCollector Qs(S.Context); 5621 Qs.strip(Param); 5622 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl()); 5623 assert(S.Context.hasSameType(Param, NonCanonParam)); 5624 5625 // Arg has also been canonicalized, but there's nothing we can do 5626 // about that. It also doesn't matter as much, because it won't 5627 // have any template parameters in it (because deduction isn't 5628 // done on dependent types). 5629 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 5630 5631 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 5632 << ParamD->getDeclName() << Arg << NonCanonParam; 5633 return; 5634 } 5635 5636 case Sema::TDK_Inconsistent: { 5637 assert(ParamD && "no parameter found for inconsistent deduction result"); 5638 int which = 0; 5639 if (isa<TemplateTypeParmDecl>(ParamD)) 5640 which = 0; 5641 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 5642 which = 1; 5643 else { 5644 which = 2; 5645 } 5646 5647 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 5648 << which << ParamD->getDeclName() 5649 << *Cand->DeductionFailure.getFirstArg() 5650 << *Cand->DeductionFailure.getSecondArg(); 5651 return; 5652 } 5653 5654 case Sema::TDK_InvalidExplicitArguments: 5655 assert(ParamD && "no parameter found for invalid explicit arguments"); 5656 if (ParamD->getDeclName()) 5657 S.Diag(Fn->getLocation(), 5658 diag::note_ovl_candidate_explicit_arg_mismatch_named) 5659 << ParamD->getDeclName(); 5660 else { 5661 int index = 0; 5662 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 5663 index = TTP->getIndex(); 5664 else if (NonTypeTemplateParmDecl *NTTP 5665 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 5666 index = NTTP->getIndex(); 5667 else 5668 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 5669 S.Diag(Fn->getLocation(), 5670 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 5671 << (index + 1); 5672 } 5673 return; 5674 5675 case Sema::TDK_TooManyArguments: 5676 case Sema::TDK_TooFewArguments: 5677 DiagnoseArityMismatch(S, Cand, NumArgs); 5678 return; 5679 5680 case Sema::TDK_InstantiationDepth: 5681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 5682 return; 5683 5684 case Sema::TDK_SubstitutionFailure: { 5685 std::string ArgString; 5686 if (TemplateArgumentList *Args 5687 = Cand->DeductionFailure.getTemplateArgumentList()) 5688 ArgString = S.getTemplateArgumentBindingsText( 5689 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), 5690 *Args); 5691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 5692 << ArgString; 5693 return; 5694 } 5695 5696 // TODO: diagnose these individually, then kill off 5697 // note_ovl_candidate_bad_deduction, which is uselessly vague. 5698 case Sema::TDK_NonDeducedMismatch: 5699 case Sema::TDK_FailedOverloadResolution: 5700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 5701 return; 5702 } 5703} 5704 5705/// Generates a 'note' diagnostic for an overload candidate. We've 5706/// already generated a primary error at the call site. 5707/// 5708/// It really does need to be a single diagnostic with its caret 5709/// pointed at the candidate declaration. Yes, this creates some 5710/// major challenges of technical writing. Yes, this makes pointing 5711/// out problems with specific arguments quite awkward. It's still 5712/// better than generating twenty screens of text for every failed 5713/// overload. 5714/// 5715/// It would be great to be able to express per-candidate problems 5716/// more richly for those diagnostic clients that cared, but we'd 5717/// still have to be just as careful with the default diagnostics. 5718void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 5719 Expr **Args, unsigned NumArgs) { 5720 FunctionDecl *Fn = Cand->Function; 5721 5722 // Note deleted candidates, but only if they're viable. 5723 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) { 5724 std::string FnDesc; 5725 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 5726 5727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 5728 << FnKind << FnDesc << Fn->isDeleted(); 5729 return; 5730 } 5731 5732 // We don't really have anything else to say about viable candidates. 5733 if (Cand->Viable) { 5734 S.NoteOverloadCandidate(Fn); 5735 return; 5736 } 5737 5738 switch (Cand->FailureKind) { 5739 case ovl_fail_too_many_arguments: 5740 case ovl_fail_too_few_arguments: 5741 return DiagnoseArityMismatch(S, Cand, NumArgs); 5742 5743 case ovl_fail_bad_deduction: 5744 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 5745 5746 case ovl_fail_trivial_conversion: 5747 case ovl_fail_bad_final_conversion: 5748 case ovl_fail_final_conversion_not_exact: 5749 return S.NoteOverloadCandidate(Fn); 5750 5751 case ovl_fail_bad_conversion: { 5752 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 5753 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 5754 if (Cand->Conversions[I].isBad()) 5755 return DiagnoseBadConversion(S, Cand, I); 5756 5757 // FIXME: this currently happens when we're called from SemaInit 5758 // when user-conversion overload fails. Figure out how to handle 5759 // those conditions and diagnose them well. 5760 return S.NoteOverloadCandidate(Fn); 5761 } 5762 } 5763} 5764 5765void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 5766 // Desugar the type of the surrogate down to a function type, 5767 // retaining as many typedefs as possible while still showing 5768 // the function type (and, therefore, its parameter types). 5769 QualType FnType = Cand->Surrogate->getConversionType(); 5770 bool isLValueReference = false; 5771 bool isRValueReference = false; 5772 bool isPointer = false; 5773 if (const LValueReferenceType *FnTypeRef = 5774 FnType->getAs<LValueReferenceType>()) { 5775 FnType = FnTypeRef->getPointeeType(); 5776 isLValueReference = true; 5777 } else if (const RValueReferenceType *FnTypeRef = 5778 FnType->getAs<RValueReferenceType>()) { 5779 FnType = FnTypeRef->getPointeeType(); 5780 isRValueReference = true; 5781 } 5782 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 5783 FnType = FnTypePtr->getPointeeType(); 5784 isPointer = true; 5785 } 5786 // Desugar down to a function type. 5787 FnType = QualType(FnType->getAs<FunctionType>(), 0); 5788 // Reconstruct the pointer/reference as appropriate. 5789 if (isPointer) FnType = S.Context.getPointerType(FnType); 5790 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 5791 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 5792 5793 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 5794 << FnType; 5795} 5796 5797void NoteBuiltinOperatorCandidate(Sema &S, 5798 const char *Opc, 5799 SourceLocation OpLoc, 5800 OverloadCandidate *Cand) { 5801 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 5802 std::string TypeStr("operator"); 5803 TypeStr += Opc; 5804 TypeStr += "("; 5805 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 5806 if (Cand->Conversions.size() == 1) { 5807 TypeStr += ")"; 5808 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 5809 } else { 5810 TypeStr += ", "; 5811 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 5812 TypeStr += ")"; 5813 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 5814 } 5815} 5816 5817void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 5818 OverloadCandidate *Cand) { 5819 unsigned NoOperands = Cand->Conversions.size(); 5820 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 5821 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 5822 if (ICS.isBad()) break; // all meaningless after first invalid 5823 if (!ICS.isAmbiguous()) continue; 5824 5825 S.DiagnoseAmbiguousConversion(ICS, OpLoc, 5826 S.PDiag(diag::note_ambiguous_type_conversion)); 5827 } 5828} 5829 5830SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 5831 if (Cand->Function) 5832 return Cand->Function->getLocation(); 5833 if (Cand->IsSurrogate) 5834 return Cand->Surrogate->getLocation(); 5835 return SourceLocation(); 5836} 5837 5838struct CompareOverloadCandidatesForDisplay { 5839 Sema &S; 5840 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 5841 5842 bool operator()(const OverloadCandidate *L, 5843 const OverloadCandidate *R) { 5844 // Fast-path this check. 5845 if (L == R) return false; 5846 5847 // Order first by viability. 5848 if (L->Viable) { 5849 if (!R->Viable) return true; 5850 5851 // TODO: introduce a tri-valued comparison for overload 5852 // candidates. Would be more worthwhile if we had a sort 5853 // that could exploit it. 5854 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true; 5855 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false; 5856 } else if (R->Viable) 5857 return false; 5858 5859 assert(L->Viable == R->Viable); 5860 5861 // Criteria by which we can sort non-viable candidates: 5862 if (!L->Viable) { 5863 // 1. Arity mismatches come after other candidates. 5864 if (L->FailureKind == ovl_fail_too_many_arguments || 5865 L->FailureKind == ovl_fail_too_few_arguments) 5866 return false; 5867 if (R->FailureKind == ovl_fail_too_many_arguments || 5868 R->FailureKind == ovl_fail_too_few_arguments) 5869 return true; 5870 5871 // 2. Bad conversions come first and are ordered by the number 5872 // of bad conversions and quality of good conversions. 5873 if (L->FailureKind == ovl_fail_bad_conversion) { 5874 if (R->FailureKind != ovl_fail_bad_conversion) 5875 return true; 5876 5877 // If there's any ordering between the defined conversions... 5878 // FIXME: this might not be transitive. 5879 assert(L->Conversions.size() == R->Conversions.size()); 5880 5881 int leftBetter = 0; 5882 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 5883 for (unsigned E = L->Conversions.size(); I != E; ++I) { 5884 switch (S.CompareImplicitConversionSequences(L->Conversions[I], 5885 R->Conversions[I])) { 5886 case ImplicitConversionSequence::Better: 5887 leftBetter++; 5888 break; 5889 5890 case ImplicitConversionSequence::Worse: 5891 leftBetter--; 5892 break; 5893 5894 case ImplicitConversionSequence::Indistinguishable: 5895 break; 5896 } 5897 } 5898 if (leftBetter > 0) return true; 5899 if (leftBetter < 0) return false; 5900 5901 } else if (R->FailureKind == ovl_fail_bad_conversion) 5902 return false; 5903 5904 // TODO: others? 5905 } 5906 5907 // Sort everything else by location. 5908 SourceLocation LLoc = GetLocationForCandidate(L); 5909 SourceLocation RLoc = GetLocationForCandidate(R); 5910 5911 // Put candidates without locations (e.g. builtins) at the end. 5912 if (LLoc.isInvalid()) return false; 5913 if (RLoc.isInvalid()) return true; 5914 5915 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 5916 } 5917}; 5918 5919/// CompleteNonViableCandidate - Normally, overload resolution only 5920/// computes up to the first 5921void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 5922 Expr **Args, unsigned NumArgs) { 5923 assert(!Cand->Viable); 5924 5925 // Don't do anything on failures other than bad conversion. 5926 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 5927 5928 // Skip forward to the first bad conversion. 5929 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 5930 unsigned ConvCount = Cand->Conversions.size(); 5931 while (true) { 5932 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 5933 ConvIdx++; 5934 if (Cand->Conversions[ConvIdx - 1].isBad()) 5935 break; 5936 } 5937 5938 if (ConvIdx == ConvCount) 5939 return; 5940 5941 assert(!Cand->Conversions[ConvIdx].isInitialized() && 5942 "remaining conversion is initialized?"); 5943 5944 // FIXME: this should probably be preserved from the overload 5945 // operation somehow. 5946 bool SuppressUserConversions = false; 5947 5948 const FunctionProtoType* Proto; 5949 unsigned ArgIdx = ConvIdx; 5950 5951 if (Cand->IsSurrogate) { 5952 QualType ConvType 5953 = Cand->Surrogate->getConversionType().getNonReferenceType(); 5954 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 5955 ConvType = ConvPtrType->getPointeeType(); 5956 Proto = ConvType->getAs<FunctionProtoType>(); 5957 ArgIdx--; 5958 } else if (Cand->Function) { 5959 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 5960 if (isa<CXXMethodDecl>(Cand->Function) && 5961 !isa<CXXConstructorDecl>(Cand->Function)) 5962 ArgIdx--; 5963 } else { 5964 // Builtin binary operator with a bad first conversion. 5965 assert(ConvCount <= 3); 5966 for (; ConvIdx != ConvCount; ++ConvIdx) 5967 Cand->Conversions[ConvIdx] 5968 = TryCopyInitialization(S, Args[ConvIdx], 5969 Cand->BuiltinTypes.ParamTypes[ConvIdx], 5970 SuppressUserConversions, 5971 /*InOverloadResolution*/ true); 5972 return; 5973 } 5974 5975 // Fill in the rest of the conversions. 5976 unsigned NumArgsInProto = Proto->getNumArgs(); 5977 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 5978 if (ArgIdx < NumArgsInProto) 5979 Cand->Conversions[ConvIdx] 5980 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 5981 SuppressUserConversions, 5982 /*InOverloadResolution=*/true); 5983 else 5984 Cand->Conversions[ConvIdx].setEllipsis(); 5985 } 5986} 5987 5988} // end anonymous namespace 5989 5990/// PrintOverloadCandidates - When overload resolution fails, prints 5991/// diagnostic messages containing the candidates in the candidate 5992/// set. 5993void 5994Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 5995 OverloadCandidateDisplayKind OCD, 5996 Expr **Args, unsigned NumArgs, 5997 const char *Opc, 5998 SourceLocation OpLoc) { 5999 // Sort the candidates by viability and position. Sorting directly would 6000 // be prohibitive, so we make a set of pointers and sort those. 6001 llvm::SmallVector<OverloadCandidate*, 32> Cands; 6002 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size()); 6003 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 6004 LastCand = CandidateSet.end(); 6005 Cand != LastCand; ++Cand) { 6006 if (Cand->Viable) 6007 Cands.push_back(Cand); 6008 else if (OCD == OCD_AllCandidates) { 6009 CompleteNonViableCandidate(*this, Cand, Args, NumArgs); 6010 if (Cand->Function || Cand->IsSurrogate) 6011 Cands.push_back(Cand); 6012 // Otherwise, this a non-viable builtin candidate. We do not, in general, 6013 // want to list every possible builtin candidate. 6014 } 6015 } 6016 6017 std::sort(Cands.begin(), Cands.end(), 6018 CompareOverloadCandidatesForDisplay(*this)); 6019 6020 bool ReportedAmbiguousConversions = false; 6021 6022 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E; 6023 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads(); 6024 unsigned CandsShown = 0; 6025 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 6026 OverloadCandidate *Cand = *I; 6027 6028 // Set an arbitrary limit on the number of candidate functions we'll spam 6029 // the user with. FIXME: This limit should depend on details of the 6030 // candidate list. 6031 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) { 6032 break; 6033 } 6034 ++CandsShown; 6035 6036 if (Cand->Function) 6037 NoteFunctionCandidate(*this, Cand, Args, NumArgs); 6038 else if (Cand->IsSurrogate) 6039 NoteSurrogateCandidate(*this, Cand); 6040 else { 6041 assert(Cand->Viable && 6042 "Non-viable built-in candidates are not added to Cands."); 6043 // Generally we only see ambiguities including viable builtin 6044 // operators if overload resolution got screwed up by an 6045 // ambiguous user-defined conversion. 6046 // 6047 // FIXME: It's quite possible for different conversions to see 6048 // different ambiguities, though. 6049 if (!ReportedAmbiguousConversions) { 6050 NoteAmbiguousUserConversions(*this, OpLoc, Cand); 6051 ReportedAmbiguousConversions = true; 6052 } 6053 6054 // If this is a viable builtin, print it. 6055 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand); 6056 } 6057 } 6058 6059 if (I != E) 6060 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 6061} 6062 6063static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) { 6064 if (isa<UnresolvedLookupExpr>(E)) 6065 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D); 6066 6067 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D); 6068} 6069 6070/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 6071/// an overloaded function (C++ [over.over]), where @p From is an 6072/// expression with overloaded function type and @p ToType is the type 6073/// we're trying to resolve to. For example: 6074/// 6075/// @code 6076/// int f(double); 6077/// int f(int); 6078/// 6079/// int (*pfd)(double) = f; // selects f(double) 6080/// @endcode 6081/// 6082/// This routine returns the resulting FunctionDecl if it could be 6083/// resolved, and NULL otherwise. When @p Complain is true, this 6084/// routine will emit diagnostics if there is an error. 6085FunctionDecl * 6086Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 6087 bool Complain, 6088 DeclAccessPair &FoundResult) { 6089 QualType FunctionType = ToType; 6090 bool IsMember = false; 6091 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>()) 6092 FunctionType = ToTypePtr->getPointeeType(); 6093 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>()) 6094 FunctionType = ToTypeRef->getPointeeType(); 6095 else if (const MemberPointerType *MemTypePtr = 6096 ToType->getAs<MemberPointerType>()) { 6097 FunctionType = MemTypePtr->getPointeeType(); 6098 IsMember = true; 6099 } 6100 6101 // C++ [over.over]p1: 6102 // [...] [Note: any redundant set of parentheses surrounding the 6103 // overloaded function name is ignored (5.1). ] 6104 // C++ [over.over]p1: 6105 // [...] The overloaded function name can be preceded by the & 6106 // operator. 6107 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer(); 6108 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0; 6109 if (OvlExpr->hasExplicitTemplateArgs()) { 6110 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer); 6111 ExplicitTemplateArgs = &ETABuffer; 6112 } 6113 6114 // We expect a pointer or reference to function, or a function pointer. 6115 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType(); 6116 if (!FunctionType->isFunctionType()) { 6117 if (Complain) 6118 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 6119 << OvlExpr->getName() << ToType; 6120 6121 return 0; 6122 } 6123 6124 assert(From->getType() == Context.OverloadTy); 6125 6126 // Look through all of the overloaded functions, searching for one 6127 // whose type matches exactly. 6128 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 6129 llvm::SmallVector<FunctionDecl *, 4> NonMatches; 6130 6131 bool FoundNonTemplateFunction = false; 6132 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6133 E = OvlExpr->decls_end(); I != E; ++I) { 6134 // Look through any using declarations to find the underlying function. 6135 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 6136 6137 // C++ [over.over]p3: 6138 // Non-member functions and static member functions match 6139 // targets of type "pointer-to-function" or "reference-to-function." 6140 // Nonstatic member functions match targets of 6141 // type "pointer-to-member-function." 6142 // Note that according to DR 247, the containing class does not matter. 6143 6144 if (FunctionTemplateDecl *FunctionTemplate 6145 = dyn_cast<FunctionTemplateDecl>(Fn)) { 6146 if (CXXMethodDecl *Method 6147 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 6148 // Skip non-static function templates when converting to pointer, and 6149 // static when converting to member pointer. 6150 if (Method->isStatic() == IsMember) 6151 continue; 6152 } else if (IsMember) 6153 continue; 6154 6155 // C++ [over.over]p2: 6156 // If the name is a function template, template argument deduction is 6157 // done (14.8.2.2), and if the argument deduction succeeds, the 6158 // resulting template argument list is used to generate a single 6159 // function template specialization, which is added to the set of 6160 // overloaded functions considered. 6161 // FIXME: We don't really want to build the specialization here, do we? 6162 FunctionDecl *Specialization = 0; 6163 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 6164 if (TemplateDeductionResult Result 6165 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 6166 FunctionType, Specialization, Info)) { 6167 // FIXME: make a note of the failed deduction for diagnostics. 6168 (void)Result; 6169 } else { 6170 // FIXME: If the match isn't exact, shouldn't we just drop this as 6171 // a candidate? Find a testcase before changing the code. 6172 assert(FunctionType 6173 == Context.getCanonicalType(Specialization->getType())); 6174 Matches.push_back(std::make_pair(I.getPair(), 6175 cast<FunctionDecl>(Specialization->getCanonicalDecl()))); 6176 } 6177 6178 continue; 6179 } 6180 6181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 6182 // Skip non-static functions when converting to pointer, and static 6183 // when converting to member pointer. 6184 if (Method->isStatic() == IsMember) 6185 continue; 6186 6187 // If we have explicit template arguments, skip non-templates. 6188 if (OvlExpr->hasExplicitTemplateArgs()) 6189 continue; 6190 } else if (IsMember) 6191 continue; 6192 6193 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 6194 QualType ResultTy; 6195 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) || 6196 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType, 6197 ResultTy)) { 6198 Matches.push_back(std::make_pair(I.getPair(), 6199 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 6200 FoundNonTemplateFunction = true; 6201 } 6202 } 6203 } 6204 6205 // If there were 0 or 1 matches, we're done. 6206 if (Matches.empty()) { 6207 if (Complain) { 6208 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable) 6209 << OvlExpr->getName() << FunctionType; 6210 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6211 E = OvlExpr->decls_end(); 6212 I != E; ++I) 6213 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 6214 NoteOverloadCandidate(F); 6215 } 6216 6217 return 0; 6218 } else if (Matches.size() == 1) { 6219 FunctionDecl *Result = Matches[0].second; 6220 FoundResult = Matches[0].first; 6221 MarkDeclarationReferenced(From->getLocStart(), Result); 6222 if (Complain) 6223 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first); 6224 return Result; 6225 } 6226 6227 // C++ [over.over]p4: 6228 // If more than one function is selected, [...] 6229 if (!FoundNonTemplateFunction) { 6230 // [...] and any given function template specialization F1 is 6231 // eliminated if the set contains a second function template 6232 // specialization whose function template is more specialized 6233 // than the function template of F1 according to the partial 6234 // ordering rules of 14.5.5.2. 6235 6236 // The algorithm specified above is quadratic. We instead use a 6237 // two-pass algorithm (similar to the one used to identify the 6238 // best viable function in an overload set) that identifies the 6239 // best function template (if it exists). 6240 6241 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 6242 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 6243 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 6244 6245 UnresolvedSetIterator Result = 6246 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 6247 TPOC_Other, From->getLocStart(), 6248 PDiag(), 6249 PDiag(diag::err_addr_ovl_ambiguous) 6250 << Matches[0].second->getDeclName(), 6251 PDiag(diag::note_ovl_candidate) 6252 << (unsigned) oc_function_template); 6253 assert(Result != MatchesCopy.end() && "no most-specialized template"); 6254 MarkDeclarationReferenced(From->getLocStart(), *Result); 6255 FoundResult = Matches[Result - MatchesCopy.begin()].first; 6256 if (Complain) { 6257 CheckUnresolvedAccess(*this, OvlExpr, FoundResult); 6258 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc()); 6259 } 6260 return cast<FunctionDecl>(*Result); 6261 } 6262 6263 // [...] any function template specializations in the set are 6264 // eliminated if the set also contains a non-template function, [...] 6265 for (unsigned I = 0, N = Matches.size(); I != N; ) { 6266 if (Matches[I].second->getPrimaryTemplate() == 0) 6267 ++I; 6268 else { 6269 Matches[I] = Matches[--N]; 6270 Matches.set_size(N); 6271 } 6272 } 6273 6274 // [...] After such eliminations, if any, there shall remain exactly one 6275 // selected function. 6276 if (Matches.size() == 1) { 6277 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second); 6278 FoundResult = Matches[0].first; 6279 if (Complain) { 6280 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first); 6281 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc()); 6282 } 6283 return cast<FunctionDecl>(Matches[0].second); 6284 } 6285 6286 // FIXME: We should probably return the same thing that BestViableFunction 6287 // returns (even if we issue the diagnostics here). 6288 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous) 6289 << Matches[0].second->getDeclName(); 6290 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 6291 NoteOverloadCandidate(Matches[I].second); 6292 return 0; 6293} 6294 6295/// \brief Given an expression that refers to an overloaded function, try to 6296/// resolve that overloaded function expression down to a single function. 6297/// 6298/// This routine can only resolve template-ids that refer to a single function 6299/// template, where that template-id refers to a single template whose template 6300/// arguments are either provided by the template-id or have defaults, 6301/// as described in C++0x [temp.arg.explicit]p3. 6302FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) { 6303 // C++ [over.over]p1: 6304 // [...] [Note: any redundant set of parentheses surrounding the 6305 // overloaded function name is ignored (5.1). ] 6306 // C++ [over.over]p1: 6307 // [...] The overloaded function name can be preceded by the & 6308 // operator. 6309 6310 if (From->getType() != Context.OverloadTy) 6311 return 0; 6312 6313 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer(); 6314 6315 // If we didn't actually find any template-ids, we're done. 6316 if (!OvlExpr->hasExplicitTemplateArgs()) 6317 return 0; 6318 6319 TemplateArgumentListInfo ExplicitTemplateArgs; 6320 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 6321 6322 // Look through all of the overloaded functions, searching for one 6323 // whose type matches exactly. 6324 FunctionDecl *Matched = 0; 6325 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6326 E = OvlExpr->decls_end(); I != E; ++I) { 6327 // C++0x [temp.arg.explicit]p3: 6328 // [...] In contexts where deduction is done and fails, or in contexts 6329 // where deduction is not done, if a template argument list is 6330 // specified and it, along with any default template arguments, 6331 // identifies a single function template specialization, then the 6332 // template-id is an lvalue for the function template specialization. 6333 FunctionTemplateDecl *FunctionTemplate 6334 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 6335 6336 // C++ [over.over]p2: 6337 // If the name is a function template, template argument deduction is 6338 // done (14.8.2.2), and if the argument deduction succeeds, the 6339 // resulting template argument list is used to generate a single 6340 // function template specialization, which is added to the set of 6341 // overloaded functions considered. 6342 FunctionDecl *Specialization = 0; 6343 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 6344 if (TemplateDeductionResult Result 6345 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 6346 Specialization, Info)) { 6347 // FIXME: make a note of the failed deduction for diagnostics. 6348 (void)Result; 6349 continue; 6350 } 6351 6352 // Multiple matches; we can't resolve to a single declaration. 6353 if (Matched) 6354 return 0; 6355 6356 Matched = Specialization; 6357 } 6358 6359 return Matched; 6360} 6361 6362/// \brief Add a single candidate to the overload set. 6363static void AddOverloadedCallCandidate(Sema &S, 6364 DeclAccessPair FoundDecl, 6365 const TemplateArgumentListInfo *ExplicitTemplateArgs, 6366 Expr **Args, unsigned NumArgs, 6367 OverloadCandidateSet &CandidateSet, 6368 bool PartialOverloading) { 6369 NamedDecl *Callee = FoundDecl.getDecl(); 6370 if (isa<UsingShadowDecl>(Callee)) 6371 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 6372 6373 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 6374 assert(!ExplicitTemplateArgs && "Explicit template arguments?"); 6375 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 6376 false, PartialOverloading); 6377 return; 6378 } 6379 6380 if (FunctionTemplateDecl *FuncTemplate 6381 = dyn_cast<FunctionTemplateDecl>(Callee)) { 6382 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 6383 ExplicitTemplateArgs, 6384 Args, NumArgs, CandidateSet); 6385 return; 6386 } 6387 6388 assert(false && "unhandled case in overloaded call candidate"); 6389 6390 // do nothing? 6391} 6392 6393/// \brief Add the overload candidates named by callee and/or found by argument 6394/// dependent lookup to the given overload set. 6395void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 6396 Expr **Args, unsigned NumArgs, 6397 OverloadCandidateSet &CandidateSet, 6398 bool PartialOverloading) { 6399 6400#ifndef NDEBUG 6401 // Verify that ArgumentDependentLookup is consistent with the rules 6402 // in C++0x [basic.lookup.argdep]p3: 6403 // 6404 // Let X be the lookup set produced by unqualified lookup (3.4.1) 6405 // and let Y be the lookup set produced by argument dependent 6406 // lookup (defined as follows). If X contains 6407 // 6408 // -- a declaration of a class member, or 6409 // 6410 // -- a block-scope function declaration that is not a 6411 // using-declaration, or 6412 // 6413 // -- a declaration that is neither a function or a function 6414 // template 6415 // 6416 // then Y is empty. 6417 6418 if (ULE->requiresADL()) { 6419 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 6420 E = ULE->decls_end(); I != E; ++I) { 6421 assert(!(*I)->getDeclContext()->isRecord()); 6422 assert(isa<UsingShadowDecl>(*I) || 6423 !(*I)->getDeclContext()->isFunctionOrMethod()); 6424 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 6425 } 6426 } 6427#endif 6428 6429 // It would be nice to avoid this copy. 6430 TemplateArgumentListInfo TABuffer; 6431 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 6432 if (ULE->hasExplicitTemplateArgs()) { 6433 ULE->copyTemplateArgumentsInto(TABuffer); 6434 ExplicitTemplateArgs = &TABuffer; 6435 } 6436 6437 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 6438 E = ULE->decls_end(); I != E; ++I) 6439 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 6440 Args, NumArgs, CandidateSet, 6441 PartialOverloading); 6442 6443 if (ULE->requiresADL()) 6444 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 6445 Args, NumArgs, 6446 ExplicitTemplateArgs, 6447 CandidateSet, 6448 PartialOverloading); 6449} 6450 6451/// Attempts to recover from a call where no functions were found. 6452/// 6453/// Returns true if new candidates were found. 6454static Sema::OwningExprResult 6455BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 6456 UnresolvedLookupExpr *ULE, 6457 SourceLocation LParenLoc, 6458 Expr **Args, unsigned NumArgs, 6459 SourceLocation *CommaLocs, 6460 SourceLocation RParenLoc) { 6461 6462 CXXScopeSpec SS; 6463 if (ULE->getQualifier()) { 6464 SS.setScopeRep(ULE->getQualifier()); 6465 SS.setRange(ULE->getQualifierRange()); 6466 } 6467 6468 TemplateArgumentListInfo TABuffer; 6469 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 6470 if (ULE->hasExplicitTemplateArgs()) { 6471 ULE->copyTemplateArgumentsInto(TABuffer); 6472 ExplicitTemplateArgs = &TABuffer; 6473 } 6474 6475 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 6476 Sema::LookupOrdinaryName); 6477 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)) 6478 return SemaRef.ExprError(); 6479 6480 assert(!R.empty() && "lookup results empty despite recovery"); 6481 6482 // Build an implicit member call if appropriate. Just drop the 6483 // casts and such from the call, we don't really care. 6484 Sema::OwningExprResult NewFn = SemaRef.ExprError(); 6485 if ((*R.begin())->isCXXClassMember()) 6486 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs); 6487 else if (ExplicitTemplateArgs) 6488 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 6489 else 6490 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 6491 6492 if (NewFn.isInvalid()) 6493 return SemaRef.ExprError(); 6494 6495 // This shouldn't cause an infinite loop because we're giving it 6496 // an expression with non-empty lookup results, which should never 6497 // end up here. 6498 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc, 6499 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs), 6500 CommaLocs, RParenLoc); 6501} 6502 6503/// ResolveOverloadedCallFn - Given the call expression that calls Fn 6504/// (which eventually refers to the declaration Func) and the call 6505/// arguments Args/NumArgs, attempt to resolve the function call down 6506/// to a specific function. If overload resolution succeeds, returns 6507/// the function declaration produced by overload 6508/// resolution. Otherwise, emits diagnostics, deletes all of the 6509/// arguments and Fn, and returns NULL. 6510Sema::OwningExprResult 6511Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 6512 SourceLocation LParenLoc, 6513 Expr **Args, unsigned NumArgs, 6514 SourceLocation *CommaLocs, 6515 SourceLocation RParenLoc) { 6516#ifndef NDEBUG 6517 if (ULE->requiresADL()) { 6518 // To do ADL, we must have found an unqualified name. 6519 assert(!ULE->getQualifier() && "qualified name with ADL"); 6520 6521 // We don't perform ADL for implicit declarations of builtins. 6522 // Verify that this was correctly set up. 6523 FunctionDecl *F; 6524 if (ULE->decls_begin() + 1 == ULE->decls_end() && 6525 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 6526 F->getBuiltinID() && F->isImplicit()) 6527 assert(0 && "performing ADL for builtin"); 6528 6529 // We don't perform ADL in C. 6530 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 6531 } 6532#endif 6533 6534 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 6535 6536 // Add the functions denoted by the callee to the set of candidate 6537 // functions, including those from argument-dependent lookup. 6538 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 6539 6540 // If we found nothing, try to recover. 6541 // AddRecoveryCallCandidates diagnoses the error itself, so we just 6542 // bailout out if it fails. 6543 if (CandidateSet.empty()) 6544 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 6545 CommaLocs, RParenLoc); 6546 6547 OverloadCandidateSet::iterator Best; 6548 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) { 6549 case OR_Success: { 6550 FunctionDecl *FDecl = Best->Function; 6551 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 6552 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc()); 6553 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 6554 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc); 6555 } 6556 6557 case OR_No_Viable_Function: 6558 Diag(Fn->getSourceRange().getBegin(), 6559 diag::err_ovl_no_viable_function_in_call) 6560 << ULE->getName() << Fn->getSourceRange(); 6561 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6562 break; 6563 6564 case OR_Ambiguous: 6565 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 6566 << ULE->getName() << Fn->getSourceRange(); 6567 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 6568 break; 6569 6570 case OR_Deleted: 6571 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 6572 << Best->Function->isDeleted() 6573 << ULE->getName() 6574 << Fn->getSourceRange(); 6575 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6576 break; 6577 } 6578 6579 // Overload resolution failed. 6580 return ExprError(); 6581} 6582 6583static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 6584 return Functions.size() > 1 || 6585 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 6586} 6587 6588/// \brief Create a unary operation that may resolve to an overloaded 6589/// operator. 6590/// 6591/// \param OpLoc The location of the operator itself (e.g., '*'). 6592/// 6593/// \param OpcIn The UnaryOperator::Opcode that describes this 6594/// operator. 6595/// 6596/// \param Functions The set of non-member functions that will be 6597/// considered by overload resolution. The caller needs to build this 6598/// set based on the context using, e.g., 6599/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 6600/// set should not contain any member functions; those will be added 6601/// by CreateOverloadedUnaryOp(). 6602/// 6603/// \param input The input argument. 6604Sema::OwningExprResult 6605Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 6606 const UnresolvedSetImpl &Fns, 6607 ExprArg input) { 6608 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 6609 Expr *Input = (Expr *)input.get(); 6610 6611 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 6612 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 6613 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6614 6615 Expr *Args[2] = { Input, 0 }; 6616 unsigned NumArgs = 1; 6617 6618 // For post-increment and post-decrement, add the implicit '0' as 6619 // the second argument, so that we know this is a post-increment or 6620 // post-decrement. 6621 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) { 6622 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 6623 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy, 6624 SourceLocation()); 6625 NumArgs = 2; 6626 } 6627 6628 if (Input->isTypeDependent()) { 6629 if (Fns.empty()) 6630 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(), 6631 Opc, 6632 Context.DependentTy, 6633 OpLoc)); 6634 6635 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 6636 UnresolvedLookupExpr *Fn 6637 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 6638 0, SourceRange(), OpName, OpLoc, 6639 /*ADL*/ true, IsOverloaded(Fns), 6640 Fns.begin(), Fns.end()); 6641 input.release(); 6642 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 6643 &Args[0], NumArgs, 6644 Context.DependentTy, 6645 OpLoc)); 6646 } 6647 6648 // Build an empty overload set. 6649 OverloadCandidateSet CandidateSet(OpLoc); 6650 6651 // Add the candidates from the given function set. 6652 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 6653 6654 // Add operator candidates that are member functions. 6655 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 6656 6657 // Add candidates from ADL. 6658 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 6659 Args, NumArgs, 6660 /*ExplicitTemplateArgs*/ 0, 6661 CandidateSet); 6662 6663 // Add builtin operator candidates. 6664 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 6665 6666 // Perform overload resolution. 6667 OverloadCandidateSet::iterator Best; 6668 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 6669 case OR_Success: { 6670 // We found a built-in operator or an overloaded operator. 6671 FunctionDecl *FnDecl = Best->Function; 6672 6673 if (FnDecl) { 6674 // We matched an overloaded operator. Build a call to that 6675 // operator. 6676 6677 // Convert the arguments. 6678 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 6679 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 6680 6681 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 6682 Best->FoundDecl, Method)) 6683 return ExprError(); 6684 } else { 6685 // Convert the arguments. 6686 OwningExprResult InputInit 6687 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6688 FnDecl->getParamDecl(0)), 6689 SourceLocation(), 6690 move(input)); 6691 if (InputInit.isInvalid()) 6692 return ExprError(); 6693 6694 input = move(InputInit); 6695 Input = (Expr *)input.get(); 6696 } 6697 6698 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 6699 6700 // Determine the result type 6701 QualType ResultTy = FnDecl->getCallResultType(); 6702 6703 // Build the actual expression node. 6704 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 6705 SourceLocation()); 6706 UsualUnaryConversions(FnExpr); 6707 6708 input.release(); 6709 Args[0] = Input; 6710 ExprOwningPtr<CallExpr> TheCall(this, 6711 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 6712 Args, NumArgs, ResultTy, OpLoc)); 6713 6714 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 6715 FnDecl)) 6716 return ExprError(); 6717 6718 return MaybeBindToTemporary(TheCall.release()); 6719 } else { 6720 // We matched a built-in operator. Convert the arguments, then 6721 // break out so that we will build the appropriate built-in 6722 // operator node. 6723 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 6724 Best->Conversions[0], AA_Passing)) 6725 return ExprError(); 6726 6727 break; 6728 } 6729 } 6730 6731 case OR_No_Viable_Function: 6732 // No viable function; fall through to handling this as a 6733 // built-in operator, which will produce an error message for us. 6734 break; 6735 6736 case OR_Ambiguous: 6737 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 6738 << UnaryOperator::getOpcodeStr(Opc) 6739 << Input->getSourceRange(); 6740 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs, 6741 UnaryOperator::getOpcodeStr(Opc), OpLoc); 6742 return ExprError(); 6743 6744 case OR_Deleted: 6745 Diag(OpLoc, diag::err_ovl_deleted_oper) 6746 << Best->Function->isDeleted() 6747 << UnaryOperator::getOpcodeStr(Opc) 6748 << Input->getSourceRange(); 6749 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6750 return ExprError(); 6751 } 6752 6753 // Either we found no viable overloaded operator or we matched a 6754 // built-in operator. In either case, fall through to trying to 6755 // build a built-in operation. 6756 input.release(); 6757 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input)); 6758} 6759 6760/// \brief Create a binary operation that may resolve to an overloaded 6761/// operator. 6762/// 6763/// \param OpLoc The location of the operator itself (e.g., '+'). 6764/// 6765/// \param OpcIn The BinaryOperator::Opcode that describes this 6766/// operator. 6767/// 6768/// \param Functions The set of non-member functions that will be 6769/// considered by overload resolution. The caller needs to build this 6770/// set based on the context using, e.g., 6771/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 6772/// set should not contain any member functions; those will be added 6773/// by CreateOverloadedBinOp(). 6774/// 6775/// \param LHS Left-hand argument. 6776/// \param RHS Right-hand argument. 6777Sema::OwningExprResult 6778Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 6779 unsigned OpcIn, 6780 const UnresolvedSetImpl &Fns, 6781 Expr *LHS, Expr *RHS) { 6782 Expr *Args[2] = { LHS, RHS }; 6783 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 6784 6785 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 6786 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 6787 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6788 6789 // If either side is type-dependent, create an appropriate dependent 6790 // expression. 6791 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 6792 if (Fns.empty()) { 6793 // If there are no functions to store, just build a dependent 6794 // BinaryOperator or CompoundAssignment. 6795 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign) 6796 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 6797 Context.DependentTy, OpLoc)); 6798 6799 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 6800 Context.DependentTy, 6801 Context.DependentTy, 6802 Context.DependentTy, 6803 OpLoc)); 6804 } 6805 6806 // FIXME: save results of ADL from here? 6807 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 6808 UnresolvedLookupExpr *Fn 6809 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 6810 0, SourceRange(), OpName, OpLoc, 6811 /*ADL*/ true, IsOverloaded(Fns), 6812 Fns.begin(), Fns.end()); 6813 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 6814 Args, 2, 6815 Context.DependentTy, 6816 OpLoc)); 6817 } 6818 6819 // If this is the .* operator, which is not overloadable, just 6820 // create a built-in binary operator. 6821 if (Opc == BinaryOperator::PtrMemD) 6822 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6823 6824 // If this is the assignment operator, we only perform overload resolution 6825 // if the left-hand side is a class or enumeration type. This is actually 6826 // a hack. The standard requires that we do overload resolution between the 6827 // various built-in candidates, but as DR507 points out, this can lead to 6828 // problems. So we do it this way, which pretty much follows what GCC does. 6829 // Note that we go the traditional code path for compound assignment forms. 6830 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType()) 6831 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6832 6833 // Build an empty overload set. 6834 OverloadCandidateSet CandidateSet(OpLoc); 6835 6836 // Add the candidates from the given function set. 6837 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 6838 6839 // Add operator candidates that are member functions. 6840 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 6841 6842 // Add candidates from ADL. 6843 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 6844 Args, 2, 6845 /*ExplicitTemplateArgs*/ 0, 6846 CandidateSet); 6847 6848 // Add builtin operator candidates. 6849 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 6850 6851 // Perform overload resolution. 6852 OverloadCandidateSet::iterator Best; 6853 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 6854 case OR_Success: { 6855 // We found a built-in operator or an overloaded operator. 6856 FunctionDecl *FnDecl = Best->Function; 6857 6858 if (FnDecl) { 6859 // We matched an overloaded operator. Build a call to that 6860 // operator. 6861 6862 // Convert the arguments. 6863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 6864 // Best->Access is only meaningful for class members. 6865 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 6866 6867 OwningExprResult Arg1 6868 = PerformCopyInitialization( 6869 InitializedEntity::InitializeParameter( 6870 FnDecl->getParamDecl(0)), 6871 SourceLocation(), 6872 Owned(Args[1])); 6873 if (Arg1.isInvalid()) 6874 return ExprError(); 6875 6876 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 6877 Best->FoundDecl, Method)) 6878 return ExprError(); 6879 6880 Args[1] = RHS = Arg1.takeAs<Expr>(); 6881 } else { 6882 // Convert the arguments. 6883 OwningExprResult Arg0 6884 = PerformCopyInitialization( 6885 InitializedEntity::InitializeParameter( 6886 FnDecl->getParamDecl(0)), 6887 SourceLocation(), 6888 Owned(Args[0])); 6889 if (Arg0.isInvalid()) 6890 return ExprError(); 6891 6892 OwningExprResult Arg1 6893 = PerformCopyInitialization( 6894 InitializedEntity::InitializeParameter( 6895 FnDecl->getParamDecl(1)), 6896 SourceLocation(), 6897 Owned(Args[1])); 6898 if (Arg1.isInvalid()) 6899 return ExprError(); 6900 Args[0] = LHS = Arg0.takeAs<Expr>(); 6901 Args[1] = RHS = Arg1.takeAs<Expr>(); 6902 } 6903 6904 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 6905 6906 // Determine the result type 6907 QualType ResultTy 6908 = FnDecl->getType()->getAs<FunctionType>() 6909 ->getCallResultType(Context); 6910 6911 // Build the actual expression node. 6912 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 6913 OpLoc); 6914 UsualUnaryConversions(FnExpr); 6915 6916 ExprOwningPtr<CXXOperatorCallExpr> 6917 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 6918 Args, 2, ResultTy, 6919 OpLoc)); 6920 6921 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 6922 FnDecl)) 6923 return ExprError(); 6924 6925 return MaybeBindToTemporary(TheCall.release()); 6926 } else { 6927 // We matched a built-in operator. Convert the arguments, then 6928 // break out so that we will build the appropriate built-in 6929 // operator node. 6930 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 6931 Best->Conversions[0], AA_Passing) || 6932 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 6933 Best->Conversions[1], AA_Passing)) 6934 return ExprError(); 6935 6936 break; 6937 } 6938 } 6939 6940 case OR_No_Viable_Function: { 6941 // C++ [over.match.oper]p9: 6942 // If the operator is the operator , [...] and there are no 6943 // viable functions, then the operator is assumed to be the 6944 // built-in operator and interpreted according to clause 5. 6945 if (Opc == BinaryOperator::Comma) 6946 break; 6947 6948 // For class as left operand for assignment or compound assigment operator 6949 // do not fall through to handling in built-in, but report that no overloaded 6950 // assignment operator found 6951 OwningExprResult Result = ExprError(); 6952 if (Args[0]->getType()->isRecordType() && 6953 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) { 6954 Diag(OpLoc, diag::err_ovl_no_viable_oper) 6955 << BinaryOperator::getOpcodeStr(Opc) 6956 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6957 } else { 6958 // No viable function; try to create a built-in operation, which will 6959 // produce an error. Then, show the non-viable candidates. 6960 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6961 } 6962 assert(Result.isInvalid() && 6963 "C++ binary operator overloading is missing candidates!"); 6964 if (Result.isInvalid()) 6965 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 6966 BinaryOperator::getOpcodeStr(Opc), OpLoc); 6967 return move(Result); 6968 } 6969 6970 case OR_Ambiguous: 6971 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 6972 << BinaryOperator::getOpcodeStr(Opc) 6973 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6974 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2, 6975 BinaryOperator::getOpcodeStr(Opc), OpLoc); 6976 return ExprError(); 6977 6978 case OR_Deleted: 6979 Diag(OpLoc, diag::err_ovl_deleted_oper) 6980 << Best->Function->isDeleted() 6981 << BinaryOperator::getOpcodeStr(Opc) 6982 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6983 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2); 6984 return ExprError(); 6985 } 6986 6987 // We matched a built-in operator; build it. 6988 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6989} 6990 6991Action::OwningExprResult 6992Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 6993 SourceLocation RLoc, 6994 ExprArg Base, ExprArg Idx) { 6995 Expr *Args[2] = { static_cast<Expr*>(Base.get()), 6996 static_cast<Expr*>(Idx.get()) }; 6997 DeclarationName OpName = 6998 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 6999 7000 // If either side is type-dependent, create an appropriate dependent 7001 // expression. 7002 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 7003 7004 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 7005 UnresolvedLookupExpr *Fn 7006 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 7007 0, SourceRange(), OpName, LLoc, 7008 /*ADL*/ true, /*Overloaded*/ false, 7009 UnresolvedSetIterator(), 7010 UnresolvedSetIterator()); 7011 // Can't add any actual overloads yet 7012 7013 Base.release(); 7014 Idx.release(); 7015 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 7016 Args, 2, 7017 Context.DependentTy, 7018 RLoc)); 7019 } 7020 7021 // Build an empty overload set. 7022 OverloadCandidateSet CandidateSet(LLoc); 7023 7024 // Subscript can only be overloaded as a member function. 7025 7026 // Add operator candidates that are member functions. 7027 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 7028 7029 // Add builtin operator candidates. 7030 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 7031 7032 // Perform overload resolution. 7033 OverloadCandidateSet::iterator Best; 7034 switch (BestViableFunction(CandidateSet, LLoc, Best)) { 7035 case OR_Success: { 7036 // We found a built-in operator or an overloaded operator. 7037 FunctionDecl *FnDecl = Best->Function; 7038 7039 if (FnDecl) { 7040 // We matched an overloaded operator. Build a call to that 7041 // operator. 7042 7043 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 7044 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 7045 7046 // Convert the arguments. 7047 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 7048 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 7049 Best->FoundDecl, Method)) 7050 return ExprError(); 7051 7052 // Convert the arguments. 7053 OwningExprResult InputInit 7054 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 7055 FnDecl->getParamDecl(0)), 7056 SourceLocation(), 7057 Owned(Args[1])); 7058 if (InputInit.isInvalid()) 7059 return ExprError(); 7060 7061 Args[1] = InputInit.takeAs<Expr>(); 7062 7063 // Determine the result type 7064 QualType ResultTy 7065 = FnDecl->getType()->getAs<FunctionType>() 7066 ->getCallResultType(Context); 7067 7068 // Build the actual expression node. 7069 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 7070 LLoc); 7071 UsualUnaryConversions(FnExpr); 7072 7073 Base.release(); 7074 Idx.release(); 7075 ExprOwningPtr<CXXOperatorCallExpr> 7076 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 7077 FnExpr, Args, 2, 7078 ResultTy, RLoc)); 7079 7080 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(), 7081 FnDecl)) 7082 return ExprError(); 7083 7084 return MaybeBindToTemporary(TheCall.release()); 7085 } else { 7086 // We matched a built-in operator. Convert the arguments, then 7087 // break out so that we will build the appropriate built-in 7088 // operator node. 7089 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 7090 Best->Conversions[0], AA_Passing) || 7091 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 7092 Best->Conversions[1], AA_Passing)) 7093 return ExprError(); 7094 7095 break; 7096 } 7097 } 7098 7099 case OR_No_Viable_Function: { 7100 if (CandidateSet.empty()) 7101 Diag(LLoc, diag::err_ovl_no_oper) 7102 << Args[0]->getType() << /*subscript*/ 0 7103 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7104 else 7105 Diag(LLoc, diag::err_ovl_no_viable_subscript) 7106 << Args[0]->getType() 7107 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7108 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 7109 "[]", LLoc); 7110 return ExprError(); 7111 } 7112 7113 case OR_Ambiguous: 7114 Diag(LLoc, diag::err_ovl_ambiguous_oper) 7115 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7116 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2, 7117 "[]", LLoc); 7118 return ExprError(); 7119 7120 case OR_Deleted: 7121 Diag(LLoc, diag::err_ovl_deleted_oper) 7122 << Best->Function->isDeleted() << "[]" 7123 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7124 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 7125 "[]", LLoc); 7126 return ExprError(); 7127 } 7128 7129 // We matched a built-in operator; build it. 7130 Base.release(); 7131 Idx.release(); 7132 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc, 7133 Owned(Args[1]), RLoc); 7134} 7135 7136/// BuildCallToMemberFunction - Build a call to a member 7137/// function. MemExpr is the expression that refers to the member 7138/// function (and includes the object parameter), Args/NumArgs are the 7139/// arguments to the function call (not including the object 7140/// parameter). The caller needs to validate that the member 7141/// expression refers to a member function or an overloaded member 7142/// function. 7143Sema::OwningExprResult 7144Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 7145 SourceLocation LParenLoc, Expr **Args, 7146 unsigned NumArgs, SourceLocation *CommaLocs, 7147 SourceLocation RParenLoc) { 7148 // Dig out the member expression. This holds both the object 7149 // argument and the member function we're referring to. 7150 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 7151 7152 MemberExpr *MemExpr; 7153 CXXMethodDecl *Method = 0; 7154 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 7155 NestedNameSpecifier *Qualifier = 0; 7156 if (isa<MemberExpr>(NakedMemExpr)) { 7157 MemExpr = cast<MemberExpr>(NakedMemExpr); 7158 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 7159 FoundDecl = MemExpr->getFoundDecl(); 7160 Qualifier = MemExpr->getQualifier(); 7161 } else { 7162 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 7163 Qualifier = UnresExpr->getQualifier(); 7164 7165 QualType ObjectType = UnresExpr->getBaseType(); 7166 7167 // Add overload candidates 7168 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 7169 7170 // FIXME: avoid copy. 7171 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7172 if (UnresExpr->hasExplicitTemplateArgs()) { 7173 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 7174 TemplateArgs = &TemplateArgsBuffer; 7175 } 7176 7177 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 7178 E = UnresExpr->decls_end(); I != E; ++I) { 7179 7180 NamedDecl *Func = *I; 7181 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 7182 if (isa<UsingShadowDecl>(Func)) 7183 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 7184 7185 if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 7186 // If explicit template arguments were provided, we can't call a 7187 // non-template member function. 7188 if (TemplateArgs) 7189 continue; 7190 7191 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 7192 Args, NumArgs, 7193 CandidateSet, /*SuppressUserConversions=*/false); 7194 } else { 7195 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 7196 I.getPair(), ActingDC, TemplateArgs, 7197 ObjectType, Args, NumArgs, 7198 CandidateSet, 7199 /*SuppressUsedConversions=*/false); 7200 } 7201 } 7202 7203 DeclarationName DeclName = UnresExpr->getMemberName(); 7204 7205 OverloadCandidateSet::iterator Best; 7206 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) { 7207 case OR_Success: 7208 Method = cast<CXXMethodDecl>(Best->Function); 7209 FoundDecl = Best->FoundDecl; 7210 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 7211 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 7212 break; 7213 7214 case OR_No_Viable_Function: 7215 Diag(UnresExpr->getMemberLoc(), 7216 diag::err_ovl_no_viable_member_function_in_call) 7217 << DeclName << MemExprE->getSourceRange(); 7218 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 7219 // FIXME: Leaking incoming expressions! 7220 return ExprError(); 7221 7222 case OR_Ambiguous: 7223 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 7224 << DeclName << MemExprE->getSourceRange(); 7225 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 7226 // FIXME: Leaking incoming expressions! 7227 return ExprError(); 7228 7229 case OR_Deleted: 7230 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 7231 << Best->Function->isDeleted() 7232 << DeclName << MemExprE->getSourceRange(); 7233 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 7234 // FIXME: Leaking incoming expressions! 7235 return ExprError(); 7236 } 7237 7238 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 7239 7240 // If overload resolution picked a static member, build a 7241 // non-member call based on that function. 7242 if (Method->isStatic()) { 7243 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 7244 Args, NumArgs, RParenLoc); 7245 } 7246 7247 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 7248 } 7249 7250 assert(Method && "Member call to something that isn't a method?"); 7251 ExprOwningPtr<CXXMemberCallExpr> 7252 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 7253 NumArgs, 7254 Method->getCallResultType(), 7255 RParenLoc)); 7256 7257 // Check for a valid return type. 7258 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 7259 TheCall.get(), Method)) 7260 return ExprError(); 7261 7262 // Convert the object argument (for a non-static member function call). 7263 // We only need to do this if there was actually an overload; otherwise 7264 // it was done at lookup. 7265 Expr *ObjectArg = MemExpr->getBase(); 7266 if (!Method->isStatic() && 7267 PerformObjectArgumentInitialization(ObjectArg, Qualifier, 7268 FoundDecl, Method)) 7269 return ExprError(); 7270 MemExpr->setBase(ObjectArg); 7271 7272 // Convert the rest of the arguments 7273 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 7274 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs, 7275 RParenLoc)) 7276 return ExprError(); 7277 7278 if (CheckFunctionCall(Method, TheCall.get())) 7279 return ExprError(); 7280 7281 return MaybeBindToTemporary(TheCall.release()); 7282} 7283 7284/// BuildCallToObjectOfClassType - Build a call to an object of class 7285/// type (C++ [over.call.object]), which can end up invoking an 7286/// overloaded function call operator (@c operator()) or performing a 7287/// user-defined conversion on the object argument. 7288Sema::ExprResult 7289Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 7290 SourceLocation LParenLoc, 7291 Expr **Args, unsigned NumArgs, 7292 SourceLocation *CommaLocs, 7293 SourceLocation RParenLoc) { 7294 assert(Object->getType()->isRecordType() && "Requires object type argument"); 7295 const RecordType *Record = Object->getType()->getAs<RecordType>(); 7296 7297 // C++ [over.call.object]p1: 7298 // If the primary-expression E in the function call syntax 7299 // evaluates to a class object of type "cv T", then the set of 7300 // candidate functions includes at least the function call 7301 // operators of T. The function call operators of T are obtained by 7302 // ordinary lookup of the name operator() in the context of 7303 // (E).operator(). 7304 OverloadCandidateSet CandidateSet(LParenLoc); 7305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 7306 7307 if (RequireCompleteType(LParenLoc, Object->getType(), 7308 PDiag(diag::err_incomplete_object_call) 7309 << Object->getSourceRange())) 7310 return true; 7311 7312 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 7313 LookupQualifiedName(R, Record->getDecl()); 7314 R.suppressDiagnostics(); 7315 7316 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 7317 Oper != OperEnd; ++Oper) { 7318 AddMethodCandidate(Oper.getPair(), Object->getType(), 7319 Args, NumArgs, CandidateSet, 7320 /*SuppressUserConversions=*/ false); 7321 } 7322 7323 // C++ [over.call.object]p2: 7324 // In addition, for each conversion function declared in T of the 7325 // form 7326 // 7327 // operator conversion-type-id () cv-qualifier; 7328 // 7329 // where cv-qualifier is the same cv-qualification as, or a 7330 // greater cv-qualification than, cv, and where conversion-type-id 7331 // denotes the type "pointer to function of (P1,...,Pn) returning 7332 // R", or the type "reference to pointer to function of 7333 // (P1,...,Pn) returning R", or the type "reference to function 7334 // of (P1,...,Pn) returning R", a surrogate call function [...] 7335 // is also considered as a candidate function. Similarly, 7336 // surrogate call functions are added to the set of candidate 7337 // functions for each conversion function declared in an 7338 // accessible base class provided the function is not hidden 7339 // within T by another intervening declaration. 7340 const UnresolvedSetImpl *Conversions 7341 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 7342 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 7343 E = Conversions->end(); I != E; ++I) { 7344 NamedDecl *D = *I; 7345 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 7346 if (isa<UsingShadowDecl>(D)) 7347 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7348 7349 // Skip over templated conversion functions; they aren't 7350 // surrogates. 7351 if (isa<FunctionTemplateDecl>(D)) 7352 continue; 7353 7354 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7355 7356 // Strip the reference type (if any) and then the pointer type (if 7357 // any) to get down to what might be a function type. 7358 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 7359 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 7360 ConvType = ConvPtrType->getPointeeType(); 7361 7362 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 7363 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 7364 Object->getType(), Args, NumArgs, 7365 CandidateSet); 7366 } 7367 7368 // Perform overload resolution. 7369 OverloadCandidateSet::iterator Best; 7370 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) { 7371 case OR_Success: 7372 // Overload resolution succeeded; we'll build the appropriate call 7373 // below. 7374 break; 7375 7376 case OR_No_Viable_Function: 7377 if (CandidateSet.empty()) 7378 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper) 7379 << Object->getType() << /*call*/ 1 7380 << Object->getSourceRange(); 7381 else 7382 Diag(Object->getSourceRange().getBegin(), 7383 diag::err_ovl_no_viable_object_call) 7384 << Object->getType() << Object->getSourceRange(); 7385 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 7386 break; 7387 7388 case OR_Ambiguous: 7389 Diag(Object->getSourceRange().getBegin(), 7390 diag::err_ovl_ambiguous_object_call) 7391 << Object->getType() << Object->getSourceRange(); 7392 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 7393 break; 7394 7395 case OR_Deleted: 7396 Diag(Object->getSourceRange().getBegin(), 7397 diag::err_ovl_deleted_object_call) 7398 << Best->Function->isDeleted() 7399 << Object->getType() << Object->getSourceRange(); 7400 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 7401 break; 7402 } 7403 7404 if (Best == CandidateSet.end()) 7405 return true; 7406 7407 if (Best->Function == 0) { 7408 // Since there is no function declaration, this is one of the 7409 // surrogate candidates. Dig out the conversion function. 7410 CXXConversionDecl *Conv 7411 = cast<CXXConversionDecl>( 7412 Best->Conversions[0].UserDefined.ConversionFunction); 7413 7414 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 7415 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 7416 7417 // We selected one of the surrogate functions that converts the 7418 // object parameter to a function pointer. Perform the conversion 7419 // on the object argument, then let ActOnCallExpr finish the job. 7420 7421 // Create an implicit member expr to refer to the conversion operator. 7422 // and then call it. 7423 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl, 7424 Conv); 7425 7426 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc, 7427 MultiExprArg(*this, (ExprTy**)Args, NumArgs), 7428 CommaLocs, RParenLoc).result(); 7429 } 7430 7431 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 7432 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 7433 7434 // We found an overloaded operator(). Build a CXXOperatorCallExpr 7435 // that calls this method, using Object for the implicit object 7436 // parameter and passing along the remaining arguments. 7437 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 7438 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 7439 7440 unsigned NumArgsInProto = Proto->getNumArgs(); 7441 unsigned NumArgsToCheck = NumArgs; 7442 7443 // Build the full argument list for the method call (the 7444 // implicit object parameter is placed at the beginning of the 7445 // list). 7446 Expr **MethodArgs; 7447 if (NumArgs < NumArgsInProto) { 7448 NumArgsToCheck = NumArgsInProto; 7449 MethodArgs = new Expr*[NumArgsInProto + 1]; 7450 } else { 7451 MethodArgs = new Expr*[NumArgs + 1]; 7452 } 7453 MethodArgs[0] = Object; 7454 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7455 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 7456 7457 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 7458 SourceLocation()); 7459 UsualUnaryConversions(NewFn); 7460 7461 // Once we've built TheCall, all of the expressions are properly 7462 // owned. 7463 QualType ResultTy = Method->getCallResultType(); 7464 ExprOwningPtr<CXXOperatorCallExpr> 7465 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn, 7466 MethodArgs, NumArgs + 1, 7467 ResultTy, RParenLoc)); 7468 delete [] MethodArgs; 7469 7470 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(), 7471 Method)) 7472 return true; 7473 7474 // We may have default arguments. If so, we need to allocate more 7475 // slots in the call for them. 7476 if (NumArgs < NumArgsInProto) 7477 TheCall->setNumArgs(Context, NumArgsInProto + 1); 7478 else if (NumArgs > NumArgsInProto) 7479 NumArgsToCheck = NumArgsInProto; 7480 7481 bool IsError = false; 7482 7483 // Initialize the implicit object parameter. 7484 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0, 7485 Best->FoundDecl, Method); 7486 TheCall->setArg(0, Object); 7487 7488 7489 // Check the argument types. 7490 for (unsigned i = 0; i != NumArgsToCheck; i++) { 7491 Expr *Arg; 7492 if (i < NumArgs) { 7493 Arg = Args[i]; 7494 7495 // Pass the argument. 7496 7497 OwningExprResult InputInit 7498 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 7499 Method->getParamDecl(i)), 7500 SourceLocation(), Owned(Arg)); 7501 7502 IsError |= InputInit.isInvalid(); 7503 Arg = InputInit.takeAs<Expr>(); 7504 } else { 7505 OwningExprResult DefArg 7506 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 7507 if (DefArg.isInvalid()) { 7508 IsError = true; 7509 break; 7510 } 7511 7512 Arg = DefArg.takeAs<Expr>(); 7513 } 7514 7515 TheCall->setArg(i + 1, Arg); 7516 } 7517 7518 // If this is a variadic call, handle args passed through "...". 7519 if (Proto->isVariadic()) { 7520 // Promote the arguments (C99 6.5.2.2p7). 7521 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 7522 Expr *Arg = Args[i]; 7523 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0); 7524 TheCall->setArg(i + 1, Arg); 7525 } 7526 } 7527 7528 if (IsError) return true; 7529 7530 if (CheckFunctionCall(Method, TheCall.get())) 7531 return true; 7532 7533 return MaybeBindToTemporary(TheCall.release()).result(); 7534} 7535 7536/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 7537/// (if one exists), where @c Base is an expression of class type and 7538/// @c Member is the name of the member we're trying to find. 7539Sema::OwningExprResult 7540Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) { 7541 Expr *Base = static_cast<Expr *>(BaseIn.get()); 7542 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 7543 7544 SourceLocation Loc = Base->getExprLoc(); 7545 7546 // C++ [over.ref]p1: 7547 // 7548 // [...] An expression x->m is interpreted as (x.operator->())->m 7549 // for a class object x of type T if T::operator->() exists and if 7550 // the operator is selected as the best match function by the 7551 // overload resolution mechanism (13.3). 7552 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 7553 OverloadCandidateSet CandidateSet(Loc); 7554 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 7555 7556 if (RequireCompleteType(Loc, Base->getType(), 7557 PDiag(diag::err_typecheck_incomplete_tag) 7558 << Base->getSourceRange())) 7559 return ExprError(); 7560 7561 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 7562 LookupQualifiedName(R, BaseRecord->getDecl()); 7563 R.suppressDiagnostics(); 7564 7565 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 7566 Oper != OperEnd; ++Oper) { 7567 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet, 7568 /*SuppressUserConversions=*/false); 7569 } 7570 7571 // Perform overload resolution. 7572 OverloadCandidateSet::iterator Best; 7573 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 7574 case OR_Success: 7575 // Overload resolution succeeded; we'll build the call below. 7576 break; 7577 7578 case OR_No_Viable_Function: 7579 if (CandidateSet.empty()) 7580 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 7581 << Base->getType() << Base->getSourceRange(); 7582 else 7583 Diag(OpLoc, diag::err_ovl_no_viable_oper) 7584 << "operator->" << Base->getSourceRange(); 7585 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1); 7586 return ExprError(); 7587 7588 case OR_Ambiguous: 7589 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 7590 << "->" << Base->getSourceRange(); 7591 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1); 7592 return ExprError(); 7593 7594 case OR_Deleted: 7595 Diag(OpLoc, diag::err_ovl_deleted_oper) 7596 << Best->Function->isDeleted() 7597 << "->" << Base->getSourceRange(); 7598 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1); 7599 return ExprError(); 7600 } 7601 7602 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 7603 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 7604 7605 // Convert the object parameter. 7606 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 7607 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 7608 Best->FoundDecl, Method)) 7609 return ExprError(); 7610 7611 // No concerns about early exits now. 7612 BaseIn.release(); 7613 7614 // Build the operator call. 7615 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(), 7616 SourceLocation()); 7617 UsualUnaryConversions(FnExpr); 7618 7619 QualType ResultTy = Method->getCallResultType(); 7620 ExprOwningPtr<CXXOperatorCallExpr> 7621 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 7622 &Base, 1, ResultTy, OpLoc)); 7623 7624 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(), 7625 Method)) 7626 return ExprError(); 7627 return move(TheCall); 7628} 7629 7630/// FixOverloadedFunctionReference - E is an expression that refers to 7631/// a C++ overloaded function (possibly with some parentheses and 7632/// perhaps a '&' around it). We have resolved the overloaded function 7633/// to the function declaration Fn, so patch up the expression E to 7634/// refer (possibly indirectly) to Fn. Returns the new expr. 7635Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 7636 FunctionDecl *Fn) { 7637 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 7638 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 7639 Found, Fn); 7640 if (SubExpr == PE->getSubExpr()) 7641 return PE->Retain(); 7642 7643 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 7644 } 7645 7646 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7647 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 7648 Found, Fn); 7649 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 7650 SubExpr->getType()) && 7651 "Implicit cast type cannot be determined from overload"); 7652 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 7653 if (SubExpr == ICE->getSubExpr()) 7654 return ICE->Retain(); 7655 7656 return ImplicitCastExpr::Create(Context, ICE->getType(), 7657 ICE->getCastKind(), 7658 SubExpr, 0, 7659 ICE->getCategory()); 7660 } 7661 7662 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 7663 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 7664 "Can only take the address of an overloaded function"); 7665 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7666 if (Method->isStatic()) { 7667 // Do nothing: static member functions aren't any different 7668 // from non-member functions. 7669 } else { 7670 // Fix the sub expression, which really has to be an 7671 // UnresolvedLookupExpr holding an overloaded member function 7672 // or template. 7673 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 7674 Found, Fn); 7675 if (SubExpr == UnOp->getSubExpr()) 7676 return UnOp->Retain(); 7677 7678 assert(isa<DeclRefExpr>(SubExpr) 7679 && "fixed to something other than a decl ref"); 7680 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 7681 && "fixed to a member ref with no nested name qualifier"); 7682 7683 // We have taken the address of a pointer to member 7684 // function. Perform the computation here so that we get the 7685 // appropriate pointer to member type. 7686 QualType ClassType 7687 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 7688 QualType MemPtrType 7689 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 7690 7691 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 7692 MemPtrType, UnOp->getOperatorLoc()); 7693 } 7694 } 7695 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 7696 Found, Fn); 7697 if (SubExpr == UnOp->getSubExpr()) 7698 return UnOp->Retain(); 7699 7700 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 7701 Context.getPointerType(SubExpr->getType()), 7702 UnOp->getOperatorLoc()); 7703 } 7704 7705 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 7706 // FIXME: avoid copy. 7707 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7708 if (ULE->hasExplicitTemplateArgs()) { 7709 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 7710 TemplateArgs = &TemplateArgsBuffer; 7711 } 7712 7713 return DeclRefExpr::Create(Context, 7714 ULE->getQualifier(), 7715 ULE->getQualifierRange(), 7716 Fn, 7717 ULE->getNameLoc(), 7718 Fn->getType(), 7719 TemplateArgs); 7720 } 7721 7722 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 7723 // FIXME: avoid copy. 7724 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7725 if (MemExpr->hasExplicitTemplateArgs()) { 7726 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 7727 TemplateArgs = &TemplateArgsBuffer; 7728 } 7729 7730 Expr *Base; 7731 7732 // If we're filling in 7733 if (MemExpr->isImplicitAccess()) { 7734 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 7735 return DeclRefExpr::Create(Context, 7736 MemExpr->getQualifier(), 7737 MemExpr->getQualifierRange(), 7738 Fn, 7739 MemExpr->getMemberLoc(), 7740 Fn->getType(), 7741 TemplateArgs); 7742 } else { 7743 SourceLocation Loc = MemExpr->getMemberLoc(); 7744 if (MemExpr->getQualifier()) 7745 Loc = MemExpr->getQualifierRange().getBegin(); 7746 Base = new (Context) CXXThisExpr(Loc, 7747 MemExpr->getBaseType(), 7748 /*isImplicit=*/true); 7749 } 7750 } else 7751 Base = MemExpr->getBase()->Retain(); 7752 7753 return MemberExpr::Create(Context, Base, 7754 MemExpr->isArrow(), 7755 MemExpr->getQualifier(), 7756 MemExpr->getQualifierRange(), 7757 Fn, 7758 Found, 7759 MemExpr->getMemberLoc(), 7760 TemplateArgs, 7761 Fn->getType()); 7762 } 7763 7764 assert(false && "Invalid reference to overloaded function"); 7765 return E->Retain(); 7766} 7767 7768Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E, 7769 DeclAccessPair Found, 7770 FunctionDecl *Fn) { 7771 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 7772} 7773 7774} // end namespace clang 7775