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