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