SemaOverload.cpp revision a18592ec62e898aed7ed71e1f09c314590ce9ec7
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 // FIXME: variadic templates "at most" should account for parameter packs 5060 unsigned mode, modeCount; 5061 if (NumFormalArgs < MinParams) { 5062 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 5063 (Cand->FailureKind == ovl_fail_bad_deduction && 5064 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 5065 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic()) 5066 mode = 0; // "at least" 5067 else 5068 mode = 2; // "exactly" 5069 modeCount = MinParams; 5070 } else { 5071 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 5072 (Cand->FailureKind == ovl_fail_bad_deduction && 5073 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 5074 if (MinParams != FnTy->getNumArgs()) 5075 mode = 1; // "at most" 5076 else 5077 mode = 2; // "exactly" 5078 modeCount = FnTy->getNumArgs(); 5079 } 5080 5081 std::string Description; 5082 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 5083 5084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 5085 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 5086 << modeCount << NumFormalArgs; 5087} 5088 5089/// Diagnose a failed template-argument deduction. 5090void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 5091 Expr **Args, unsigned NumArgs) { 5092 FunctionDecl *Fn = Cand->Function; // pattern 5093 5094 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 5095 switch (Cand->DeductionFailure.Result) { 5096 case Sema::TDK_Success: 5097 llvm_unreachable("TDK_success while diagnosing bad deduction"); 5098 5099 case Sema::TDK_Incomplete: { 5100 NamedDecl *ParamD; 5101 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 5102 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 5103 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 5104 assert(ParamD && "no parameter found for incomplete deduction result"); 5105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 5106 << ParamD->getDeclName(); 5107 return; 5108 } 5109 5110 case Sema::TDK_Inconsistent: 5111 case Sema::TDK_InconsistentQuals: { 5112 NamedDecl *ParamD; 5113 int which = 0; 5114 if ((ParamD = Param.dyn_cast<TemplateTypeParmDecl*>())) 5115 which = 0; 5116 else if ((ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>())) 5117 which = 1; 5118 else { 5119 ParamD = Param.get<TemplateTemplateParmDecl*>(); 5120 which = 2; 5121 } 5122 5123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 5124 << which << ParamD->getDeclName() 5125 << *Cand->DeductionFailure.getFirstArg() 5126 << *Cand->DeductionFailure.getSecondArg(); 5127 return; 5128 } 5129 5130 case Sema::TDK_TooManyArguments: 5131 case Sema::TDK_TooFewArguments: 5132 DiagnoseArityMismatch(S, Cand, NumArgs); 5133 return; 5134 5135 // TODO: diagnose these individually, then kill off 5136 // note_ovl_candidate_bad_deduction, which is uselessly vague. 5137 case Sema::TDK_InstantiationDepth: 5138 case Sema::TDK_SubstitutionFailure: 5139 case Sema::TDK_NonDeducedMismatch: 5140 case Sema::TDK_InvalidExplicitArguments: 5141 case Sema::TDK_FailedOverloadResolution: 5142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 5143 return; 5144 } 5145} 5146 5147/// Generates a 'note' diagnostic for an overload candidate. We've 5148/// already generated a primary error at the call site. 5149/// 5150/// It really does need to be a single diagnostic with its caret 5151/// pointed at the candidate declaration. Yes, this creates some 5152/// major challenges of technical writing. Yes, this makes pointing 5153/// out problems with specific arguments quite awkward. It's still 5154/// better than generating twenty screens of text for every failed 5155/// overload. 5156/// 5157/// It would be great to be able to express per-candidate problems 5158/// more richly for those diagnostic clients that cared, but we'd 5159/// still have to be just as careful with the default diagnostics. 5160void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 5161 Expr **Args, unsigned NumArgs) { 5162 FunctionDecl *Fn = Cand->Function; 5163 5164 // Note deleted candidates, but only if they're viable. 5165 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) { 5166 std::string FnDesc; 5167 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 5168 5169 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 5170 << FnKind << FnDesc << Fn->isDeleted(); 5171 return; 5172 } 5173 5174 // We don't really have anything else to say about viable candidates. 5175 if (Cand->Viable) { 5176 S.NoteOverloadCandidate(Fn); 5177 return; 5178 } 5179 5180 switch (Cand->FailureKind) { 5181 case ovl_fail_too_many_arguments: 5182 case ovl_fail_too_few_arguments: 5183 return DiagnoseArityMismatch(S, Cand, NumArgs); 5184 5185 case ovl_fail_bad_deduction: 5186 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 5187 5188 case ovl_fail_trivial_conversion: 5189 case ovl_fail_bad_final_conversion: 5190 case ovl_fail_final_conversion_not_exact: 5191 return S.NoteOverloadCandidate(Fn); 5192 5193 case ovl_fail_bad_conversion: { 5194 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 5195 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 5196 if (Cand->Conversions[I].isBad()) 5197 return DiagnoseBadConversion(S, Cand, I); 5198 5199 // FIXME: this currently happens when we're called from SemaInit 5200 // when user-conversion overload fails. Figure out how to handle 5201 // those conditions and diagnose them well. 5202 return S.NoteOverloadCandidate(Fn); 5203 } 5204 } 5205} 5206 5207void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 5208 // Desugar the type of the surrogate down to a function type, 5209 // retaining as many typedefs as possible while still showing 5210 // the function type (and, therefore, its parameter types). 5211 QualType FnType = Cand->Surrogate->getConversionType(); 5212 bool isLValueReference = false; 5213 bool isRValueReference = false; 5214 bool isPointer = false; 5215 if (const LValueReferenceType *FnTypeRef = 5216 FnType->getAs<LValueReferenceType>()) { 5217 FnType = FnTypeRef->getPointeeType(); 5218 isLValueReference = true; 5219 } else if (const RValueReferenceType *FnTypeRef = 5220 FnType->getAs<RValueReferenceType>()) { 5221 FnType = FnTypeRef->getPointeeType(); 5222 isRValueReference = true; 5223 } 5224 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 5225 FnType = FnTypePtr->getPointeeType(); 5226 isPointer = true; 5227 } 5228 // Desugar down to a function type. 5229 FnType = QualType(FnType->getAs<FunctionType>(), 0); 5230 // Reconstruct the pointer/reference as appropriate. 5231 if (isPointer) FnType = S.Context.getPointerType(FnType); 5232 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 5233 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 5234 5235 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 5236 << FnType; 5237} 5238 5239void NoteBuiltinOperatorCandidate(Sema &S, 5240 const char *Opc, 5241 SourceLocation OpLoc, 5242 OverloadCandidate *Cand) { 5243 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 5244 std::string TypeStr("operator"); 5245 TypeStr += Opc; 5246 TypeStr += "("; 5247 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 5248 if (Cand->Conversions.size() == 1) { 5249 TypeStr += ")"; 5250 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 5251 } else { 5252 TypeStr += ", "; 5253 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 5254 TypeStr += ")"; 5255 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 5256 } 5257} 5258 5259void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 5260 OverloadCandidate *Cand) { 5261 unsigned NoOperands = Cand->Conversions.size(); 5262 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 5263 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 5264 if (ICS.isBad()) break; // all meaningless after first invalid 5265 if (!ICS.isAmbiguous()) continue; 5266 5267 S.DiagnoseAmbiguousConversion(ICS, OpLoc, 5268 S.PDiag(diag::note_ambiguous_type_conversion)); 5269 } 5270} 5271 5272SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 5273 if (Cand->Function) 5274 return Cand->Function->getLocation(); 5275 if (Cand->IsSurrogate) 5276 return Cand->Surrogate->getLocation(); 5277 return SourceLocation(); 5278} 5279 5280struct CompareOverloadCandidatesForDisplay { 5281 Sema &S; 5282 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 5283 5284 bool operator()(const OverloadCandidate *L, 5285 const OverloadCandidate *R) { 5286 // Fast-path this check. 5287 if (L == R) return false; 5288 5289 // Order first by viability. 5290 if (L->Viable) { 5291 if (!R->Viable) return true; 5292 5293 // TODO: introduce a tri-valued comparison for overload 5294 // candidates. Would be more worthwhile if we had a sort 5295 // that could exploit it. 5296 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true; 5297 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false; 5298 } else if (R->Viable) 5299 return false; 5300 5301 assert(L->Viable == R->Viable); 5302 5303 // Criteria by which we can sort non-viable candidates: 5304 if (!L->Viable) { 5305 // 1. Arity mismatches come after other candidates. 5306 if (L->FailureKind == ovl_fail_too_many_arguments || 5307 L->FailureKind == ovl_fail_too_few_arguments) 5308 return false; 5309 if (R->FailureKind == ovl_fail_too_many_arguments || 5310 R->FailureKind == ovl_fail_too_few_arguments) 5311 return true; 5312 5313 // 2. Bad conversions come first and are ordered by the number 5314 // of bad conversions and quality of good conversions. 5315 if (L->FailureKind == ovl_fail_bad_conversion) { 5316 if (R->FailureKind != ovl_fail_bad_conversion) 5317 return true; 5318 5319 // If there's any ordering between the defined conversions... 5320 // FIXME: this might not be transitive. 5321 assert(L->Conversions.size() == R->Conversions.size()); 5322 5323 int leftBetter = 0; 5324 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 5325 for (unsigned E = L->Conversions.size(); I != E; ++I) { 5326 switch (S.CompareImplicitConversionSequences(L->Conversions[I], 5327 R->Conversions[I])) { 5328 case ImplicitConversionSequence::Better: 5329 leftBetter++; 5330 break; 5331 5332 case ImplicitConversionSequence::Worse: 5333 leftBetter--; 5334 break; 5335 5336 case ImplicitConversionSequence::Indistinguishable: 5337 break; 5338 } 5339 } 5340 if (leftBetter > 0) return true; 5341 if (leftBetter < 0) return false; 5342 5343 } else if (R->FailureKind == ovl_fail_bad_conversion) 5344 return false; 5345 5346 // TODO: others? 5347 } 5348 5349 // Sort everything else by location. 5350 SourceLocation LLoc = GetLocationForCandidate(L); 5351 SourceLocation RLoc = GetLocationForCandidate(R); 5352 5353 // Put candidates without locations (e.g. builtins) at the end. 5354 if (LLoc.isInvalid()) return false; 5355 if (RLoc.isInvalid()) return true; 5356 5357 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 5358 } 5359}; 5360 5361/// CompleteNonViableCandidate - Normally, overload resolution only 5362/// computes up to the first 5363void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 5364 Expr **Args, unsigned NumArgs) { 5365 assert(!Cand->Viable); 5366 5367 // Don't do anything on failures other than bad conversion. 5368 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 5369 5370 // Skip forward to the first bad conversion. 5371 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 5372 unsigned ConvCount = Cand->Conversions.size(); 5373 while (true) { 5374 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 5375 ConvIdx++; 5376 if (Cand->Conversions[ConvIdx - 1].isBad()) 5377 break; 5378 } 5379 5380 if (ConvIdx == ConvCount) 5381 return; 5382 5383 assert(!Cand->Conversions[ConvIdx].isInitialized() && 5384 "remaining conversion is initialized?"); 5385 5386 // FIXME: this should probably be preserved from the overload 5387 // operation somehow. 5388 bool SuppressUserConversions = false; 5389 5390 const FunctionProtoType* Proto; 5391 unsigned ArgIdx = ConvIdx; 5392 5393 if (Cand->IsSurrogate) { 5394 QualType ConvType 5395 = Cand->Surrogate->getConversionType().getNonReferenceType(); 5396 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 5397 ConvType = ConvPtrType->getPointeeType(); 5398 Proto = ConvType->getAs<FunctionProtoType>(); 5399 ArgIdx--; 5400 } else if (Cand->Function) { 5401 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 5402 if (isa<CXXMethodDecl>(Cand->Function) && 5403 !isa<CXXConstructorDecl>(Cand->Function)) 5404 ArgIdx--; 5405 } else { 5406 // Builtin binary operator with a bad first conversion. 5407 assert(ConvCount <= 3); 5408 for (; ConvIdx != ConvCount; ++ConvIdx) 5409 Cand->Conversions[ConvIdx] 5410 = TryCopyInitialization(S, Args[ConvIdx], 5411 Cand->BuiltinTypes.ParamTypes[ConvIdx], 5412 SuppressUserConversions, 5413 /*InOverloadResolution*/ true); 5414 return; 5415 } 5416 5417 // Fill in the rest of the conversions. 5418 unsigned NumArgsInProto = Proto->getNumArgs(); 5419 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 5420 if (ArgIdx < NumArgsInProto) 5421 Cand->Conversions[ConvIdx] 5422 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 5423 SuppressUserConversions, 5424 /*InOverloadResolution=*/true); 5425 else 5426 Cand->Conversions[ConvIdx].setEllipsis(); 5427 } 5428} 5429 5430} // end anonymous namespace 5431 5432/// PrintOverloadCandidates - When overload resolution fails, prints 5433/// diagnostic messages containing the candidates in the candidate 5434/// set. 5435void 5436Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 5437 OverloadCandidateDisplayKind OCD, 5438 Expr **Args, unsigned NumArgs, 5439 const char *Opc, 5440 SourceLocation OpLoc) { 5441 // Sort the candidates by viability and position. Sorting directly would 5442 // be prohibitive, so we make a set of pointers and sort those. 5443 llvm::SmallVector<OverloadCandidate*, 32> Cands; 5444 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size()); 5445 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 5446 LastCand = CandidateSet.end(); 5447 Cand != LastCand; ++Cand) { 5448 if (Cand->Viable) 5449 Cands.push_back(Cand); 5450 else if (OCD == OCD_AllCandidates) { 5451 CompleteNonViableCandidate(*this, Cand, Args, NumArgs); 5452 Cands.push_back(Cand); 5453 } 5454 } 5455 5456 std::sort(Cands.begin(), Cands.end(), 5457 CompareOverloadCandidatesForDisplay(*this)); 5458 5459 bool ReportedAmbiguousConversions = false; 5460 5461 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E; 5462 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 5463 OverloadCandidate *Cand = *I; 5464 5465 if (Cand->Function) 5466 NoteFunctionCandidate(*this, Cand, Args, NumArgs); 5467 else if (Cand->IsSurrogate) 5468 NoteSurrogateCandidate(*this, Cand); 5469 5470 // This a builtin candidate. We do not, in general, want to list 5471 // every possible builtin candidate. 5472 else if (Cand->Viable) { 5473 // Generally we only see ambiguities including viable builtin 5474 // operators if overload resolution got screwed up by an 5475 // ambiguous user-defined conversion. 5476 // 5477 // FIXME: It's quite possible for different conversions to see 5478 // different ambiguities, though. 5479 if (!ReportedAmbiguousConversions) { 5480 NoteAmbiguousUserConversions(*this, OpLoc, Cand); 5481 ReportedAmbiguousConversions = true; 5482 } 5483 5484 // If this is a viable builtin, print it. 5485 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand); 5486 } 5487 } 5488} 5489 5490static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) { 5491 if (isa<UnresolvedLookupExpr>(E)) 5492 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D); 5493 5494 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D); 5495} 5496 5497/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 5498/// an overloaded function (C++ [over.over]), where @p From is an 5499/// expression with overloaded function type and @p ToType is the type 5500/// we're trying to resolve to. For example: 5501/// 5502/// @code 5503/// int f(double); 5504/// int f(int); 5505/// 5506/// int (*pfd)(double) = f; // selects f(double) 5507/// @endcode 5508/// 5509/// This routine returns the resulting FunctionDecl if it could be 5510/// resolved, and NULL otherwise. When @p Complain is true, this 5511/// routine will emit diagnostics if there is an error. 5512FunctionDecl * 5513Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 5514 bool Complain, 5515 DeclAccessPair &FoundResult) { 5516 QualType FunctionType = ToType; 5517 bool IsMember = false; 5518 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>()) 5519 FunctionType = ToTypePtr->getPointeeType(); 5520 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>()) 5521 FunctionType = ToTypeRef->getPointeeType(); 5522 else if (const MemberPointerType *MemTypePtr = 5523 ToType->getAs<MemberPointerType>()) { 5524 FunctionType = MemTypePtr->getPointeeType(); 5525 IsMember = true; 5526 } 5527 5528 // C++ [over.over]p1: 5529 // [...] [Note: any redundant set of parentheses surrounding the 5530 // overloaded function name is ignored (5.1). ] 5531 // C++ [over.over]p1: 5532 // [...] The overloaded function name can be preceded by the & 5533 // operator. 5534 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer(); 5535 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0; 5536 if (OvlExpr->hasExplicitTemplateArgs()) { 5537 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer); 5538 ExplicitTemplateArgs = &ETABuffer; 5539 } 5540 5541 // We expect a pointer or reference to function, or a function pointer. 5542 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType(); 5543 if (!FunctionType->isFunctionType()) { 5544 if (Complain) 5545 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 5546 << OvlExpr->getName() << ToType; 5547 5548 return 0; 5549 } 5550 5551 assert(From->getType() == Context.OverloadTy); 5552 5553 // Look through all of the overloaded functions, searching for one 5554 // whose type matches exactly. 5555 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 5556 llvm::SmallVector<FunctionDecl *, 4> NonMatches; 5557 5558 bool FoundNonTemplateFunction = false; 5559 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 5560 E = OvlExpr->decls_end(); I != E; ++I) { 5561 // Look through any using declarations to find the underlying function. 5562 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 5563 5564 // C++ [over.over]p3: 5565 // Non-member functions and static member functions match 5566 // targets of type "pointer-to-function" or "reference-to-function." 5567 // Nonstatic member functions match targets of 5568 // type "pointer-to-member-function." 5569 // Note that according to DR 247, the containing class does not matter. 5570 5571 if (FunctionTemplateDecl *FunctionTemplate 5572 = dyn_cast<FunctionTemplateDecl>(Fn)) { 5573 if (CXXMethodDecl *Method 5574 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 5575 // Skip non-static function templates when converting to pointer, and 5576 // static when converting to member pointer. 5577 if (Method->isStatic() == IsMember) 5578 continue; 5579 } else if (IsMember) 5580 continue; 5581 5582 // C++ [over.over]p2: 5583 // If the name is a function template, template argument deduction is 5584 // done (14.8.2.2), and if the argument deduction succeeds, the 5585 // resulting template argument list is used to generate a single 5586 // function template specialization, which is added to the set of 5587 // overloaded functions considered. 5588 // FIXME: We don't really want to build the specialization here, do we? 5589 FunctionDecl *Specialization = 0; 5590 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 5591 if (TemplateDeductionResult Result 5592 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 5593 FunctionType, Specialization, Info)) { 5594 // FIXME: make a note of the failed deduction for diagnostics. 5595 (void)Result; 5596 } else { 5597 // FIXME: If the match isn't exact, shouldn't we just drop this as 5598 // a candidate? Find a testcase before changing the code. 5599 assert(FunctionType 5600 == Context.getCanonicalType(Specialization->getType())); 5601 Matches.push_back(std::make_pair(I.getPair(), 5602 cast<FunctionDecl>(Specialization->getCanonicalDecl()))); 5603 } 5604 5605 continue; 5606 } 5607 5608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 5609 // Skip non-static functions when converting to pointer, and static 5610 // when converting to member pointer. 5611 if (Method->isStatic() == IsMember) 5612 continue; 5613 5614 // If we have explicit template arguments, skip non-templates. 5615 if (OvlExpr->hasExplicitTemplateArgs()) 5616 continue; 5617 } else if (IsMember) 5618 continue; 5619 5620 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 5621 QualType ResultTy; 5622 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) || 5623 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType, 5624 ResultTy)) { 5625 Matches.push_back(std::make_pair(I.getPair(), 5626 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 5627 FoundNonTemplateFunction = true; 5628 } 5629 } 5630 } 5631 5632 // If there were 0 or 1 matches, we're done. 5633 if (Matches.empty()) { 5634 if (Complain) { 5635 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable) 5636 << OvlExpr->getName() << FunctionType; 5637 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 5638 E = OvlExpr->decls_end(); 5639 I != E; ++I) 5640 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 5641 NoteOverloadCandidate(F); 5642 } 5643 5644 return 0; 5645 } else if (Matches.size() == 1) { 5646 FunctionDecl *Result = Matches[0].second; 5647 FoundResult = Matches[0].first; 5648 MarkDeclarationReferenced(From->getLocStart(), Result); 5649 if (Complain) 5650 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first); 5651 return Result; 5652 } 5653 5654 // C++ [over.over]p4: 5655 // If more than one function is selected, [...] 5656 if (!FoundNonTemplateFunction) { 5657 // [...] and any given function template specialization F1 is 5658 // eliminated if the set contains a second function template 5659 // specialization whose function template is more specialized 5660 // than the function template of F1 according to the partial 5661 // ordering rules of 14.5.5.2. 5662 5663 // The algorithm specified above is quadratic. We instead use a 5664 // two-pass algorithm (similar to the one used to identify the 5665 // best viable function in an overload set) that identifies the 5666 // best function template (if it exists). 5667 5668 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 5669 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 5670 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 5671 5672 UnresolvedSetIterator Result = 5673 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 5674 TPOC_Other, From->getLocStart(), 5675 PDiag(), 5676 PDiag(diag::err_addr_ovl_ambiguous) 5677 << Matches[0].second->getDeclName(), 5678 PDiag(diag::note_ovl_candidate) 5679 << (unsigned) oc_function_template); 5680 assert(Result != MatchesCopy.end() && "no most-specialized template"); 5681 MarkDeclarationReferenced(From->getLocStart(), *Result); 5682 FoundResult = Matches[Result - MatchesCopy.begin()].first; 5683 if (Complain) { 5684 CheckUnresolvedAccess(*this, OvlExpr, FoundResult); 5685 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc()); 5686 } 5687 return cast<FunctionDecl>(*Result); 5688 } 5689 5690 // [...] any function template specializations in the set are 5691 // eliminated if the set also contains a non-template function, [...] 5692 for (unsigned I = 0, N = Matches.size(); I != N; ) { 5693 if (Matches[I].second->getPrimaryTemplate() == 0) 5694 ++I; 5695 else { 5696 Matches[I] = Matches[--N]; 5697 Matches.set_size(N); 5698 } 5699 } 5700 5701 // [...] After such eliminations, if any, there shall remain exactly one 5702 // selected function. 5703 if (Matches.size() == 1) { 5704 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second); 5705 FoundResult = Matches[0].first; 5706 if (Complain) { 5707 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first); 5708 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc()); 5709 } 5710 return cast<FunctionDecl>(Matches[0].second); 5711 } 5712 5713 // FIXME: We should probably return the same thing that BestViableFunction 5714 // returns (even if we issue the diagnostics here). 5715 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous) 5716 << Matches[0].second->getDeclName(); 5717 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 5718 NoteOverloadCandidate(Matches[I].second); 5719 return 0; 5720} 5721 5722/// \brief Given an expression that refers to an overloaded function, try to 5723/// resolve that overloaded function expression down to a single function. 5724/// 5725/// This routine can only resolve template-ids that refer to a single function 5726/// template, where that template-id refers to a single template whose template 5727/// arguments are either provided by the template-id or have defaults, 5728/// as described in C++0x [temp.arg.explicit]p3. 5729FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) { 5730 // C++ [over.over]p1: 5731 // [...] [Note: any redundant set of parentheses surrounding the 5732 // overloaded function name is ignored (5.1). ] 5733 // C++ [over.over]p1: 5734 // [...] The overloaded function name can be preceded by the & 5735 // operator. 5736 5737 if (From->getType() != Context.OverloadTy) 5738 return 0; 5739 5740 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer(); 5741 5742 // If we didn't actually find any template-ids, we're done. 5743 if (!OvlExpr->hasExplicitTemplateArgs()) 5744 return 0; 5745 5746 TemplateArgumentListInfo ExplicitTemplateArgs; 5747 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 5748 5749 // Look through all of the overloaded functions, searching for one 5750 // whose type matches exactly. 5751 FunctionDecl *Matched = 0; 5752 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 5753 E = OvlExpr->decls_end(); I != E; ++I) { 5754 // C++0x [temp.arg.explicit]p3: 5755 // [...] In contexts where deduction is done and fails, or in contexts 5756 // where deduction is not done, if a template argument list is 5757 // specified and it, along with any default template arguments, 5758 // identifies a single function template specialization, then the 5759 // template-id is an lvalue for the function template specialization. 5760 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I); 5761 5762 // C++ [over.over]p2: 5763 // If the name is a function template, template argument deduction is 5764 // done (14.8.2.2), and if the argument deduction succeeds, the 5765 // resulting template argument list is used to generate a single 5766 // function template specialization, which is added to the set of 5767 // overloaded functions considered. 5768 FunctionDecl *Specialization = 0; 5769 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 5770 if (TemplateDeductionResult Result 5771 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 5772 Specialization, Info)) { 5773 // FIXME: make a note of the failed deduction for diagnostics. 5774 (void)Result; 5775 continue; 5776 } 5777 5778 // Multiple matches; we can't resolve to a single declaration. 5779 if (Matched) 5780 return 0; 5781 5782 Matched = Specialization; 5783 } 5784 5785 return Matched; 5786} 5787 5788/// \brief Add a single candidate to the overload set. 5789static void AddOverloadedCallCandidate(Sema &S, 5790 DeclAccessPair FoundDecl, 5791 const TemplateArgumentListInfo *ExplicitTemplateArgs, 5792 Expr **Args, unsigned NumArgs, 5793 OverloadCandidateSet &CandidateSet, 5794 bool PartialOverloading) { 5795 NamedDecl *Callee = FoundDecl.getDecl(); 5796 if (isa<UsingShadowDecl>(Callee)) 5797 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 5798 5799 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 5800 assert(!ExplicitTemplateArgs && "Explicit template arguments?"); 5801 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 5802 false, PartialOverloading); 5803 return; 5804 } 5805 5806 if (FunctionTemplateDecl *FuncTemplate 5807 = dyn_cast<FunctionTemplateDecl>(Callee)) { 5808 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 5809 ExplicitTemplateArgs, 5810 Args, NumArgs, CandidateSet); 5811 return; 5812 } 5813 5814 assert(false && "unhandled case in overloaded call candidate"); 5815 5816 // do nothing? 5817} 5818 5819/// \brief Add the overload candidates named by callee and/or found by argument 5820/// dependent lookup to the given overload set. 5821void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 5822 Expr **Args, unsigned NumArgs, 5823 OverloadCandidateSet &CandidateSet, 5824 bool PartialOverloading) { 5825 5826#ifndef NDEBUG 5827 // Verify that ArgumentDependentLookup is consistent with the rules 5828 // in C++0x [basic.lookup.argdep]p3: 5829 // 5830 // Let X be the lookup set produced by unqualified lookup (3.4.1) 5831 // and let Y be the lookup set produced by argument dependent 5832 // lookup (defined as follows). If X contains 5833 // 5834 // -- a declaration of a class member, or 5835 // 5836 // -- a block-scope function declaration that is not a 5837 // using-declaration, or 5838 // 5839 // -- a declaration that is neither a function or a function 5840 // template 5841 // 5842 // then Y is empty. 5843 5844 if (ULE->requiresADL()) { 5845 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 5846 E = ULE->decls_end(); I != E; ++I) { 5847 assert(!(*I)->getDeclContext()->isRecord()); 5848 assert(isa<UsingShadowDecl>(*I) || 5849 !(*I)->getDeclContext()->isFunctionOrMethod()); 5850 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 5851 } 5852 } 5853#endif 5854 5855 // It would be nice to avoid this copy. 5856 TemplateArgumentListInfo TABuffer; 5857 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 5858 if (ULE->hasExplicitTemplateArgs()) { 5859 ULE->copyTemplateArgumentsInto(TABuffer); 5860 ExplicitTemplateArgs = &TABuffer; 5861 } 5862 5863 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 5864 E = ULE->decls_end(); I != E; ++I) 5865 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 5866 Args, NumArgs, CandidateSet, 5867 PartialOverloading); 5868 5869 if (ULE->requiresADL()) 5870 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 5871 Args, NumArgs, 5872 ExplicitTemplateArgs, 5873 CandidateSet, 5874 PartialOverloading); 5875} 5876 5877static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn, 5878 Expr **Args, unsigned NumArgs) { 5879 Fn->Destroy(SemaRef.Context); 5880 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 5881 Args[Arg]->Destroy(SemaRef.Context); 5882 return SemaRef.ExprError(); 5883} 5884 5885/// Attempts to recover from a call where no functions were found. 5886/// 5887/// Returns true if new candidates were found. 5888static Sema::OwningExprResult 5889BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 5890 UnresolvedLookupExpr *ULE, 5891 SourceLocation LParenLoc, 5892 Expr **Args, unsigned NumArgs, 5893 SourceLocation *CommaLocs, 5894 SourceLocation RParenLoc) { 5895 5896 CXXScopeSpec SS; 5897 if (ULE->getQualifier()) { 5898 SS.setScopeRep(ULE->getQualifier()); 5899 SS.setRange(ULE->getQualifierRange()); 5900 } 5901 5902 TemplateArgumentListInfo TABuffer; 5903 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 5904 if (ULE->hasExplicitTemplateArgs()) { 5905 ULE->copyTemplateArgumentsInto(TABuffer); 5906 ExplicitTemplateArgs = &TABuffer; 5907 } 5908 5909 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 5910 Sema::LookupOrdinaryName); 5911 if (SemaRef.DiagnoseEmptyLookup(S, SS, R)) 5912 return Destroy(SemaRef, Fn, Args, NumArgs); 5913 5914 assert(!R.empty() && "lookup results empty despite recovery"); 5915 5916 // Build an implicit member call if appropriate. Just drop the 5917 // casts and such from the call, we don't really care. 5918 Sema::OwningExprResult NewFn = SemaRef.ExprError(); 5919 if ((*R.begin())->isCXXClassMember()) 5920 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs); 5921 else if (ExplicitTemplateArgs) 5922 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 5923 else 5924 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 5925 5926 if (NewFn.isInvalid()) 5927 return Destroy(SemaRef, Fn, Args, NumArgs); 5928 5929 Fn->Destroy(SemaRef.Context); 5930 5931 // This shouldn't cause an infinite loop because we're giving it 5932 // an expression with non-empty lookup results, which should never 5933 // end up here. 5934 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc, 5935 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs), 5936 CommaLocs, RParenLoc); 5937} 5938 5939/// ResolveOverloadedCallFn - Given the call expression that calls Fn 5940/// (which eventually refers to the declaration Func) and the call 5941/// arguments Args/NumArgs, attempt to resolve the function call down 5942/// to a specific function. If overload resolution succeeds, returns 5943/// the function declaration produced by overload 5944/// resolution. Otherwise, emits diagnostics, deletes all of the 5945/// arguments and Fn, and returns NULL. 5946Sema::OwningExprResult 5947Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 5948 SourceLocation LParenLoc, 5949 Expr **Args, unsigned NumArgs, 5950 SourceLocation *CommaLocs, 5951 SourceLocation RParenLoc) { 5952#ifndef NDEBUG 5953 if (ULE->requiresADL()) { 5954 // To do ADL, we must have found an unqualified name. 5955 assert(!ULE->getQualifier() && "qualified name with ADL"); 5956 5957 // We don't perform ADL for implicit declarations of builtins. 5958 // Verify that this was correctly set up. 5959 FunctionDecl *F; 5960 if (ULE->decls_begin() + 1 == ULE->decls_end() && 5961 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 5962 F->getBuiltinID() && F->isImplicit()) 5963 assert(0 && "performing ADL for builtin"); 5964 5965 // We don't perform ADL in C. 5966 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 5967 } 5968#endif 5969 5970 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 5971 5972 // Add the functions denoted by the callee to the set of candidate 5973 // functions, including those from argument-dependent lookup. 5974 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 5975 5976 // If we found nothing, try to recover. 5977 // AddRecoveryCallCandidates diagnoses the error itself, so we just 5978 // bailout out if it fails. 5979 if (CandidateSet.empty()) 5980 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 5981 CommaLocs, RParenLoc); 5982 5983 OverloadCandidateSet::iterator Best; 5984 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) { 5985 case OR_Success: { 5986 FunctionDecl *FDecl = Best->Function; 5987 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 5988 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc()); 5989 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 5990 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc); 5991 } 5992 5993 case OR_No_Viable_Function: 5994 Diag(Fn->getSourceRange().getBegin(), 5995 diag::err_ovl_no_viable_function_in_call) 5996 << ULE->getName() << Fn->getSourceRange(); 5997 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 5998 break; 5999 6000 case OR_Ambiguous: 6001 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 6002 << ULE->getName() << Fn->getSourceRange(); 6003 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 6004 break; 6005 6006 case OR_Deleted: 6007 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 6008 << Best->Function->isDeleted() 6009 << ULE->getName() 6010 << Fn->getSourceRange(); 6011 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6012 break; 6013 } 6014 6015 // Overload resolution failed. Destroy all of the subexpressions and 6016 // return NULL. 6017 Fn->Destroy(Context); 6018 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 6019 Args[Arg]->Destroy(Context); 6020 return ExprError(); 6021} 6022 6023static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 6024 return Functions.size() > 1 || 6025 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 6026} 6027 6028/// \brief Create a unary operation that may resolve to an overloaded 6029/// operator. 6030/// 6031/// \param OpLoc The location of the operator itself (e.g., '*'). 6032/// 6033/// \param OpcIn The UnaryOperator::Opcode that describes this 6034/// operator. 6035/// 6036/// \param Functions The set of non-member functions that will be 6037/// considered by overload resolution. The caller needs to build this 6038/// set based on the context using, e.g., 6039/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 6040/// set should not contain any member functions; those will be added 6041/// by CreateOverloadedUnaryOp(). 6042/// 6043/// \param input The input argument. 6044Sema::OwningExprResult 6045Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 6046 const UnresolvedSetImpl &Fns, 6047 ExprArg input) { 6048 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 6049 Expr *Input = (Expr *)input.get(); 6050 6051 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 6052 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 6053 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6054 6055 Expr *Args[2] = { Input, 0 }; 6056 unsigned NumArgs = 1; 6057 6058 // For post-increment and post-decrement, add the implicit '0' as 6059 // the second argument, so that we know this is a post-increment or 6060 // post-decrement. 6061 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) { 6062 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 6063 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy, 6064 SourceLocation()); 6065 NumArgs = 2; 6066 } 6067 6068 if (Input->isTypeDependent()) { 6069 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 6070 UnresolvedLookupExpr *Fn 6071 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 6072 0, SourceRange(), OpName, OpLoc, 6073 /*ADL*/ true, IsOverloaded(Fns)); 6074 Fn->addDecls(Fns.begin(), Fns.end()); 6075 6076 input.release(); 6077 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 6078 &Args[0], NumArgs, 6079 Context.DependentTy, 6080 OpLoc)); 6081 } 6082 6083 // Build an empty overload set. 6084 OverloadCandidateSet CandidateSet(OpLoc); 6085 6086 // Add the candidates from the given function set. 6087 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 6088 6089 // Add operator candidates that are member functions. 6090 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 6091 6092 // Add candidates from ADL. 6093 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 6094 Args, NumArgs, 6095 /*ExplicitTemplateArgs*/ 0, 6096 CandidateSet); 6097 6098 // Add builtin operator candidates. 6099 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 6100 6101 // Perform overload resolution. 6102 OverloadCandidateSet::iterator Best; 6103 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 6104 case OR_Success: { 6105 // We found a built-in operator or an overloaded operator. 6106 FunctionDecl *FnDecl = Best->Function; 6107 6108 if (FnDecl) { 6109 // We matched an overloaded operator. Build a call to that 6110 // operator. 6111 6112 // Convert the arguments. 6113 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 6114 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 6115 6116 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 6117 Best->FoundDecl, Method)) 6118 return ExprError(); 6119 } else { 6120 // Convert the arguments. 6121 OwningExprResult InputInit 6122 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6123 FnDecl->getParamDecl(0)), 6124 SourceLocation(), 6125 move(input)); 6126 if (InputInit.isInvalid()) 6127 return ExprError(); 6128 6129 input = move(InputInit); 6130 Input = (Expr *)input.get(); 6131 } 6132 6133 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 6134 6135 // Determine the result type 6136 QualType ResultTy = FnDecl->getResultType().getNonReferenceType(); 6137 6138 // Build the actual expression node. 6139 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 6140 SourceLocation()); 6141 UsualUnaryConversions(FnExpr); 6142 6143 input.release(); 6144 Args[0] = Input; 6145 ExprOwningPtr<CallExpr> TheCall(this, 6146 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 6147 Args, NumArgs, ResultTy, OpLoc)); 6148 6149 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 6150 FnDecl)) 6151 return ExprError(); 6152 6153 return MaybeBindToTemporary(TheCall.release()); 6154 } else { 6155 // We matched a built-in operator. Convert the arguments, then 6156 // break out so that we will build the appropriate built-in 6157 // operator node. 6158 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 6159 Best->Conversions[0], AA_Passing)) 6160 return ExprError(); 6161 6162 break; 6163 } 6164 } 6165 6166 case OR_No_Viable_Function: 6167 // No viable function; fall through to handling this as a 6168 // built-in operator, which will produce an error message for us. 6169 break; 6170 6171 case OR_Ambiguous: 6172 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 6173 << UnaryOperator::getOpcodeStr(Opc) 6174 << Input->getSourceRange(); 6175 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs, 6176 UnaryOperator::getOpcodeStr(Opc), OpLoc); 6177 return ExprError(); 6178 6179 case OR_Deleted: 6180 Diag(OpLoc, diag::err_ovl_deleted_oper) 6181 << Best->Function->isDeleted() 6182 << UnaryOperator::getOpcodeStr(Opc) 6183 << Input->getSourceRange(); 6184 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6185 return ExprError(); 6186 } 6187 6188 // Either we found no viable overloaded operator or we matched a 6189 // built-in operator. In either case, fall through to trying to 6190 // build a built-in operation. 6191 input.release(); 6192 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input)); 6193} 6194 6195/// \brief Create a binary operation that may resolve to an overloaded 6196/// operator. 6197/// 6198/// \param OpLoc The location of the operator itself (e.g., '+'). 6199/// 6200/// \param OpcIn The BinaryOperator::Opcode that describes this 6201/// operator. 6202/// 6203/// \param Functions The set of non-member functions that will be 6204/// considered by overload resolution. The caller needs to build this 6205/// set based on the context using, e.g., 6206/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 6207/// set should not contain any member functions; those will be added 6208/// by CreateOverloadedBinOp(). 6209/// 6210/// \param LHS Left-hand argument. 6211/// \param RHS Right-hand argument. 6212Sema::OwningExprResult 6213Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 6214 unsigned OpcIn, 6215 const UnresolvedSetImpl &Fns, 6216 Expr *LHS, Expr *RHS) { 6217 Expr *Args[2] = { LHS, RHS }; 6218 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 6219 6220 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 6221 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 6222 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6223 6224 // If either side is type-dependent, create an appropriate dependent 6225 // expression. 6226 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 6227 if (Fns.empty()) { 6228 // If there are no functions to store, just build a dependent 6229 // BinaryOperator or CompoundAssignment. 6230 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign) 6231 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 6232 Context.DependentTy, OpLoc)); 6233 6234 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 6235 Context.DependentTy, 6236 Context.DependentTy, 6237 Context.DependentTy, 6238 OpLoc)); 6239 } 6240 6241 // FIXME: save results of ADL from here? 6242 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 6243 UnresolvedLookupExpr *Fn 6244 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 6245 0, SourceRange(), OpName, OpLoc, 6246 /*ADL*/ true, IsOverloaded(Fns)); 6247 6248 Fn->addDecls(Fns.begin(), Fns.end()); 6249 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 6250 Args, 2, 6251 Context.DependentTy, 6252 OpLoc)); 6253 } 6254 6255 // If this is the .* operator, which is not overloadable, just 6256 // create a built-in binary operator. 6257 if (Opc == BinaryOperator::PtrMemD) 6258 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6259 6260 // If this is the assignment operator, we only perform overload resolution 6261 // if the left-hand side is a class or enumeration type. This is actually 6262 // a hack. The standard requires that we do overload resolution between the 6263 // various built-in candidates, but as DR507 points out, this can lead to 6264 // problems. So we do it this way, which pretty much follows what GCC does. 6265 // Note that we go the traditional code path for compound assignment forms. 6266 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType()) 6267 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6268 6269 // Build an empty overload set. 6270 OverloadCandidateSet CandidateSet(OpLoc); 6271 6272 // Add the candidates from the given function set. 6273 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 6274 6275 // Add operator candidates that are member functions. 6276 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 6277 6278 // Add candidates from ADL. 6279 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 6280 Args, 2, 6281 /*ExplicitTemplateArgs*/ 0, 6282 CandidateSet); 6283 6284 // Add builtin operator candidates. 6285 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 6286 6287 // Perform overload resolution. 6288 OverloadCandidateSet::iterator Best; 6289 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 6290 case OR_Success: { 6291 // We found a built-in operator or an overloaded operator. 6292 FunctionDecl *FnDecl = Best->Function; 6293 6294 if (FnDecl) { 6295 // We matched an overloaded operator. Build a call to that 6296 // operator. 6297 6298 // Convert the arguments. 6299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 6300 // Best->Access is only meaningful for class members. 6301 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 6302 6303 OwningExprResult Arg1 6304 = PerformCopyInitialization( 6305 InitializedEntity::InitializeParameter( 6306 FnDecl->getParamDecl(0)), 6307 SourceLocation(), 6308 Owned(Args[1])); 6309 if (Arg1.isInvalid()) 6310 return ExprError(); 6311 6312 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 6313 Best->FoundDecl, Method)) 6314 return ExprError(); 6315 6316 Args[1] = RHS = Arg1.takeAs<Expr>(); 6317 } else { 6318 // Convert the arguments. 6319 OwningExprResult Arg0 6320 = PerformCopyInitialization( 6321 InitializedEntity::InitializeParameter( 6322 FnDecl->getParamDecl(0)), 6323 SourceLocation(), 6324 Owned(Args[0])); 6325 if (Arg0.isInvalid()) 6326 return ExprError(); 6327 6328 OwningExprResult Arg1 6329 = PerformCopyInitialization( 6330 InitializedEntity::InitializeParameter( 6331 FnDecl->getParamDecl(1)), 6332 SourceLocation(), 6333 Owned(Args[1])); 6334 if (Arg1.isInvalid()) 6335 return ExprError(); 6336 Args[0] = LHS = Arg0.takeAs<Expr>(); 6337 Args[1] = RHS = Arg1.takeAs<Expr>(); 6338 } 6339 6340 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 6341 6342 // Determine the result type 6343 QualType ResultTy 6344 = FnDecl->getType()->getAs<FunctionType>()->getResultType(); 6345 ResultTy = ResultTy.getNonReferenceType(); 6346 6347 // Build the actual expression node. 6348 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 6349 OpLoc); 6350 UsualUnaryConversions(FnExpr); 6351 6352 ExprOwningPtr<CXXOperatorCallExpr> 6353 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 6354 Args, 2, ResultTy, 6355 OpLoc)); 6356 6357 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 6358 FnDecl)) 6359 return ExprError(); 6360 6361 return MaybeBindToTemporary(TheCall.release()); 6362 } else { 6363 // We matched a built-in operator. Convert the arguments, then 6364 // break out so that we will build the appropriate built-in 6365 // operator node. 6366 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 6367 Best->Conversions[0], AA_Passing) || 6368 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 6369 Best->Conversions[1], AA_Passing)) 6370 return ExprError(); 6371 6372 break; 6373 } 6374 } 6375 6376 case OR_No_Viable_Function: { 6377 // C++ [over.match.oper]p9: 6378 // If the operator is the operator , [...] and there are no 6379 // viable functions, then the operator is assumed to be the 6380 // built-in operator and interpreted according to clause 5. 6381 if (Opc == BinaryOperator::Comma) 6382 break; 6383 6384 // For class as left operand for assignment or compound assigment operator 6385 // do not fall through to handling in built-in, but report that no overloaded 6386 // assignment operator found 6387 OwningExprResult Result = ExprError(); 6388 if (Args[0]->getType()->isRecordType() && 6389 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) { 6390 Diag(OpLoc, diag::err_ovl_no_viable_oper) 6391 << BinaryOperator::getOpcodeStr(Opc) 6392 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6393 } else { 6394 // No viable function; try to create a built-in operation, which will 6395 // produce an error. Then, show the non-viable candidates. 6396 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6397 } 6398 assert(Result.isInvalid() && 6399 "C++ binary operator overloading is missing candidates!"); 6400 if (Result.isInvalid()) 6401 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 6402 BinaryOperator::getOpcodeStr(Opc), OpLoc); 6403 return move(Result); 6404 } 6405 6406 case OR_Ambiguous: 6407 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 6408 << BinaryOperator::getOpcodeStr(Opc) 6409 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6410 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2, 6411 BinaryOperator::getOpcodeStr(Opc), OpLoc); 6412 return ExprError(); 6413 6414 case OR_Deleted: 6415 Diag(OpLoc, diag::err_ovl_deleted_oper) 6416 << Best->Function->isDeleted() 6417 << BinaryOperator::getOpcodeStr(Opc) 6418 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6419 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2); 6420 return ExprError(); 6421 } 6422 6423 // We matched a built-in operator; build it. 6424 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 6425} 6426 6427Action::OwningExprResult 6428Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 6429 SourceLocation RLoc, 6430 ExprArg Base, ExprArg Idx) { 6431 Expr *Args[2] = { static_cast<Expr*>(Base.get()), 6432 static_cast<Expr*>(Idx.get()) }; 6433 DeclarationName OpName = 6434 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 6435 6436 // If either side is type-dependent, create an appropriate dependent 6437 // expression. 6438 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 6439 6440 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 6441 UnresolvedLookupExpr *Fn 6442 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 6443 0, SourceRange(), OpName, LLoc, 6444 /*ADL*/ true, /*Overloaded*/ false); 6445 // Can't add any actual overloads yet 6446 6447 Base.release(); 6448 Idx.release(); 6449 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 6450 Args, 2, 6451 Context.DependentTy, 6452 RLoc)); 6453 } 6454 6455 // Build an empty overload set. 6456 OverloadCandidateSet CandidateSet(LLoc); 6457 6458 // Subscript can only be overloaded as a member function. 6459 6460 // Add operator candidates that are member functions. 6461 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 6462 6463 // Add builtin operator candidates. 6464 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 6465 6466 // Perform overload resolution. 6467 OverloadCandidateSet::iterator Best; 6468 switch (BestViableFunction(CandidateSet, LLoc, Best)) { 6469 case OR_Success: { 6470 // We found a built-in operator or an overloaded operator. 6471 FunctionDecl *FnDecl = Best->Function; 6472 6473 if (FnDecl) { 6474 // We matched an overloaded operator. Build a call to that 6475 // operator. 6476 6477 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 6478 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 6479 6480 // Convert the arguments. 6481 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 6482 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 6483 Best->FoundDecl, Method)) 6484 return ExprError(); 6485 6486 // Convert the arguments. 6487 OwningExprResult InputInit 6488 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6489 FnDecl->getParamDecl(0)), 6490 SourceLocation(), 6491 Owned(Args[1])); 6492 if (InputInit.isInvalid()) 6493 return ExprError(); 6494 6495 Args[1] = InputInit.takeAs<Expr>(); 6496 6497 // Determine the result type 6498 QualType ResultTy 6499 = FnDecl->getType()->getAs<FunctionType>()->getResultType(); 6500 ResultTy = ResultTy.getNonReferenceType(); 6501 6502 // Build the actual expression node. 6503 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 6504 LLoc); 6505 UsualUnaryConversions(FnExpr); 6506 6507 Base.release(); 6508 Idx.release(); 6509 ExprOwningPtr<CXXOperatorCallExpr> 6510 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 6511 FnExpr, Args, 2, 6512 ResultTy, RLoc)); 6513 6514 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(), 6515 FnDecl)) 6516 return ExprError(); 6517 6518 return MaybeBindToTemporary(TheCall.release()); 6519 } else { 6520 // We matched a built-in operator. Convert the arguments, then 6521 // break out so that we will build the appropriate built-in 6522 // operator node. 6523 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 6524 Best->Conversions[0], AA_Passing) || 6525 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 6526 Best->Conversions[1], AA_Passing)) 6527 return ExprError(); 6528 6529 break; 6530 } 6531 } 6532 6533 case OR_No_Viable_Function: { 6534 if (CandidateSet.empty()) 6535 Diag(LLoc, diag::err_ovl_no_oper) 6536 << Args[0]->getType() << /*subscript*/ 0 6537 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6538 else 6539 Diag(LLoc, diag::err_ovl_no_viable_subscript) 6540 << Args[0]->getType() 6541 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6542 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 6543 "[]", LLoc); 6544 return ExprError(); 6545 } 6546 6547 case OR_Ambiguous: 6548 Diag(LLoc, diag::err_ovl_ambiguous_oper) 6549 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6550 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2, 6551 "[]", LLoc); 6552 return ExprError(); 6553 6554 case OR_Deleted: 6555 Diag(LLoc, diag::err_ovl_deleted_oper) 6556 << Best->Function->isDeleted() << "[]" 6557 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 6558 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 6559 "[]", LLoc); 6560 return ExprError(); 6561 } 6562 6563 // We matched a built-in operator; build it. 6564 Base.release(); 6565 Idx.release(); 6566 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc, 6567 Owned(Args[1]), RLoc); 6568} 6569 6570/// BuildCallToMemberFunction - Build a call to a member 6571/// function. MemExpr is the expression that refers to the member 6572/// function (and includes the object parameter), Args/NumArgs are the 6573/// arguments to the function call (not including the object 6574/// parameter). The caller needs to validate that the member 6575/// expression refers to a member function or an overloaded member 6576/// function. 6577Sema::OwningExprResult 6578Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 6579 SourceLocation LParenLoc, Expr **Args, 6580 unsigned NumArgs, SourceLocation *CommaLocs, 6581 SourceLocation RParenLoc) { 6582 // Dig out the member expression. This holds both the object 6583 // argument and the member function we're referring to. 6584 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 6585 6586 MemberExpr *MemExpr; 6587 CXXMethodDecl *Method = 0; 6588 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 6589 NestedNameSpecifier *Qualifier = 0; 6590 if (isa<MemberExpr>(NakedMemExpr)) { 6591 MemExpr = cast<MemberExpr>(NakedMemExpr); 6592 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 6593 FoundDecl = MemExpr->getFoundDecl(); 6594 Qualifier = MemExpr->getQualifier(); 6595 } else { 6596 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 6597 Qualifier = UnresExpr->getQualifier(); 6598 6599 QualType ObjectType = UnresExpr->getBaseType(); 6600 6601 // Add overload candidates 6602 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 6603 6604 // FIXME: avoid copy. 6605 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 6606 if (UnresExpr->hasExplicitTemplateArgs()) { 6607 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 6608 TemplateArgs = &TemplateArgsBuffer; 6609 } 6610 6611 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 6612 E = UnresExpr->decls_end(); I != E; ++I) { 6613 6614 NamedDecl *Func = *I; 6615 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 6616 if (isa<UsingShadowDecl>(Func)) 6617 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 6618 6619 if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 6620 // If explicit template arguments were provided, we can't call a 6621 // non-template member function. 6622 if (TemplateArgs) 6623 continue; 6624 6625 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 6626 Args, NumArgs, 6627 CandidateSet, /*SuppressUserConversions=*/false); 6628 } else { 6629 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 6630 I.getPair(), ActingDC, TemplateArgs, 6631 ObjectType, Args, NumArgs, 6632 CandidateSet, 6633 /*SuppressUsedConversions=*/false); 6634 } 6635 } 6636 6637 DeclarationName DeclName = UnresExpr->getMemberName(); 6638 6639 OverloadCandidateSet::iterator Best; 6640 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) { 6641 case OR_Success: 6642 Method = cast<CXXMethodDecl>(Best->Function); 6643 FoundDecl = Best->FoundDecl; 6644 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 6645 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 6646 break; 6647 6648 case OR_No_Viable_Function: 6649 Diag(UnresExpr->getMemberLoc(), 6650 diag::err_ovl_no_viable_member_function_in_call) 6651 << DeclName << MemExprE->getSourceRange(); 6652 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6653 // FIXME: Leaking incoming expressions! 6654 return ExprError(); 6655 6656 case OR_Ambiguous: 6657 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 6658 << DeclName << MemExprE->getSourceRange(); 6659 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6660 // FIXME: Leaking incoming expressions! 6661 return ExprError(); 6662 6663 case OR_Deleted: 6664 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 6665 << Best->Function->isDeleted() 6666 << DeclName << MemExprE->getSourceRange(); 6667 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6668 // FIXME: Leaking incoming expressions! 6669 return ExprError(); 6670 } 6671 6672 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 6673 6674 // If overload resolution picked a static member, build a 6675 // non-member call based on that function. 6676 if (Method->isStatic()) { 6677 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 6678 Args, NumArgs, RParenLoc); 6679 } 6680 6681 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 6682 } 6683 6684 assert(Method && "Member call to something that isn't a method?"); 6685 ExprOwningPtr<CXXMemberCallExpr> 6686 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 6687 NumArgs, 6688 Method->getResultType().getNonReferenceType(), 6689 RParenLoc)); 6690 6691 // Check for a valid return type. 6692 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 6693 TheCall.get(), Method)) 6694 return ExprError(); 6695 6696 // Convert the object argument (for a non-static member function call). 6697 // We only need to do this if there was actually an overload; otherwise 6698 // it was done at lookup. 6699 Expr *ObjectArg = MemExpr->getBase(); 6700 if (!Method->isStatic() && 6701 PerformObjectArgumentInitialization(ObjectArg, Qualifier, 6702 FoundDecl, Method)) 6703 return ExprError(); 6704 MemExpr->setBase(ObjectArg); 6705 6706 // Convert the rest of the arguments 6707 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 6708 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs, 6709 RParenLoc)) 6710 return ExprError(); 6711 6712 if (CheckFunctionCall(Method, TheCall.get())) 6713 return ExprError(); 6714 6715 return MaybeBindToTemporary(TheCall.release()); 6716} 6717 6718/// BuildCallToObjectOfClassType - Build a call to an object of class 6719/// type (C++ [over.call.object]), which can end up invoking an 6720/// overloaded function call operator (@c operator()) or performing a 6721/// user-defined conversion on the object argument. 6722Sema::ExprResult 6723Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 6724 SourceLocation LParenLoc, 6725 Expr **Args, unsigned NumArgs, 6726 SourceLocation *CommaLocs, 6727 SourceLocation RParenLoc) { 6728 assert(Object->getType()->isRecordType() && "Requires object type argument"); 6729 const RecordType *Record = Object->getType()->getAs<RecordType>(); 6730 6731 // C++ [over.call.object]p1: 6732 // If the primary-expression E in the function call syntax 6733 // evaluates to a class object of type "cv T", then the set of 6734 // candidate functions includes at least the function call 6735 // operators of T. The function call operators of T are obtained by 6736 // ordinary lookup of the name operator() in the context of 6737 // (E).operator(). 6738 OverloadCandidateSet CandidateSet(LParenLoc); 6739 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 6740 6741 if (RequireCompleteType(LParenLoc, Object->getType(), 6742 PDiag(diag::err_incomplete_object_call) 6743 << Object->getSourceRange())) 6744 return true; 6745 6746 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 6747 LookupQualifiedName(R, Record->getDecl()); 6748 R.suppressDiagnostics(); 6749 6750 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 6751 Oper != OperEnd; ++Oper) { 6752 AddMethodCandidate(Oper.getPair(), Object->getType(), 6753 Args, NumArgs, CandidateSet, 6754 /*SuppressUserConversions=*/ false); 6755 } 6756 6757 // C++ [over.call.object]p2: 6758 // In addition, for each conversion function declared in T of the 6759 // form 6760 // 6761 // operator conversion-type-id () cv-qualifier; 6762 // 6763 // where cv-qualifier is the same cv-qualification as, or a 6764 // greater cv-qualification than, cv, and where conversion-type-id 6765 // denotes the type "pointer to function of (P1,...,Pn) returning 6766 // R", or the type "reference to pointer to function of 6767 // (P1,...,Pn) returning R", or the type "reference to function 6768 // of (P1,...,Pn) returning R", a surrogate call function [...] 6769 // is also considered as a candidate function. Similarly, 6770 // surrogate call functions are added to the set of candidate 6771 // functions for each conversion function declared in an 6772 // accessible base class provided the function is not hidden 6773 // within T by another intervening declaration. 6774 const UnresolvedSetImpl *Conversions 6775 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 6776 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6777 E = Conversions->end(); I != E; ++I) { 6778 NamedDecl *D = *I; 6779 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6780 if (isa<UsingShadowDecl>(D)) 6781 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6782 6783 // Skip over templated conversion functions; they aren't 6784 // surrogates. 6785 if (isa<FunctionTemplateDecl>(D)) 6786 continue; 6787 6788 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6789 6790 // Strip the reference type (if any) and then the pointer type (if 6791 // any) to get down to what might be a function type. 6792 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 6793 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 6794 ConvType = ConvPtrType->getPointeeType(); 6795 6796 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 6797 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 6798 Object->getType(), Args, NumArgs, 6799 CandidateSet); 6800 } 6801 6802 // Perform overload resolution. 6803 OverloadCandidateSet::iterator Best; 6804 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) { 6805 case OR_Success: 6806 // Overload resolution succeeded; we'll build the appropriate call 6807 // below. 6808 break; 6809 6810 case OR_No_Viable_Function: 6811 if (CandidateSet.empty()) 6812 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper) 6813 << Object->getType() << /*call*/ 1 6814 << Object->getSourceRange(); 6815 else 6816 Diag(Object->getSourceRange().getBegin(), 6817 diag::err_ovl_no_viable_object_call) 6818 << Object->getType() << Object->getSourceRange(); 6819 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6820 break; 6821 6822 case OR_Ambiguous: 6823 Diag(Object->getSourceRange().getBegin(), 6824 diag::err_ovl_ambiguous_object_call) 6825 << Object->getType() << Object->getSourceRange(); 6826 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 6827 break; 6828 6829 case OR_Deleted: 6830 Diag(Object->getSourceRange().getBegin(), 6831 diag::err_ovl_deleted_object_call) 6832 << Best->Function->isDeleted() 6833 << Object->getType() << Object->getSourceRange(); 6834 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6835 break; 6836 } 6837 6838 if (Best == CandidateSet.end()) { 6839 // We had an error; delete all of the subexpressions and return 6840 // the error. 6841 Object->Destroy(Context); 6842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6843 Args[ArgIdx]->Destroy(Context); 6844 return true; 6845 } 6846 6847 if (Best->Function == 0) { 6848 // Since there is no function declaration, this is one of the 6849 // surrogate candidates. Dig out the conversion function. 6850 CXXConversionDecl *Conv 6851 = cast<CXXConversionDecl>( 6852 Best->Conversions[0].UserDefined.ConversionFunction); 6853 6854 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 6855 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 6856 6857 // We selected one of the surrogate functions that converts the 6858 // object parameter to a function pointer. Perform the conversion 6859 // on the object argument, then let ActOnCallExpr finish the job. 6860 6861 // Create an implicit member expr to refer to the conversion operator. 6862 // and then call it. 6863 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl, 6864 Conv); 6865 6866 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc, 6867 MultiExprArg(*this, (ExprTy**)Args, NumArgs), 6868 CommaLocs, RParenLoc).result(); 6869 } 6870 6871 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 6872 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 6873 6874 // We found an overloaded operator(). Build a CXXOperatorCallExpr 6875 // that calls this method, using Object for the implicit object 6876 // parameter and passing along the remaining arguments. 6877 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 6878 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 6879 6880 unsigned NumArgsInProto = Proto->getNumArgs(); 6881 unsigned NumArgsToCheck = NumArgs; 6882 6883 // Build the full argument list for the method call (the 6884 // implicit object parameter is placed at the beginning of the 6885 // list). 6886 Expr **MethodArgs; 6887 if (NumArgs < NumArgsInProto) { 6888 NumArgsToCheck = NumArgsInProto; 6889 MethodArgs = new Expr*[NumArgsInProto + 1]; 6890 } else { 6891 MethodArgs = new Expr*[NumArgs + 1]; 6892 } 6893 MethodArgs[0] = Object; 6894 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6895 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 6896 6897 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 6898 SourceLocation()); 6899 UsualUnaryConversions(NewFn); 6900 6901 // Once we've built TheCall, all of the expressions are properly 6902 // owned. 6903 QualType ResultTy = Method->getResultType().getNonReferenceType(); 6904 ExprOwningPtr<CXXOperatorCallExpr> 6905 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn, 6906 MethodArgs, NumArgs + 1, 6907 ResultTy, RParenLoc)); 6908 delete [] MethodArgs; 6909 6910 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(), 6911 Method)) 6912 return true; 6913 6914 // We may have default arguments. If so, we need to allocate more 6915 // slots in the call for them. 6916 if (NumArgs < NumArgsInProto) 6917 TheCall->setNumArgs(Context, NumArgsInProto + 1); 6918 else if (NumArgs > NumArgsInProto) 6919 NumArgsToCheck = NumArgsInProto; 6920 6921 bool IsError = false; 6922 6923 // Initialize the implicit object parameter. 6924 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0, 6925 Best->FoundDecl, Method); 6926 TheCall->setArg(0, Object); 6927 6928 6929 // Check the argument types. 6930 for (unsigned i = 0; i != NumArgsToCheck; i++) { 6931 Expr *Arg; 6932 if (i < NumArgs) { 6933 Arg = Args[i]; 6934 6935 // Pass the argument. 6936 6937 OwningExprResult InputInit 6938 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6939 Method->getParamDecl(i)), 6940 SourceLocation(), Owned(Arg)); 6941 6942 IsError |= InputInit.isInvalid(); 6943 Arg = InputInit.takeAs<Expr>(); 6944 } else { 6945 OwningExprResult DefArg 6946 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 6947 if (DefArg.isInvalid()) { 6948 IsError = true; 6949 break; 6950 } 6951 6952 Arg = DefArg.takeAs<Expr>(); 6953 } 6954 6955 TheCall->setArg(i + 1, Arg); 6956 } 6957 6958 // If this is a variadic call, handle args passed through "...". 6959 if (Proto->isVariadic()) { 6960 // Promote the arguments (C99 6.5.2.2p7). 6961 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 6962 Expr *Arg = Args[i]; 6963 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod); 6964 TheCall->setArg(i + 1, Arg); 6965 } 6966 } 6967 6968 if (IsError) return true; 6969 6970 if (CheckFunctionCall(Method, TheCall.get())) 6971 return true; 6972 6973 return MaybeBindToTemporary(TheCall.release()).result(); 6974} 6975 6976/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 6977/// (if one exists), where @c Base is an expression of class type and 6978/// @c Member is the name of the member we're trying to find. 6979Sema::OwningExprResult 6980Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) { 6981 Expr *Base = static_cast<Expr *>(BaseIn.get()); 6982 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 6983 6984 SourceLocation Loc = Base->getExprLoc(); 6985 6986 // C++ [over.ref]p1: 6987 // 6988 // [...] An expression x->m is interpreted as (x.operator->())->m 6989 // for a class object x of type T if T::operator->() exists and if 6990 // the operator is selected as the best match function by the 6991 // overload resolution mechanism (13.3). 6992 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 6993 OverloadCandidateSet CandidateSet(Loc); 6994 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 6995 6996 if (RequireCompleteType(Loc, Base->getType(), 6997 PDiag(diag::err_typecheck_incomplete_tag) 6998 << Base->getSourceRange())) 6999 return ExprError(); 7000 7001 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 7002 LookupQualifiedName(R, BaseRecord->getDecl()); 7003 R.suppressDiagnostics(); 7004 7005 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 7006 Oper != OperEnd; ++Oper) { 7007 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet, 7008 /*SuppressUserConversions=*/false); 7009 } 7010 7011 // Perform overload resolution. 7012 OverloadCandidateSet::iterator Best; 7013 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 7014 case OR_Success: 7015 // Overload resolution succeeded; we'll build the call below. 7016 break; 7017 7018 case OR_No_Viable_Function: 7019 if (CandidateSet.empty()) 7020 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 7021 << Base->getType() << Base->getSourceRange(); 7022 else 7023 Diag(OpLoc, diag::err_ovl_no_viable_oper) 7024 << "operator->" << Base->getSourceRange(); 7025 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1); 7026 return ExprError(); 7027 7028 case OR_Ambiguous: 7029 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 7030 << "->" << Base->getSourceRange(); 7031 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1); 7032 return ExprError(); 7033 7034 case OR_Deleted: 7035 Diag(OpLoc, diag::err_ovl_deleted_oper) 7036 << Best->Function->isDeleted() 7037 << "->" << Base->getSourceRange(); 7038 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1); 7039 return ExprError(); 7040 } 7041 7042 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 7043 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 7044 7045 // Convert the object parameter. 7046 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 7047 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 7048 Best->FoundDecl, Method)) 7049 return ExprError(); 7050 7051 // No concerns about early exits now. 7052 BaseIn.release(); 7053 7054 // Build the operator call. 7055 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(), 7056 SourceLocation()); 7057 UsualUnaryConversions(FnExpr); 7058 7059 QualType ResultTy = Method->getResultType().getNonReferenceType(); 7060 ExprOwningPtr<CXXOperatorCallExpr> 7061 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 7062 &Base, 1, ResultTy, OpLoc)); 7063 7064 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(), 7065 Method)) 7066 return ExprError(); 7067 return move(TheCall); 7068} 7069 7070/// FixOverloadedFunctionReference - E is an expression that refers to 7071/// a C++ overloaded function (possibly with some parentheses and 7072/// perhaps a '&' around it). We have resolved the overloaded function 7073/// to the function declaration Fn, so patch up the expression E to 7074/// refer (possibly indirectly) to Fn. Returns the new expr. 7075Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 7076 FunctionDecl *Fn) { 7077 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 7078 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 7079 Found, Fn); 7080 if (SubExpr == PE->getSubExpr()) 7081 return PE->Retain(); 7082 7083 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 7084 } 7085 7086 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7087 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 7088 Found, Fn); 7089 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 7090 SubExpr->getType()) && 7091 "Implicit cast type cannot be determined from overload"); 7092 if (SubExpr == ICE->getSubExpr()) 7093 return ICE->Retain(); 7094 7095 return new (Context) ImplicitCastExpr(ICE->getType(), 7096 ICE->getCastKind(), 7097 SubExpr, CXXBaseSpecifierArray(), 7098 ICE->isLvalueCast()); 7099 } 7100 7101 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 7102 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 7103 "Can only take the address of an overloaded function"); 7104 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7105 if (Method->isStatic()) { 7106 // Do nothing: static member functions aren't any different 7107 // from non-member functions. 7108 } else { 7109 // Fix the sub expression, which really has to be an 7110 // UnresolvedLookupExpr holding an overloaded member function 7111 // or template. 7112 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 7113 Found, Fn); 7114 if (SubExpr == UnOp->getSubExpr()) 7115 return UnOp->Retain(); 7116 7117 assert(isa<DeclRefExpr>(SubExpr) 7118 && "fixed to something other than a decl ref"); 7119 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 7120 && "fixed to a member ref with no nested name qualifier"); 7121 7122 // We have taken the address of a pointer to member 7123 // function. Perform the computation here so that we get the 7124 // appropriate pointer to member type. 7125 QualType ClassType 7126 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 7127 QualType MemPtrType 7128 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 7129 7130 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 7131 MemPtrType, UnOp->getOperatorLoc()); 7132 } 7133 } 7134 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 7135 Found, Fn); 7136 if (SubExpr == UnOp->getSubExpr()) 7137 return UnOp->Retain(); 7138 7139 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 7140 Context.getPointerType(SubExpr->getType()), 7141 UnOp->getOperatorLoc()); 7142 } 7143 7144 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 7145 // FIXME: avoid copy. 7146 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7147 if (ULE->hasExplicitTemplateArgs()) { 7148 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 7149 TemplateArgs = &TemplateArgsBuffer; 7150 } 7151 7152 return DeclRefExpr::Create(Context, 7153 ULE->getQualifier(), 7154 ULE->getQualifierRange(), 7155 Fn, 7156 ULE->getNameLoc(), 7157 Fn->getType(), 7158 TemplateArgs); 7159 } 7160 7161 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 7162 // FIXME: avoid copy. 7163 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7164 if (MemExpr->hasExplicitTemplateArgs()) { 7165 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 7166 TemplateArgs = &TemplateArgsBuffer; 7167 } 7168 7169 Expr *Base; 7170 7171 // If we're filling in 7172 if (MemExpr->isImplicitAccess()) { 7173 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 7174 return DeclRefExpr::Create(Context, 7175 MemExpr->getQualifier(), 7176 MemExpr->getQualifierRange(), 7177 Fn, 7178 MemExpr->getMemberLoc(), 7179 Fn->getType(), 7180 TemplateArgs); 7181 } else { 7182 SourceLocation Loc = MemExpr->getMemberLoc(); 7183 if (MemExpr->getQualifier()) 7184 Loc = MemExpr->getQualifierRange().getBegin(); 7185 Base = new (Context) CXXThisExpr(Loc, 7186 MemExpr->getBaseType(), 7187 /*isImplicit=*/true); 7188 } 7189 } else 7190 Base = MemExpr->getBase()->Retain(); 7191 7192 return MemberExpr::Create(Context, Base, 7193 MemExpr->isArrow(), 7194 MemExpr->getQualifier(), 7195 MemExpr->getQualifierRange(), 7196 Fn, 7197 Found, 7198 MemExpr->getMemberLoc(), 7199 TemplateArgs, 7200 Fn->getType()); 7201 } 7202 7203 assert(false && "Invalid reference to overloaded function"); 7204 return E->Retain(); 7205} 7206 7207Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E, 7208 DeclAccessPair Found, 7209 FunctionDecl *Fn) { 7210 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 7211} 7212 7213} // end namespace clang 7214