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