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