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