1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 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/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 namespace clang { 39 using namespace sema; 40 41 /// A convenience routine for creating a decayed reference to a function. 42 static ExprResult 43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 44 bool HadMultipleCandidates, 45 SourceLocation Loc = SourceLocation(), 46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 48 return ExprError(); 49 // If FoundDecl is different from Fn (such as if one is a template 50 // and the other a specialization), make sure DiagnoseUseOfDecl is 51 // called on both. 52 // FIXME: This would be more comprehensively addressed by modifying 53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 54 // being used. 55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 56 return ExprError(); 57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 58 VK_LValue, Loc, LocInfo); 59 if (HadMultipleCandidates) 60 DRE->setHadMultipleCandidates(true); 61 62 S.MarkDeclRefReferenced(DRE); 63 64 ExprResult E = DRE; 65 E = S.DefaultFunctionArrayConversion(E.get()); 66 if (E.isInvalid()) 67 return ExprError(); 68 return E; 69 } 70 71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 72 bool InOverloadResolution, 73 StandardConversionSequence &SCS, 74 bool CStyle, 75 bool AllowObjCWritebackConversion); 76 77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 78 QualType &ToType, 79 bool InOverloadResolution, 80 StandardConversionSequence &SCS, 81 bool CStyle); 82 static OverloadingResult 83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 84 UserDefinedConversionSequence& User, 85 OverloadCandidateSet& Conversions, 86 bool AllowExplicit, 87 bool AllowObjCConversionOnExplicit); 88 89 90 static ImplicitConversionSequence::CompareKind 91 CompareStandardConversionSequences(Sema &S, 92 const StandardConversionSequence& SCS1, 93 const StandardConversionSequence& SCS2); 94 95 static ImplicitConversionSequence::CompareKind 96 CompareQualificationConversions(Sema &S, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareDerivedToBaseConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 106 107 /// GetConversionCategory - Retrieve the implicit conversion 108 /// category corresponding to the given implicit conversion kind. 109 ImplicitConversionCategory 110 GetConversionCategory(ImplicitConversionKind Kind) { 111 static const ImplicitConversionCategory 112 Category[(int)ICK_Num_Conversion_Kinds] = { 113 ICC_Identity, 114 ICC_Lvalue_Transformation, 115 ICC_Lvalue_Transformation, 116 ICC_Lvalue_Transformation, 117 ICC_Identity, 118 ICC_Qualification_Adjustment, 119 ICC_Promotion, 120 ICC_Promotion, 121 ICC_Promotion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion, 132 ICC_Conversion, 133 ICC_Conversion, 134 ICC_Conversion 135 }; 136 return Category[(int)Kind]; 137 } 138 139 /// GetConversionRank - Retrieve the implicit conversion rank 140 /// corresponding to the given implicit conversion kind. 141 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 142 static const ImplicitConversionRank 143 Rank[(int)ICK_Num_Conversion_Kinds] = { 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Exact_Match, 148 ICR_Exact_Match, 149 ICR_Exact_Match, 150 ICR_Promotion, 151 ICR_Promotion, 152 ICR_Promotion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Conversion, 162 ICR_Conversion, 163 ICR_Conversion, 164 ICR_Complex_Real_Conversion, 165 ICR_Conversion, 166 ICR_Conversion, 167 ICR_Writeback_Conversion 168 }; 169 return Rank[(int)Kind]; 170 } 171 172 /// GetImplicitConversionName - Return the name of this kind of 173 /// implicit conversion. 174 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 175 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 176 "No conversion", 177 "Lvalue-to-rvalue", 178 "Array-to-pointer", 179 "Function-to-pointer", 180 "Noreturn adjustment", 181 "Qualification", 182 "Integral promotion", 183 "Floating point promotion", 184 "Complex promotion", 185 "Integral conversion", 186 "Floating conversion", 187 "Complex conversion", 188 "Floating-integral conversion", 189 "Pointer conversion", 190 "Pointer-to-member conversion", 191 "Boolean conversion", 192 "Compatible-types conversion", 193 "Derived-to-base conversion", 194 "Vector conversion", 195 "Vector splat", 196 "Complex-real conversion", 197 "Block Pointer conversion", 198 "Transparent Union Conversion" 199 "Writeback conversion" 200 }; 201 return Name[Kind]; 202 } 203 204 /// StandardConversionSequence - Set the standard conversion 205 /// sequence to the identity conversion. 206 void StandardConversionSequence::setAsIdentityConversion() { 207 First = ICK_Identity; 208 Second = ICK_Identity; 209 Third = ICK_Identity; 210 DeprecatedStringLiteralToCharPtr = false; 211 QualificationIncludesObjCLifetime = false; 212 ReferenceBinding = false; 213 DirectBinding = false; 214 IsLvalueReference = true; 215 BindsToFunctionLvalue = false; 216 BindsToRvalue = false; 217 BindsImplicitObjectArgumentWithoutRefQualifier = false; 218 ObjCLifetimeConversionBinding = false; 219 CopyConstructor = nullptr; 220 } 221 222 /// getRank - Retrieve the rank of this standard conversion sequence 223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 224 /// implicit conversions. 225 ImplicitConversionRank StandardConversionSequence::getRank() const { 226 ImplicitConversionRank Rank = ICR_Exact_Match; 227 if (GetConversionRank(First) > Rank) 228 Rank = GetConversionRank(First); 229 if (GetConversionRank(Second) > Rank) 230 Rank = GetConversionRank(Second); 231 if (GetConversionRank(Third) > Rank) 232 Rank = GetConversionRank(Third); 233 return Rank; 234 } 235 236 /// isPointerConversionToBool - Determines whether this conversion is 237 /// a conversion of a pointer or pointer-to-member to bool. This is 238 /// used as part of the ranking of standard conversion sequences 239 /// (C++ 13.3.3.2p4). 240 bool StandardConversionSequence::isPointerConversionToBool() const { 241 // Note that FromType has not necessarily been transformed by the 242 // array-to-pointer or function-to-pointer implicit conversions, so 243 // check for their presence as well as checking whether FromType is 244 // a pointer. 245 if (getToType(1)->isBooleanType() && 246 (getFromType()->isPointerType() || 247 getFromType()->isObjCObjectPointerType() || 248 getFromType()->isBlockPointerType() || 249 getFromType()->isNullPtrType() || 250 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 251 return true; 252 253 return false; 254 } 255 256 /// isPointerConversionToVoidPointer - Determines whether this 257 /// conversion is a conversion of a pointer to a void pointer. This is 258 /// used as part of the ranking of standard conversion sequences (C++ 259 /// 13.3.3.2p4). 260 bool 261 StandardConversionSequence:: 262 isPointerConversionToVoidPointer(ASTContext& Context) const { 263 QualType FromType = getFromType(); 264 QualType ToType = getToType(1); 265 266 // Note that FromType has not necessarily been transformed by the 267 // array-to-pointer implicit conversion, so check for its presence 268 // and redo the conversion to get a pointer. 269 if (First == ICK_Array_To_Pointer) 270 FromType = Context.getArrayDecayedType(FromType); 271 272 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 273 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 274 return ToPtrType->getPointeeType()->isVoidType(); 275 276 return false; 277 } 278 279 /// Skip any implicit casts which could be either part of a narrowing conversion 280 /// or after one in an implicit conversion. 281 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 282 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 283 switch (ICE->getCastKind()) { 284 case CK_NoOp: 285 case CK_IntegralCast: 286 case CK_IntegralToBoolean: 287 case CK_IntegralToFloating: 288 case CK_FloatingToIntegral: 289 case CK_FloatingToBoolean: 290 case CK_FloatingCast: 291 Converted = ICE->getSubExpr(); 292 continue; 293 294 default: 295 return Converted; 296 } 297 } 298 299 return Converted; 300 } 301 302 /// Check if this standard conversion sequence represents a narrowing 303 /// conversion, according to C++11 [dcl.init.list]p7. 304 /// 305 /// \param Ctx The AST context. 306 /// \param Converted The result of applying this standard conversion sequence. 307 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 308 /// value of the expression prior to the narrowing conversion. 309 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 310 /// type of the expression prior to the narrowing conversion. 311 NarrowingKind 312 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 313 const Expr *Converted, 314 APValue &ConstantValue, 315 QualType &ConstantType) const { 316 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 317 318 // C++11 [dcl.init.list]p7: 319 // A narrowing conversion is an implicit conversion ... 320 QualType FromType = getToType(0); 321 QualType ToType = getToType(1); 322 switch (Second) { 323 // -- from a floating-point type to an integer type, or 324 // 325 // -- from an integer type or unscoped enumeration type to a floating-point 326 // type, except where the source is a constant expression and the actual 327 // value after conversion will fit into the target type and will produce 328 // the original value when converted back to the original type, or 329 case ICK_Floating_Integral: 330 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 331 return NK_Type_Narrowing; 332 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 333 llvm::APSInt IntConstantValue; 334 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 335 if (Initializer && 336 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 337 // Convert the integer to the floating type. 338 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 339 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 340 llvm::APFloat::rmNearestTiesToEven); 341 // And back. 342 llvm::APSInt ConvertedValue = IntConstantValue; 343 bool ignored; 344 Result.convertToInteger(ConvertedValue, 345 llvm::APFloat::rmTowardZero, &ignored); 346 // If the resulting value is different, this was a narrowing conversion. 347 if (IntConstantValue != ConvertedValue) { 348 ConstantValue = APValue(IntConstantValue); 349 ConstantType = Initializer->getType(); 350 return NK_Constant_Narrowing; 351 } 352 } else { 353 // Variables are always narrowings. 354 return NK_Variable_Narrowing; 355 } 356 } 357 return NK_Not_Narrowing; 358 359 // -- from long double to double or float, or from double to float, except 360 // where the source is a constant expression and the actual value after 361 // conversion is within the range of values that can be represented (even 362 // if it cannot be represented exactly), or 363 case ICK_Floating_Conversion: 364 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 365 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 366 // FromType is larger than ToType. 367 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 368 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 369 // Constant! 370 assert(ConstantValue.isFloat()); 371 llvm::APFloat FloatVal = ConstantValue.getFloat(); 372 // Convert the source value into the target type. 373 bool ignored; 374 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 375 Ctx.getFloatTypeSemantics(ToType), 376 llvm::APFloat::rmNearestTiesToEven, &ignored); 377 // If there was no overflow, the source value is within the range of 378 // values that can be represented. 379 if (ConvertStatus & llvm::APFloat::opOverflow) { 380 ConstantType = Initializer->getType(); 381 return NK_Constant_Narrowing; 382 } 383 } else { 384 return NK_Variable_Narrowing; 385 } 386 } 387 return NK_Not_Narrowing; 388 389 // -- from an integer type or unscoped enumeration type to an integer type 390 // that cannot represent all the values of the original type, except where 391 // the source is a constant expression and the actual value after 392 // conversion will fit into the target type and will produce the original 393 // value when converted back to the original type. 394 case ICK_Boolean_Conversion: // Bools are integers too. 395 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 396 // Boolean conversions can be from pointers and pointers to members 397 // [conv.bool], and those aren't considered narrowing conversions. 398 return NK_Not_Narrowing; 399 } // Otherwise, fall through to the integral case. 400 case ICK_Integral_Conversion: { 401 assert(FromType->isIntegralOrUnscopedEnumerationType()); 402 assert(ToType->isIntegralOrUnscopedEnumerationType()); 403 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 404 const unsigned FromWidth = Ctx.getIntWidth(FromType); 405 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 406 const unsigned ToWidth = Ctx.getIntWidth(ToType); 407 408 if (FromWidth > ToWidth || 409 (FromWidth == ToWidth && FromSigned != ToSigned) || 410 (FromSigned && !ToSigned)) { 411 // Not all values of FromType can be represented in ToType. 412 llvm::APSInt InitializerValue; 413 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 414 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 415 // Such conversions on variables are always narrowing. 416 return NK_Variable_Narrowing; 417 } 418 bool Narrowing = false; 419 if (FromWidth < ToWidth) { 420 // Negative -> unsigned is narrowing. Otherwise, more bits is never 421 // narrowing. 422 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 423 Narrowing = true; 424 } else { 425 // Add a bit to the InitializerValue so we don't have to worry about 426 // signed vs. unsigned comparisons. 427 InitializerValue = InitializerValue.extend( 428 InitializerValue.getBitWidth() + 1); 429 // Convert the initializer to and from the target width and signed-ness. 430 llvm::APSInt ConvertedValue = InitializerValue; 431 ConvertedValue = ConvertedValue.trunc(ToWidth); 432 ConvertedValue.setIsSigned(ToSigned); 433 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 434 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 435 // If the result is different, this was a narrowing conversion. 436 if (ConvertedValue != InitializerValue) 437 Narrowing = true; 438 } 439 if (Narrowing) { 440 ConstantType = Initializer->getType(); 441 ConstantValue = APValue(InitializerValue); 442 return NK_Constant_Narrowing; 443 } 444 } 445 return NK_Not_Narrowing; 446 } 447 448 default: 449 // Other kinds of conversions are not narrowings. 450 return NK_Not_Narrowing; 451 } 452 } 453 454 /// dump - Print this standard conversion sequence to standard 455 /// error. Useful for debugging overloading issues. 456 void StandardConversionSequence::dump() const { 457 raw_ostream &OS = llvm::errs(); 458 bool PrintedSomething = false; 459 if (First != ICK_Identity) { 460 OS << GetImplicitConversionName(First); 461 PrintedSomething = true; 462 } 463 464 if (Second != ICK_Identity) { 465 if (PrintedSomething) { 466 OS << " -> "; 467 } 468 OS << GetImplicitConversionName(Second); 469 470 if (CopyConstructor) { 471 OS << " (by copy constructor)"; 472 } else if (DirectBinding) { 473 OS << " (direct reference binding)"; 474 } else if (ReferenceBinding) { 475 OS << " (reference binding)"; 476 } 477 PrintedSomething = true; 478 } 479 480 if (Third != ICK_Identity) { 481 if (PrintedSomething) { 482 OS << " -> "; 483 } 484 OS << GetImplicitConversionName(Third); 485 PrintedSomething = true; 486 } 487 488 if (!PrintedSomething) { 489 OS << "No conversions required"; 490 } 491 } 492 493 /// dump - Print this user-defined conversion sequence to standard 494 /// error. Useful for debugging overloading issues. 495 void UserDefinedConversionSequence::dump() const { 496 raw_ostream &OS = llvm::errs(); 497 if (Before.First || Before.Second || Before.Third) { 498 Before.dump(); 499 OS << " -> "; 500 } 501 if (ConversionFunction) 502 OS << '\'' << *ConversionFunction << '\''; 503 else 504 OS << "aggregate initialization"; 505 if (After.First || After.Second || After.Third) { 506 OS << " -> "; 507 After.dump(); 508 } 509 } 510 511 /// dump - Print this implicit conversion sequence to standard 512 /// error. Useful for debugging overloading issues. 513 void ImplicitConversionSequence::dump() const { 514 raw_ostream &OS = llvm::errs(); 515 if (isStdInitializerListElement()) 516 OS << "Worst std::initializer_list element conversion: "; 517 switch (ConversionKind) { 518 case StandardConversion: 519 OS << "Standard conversion: "; 520 Standard.dump(); 521 break; 522 case UserDefinedConversion: 523 OS << "User-defined conversion: "; 524 UserDefined.dump(); 525 break; 526 case EllipsisConversion: 527 OS << "Ellipsis conversion"; 528 break; 529 case AmbiguousConversion: 530 OS << "Ambiguous conversion"; 531 break; 532 case BadConversion: 533 OS << "Bad conversion"; 534 break; 535 } 536 537 OS << "\n"; 538 } 539 540 void AmbiguousConversionSequence::construct() { 541 new (&conversions()) ConversionSet(); 542 } 543 544 void AmbiguousConversionSequence::destruct() { 545 conversions().~ConversionSet(); 546 } 547 548 void 549 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 550 FromTypePtr = O.FromTypePtr; 551 ToTypePtr = O.ToTypePtr; 552 new (&conversions()) ConversionSet(O.conversions()); 553 } 554 555 namespace { 556 // Structure used by DeductionFailureInfo to store 557 // template argument information. 558 struct DFIArguments { 559 TemplateArgument FirstArg; 560 TemplateArgument SecondArg; 561 }; 562 // Structure used by DeductionFailureInfo to store 563 // template parameter and template argument information. 564 struct DFIParamWithArguments : DFIArguments { 565 TemplateParameter Param; 566 }; 567 } 568 569 /// \brief Convert from Sema's representation of template deduction information 570 /// to the form used in overload-candidate information. 571 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 572 Sema::TemplateDeductionResult TDK, 573 TemplateDeductionInfo &Info) { 574 DeductionFailureInfo Result; 575 Result.Result = static_cast<unsigned>(TDK); 576 Result.HasDiagnostic = false; 577 Result.Data = nullptr; 578 switch (TDK) { 579 case Sema::TDK_Success: 580 case Sema::TDK_Invalid: 581 case Sema::TDK_InstantiationDepth: 582 case Sema::TDK_TooManyArguments: 583 case Sema::TDK_TooFewArguments: 584 break; 585 586 case Sema::TDK_Incomplete: 587 case Sema::TDK_InvalidExplicitArguments: 588 Result.Data = Info.Param.getOpaqueValue(); 589 break; 590 591 case Sema::TDK_NonDeducedMismatch: { 592 // FIXME: Should allocate from normal heap so that we can free this later. 593 DFIArguments *Saved = new (Context) DFIArguments; 594 Saved->FirstArg = Info.FirstArg; 595 Saved->SecondArg = Info.SecondArg; 596 Result.Data = Saved; 597 break; 598 } 599 600 case Sema::TDK_Inconsistent: 601 case Sema::TDK_Underqualified: { 602 // FIXME: Should allocate from normal heap so that we can free this later. 603 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 604 Saved->Param = Info.Param; 605 Saved->FirstArg = Info.FirstArg; 606 Saved->SecondArg = Info.SecondArg; 607 Result.Data = Saved; 608 break; 609 } 610 611 case Sema::TDK_SubstitutionFailure: 612 Result.Data = Info.take(); 613 if (Info.hasSFINAEDiagnostic()) { 614 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 615 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 616 Info.takeSFINAEDiagnostic(*Diag); 617 Result.HasDiagnostic = true; 618 } 619 break; 620 621 case Sema::TDK_FailedOverloadResolution: 622 Result.Data = Info.Expression; 623 break; 624 625 case Sema::TDK_MiscellaneousDeductionFailure: 626 break; 627 } 628 629 return Result; 630 } 631 632 void DeductionFailureInfo::Destroy() { 633 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 634 case Sema::TDK_Success: 635 case Sema::TDK_Invalid: 636 case Sema::TDK_InstantiationDepth: 637 case Sema::TDK_Incomplete: 638 case Sema::TDK_TooManyArguments: 639 case Sema::TDK_TooFewArguments: 640 case Sema::TDK_InvalidExplicitArguments: 641 case Sema::TDK_FailedOverloadResolution: 642 break; 643 644 case Sema::TDK_Inconsistent: 645 case Sema::TDK_Underqualified: 646 case Sema::TDK_NonDeducedMismatch: 647 // FIXME: Destroy the data? 648 Data = nullptr; 649 break; 650 651 case Sema::TDK_SubstitutionFailure: 652 // FIXME: Destroy the template argument list? 653 Data = nullptr; 654 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 655 Diag->~PartialDiagnosticAt(); 656 HasDiagnostic = false; 657 } 658 break; 659 660 // Unhandled 661 case Sema::TDK_MiscellaneousDeductionFailure: 662 break; 663 } 664 } 665 666 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 667 if (HasDiagnostic) 668 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 669 return nullptr; 670 } 671 672 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 674 case Sema::TDK_Success: 675 case Sema::TDK_Invalid: 676 case Sema::TDK_InstantiationDepth: 677 case Sema::TDK_TooManyArguments: 678 case Sema::TDK_TooFewArguments: 679 case Sema::TDK_SubstitutionFailure: 680 case Sema::TDK_NonDeducedMismatch: 681 case Sema::TDK_FailedOverloadResolution: 682 return TemplateParameter(); 683 684 case Sema::TDK_Incomplete: 685 case Sema::TDK_InvalidExplicitArguments: 686 return TemplateParameter::getFromOpaqueValue(Data); 687 688 case Sema::TDK_Inconsistent: 689 case Sema::TDK_Underqualified: 690 return static_cast<DFIParamWithArguments*>(Data)->Param; 691 692 // Unhandled 693 case Sema::TDK_MiscellaneousDeductionFailure: 694 break; 695 } 696 697 return TemplateParameter(); 698 } 699 700 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 702 case Sema::TDK_Success: 703 case Sema::TDK_Invalid: 704 case Sema::TDK_InstantiationDepth: 705 case Sema::TDK_TooManyArguments: 706 case Sema::TDK_TooFewArguments: 707 case Sema::TDK_Incomplete: 708 case Sema::TDK_InvalidExplicitArguments: 709 case Sema::TDK_Inconsistent: 710 case Sema::TDK_Underqualified: 711 case Sema::TDK_NonDeducedMismatch: 712 case Sema::TDK_FailedOverloadResolution: 713 return nullptr; 714 715 case Sema::TDK_SubstitutionFailure: 716 return static_cast<TemplateArgumentList*>(Data); 717 718 // Unhandled 719 case Sema::TDK_MiscellaneousDeductionFailure: 720 break; 721 } 722 723 return nullptr; 724 } 725 726 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 727 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 728 case Sema::TDK_Success: 729 case Sema::TDK_Invalid: 730 case Sema::TDK_InstantiationDepth: 731 case Sema::TDK_Incomplete: 732 case Sema::TDK_TooManyArguments: 733 case Sema::TDK_TooFewArguments: 734 case Sema::TDK_InvalidExplicitArguments: 735 case Sema::TDK_SubstitutionFailure: 736 case Sema::TDK_FailedOverloadResolution: 737 return nullptr; 738 739 case Sema::TDK_Inconsistent: 740 case Sema::TDK_Underqualified: 741 case Sema::TDK_NonDeducedMismatch: 742 return &static_cast<DFIArguments*>(Data)->FirstArg; 743 744 // Unhandled 745 case Sema::TDK_MiscellaneousDeductionFailure: 746 break; 747 } 748 749 return nullptr; 750 } 751 752 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 754 case Sema::TDK_Success: 755 case Sema::TDK_Invalid: 756 case Sema::TDK_InstantiationDepth: 757 case Sema::TDK_Incomplete: 758 case Sema::TDK_TooManyArguments: 759 case Sema::TDK_TooFewArguments: 760 case Sema::TDK_InvalidExplicitArguments: 761 case Sema::TDK_SubstitutionFailure: 762 case Sema::TDK_FailedOverloadResolution: 763 return nullptr; 764 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 case Sema::TDK_NonDeducedMismatch: 768 return &static_cast<DFIArguments*>(Data)->SecondArg; 769 770 // Unhandled 771 case Sema::TDK_MiscellaneousDeductionFailure: 772 break; 773 } 774 775 return nullptr; 776 } 777 778 Expr *DeductionFailureInfo::getExpr() { 779 if (static_cast<Sema::TemplateDeductionResult>(Result) == 780 Sema::TDK_FailedOverloadResolution) 781 return static_cast<Expr*>(Data); 782 783 return nullptr; 784 } 785 786 void OverloadCandidateSet::destroyCandidates() { 787 for (iterator i = begin(), e = end(); i != e; ++i) { 788 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 789 i->Conversions[ii].~ImplicitConversionSequence(); 790 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 791 i->DeductionFailure.Destroy(); 792 } 793 } 794 795 void OverloadCandidateSet::clear() { 796 destroyCandidates(); 797 NumInlineSequences = 0; 798 Candidates.clear(); 799 Functions.clear(); 800 } 801 802 namespace { 803 class UnbridgedCastsSet { 804 struct Entry { 805 Expr **Addr; 806 Expr *Saved; 807 }; 808 SmallVector<Entry, 2> Entries; 809 810 public: 811 void save(Sema &S, Expr *&E) { 812 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 813 Entry entry = { &E, E }; 814 Entries.push_back(entry); 815 E = S.stripARCUnbridgedCast(E); 816 } 817 818 void restore() { 819 for (SmallVectorImpl<Entry>::iterator 820 i = Entries.begin(), e = Entries.end(); i != e; ++i) 821 *i->Addr = i->Saved; 822 } 823 }; 824 } 825 826 /// checkPlaceholderForOverload - Do any interesting placeholder-like 827 /// preprocessing on the given expression. 828 /// 829 /// \param unbridgedCasts a collection to which to add unbridged casts; 830 /// without this, they will be immediately diagnosed as errors 831 /// 832 /// Return true on unrecoverable error. 833 static bool 834 checkPlaceholderForOverload(Sema &S, Expr *&E, 835 UnbridgedCastsSet *unbridgedCasts = nullptr) { 836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 837 // We can't handle overloaded expressions here because overload 838 // resolution might reasonably tweak them. 839 if (placeholder->getKind() == BuiltinType::Overload) return false; 840 841 // If the context potentially accepts unbridged ARC casts, strip 842 // the unbridged cast and add it to the collection for later restoration. 843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 844 unbridgedCasts) { 845 unbridgedCasts->save(S, E); 846 return false; 847 } 848 849 // Go ahead and check everything else. 850 ExprResult result = S.CheckPlaceholderExpr(E); 851 if (result.isInvalid()) 852 return true; 853 854 E = result.get(); 855 return false; 856 } 857 858 // Nothing to do. 859 return false; 860 } 861 862 /// checkArgPlaceholdersForOverload - Check a set of call operands for 863 /// placeholders. 864 static bool checkArgPlaceholdersForOverload(Sema &S, 865 MultiExprArg Args, 866 UnbridgedCastsSet &unbridged) { 867 for (unsigned i = 0, e = Args.size(); i != e; ++i) 868 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 869 return true; 870 871 return false; 872 } 873 874 // IsOverload - Determine whether the given New declaration is an 875 // overload of the declarations in Old. This routine returns false if 876 // New and Old cannot be overloaded, e.g., if New has the same 877 // signature as some function in Old (C++ 1.3.10) or if the Old 878 // declarations aren't functions (or function templates) at all. When 879 // it does return false, MatchedDecl will point to the decl that New 880 // cannot be overloaded with. This decl may be a UsingShadowDecl on 881 // top of the underlying declaration. 882 // 883 // Example: Given the following input: 884 // 885 // void f(int, float); // #1 886 // void f(int, int); // #2 887 // int f(int, int); // #3 888 // 889 // When we process #1, there is no previous declaration of "f", 890 // so IsOverload will not be used. 891 // 892 // When we process #2, Old contains only the FunctionDecl for #1. By 893 // comparing the parameter types, we see that #1 and #2 are overloaded 894 // (since they have different signatures), so this routine returns 895 // false; MatchedDecl is unchanged. 896 // 897 // When we process #3, Old is an overload set containing #1 and #2. We 898 // compare the signatures of #3 to #1 (they're overloaded, so we do 899 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 900 // identical (return types of functions are not part of the 901 // signature), IsOverload returns false and MatchedDecl will be set to 902 // point to the FunctionDecl for #2. 903 // 904 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 905 // into a class by a using declaration. The rules for whether to hide 906 // shadow declarations ignore some properties which otherwise figure 907 // into a function template's signature. 908 Sema::OverloadKind 909 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 910 NamedDecl *&Match, bool NewIsUsingDecl) { 911 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 912 I != E; ++I) { 913 NamedDecl *OldD = *I; 914 915 bool OldIsUsingDecl = false; 916 if (isa<UsingShadowDecl>(OldD)) { 917 OldIsUsingDecl = true; 918 919 // We can always introduce two using declarations into the same 920 // context, even if they have identical signatures. 921 if (NewIsUsingDecl) continue; 922 923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 924 } 925 926 // If either declaration was introduced by a using declaration, 927 // we'll need to use slightly different rules for matching. 928 // Essentially, these rules are the normal rules, except that 929 // function templates hide function templates with different 930 // return types or template parameter lists. 931 bool UseMemberUsingDeclRules = 932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 933 !New->getFriendObjectKind(); 934 935 if (FunctionDecl *OldF = OldD->getAsFunction()) { 936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 937 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 939 continue; 940 } 941 942 if (!isa<FunctionTemplateDecl>(OldD) && 943 !shouldLinkPossiblyHiddenDecl(*I, New)) 944 continue; 945 946 Match = *I; 947 return Ovl_Match; 948 } 949 } else if (isa<UsingDecl>(OldD)) { 950 // We can overload with these, which can show up when doing 951 // redeclaration checks for UsingDecls. 952 assert(Old.getLookupKind() == LookupUsingDeclName); 953 } else if (isa<TagDecl>(OldD)) { 954 // We can always overload with tags by hiding them. 955 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 956 // Optimistically assume that an unresolved using decl will 957 // overload; if it doesn't, we'll have to diagnose during 958 // template instantiation. 959 } else { 960 // (C++ 13p1): 961 // Only function declarations can be overloaded; object and type 962 // declarations cannot be overloaded. 963 Match = *I; 964 return Ovl_NonFunction; 965 } 966 } 967 968 return Ovl_Overload; 969 } 970 971 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 972 bool UseUsingDeclRules) { 973 // C++ [basic.start.main]p2: This function shall not be overloaded. 974 if (New->isMain()) 975 return false; 976 977 // MSVCRT user defined entry points cannot be overloaded. 978 if (New->isMSVCRTEntryPoint()) 979 return false; 980 981 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 982 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 983 984 // C++ [temp.fct]p2: 985 // A function template can be overloaded with other function templates 986 // and with normal (non-template) functions. 987 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 988 return true; 989 990 // Is the function New an overload of the function Old? 991 QualType OldQType = Context.getCanonicalType(Old->getType()); 992 QualType NewQType = Context.getCanonicalType(New->getType()); 993 994 // Compare the signatures (C++ 1.3.10) of the two functions to 995 // determine whether they are overloads. If we find any mismatch 996 // in the signature, they are overloads. 997 998 // If either of these functions is a K&R-style function (no 999 // prototype), then we consider them to have matching signatures. 1000 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1001 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1002 return false; 1003 1004 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1005 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1006 1007 // The signature of a function includes the types of its 1008 // parameters (C++ 1.3.10), which includes the presence or absence 1009 // of the ellipsis; see C++ DR 357). 1010 if (OldQType != NewQType && 1011 (OldType->getNumParams() != NewType->getNumParams() || 1012 OldType->isVariadic() != NewType->isVariadic() || 1013 !FunctionParamTypesAreEqual(OldType, NewType))) 1014 return true; 1015 1016 // C++ [temp.over.link]p4: 1017 // The signature of a function template consists of its function 1018 // signature, its return type and its template parameter list. The names 1019 // of the template parameters are significant only for establishing the 1020 // relationship between the template parameters and the rest of the 1021 // signature. 1022 // 1023 // We check the return type and template parameter lists for function 1024 // templates first; the remaining checks follow. 1025 // 1026 // However, we don't consider either of these when deciding whether 1027 // a member introduced by a shadow declaration is hidden. 1028 if (!UseUsingDeclRules && NewTemplate && 1029 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1030 OldTemplate->getTemplateParameters(), 1031 false, TPL_TemplateMatch) || 1032 OldType->getReturnType() != NewType->getReturnType())) 1033 return true; 1034 1035 // If the function is a class member, its signature includes the 1036 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1037 // 1038 // As part of this, also check whether one of the member functions 1039 // is static, in which case they are not overloads (C++ 1040 // 13.1p2). While not part of the definition of the signature, 1041 // this check is important to determine whether these functions 1042 // can be overloaded. 1043 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1044 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1045 if (OldMethod && NewMethod && 1046 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1047 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1048 if (!UseUsingDeclRules && 1049 (OldMethod->getRefQualifier() == RQ_None || 1050 NewMethod->getRefQualifier() == RQ_None)) { 1051 // C++0x [over.load]p2: 1052 // - Member function declarations with the same name and the same 1053 // parameter-type-list as well as member function template 1054 // declarations with the same name, the same parameter-type-list, and 1055 // the same template parameter lists cannot be overloaded if any of 1056 // them, but not all, have a ref-qualifier (8.3.5). 1057 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1058 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1059 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1060 } 1061 return true; 1062 } 1063 1064 // We may not have applied the implicit const for a constexpr member 1065 // function yet (because we haven't yet resolved whether this is a static 1066 // or non-static member function). Add it now, on the assumption that this 1067 // is a redeclaration of OldMethod. 1068 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1069 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1070 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1071 !isa<CXXConstructorDecl>(NewMethod)) 1072 NewQuals |= Qualifiers::Const; 1073 1074 // We do not allow overloading based off of '__restrict'. 1075 OldQuals &= ~Qualifiers::Restrict; 1076 NewQuals &= ~Qualifiers::Restrict; 1077 if (OldQuals != NewQuals) 1078 return true; 1079 } 1080 1081 // enable_if attributes are an order-sensitive part of the signature. 1082 for (specific_attr_iterator<EnableIfAttr> 1083 NewI = New->specific_attr_begin<EnableIfAttr>(), 1084 NewE = New->specific_attr_end<EnableIfAttr>(), 1085 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1086 OldE = Old->specific_attr_end<EnableIfAttr>(); 1087 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1088 if (NewI == NewE || OldI == OldE) 1089 return true; 1090 llvm::FoldingSetNodeID NewID, OldID; 1091 NewI->getCond()->Profile(NewID, Context, true); 1092 OldI->getCond()->Profile(OldID, Context, true); 1093 if (NewID != OldID) 1094 return true; 1095 } 1096 1097 // The signatures match; this is not an overload. 1098 return false; 1099 } 1100 1101 /// \brief Checks availability of the function depending on the current 1102 /// function context. Inside an unavailable function, unavailability is ignored. 1103 /// 1104 /// \returns true if \arg FD is unavailable and current context is inside 1105 /// an available function, false otherwise. 1106 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1107 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1108 } 1109 1110 /// \brief Tries a user-defined conversion from From to ToType. 1111 /// 1112 /// Produces an implicit conversion sequence for when a standard conversion 1113 /// is not an option. See TryImplicitConversion for more information. 1114 static ImplicitConversionSequence 1115 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1116 bool SuppressUserConversions, 1117 bool AllowExplicit, 1118 bool InOverloadResolution, 1119 bool CStyle, 1120 bool AllowObjCWritebackConversion, 1121 bool AllowObjCConversionOnExplicit) { 1122 ImplicitConversionSequence ICS; 1123 1124 if (SuppressUserConversions) { 1125 // We're not in the case above, so there is no conversion that 1126 // we can perform. 1127 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1128 return ICS; 1129 } 1130 1131 // Attempt user-defined conversion. 1132 OverloadCandidateSet Conversions(From->getExprLoc(), 1133 OverloadCandidateSet::CSK_Normal); 1134 OverloadingResult UserDefResult 1135 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1136 AllowExplicit, AllowObjCConversionOnExplicit); 1137 1138 if (UserDefResult == OR_Success) { 1139 ICS.setUserDefined(); 1140 ICS.UserDefined.Before.setAsIdentityConversion(); 1141 // C++ [over.ics.user]p4: 1142 // A conversion of an expression of class type to the same class 1143 // type is given Exact Match rank, and a conversion of an 1144 // expression of class type to a base class of that type is 1145 // given Conversion rank, in spite of the fact that a copy 1146 // constructor (i.e., a user-defined conversion function) is 1147 // called for those cases. 1148 if (CXXConstructorDecl *Constructor 1149 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1150 QualType FromCanon 1151 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1152 QualType ToCanon 1153 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1154 if (Constructor->isCopyConstructor() && 1155 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1156 // Turn this into a "standard" conversion sequence, so that it 1157 // gets ranked with standard conversion sequences. 1158 ICS.setStandard(); 1159 ICS.Standard.setAsIdentityConversion(); 1160 ICS.Standard.setFromType(From->getType()); 1161 ICS.Standard.setAllToTypes(ToType); 1162 ICS.Standard.CopyConstructor = Constructor; 1163 if (ToCanon != FromCanon) 1164 ICS.Standard.Second = ICK_Derived_To_Base; 1165 } 1166 } 1167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1168 ICS.setAmbiguous(); 1169 ICS.Ambiguous.setFromType(From->getType()); 1170 ICS.Ambiguous.setToType(ToType); 1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1172 Cand != Conversions.end(); ++Cand) 1173 if (Cand->Viable) 1174 ICS.Ambiguous.addConversion(Cand->Function); 1175 } else { 1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1177 } 1178 1179 return ICS; 1180 } 1181 1182 /// TryImplicitConversion - Attempt to perform an implicit conversion 1183 /// from the given expression (Expr) to the given type (ToType). This 1184 /// function returns an implicit conversion sequence that can be used 1185 /// to perform the initialization. Given 1186 /// 1187 /// void f(float f); 1188 /// void g(int i) { f(i); } 1189 /// 1190 /// this routine would produce an implicit conversion sequence to 1191 /// describe the initialization of f from i, which will be a standard 1192 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1193 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1194 // 1195 /// Note that this routine only determines how the conversion can be 1196 /// performed; it does not actually perform the conversion. As such, 1197 /// it will not produce any diagnostics if no conversion is available, 1198 /// but will instead return an implicit conversion sequence of kind 1199 /// "BadConversion". 1200 /// 1201 /// If @p SuppressUserConversions, then user-defined conversions are 1202 /// not permitted. 1203 /// If @p AllowExplicit, then explicit user-defined conversions are 1204 /// permitted. 1205 /// 1206 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1207 /// writeback conversion, which allows __autoreleasing id* parameters to 1208 /// be initialized with __strong id* or __weak id* arguments. 1209 static ImplicitConversionSequence 1210 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1211 bool SuppressUserConversions, 1212 bool AllowExplicit, 1213 bool InOverloadResolution, 1214 bool CStyle, 1215 bool AllowObjCWritebackConversion, 1216 bool AllowObjCConversionOnExplicit) { 1217 ImplicitConversionSequence ICS; 1218 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1219 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1220 ICS.setStandard(); 1221 return ICS; 1222 } 1223 1224 if (!S.getLangOpts().CPlusPlus) { 1225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1226 return ICS; 1227 } 1228 1229 // C++ [over.ics.user]p4: 1230 // A conversion of an expression of class type to the same class 1231 // type is given Exact Match rank, and a conversion of an 1232 // expression of class type to a base class of that type is 1233 // given Conversion rank, in spite of the fact that a copy/move 1234 // constructor (i.e., a user-defined conversion function) is 1235 // called for those cases. 1236 QualType FromType = From->getType(); 1237 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1238 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1239 S.IsDerivedFrom(FromType, ToType))) { 1240 ICS.setStandard(); 1241 ICS.Standard.setAsIdentityConversion(); 1242 ICS.Standard.setFromType(FromType); 1243 ICS.Standard.setAllToTypes(ToType); 1244 1245 // We don't actually check at this point whether there is a valid 1246 // copy/move constructor, since overloading just assumes that it 1247 // exists. When we actually perform initialization, we'll find the 1248 // appropriate constructor to copy the returned object, if needed. 1249 ICS.Standard.CopyConstructor = nullptr; 1250 1251 // Determine whether this is considered a derived-to-base conversion. 1252 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1253 ICS.Standard.Second = ICK_Derived_To_Base; 1254 1255 return ICS; 1256 } 1257 1258 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1259 AllowExplicit, InOverloadResolution, CStyle, 1260 AllowObjCWritebackConversion, 1261 AllowObjCConversionOnExplicit); 1262 } 1263 1264 ImplicitConversionSequence 1265 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1266 bool SuppressUserConversions, 1267 bool AllowExplicit, 1268 bool InOverloadResolution, 1269 bool CStyle, 1270 bool AllowObjCWritebackConversion) { 1271 return clang::TryImplicitConversion(*this, From, ToType, 1272 SuppressUserConversions, AllowExplicit, 1273 InOverloadResolution, CStyle, 1274 AllowObjCWritebackConversion, 1275 /*AllowObjCConversionOnExplicit=*/false); 1276 } 1277 1278 /// PerformImplicitConversion - Perform an implicit conversion of the 1279 /// expression From to the type ToType. Returns the 1280 /// converted expression. Flavor is the kind of conversion we're 1281 /// performing, used in the error message. If @p AllowExplicit, 1282 /// explicit user-defined conversions are permitted. 1283 ExprResult 1284 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1285 AssignmentAction Action, bool AllowExplicit) { 1286 ImplicitConversionSequence ICS; 1287 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1288 } 1289 1290 ExprResult 1291 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1292 AssignmentAction Action, bool AllowExplicit, 1293 ImplicitConversionSequence& ICS) { 1294 if (checkPlaceholderForOverload(*this, From)) 1295 return ExprError(); 1296 1297 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1298 bool AllowObjCWritebackConversion 1299 = getLangOpts().ObjCAutoRefCount && 1300 (Action == AA_Passing || Action == AA_Sending); 1301 if (getLangOpts().ObjC1) 1302 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1303 ToType, From->getType(), From); 1304 ICS = clang::TryImplicitConversion(*this, From, ToType, 1305 /*SuppressUserConversions=*/false, 1306 AllowExplicit, 1307 /*InOverloadResolution=*/false, 1308 /*CStyle=*/false, 1309 AllowObjCWritebackConversion, 1310 /*AllowObjCConversionOnExplicit=*/false); 1311 return PerformImplicitConversion(From, ToType, ICS, Action); 1312 } 1313 1314 /// \brief Determine whether the conversion from FromType to ToType is a valid 1315 /// conversion that strips "noreturn" off the nested function type. 1316 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1317 QualType &ResultTy) { 1318 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1319 return false; 1320 1321 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1322 // where F adds one of the following at most once: 1323 // - a pointer 1324 // - a member pointer 1325 // - a block pointer 1326 CanQualType CanTo = Context.getCanonicalType(ToType); 1327 CanQualType CanFrom = Context.getCanonicalType(FromType); 1328 Type::TypeClass TyClass = CanTo->getTypeClass(); 1329 if (TyClass != CanFrom->getTypeClass()) return false; 1330 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1331 if (TyClass == Type::Pointer) { 1332 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1333 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1334 } else if (TyClass == Type::BlockPointer) { 1335 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1336 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1337 } else if (TyClass == Type::MemberPointer) { 1338 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1339 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1340 } else { 1341 return false; 1342 } 1343 1344 TyClass = CanTo->getTypeClass(); 1345 if (TyClass != CanFrom->getTypeClass()) return false; 1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1347 return false; 1348 } 1349 1350 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1351 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1352 if (!EInfo.getNoReturn()) return false; 1353 1354 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1355 assert(QualType(FromFn, 0).isCanonical()); 1356 if (QualType(FromFn, 0) != CanTo) return false; 1357 1358 ResultTy = ToType; 1359 return true; 1360 } 1361 1362 /// \brief Determine whether the conversion from FromType to ToType is a valid 1363 /// vector conversion. 1364 /// 1365 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1366 /// conversion. 1367 static bool IsVectorConversion(Sema &S, QualType FromType, 1368 QualType ToType, ImplicitConversionKind &ICK) { 1369 // We need at least one of these types to be a vector type to have a vector 1370 // conversion. 1371 if (!ToType->isVectorType() && !FromType->isVectorType()) 1372 return false; 1373 1374 // Identical types require no conversions. 1375 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1376 return false; 1377 1378 // There are no conversions between extended vector types, only identity. 1379 if (ToType->isExtVectorType()) { 1380 // There are no conversions between extended vector types other than the 1381 // identity conversion. 1382 if (FromType->isExtVectorType()) 1383 return false; 1384 1385 // Vector splat from any arithmetic type to a vector. 1386 if (FromType->isArithmeticType()) { 1387 ICK = ICK_Vector_Splat; 1388 return true; 1389 } 1390 } 1391 1392 // We can perform the conversion between vector types in the following cases: 1393 // 1)vector types are equivalent AltiVec and GCC vector types 1394 // 2)lax vector conversions are permitted and the vector types are of the 1395 // same size 1396 if (ToType->isVectorType() && FromType->isVectorType()) { 1397 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1398 S.isLaxVectorConversion(FromType, ToType)) { 1399 ICK = ICK_Vector_Conversion; 1400 return true; 1401 } 1402 } 1403 1404 return false; 1405 } 1406 1407 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1408 bool InOverloadResolution, 1409 StandardConversionSequence &SCS, 1410 bool CStyle); 1411 1412 /// IsStandardConversion - Determines whether there is a standard 1413 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1414 /// expression From to the type ToType. Standard conversion sequences 1415 /// only consider non-class types; for conversions that involve class 1416 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1417 /// contain the standard conversion sequence required to perform this 1418 /// conversion and this routine will return true. Otherwise, this 1419 /// routine will return false and the value of SCS is unspecified. 1420 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1421 bool InOverloadResolution, 1422 StandardConversionSequence &SCS, 1423 bool CStyle, 1424 bool AllowObjCWritebackConversion) { 1425 QualType FromType = From->getType(); 1426 1427 // Standard conversions (C++ [conv]) 1428 SCS.setAsIdentityConversion(); 1429 SCS.IncompatibleObjC = false; 1430 SCS.setFromType(FromType); 1431 SCS.CopyConstructor = nullptr; 1432 1433 // There are no standard conversions for class types in C++, so 1434 // abort early. When overloading in C, however, we do permit 1435 if (FromType->isRecordType() || ToType->isRecordType()) { 1436 if (S.getLangOpts().CPlusPlus) 1437 return false; 1438 1439 // When we're overloading in C, we allow, as standard conversions, 1440 } 1441 1442 // The first conversion can be an lvalue-to-rvalue conversion, 1443 // array-to-pointer conversion, or function-to-pointer conversion 1444 // (C++ 4p1). 1445 1446 if (FromType == S.Context.OverloadTy) { 1447 DeclAccessPair AccessPair; 1448 if (FunctionDecl *Fn 1449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1450 AccessPair)) { 1451 // We were able to resolve the address of the overloaded function, 1452 // so we can convert to the type of that function. 1453 FromType = Fn->getType(); 1454 SCS.setFromType(FromType); 1455 1456 // we can sometimes resolve &foo<int> regardless of ToType, so check 1457 // if the type matches (identity) or we are converting to bool 1458 if (!S.Context.hasSameUnqualifiedType( 1459 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1460 QualType resultTy; 1461 // if the function type matches except for [[noreturn]], it's ok 1462 if (!S.IsNoReturnConversion(FromType, 1463 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1464 // otherwise, only a boolean conversion is standard 1465 if (!ToType->isBooleanType()) 1466 return false; 1467 } 1468 1469 // Check if the "from" expression is taking the address of an overloaded 1470 // function and recompute the FromType accordingly. Take advantage of the 1471 // fact that non-static member functions *must* have such an address-of 1472 // expression. 1473 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1474 if (Method && !Method->isStatic()) { 1475 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1476 "Non-unary operator on non-static member address"); 1477 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1478 == UO_AddrOf && 1479 "Non-address-of operator on non-static member address"); 1480 const Type *ClassType 1481 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1482 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1483 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1484 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1485 UO_AddrOf && 1486 "Non-address-of operator for overloaded function expression"); 1487 FromType = S.Context.getPointerType(FromType); 1488 } 1489 1490 // Check that we've computed the proper type after overload resolution. 1491 assert(S.Context.hasSameType( 1492 FromType, 1493 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1494 } else { 1495 return false; 1496 } 1497 } 1498 // Lvalue-to-rvalue conversion (C++11 4.1): 1499 // A glvalue (3.10) of a non-function, non-array type T can 1500 // be converted to a prvalue. 1501 bool argIsLValue = From->isGLValue(); 1502 if (argIsLValue && 1503 !FromType->isFunctionType() && !FromType->isArrayType() && 1504 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1505 SCS.First = ICK_Lvalue_To_Rvalue; 1506 1507 // C11 6.3.2.1p2: 1508 // ... if the lvalue has atomic type, the value has the non-atomic version 1509 // of the type of the lvalue ... 1510 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1511 FromType = Atomic->getValueType(); 1512 1513 // If T is a non-class type, the type of the rvalue is the 1514 // cv-unqualified version of T. Otherwise, the type of the rvalue 1515 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1516 // just strip the qualifiers because they don't matter. 1517 FromType = FromType.getUnqualifiedType(); 1518 } else if (FromType->isArrayType()) { 1519 // Array-to-pointer conversion (C++ 4.2) 1520 SCS.First = ICK_Array_To_Pointer; 1521 1522 // An lvalue or rvalue of type "array of N T" or "array of unknown 1523 // bound of T" can be converted to an rvalue of type "pointer to 1524 // T" (C++ 4.2p1). 1525 FromType = S.Context.getArrayDecayedType(FromType); 1526 1527 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1528 // This conversion is deprecated in C++03 (D.4) 1529 SCS.DeprecatedStringLiteralToCharPtr = true; 1530 1531 // For the purpose of ranking in overload resolution 1532 // (13.3.3.1.1), this conversion is considered an 1533 // array-to-pointer conversion followed by a qualification 1534 // conversion (4.4). (C++ 4.2p2) 1535 SCS.Second = ICK_Identity; 1536 SCS.Third = ICK_Qualification; 1537 SCS.QualificationIncludesObjCLifetime = false; 1538 SCS.setAllToTypes(FromType); 1539 return true; 1540 } 1541 } else if (FromType->isFunctionType() && argIsLValue) { 1542 // Function-to-pointer conversion (C++ 4.3). 1543 SCS.First = ICK_Function_To_Pointer; 1544 1545 // An lvalue of function type T can be converted to an rvalue of 1546 // type "pointer to T." The result is a pointer to the 1547 // function. (C++ 4.3p1). 1548 FromType = S.Context.getPointerType(FromType); 1549 } else { 1550 // We don't require any conversions for the first step. 1551 SCS.First = ICK_Identity; 1552 } 1553 SCS.setToType(0, FromType); 1554 1555 // The second conversion can be an integral promotion, floating 1556 // point promotion, integral conversion, floating point conversion, 1557 // floating-integral conversion, pointer conversion, 1558 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1559 // For overloading in C, this can also be a "compatible-type" 1560 // conversion. 1561 bool IncompatibleObjC = false; 1562 ImplicitConversionKind SecondICK = ICK_Identity; 1563 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1564 // The unqualified versions of the types are the same: there's no 1565 // conversion to do. 1566 SCS.Second = ICK_Identity; 1567 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1568 // Integral promotion (C++ 4.5). 1569 SCS.Second = ICK_Integral_Promotion; 1570 FromType = ToType.getUnqualifiedType(); 1571 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1572 // Floating point promotion (C++ 4.6). 1573 SCS.Second = ICK_Floating_Promotion; 1574 FromType = ToType.getUnqualifiedType(); 1575 } else if (S.IsComplexPromotion(FromType, ToType)) { 1576 // Complex promotion (Clang extension) 1577 SCS.Second = ICK_Complex_Promotion; 1578 FromType = ToType.getUnqualifiedType(); 1579 } else if (ToType->isBooleanType() && 1580 (FromType->isArithmeticType() || 1581 FromType->isAnyPointerType() || 1582 FromType->isBlockPointerType() || 1583 FromType->isMemberPointerType() || 1584 FromType->isNullPtrType())) { 1585 // Boolean conversions (C++ 4.12). 1586 SCS.Second = ICK_Boolean_Conversion; 1587 FromType = S.Context.BoolTy; 1588 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1589 ToType->isIntegralType(S.Context)) { 1590 // Integral conversions (C++ 4.7). 1591 SCS.Second = ICK_Integral_Conversion; 1592 FromType = ToType.getUnqualifiedType(); 1593 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1594 // Complex conversions (C99 6.3.1.6) 1595 SCS.Second = ICK_Complex_Conversion; 1596 FromType = ToType.getUnqualifiedType(); 1597 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1598 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1599 // Complex-real conversions (C99 6.3.1.7) 1600 SCS.Second = ICK_Complex_Real; 1601 FromType = ToType.getUnqualifiedType(); 1602 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1603 // Floating point conversions (C++ 4.8). 1604 SCS.Second = ICK_Floating_Conversion; 1605 FromType = ToType.getUnqualifiedType(); 1606 } else if ((FromType->isRealFloatingType() && 1607 ToType->isIntegralType(S.Context)) || 1608 (FromType->isIntegralOrUnscopedEnumerationType() && 1609 ToType->isRealFloatingType())) { 1610 // Floating-integral conversions (C++ 4.9). 1611 SCS.Second = ICK_Floating_Integral; 1612 FromType = ToType.getUnqualifiedType(); 1613 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1614 SCS.Second = ICK_Block_Pointer_Conversion; 1615 } else if (AllowObjCWritebackConversion && 1616 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1617 SCS.Second = ICK_Writeback_Conversion; 1618 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1619 FromType, IncompatibleObjC)) { 1620 // Pointer conversions (C++ 4.10). 1621 SCS.Second = ICK_Pointer_Conversion; 1622 SCS.IncompatibleObjC = IncompatibleObjC; 1623 FromType = FromType.getUnqualifiedType(); 1624 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1625 InOverloadResolution, FromType)) { 1626 // Pointer to member conversions (4.11). 1627 SCS.Second = ICK_Pointer_Member; 1628 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1629 SCS.Second = SecondICK; 1630 FromType = ToType.getUnqualifiedType(); 1631 } else if (!S.getLangOpts().CPlusPlus && 1632 S.Context.typesAreCompatible(ToType, FromType)) { 1633 // Compatible conversions (Clang extension for C function overloading) 1634 SCS.Second = ICK_Compatible_Conversion; 1635 FromType = ToType.getUnqualifiedType(); 1636 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1637 // Treat a conversion that strips "noreturn" as an identity conversion. 1638 SCS.Second = ICK_NoReturn_Adjustment; 1639 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1640 InOverloadResolution, 1641 SCS, CStyle)) { 1642 SCS.Second = ICK_TransparentUnionConversion; 1643 FromType = ToType; 1644 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1645 CStyle)) { 1646 // tryAtomicConversion has updated the standard conversion sequence 1647 // appropriately. 1648 return true; 1649 } else if (ToType->isEventT() && 1650 From->isIntegerConstantExpr(S.getASTContext()) && 1651 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1652 SCS.Second = ICK_Zero_Event_Conversion; 1653 FromType = ToType; 1654 } else { 1655 // No second conversion required. 1656 SCS.Second = ICK_Identity; 1657 } 1658 SCS.setToType(1, FromType); 1659 1660 QualType CanonFrom; 1661 QualType CanonTo; 1662 // The third conversion can be a qualification conversion (C++ 4p1). 1663 bool ObjCLifetimeConversion; 1664 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1665 ObjCLifetimeConversion)) { 1666 SCS.Third = ICK_Qualification; 1667 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1668 FromType = ToType; 1669 CanonFrom = S.Context.getCanonicalType(FromType); 1670 CanonTo = S.Context.getCanonicalType(ToType); 1671 } else { 1672 // No conversion required 1673 SCS.Third = ICK_Identity; 1674 1675 // C++ [over.best.ics]p6: 1676 // [...] Any difference in top-level cv-qualification is 1677 // subsumed by the initialization itself and does not constitute 1678 // a conversion. [...] 1679 CanonFrom = S.Context.getCanonicalType(FromType); 1680 CanonTo = S.Context.getCanonicalType(ToType); 1681 if (CanonFrom.getLocalUnqualifiedType() 1682 == CanonTo.getLocalUnqualifiedType() && 1683 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1684 FromType = ToType; 1685 CanonFrom = CanonTo; 1686 } 1687 } 1688 SCS.setToType(2, FromType); 1689 1690 // If we have not converted the argument type to the parameter type, 1691 // this is a bad conversion sequence. 1692 if (CanonFrom != CanonTo) 1693 return false; 1694 1695 return true; 1696 } 1697 1698 static bool 1699 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1700 QualType &ToType, 1701 bool InOverloadResolution, 1702 StandardConversionSequence &SCS, 1703 bool CStyle) { 1704 1705 const RecordType *UT = ToType->getAsUnionType(); 1706 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1707 return false; 1708 // The field to initialize within the transparent union. 1709 RecordDecl *UD = UT->getDecl(); 1710 // It's compatible if the expression matches any of the fields. 1711 for (const auto *it : UD->fields()) { 1712 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1713 CStyle, /*ObjCWritebackConversion=*/false)) { 1714 ToType = it->getType(); 1715 return true; 1716 } 1717 } 1718 return false; 1719 } 1720 1721 /// IsIntegralPromotion - Determines whether the conversion from the 1722 /// expression From (whose potentially-adjusted type is FromType) to 1723 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1724 /// sets PromotedType to the promoted type. 1725 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1726 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1727 // All integers are built-in. 1728 if (!To) { 1729 return false; 1730 } 1731 1732 // An rvalue of type char, signed char, unsigned char, short int, or 1733 // unsigned short int can be converted to an rvalue of type int if 1734 // int can represent all the values of the source type; otherwise, 1735 // the source rvalue can be converted to an rvalue of type unsigned 1736 // int (C++ 4.5p1). 1737 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1738 !FromType->isEnumeralType()) { 1739 if (// We can promote any signed, promotable integer type to an int 1740 (FromType->isSignedIntegerType() || 1741 // We can promote any unsigned integer type whose size is 1742 // less than int to an int. 1743 (!FromType->isSignedIntegerType() && 1744 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1745 return To->getKind() == BuiltinType::Int; 1746 } 1747 1748 return To->getKind() == BuiltinType::UInt; 1749 } 1750 1751 // C++11 [conv.prom]p3: 1752 // A prvalue of an unscoped enumeration type whose underlying type is not 1753 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1754 // following types that can represent all the values of the enumeration 1755 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1756 // unsigned int, long int, unsigned long int, long long int, or unsigned 1757 // long long int. If none of the types in that list can represent all the 1758 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1759 // type can be converted to an rvalue a prvalue of the extended integer type 1760 // with lowest integer conversion rank (4.13) greater than the rank of long 1761 // long in which all the values of the enumeration can be represented. If 1762 // there are two such extended types, the signed one is chosen. 1763 // C++11 [conv.prom]p4: 1764 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1765 // can be converted to a prvalue of its underlying type. Moreover, if 1766 // integral promotion can be applied to its underlying type, a prvalue of an 1767 // unscoped enumeration type whose underlying type is fixed can also be 1768 // converted to a prvalue of the promoted underlying type. 1769 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1770 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1771 // provided for a scoped enumeration. 1772 if (FromEnumType->getDecl()->isScoped()) 1773 return false; 1774 1775 // We can perform an integral promotion to the underlying type of the enum, 1776 // even if that's not the promoted type. 1777 if (FromEnumType->getDecl()->isFixed()) { 1778 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1779 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1780 IsIntegralPromotion(From, Underlying, ToType); 1781 } 1782 1783 // We have already pre-calculated the promotion type, so this is trivial. 1784 if (ToType->isIntegerType() && 1785 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1786 return Context.hasSameUnqualifiedType(ToType, 1787 FromEnumType->getDecl()->getPromotionType()); 1788 } 1789 1790 // C++0x [conv.prom]p2: 1791 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1792 // to an rvalue a prvalue of the first of the following types that can 1793 // represent all the values of its underlying type: int, unsigned int, 1794 // long int, unsigned long int, long long int, or unsigned long long int. 1795 // If none of the types in that list can represent all the values of its 1796 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1797 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1798 // type. 1799 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1800 ToType->isIntegerType()) { 1801 // Determine whether the type we're converting from is signed or 1802 // unsigned. 1803 bool FromIsSigned = FromType->isSignedIntegerType(); 1804 uint64_t FromSize = Context.getTypeSize(FromType); 1805 1806 // The types we'll try to promote to, in the appropriate 1807 // order. Try each of these types. 1808 QualType PromoteTypes[6] = { 1809 Context.IntTy, Context.UnsignedIntTy, 1810 Context.LongTy, Context.UnsignedLongTy , 1811 Context.LongLongTy, Context.UnsignedLongLongTy 1812 }; 1813 for (int Idx = 0; Idx < 6; ++Idx) { 1814 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1815 if (FromSize < ToSize || 1816 (FromSize == ToSize && 1817 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1818 // We found the type that we can promote to. If this is the 1819 // type we wanted, we have a promotion. Otherwise, no 1820 // promotion. 1821 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1822 } 1823 } 1824 } 1825 1826 // An rvalue for an integral bit-field (9.6) can be converted to an 1827 // rvalue of type int if int can represent all the values of the 1828 // bit-field; otherwise, it can be converted to unsigned int if 1829 // unsigned int can represent all the values of the bit-field. If 1830 // the bit-field is larger yet, no integral promotion applies to 1831 // it. If the bit-field has an enumerated type, it is treated as any 1832 // other value of that type for promotion purposes (C++ 4.5p3). 1833 // FIXME: We should delay checking of bit-fields until we actually perform the 1834 // conversion. 1835 using llvm::APSInt; 1836 if (From) 1837 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1838 APSInt BitWidth; 1839 if (FromType->isIntegralType(Context) && 1840 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1841 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1842 ToSize = Context.getTypeSize(ToType); 1843 1844 // Are we promoting to an int from a bitfield that fits in an int? 1845 if (BitWidth < ToSize || 1846 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1847 return To->getKind() == BuiltinType::Int; 1848 } 1849 1850 // Are we promoting to an unsigned int from an unsigned bitfield 1851 // that fits into an unsigned int? 1852 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1853 return To->getKind() == BuiltinType::UInt; 1854 } 1855 1856 return false; 1857 } 1858 } 1859 1860 // An rvalue of type bool can be converted to an rvalue of type int, 1861 // with false becoming zero and true becoming one (C++ 4.5p4). 1862 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1863 return true; 1864 } 1865 1866 return false; 1867 } 1868 1869 /// IsFloatingPointPromotion - Determines whether the conversion from 1870 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1871 /// returns true and sets PromotedType to the promoted type. 1872 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1873 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1874 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1875 /// An rvalue of type float can be converted to an rvalue of type 1876 /// double. (C++ 4.6p1). 1877 if (FromBuiltin->getKind() == BuiltinType::Float && 1878 ToBuiltin->getKind() == BuiltinType::Double) 1879 return true; 1880 1881 // C99 6.3.1.5p1: 1882 // When a float is promoted to double or long double, or a 1883 // double is promoted to long double [...]. 1884 if (!getLangOpts().CPlusPlus && 1885 (FromBuiltin->getKind() == BuiltinType::Float || 1886 FromBuiltin->getKind() == BuiltinType::Double) && 1887 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1888 return true; 1889 1890 // Half can be promoted to float. 1891 if (!getLangOpts().NativeHalfType && 1892 FromBuiltin->getKind() == BuiltinType::Half && 1893 ToBuiltin->getKind() == BuiltinType::Float) 1894 return true; 1895 } 1896 1897 return false; 1898 } 1899 1900 /// \brief Determine if a conversion is a complex promotion. 1901 /// 1902 /// A complex promotion is defined as a complex -> complex conversion 1903 /// where the conversion between the underlying real types is a 1904 /// floating-point or integral promotion. 1905 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1906 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1907 if (!FromComplex) 1908 return false; 1909 1910 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1911 if (!ToComplex) 1912 return false; 1913 1914 return IsFloatingPointPromotion(FromComplex->getElementType(), 1915 ToComplex->getElementType()) || 1916 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1917 ToComplex->getElementType()); 1918 } 1919 1920 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1921 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1922 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1923 /// if non-empty, will be a pointer to ToType that may or may not have 1924 /// the right set of qualifiers on its pointee. 1925 /// 1926 static QualType 1927 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1928 QualType ToPointee, QualType ToType, 1929 ASTContext &Context, 1930 bool StripObjCLifetime = false) { 1931 assert((FromPtr->getTypeClass() == Type::Pointer || 1932 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1933 "Invalid similarly-qualified pointer type"); 1934 1935 /// Conversions to 'id' subsume cv-qualifier conversions. 1936 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1937 return ToType.getUnqualifiedType(); 1938 1939 QualType CanonFromPointee 1940 = Context.getCanonicalType(FromPtr->getPointeeType()); 1941 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1942 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1943 1944 if (StripObjCLifetime) 1945 Quals.removeObjCLifetime(); 1946 1947 // Exact qualifier match -> return the pointer type we're converting to. 1948 if (CanonToPointee.getLocalQualifiers() == Quals) { 1949 // ToType is exactly what we need. Return it. 1950 if (!ToType.isNull()) 1951 return ToType.getUnqualifiedType(); 1952 1953 // Build a pointer to ToPointee. It has the right qualifiers 1954 // already. 1955 if (isa<ObjCObjectPointerType>(ToType)) 1956 return Context.getObjCObjectPointerType(ToPointee); 1957 return Context.getPointerType(ToPointee); 1958 } 1959 1960 // Just build a canonical type that has the right qualifiers. 1961 QualType QualifiedCanonToPointee 1962 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1963 1964 if (isa<ObjCObjectPointerType>(ToType)) 1965 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1966 return Context.getPointerType(QualifiedCanonToPointee); 1967 } 1968 1969 static bool isNullPointerConstantForConversion(Expr *Expr, 1970 bool InOverloadResolution, 1971 ASTContext &Context) { 1972 // Handle value-dependent integral null pointer constants correctly. 1973 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1974 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1975 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1976 return !InOverloadResolution; 1977 1978 return Expr->isNullPointerConstant(Context, 1979 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1980 : Expr::NPC_ValueDependentIsNull); 1981 } 1982 1983 /// IsPointerConversion - Determines whether the conversion of the 1984 /// expression From, which has the (possibly adjusted) type FromType, 1985 /// can be converted to the type ToType via a pointer conversion (C++ 1986 /// 4.10). If so, returns true and places the converted type (that 1987 /// might differ from ToType in its cv-qualifiers at some level) into 1988 /// ConvertedType. 1989 /// 1990 /// This routine also supports conversions to and from block pointers 1991 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1992 /// pointers to interfaces. FIXME: Once we've determined the 1993 /// appropriate overloading rules for Objective-C, we may want to 1994 /// split the Objective-C checks into a different routine; however, 1995 /// GCC seems to consider all of these conversions to be pointer 1996 /// conversions, so for now they live here. IncompatibleObjC will be 1997 /// set if the conversion is an allowed Objective-C conversion that 1998 /// should result in a warning. 1999 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2000 bool InOverloadResolution, 2001 QualType& ConvertedType, 2002 bool &IncompatibleObjC) { 2003 IncompatibleObjC = false; 2004 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2005 IncompatibleObjC)) 2006 return true; 2007 2008 // Conversion from a null pointer constant to any Objective-C pointer type. 2009 if (ToType->isObjCObjectPointerType() && 2010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2011 ConvertedType = ToType; 2012 return true; 2013 } 2014 2015 // Blocks: Block pointers can be converted to void*. 2016 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2017 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2018 ConvertedType = ToType; 2019 return true; 2020 } 2021 // Blocks: A null pointer constant can be converted to a block 2022 // pointer type. 2023 if (ToType->isBlockPointerType() && 2024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2025 ConvertedType = ToType; 2026 return true; 2027 } 2028 2029 // If the left-hand-side is nullptr_t, the right side can be a null 2030 // pointer constant. 2031 if (ToType->isNullPtrType() && 2032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2033 ConvertedType = ToType; 2034 return true; 2035 } 2036 2037 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2038 if (!ToTypePtr) 2039 return false; 2040 2041 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2042 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2043 ConvertedType = ToType; 2044 return true; 2045 } 2046 2047 // Beyond this point, both types need to be pointers 2048 // , including objective-c pointers. 2049 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2050 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2051 !getLangOpts().ObjCAutoRefCount) { 2052 ConvertedType = BuildSimilarlyQualifiedPointerType( 2053 FromType->getAs<ObjCObjectPointerType>(), 2054 ToPointeeType, 2055 ToType, Context); 2056 return true; 2057 } 2058 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2059 if (!FromTypePtr) 2060 return false; 2061 2062 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2063 2064 // If the unqualified pointee types are the same, this can't be a 2065 // pointer conversion, so don't do all of the work below. 2066 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2067 return false; 2068 2069 // An rvalue of type "pointer to cv T," where T is an object type, 2070 // can be converted to an rvalue of type "pointer to cv void" (C++ 2071 // 4.10p2). 2072 if (FromPointeeType->isIncompleteOrObjectType() && 2073 ToPointeeType->isVoidType()) { 2074 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2075 ToPointeeType, 2076 ToType, Context, 2077 /*StripObjCLifetime=*/true); 2078 return true; 2079 } 2080 2081 // MSVC allows implicit function to void* type conversion. 2082 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2083 ToPointeeType->isVoidType()) { 2084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2085 ToPointeeType, 2086 ToType, Context); 2087 return true; 2088 } 2089 2090 // When we're overloading in C, we allow a special kind of pointer 2091 // conversion for compatible-but-not-identical pointee types. 2092 if (!getLangOpts().CPlusPlus && 2093 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2094 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2095 ToPointeeType, 2096 ToType, Context); 2097 return true; 2098 } 2099 2100 // C++ [conv.ptr]p3: 2101 // 2102 // An rvalue of type "pointer to cv D," where D is a class type, 2103 // can be converted to an rvalue of type "pointer to cv B," where 2104 // B is a base class (clause 10) of D. If B is an inaccessible 2105 // (clause 11) or ambiguous (10.2) base class of D, a program that 2106 // necessitates this conversion is ill-formed. The result of the 2107 // conversion is a pointer to the base class sub-object of the 2108 // derived class object. The null pointer value is converted to 2109 // the null pointer value of the destination type. 2110 // 2111 // Note that we do not check for ambiguity or inaccessibility 2112 // here. That is handled by CheckPointerConversion. 2113 if (getLangOpts().CPlusPlus && 2114 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2115 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2116 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2117 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2118 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2119 ToPointeeType, 2120 ToType, Context); 2121 return true; 2122 } 2123 2124 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2125 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2126 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2127 ToPointeeType, 2128 ToType, Context); 2129 return true; 2130 } 2131 2132 return false; 2133 } 2134 2135 /// \brief Adopt the given qualifiers for the given type. 2136 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2137 Qualifiers TQs = T.getQualifiers(); 2138 2139 // Check whether qualifiers already match. 2140 if (TQs == Qs) 2141 return T; 2142 2143 if (Qs.compatiblyIncludes(TQs)) 2144 return Context.getQualifiedType(T, Qs); 2145 2146 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2147 } 2148 2149 /// isObjCPointerConversion - Determines whether this is an 2150 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2151 /// with the same arguments and return values. 2152 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2153 QualType& ConvertedType, 2154 bool &IncompatibleObjC) { 2155 if (!getLangOpts().ObjC1) 2156 return false; 2157 2158 // The set of qualifiers on the type we're converting from. 2159 Qualifiers FromQualifiers = FromType.getQualifiers(); 2160 2161 // First, we handle all conversions on ObjC object pointer types. 2162 const ObjCObjectPointerType* ToObjCPtr = 2163 ToType->getAs<ObjCObjectPointerType>(); 2164 const ObjCObjectPointerType *FromObjCPtr = 2165 FromType->getAs<ObjCObjectPointerType>(); 2166 2167 if (ToObjCPtr && FromObjCPtr) { 2168 // If the pointee types are the same (ignoring qualifications), 2169 // then this is not a pointer conversion. 2170 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2171 FromObjCPtr->getPointeeType())) 2172 return false; 2173 2174 // Check for compatible 2175 // Objective C++: We're able to convert between "id" or "Class" and a 2176 // pointer to any interface (in both directions). 2177 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2178 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2179 return true; 2180 } 2181 // Conversions with Objective-C's id<...>. 2182 if ((FromObjCPtr->isObjCQualifiedIdType() || 2183 ToObjCPtr->isObjCQualifiedIdType()) && 2184 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2185 /*compare=*/false)) { 2186 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2187 return true; 2188 } 2189 // Objective C++: We're able to convert from a pointer to an 2190 // interface to a pointer to a different interface. 2191 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2192 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2193 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2194 if (getLangOpts().CPlusPlus && LHS && RHS && 2195 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2196 FromObjCPtr->getPointeeType())) 2197 return false; 2198 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2199 ToObjCPtr->getPointeeType(), 2200 ToType, Context); 2201 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2202 return true; 2203 } 2204 2205 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2206 // Okay: this is some kind of implicit downcast of Objective-C 2207 // interfaces, which is permitted. However, we're going to 2208 // complain about it. 2209 IncompatibleObjC = true; 2210 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2211 ToObjCPtr->getPointeeType(), 2212 ToType, Context); 2213 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2214 return true; 2215 } 2216 } 2217 // Beyond this point, both types need to be C pointers or block pointers. 2218 QualType ToPointeeType; 2219 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2220 ToPointeeType = ToCPtr->getPointeeType(); 2221 else if (const BlockPointerType *ToBlockPtr = 2222 ToType->getAs<BlockPointerType>()) { 2223 // Objective C++: We're able to convert from a pointer to any object 2224 // to a block pointer type. 2225 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2226 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2227 return true; 2228 } 2229 ToPointeeType = ToBlockPtr->getPointeeType(); 2230 } 2231 else if (FromType->getAs<BlockPointerType>() && 2232 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2233 // Objective C++: We're able to convert from a block pointer type to a 2234 // pointer to any object. 2235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2236 return true; 2237 } 2238 else 2239 return false; 2240 2241 QualType FromPointeeType; 2242 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2243 FromPointeeType = FromCPtr->getPointeeType(); 2244 else if (const BlockPointerType *FromBlockPtr = 2245 FromType->getAs<BlockPointerType>()) 2246 FromPointeeType = FromBlockPtr->getPointeeType(); 2247 else 2248 return false; 2249 2250 // If we have pointers to pointers, recursively check whether this 2251 // is an Objective-C conversion. 2252 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2253 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2254 IncompatibleObjC)) { 2255 // We always complain about this conversion. 2256 IncompatibleObjC = true; 2257 ConvertedType = Context.getPointerType(ConvertedType); 2258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2259 return true; 2260 } 2261 // Allow conversion of pointee being objective-c pointer to another one; 2262 // as in I* to id. 2263 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2264 ToPointeeType->getAs<ObjCObjectPointerType>() && 2265 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2266 IncompatibleObjC)) { 2267 2268 ConvertedType = Context.getPointerType(ConvertedType); 2269 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2270 return true; 2271 } 2272 2273 // If we have pointers to functions or blocks, check whether the only 2274 // differences in the argument and result types are in Objective-C 2275 // pointer conversions. If so, we permit the conversion (but 2276 // complain about it). 2277 const FunctionProtoType *FromFunctionType 2278 = FromPointeeType->getAs<FunctionProtoType>(); 2279 const FunctionProtoType *ToFunctionType 2280 = ToPointeeType->getAs<FunctionProtoType>(); 2281 if (FromFunctionType && ToFunctionType) { 2282 // If the function types are exactly the same, this isn't an 2283 // Objective-C pointer conversion. 2284 if (Context.getCanonicalType(FromPointeeType) 2285 == Context.getCanonicalType(ToPointeeType)) 2286 return false; 2287 2288 // Perform the quick checks that will tell us whether these 2289 // function types are obviously different. 2290 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2291 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2292 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2293 return false; 2294 2295 bool HasObjCConversion = false; 2296 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2297 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2298 // Okay, the types match exactly. Nothing to do. 2299 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2300 ToFunctionType->getReturnType(), 2301 ConvertedType, IncompatibleObjC)) { 2302 // Okay, we have an Objective-C pointer conversion. 2303 HasObjCConversion = true; 2304 } else { 2305 // Function types are too different. Abort. 2306 return false; 2307 } 2308 2309 // Check argument types. 2310 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2311 ArgIdx != NumArgs; ++ArgIdx) { 2312 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2313 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2314 if (Context.getCanonicalType(FromArgType) 2315 == Context.getCanonicalType(ToArgType)) { 2316 // Okay, the types match exactly. Nothing to do. 2317 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2318 ConvertedType, IncompatibleObjC)) { 2319 // Okay, we have an Objective-C pointer conversion. 2320 HasObjCConversion = true; 2321 } else { 2322 // Argument types are too different. Abort. 2323 return false; 2324 } 2325 } 2326 2327 if (HasObjCConversion) { 2328 // We had an Objective-C conversion. Allow this pointer 2329 // conversion, but complain about it. 2330 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2331 IncompatibleObjC = true; 2332 return true; 2333 } 2334 } 2335 2336 return false; 2337 } 2338 2339 /// \brief Determine whether this is an Objective-C writeback conversion, 2340 /// used for parameter passing when performing automatic reference counting. 2341 /// 2342 /// \param FromType The type we're converting form. 2343 /// 2344 /// \param ToType The type we're converting to. 2345 /// 2346 /// \param ConvertedType The type that will be produced after applying 2347 /// this conversion. 2348 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2349 QualType &ConvertedType) { 2350 if (!getLangOpts().ObjCAutoRefCount || 2351 Context.hasSameUnqualifiedType(FromType, ToType)) 2352 return false; 2353 2354 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2355 QualType ToPointee; 2356 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2357 ToPointee = ToPointer->getPointeeType(); 2358 else 2359 return false; 2360 2361 Qualifiers ToQuals = ToPointee.getQualifiers(); 2362 if (!ToPointee->isObjCLifetimeType() || 2363 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2364 !ToQuals.withoutObjCLifetime().empty()) 2365 return false; 2366 2367 // Argument must be a pointer to __strong to __weak. 2368 QualType FromPointee; 2369 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2370 FromPointee = FromPointer->getPointeeType(); 2371 else 2372 return false; 2373 2374 Qualifiers FromQuals = FromPointee.getQualifiers(); 2375 if (!FromPointee->isObjCLifetimeType() || 2376 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2377 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2378 return false; 2379 2380 // Make sure that we have compatible qualifiers. 2381 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2382 if (!ToQuals.compatiblyIncludes(FromQuals)) 2383 return false; 2384 2385 // Remove qualifiers from the pointee type we're converting from; they 2386 // aren't used in the compatibility check belong, and we'll be adding back 2387 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2388 FromPointee = FromPointee.getUnqualifiedType(); 2389 2390 // The unqualified form of the pointee types must be compatible. 2391 ToPointee = ToPointee.getUnqualifiedType(); 2392 bool IncompatibleObjC; 2393 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2394 FromPointee = ToPointee; 2395 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2396 IncompatibleObjC)) 2397 return false; 2398 2399 /// \brief Construct the type we're converting to, which is a pointer to 2400 /// __autoreleasing pointee. 2401 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2402 ConvertedType = Context.getPointerType(FromPointee); 2403 return true; 2404 } 2405 2406 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2407 QualType& ConvertedType) { 2408 QualType ToPointeeType; 2409 if (const BlockPointerType *ToBlockPtr = 2410 ToType->getAs<BlockPointerType>()) 2411 ToPointeeType = ToBlockPtr->getPointeeType(); 2412 else 2413 return false; 2414 2415 QualType FromPointeeType; 2416 if (const BlockPointerType *FromBlockPtr = 2417 FromType->getAs<BlockPointerType>()) 2418 FromPointeeType = FromBlockPtr->getPointeeType(); 2419 else 2420 return false; 2421 // We have pointer to blocks, check whether the only 2422 // differences in the argument and result types are in Objective-C 2423 // pointer conversions. If so, we permit the conversion. 2424 2425 const FunctionProtoType *FromFunctionType 2426 = FromPointeeType->getAs<FunctionProtoType>(); 2427 const FunctionProtoType *ToFunctionType 2428 = ToPointeeType->getAs<FunctionProtoType>(); 2429 2430 if (!FromFunctionType || !ToFunctionType) 2431 return false; 2432 2433 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2434 return true; 2435 2436 // Perform the quick checks that will tell us whether these 2437 // function types are obviously different. 2438 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2439 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2440 return false; 2441 2442 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2443 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2444 if (FromEInfo != ToEInfo) 2445 return false; 2446 2447 bool IncompatibleObjC = false; 2448 if (Context.hasSameType(FromFunctionType->getReturnType(), 2449 ToFunctionType->getReturnType())) { 2450 // Okay, the types match exactly. Nothing to do. 2451 } else { 2452 QualType RHS = FromFunctionType->getReturnType(); 2453 QualType LHS = ToFunctionType->getReturnType(); 2454 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2455 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2456 LHS = LHS.getUnqualifiedType(); 2457 2458 if (Context.hasSameType(RHS,LHS)) { 2459 // OK exact match. 2460 } else if (isObjCPointerConversion(RHS, LHS, 2461 ConvertedType, IncompatibleObjC)) { 2462 if (IncompatibleObjC) 2463 return false; 2464 // Okay, we have an Objective-C pointer conversion. 2465 } 2466 else 2467 return false; 2468 } 2469 2470 // Check argument types. 2471 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2472 ArgIdx != NumArgs; ++ArgIdx) { 2473 IncompatibleObjC = false; 2474 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2475 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2476 if (Context.hasSameType(FromArgType, ToArgType)) { 2477 // Okay, the types match exactly. Nothing to do. 2478 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2479 ConvertedType, IncompatibleObjC)) { 2480 if (IncompatibleObjC) 2481 return false; 2482 // Okay, we have an Objective-C pointer conversion. 2483 } else 2484 // Argument types are too different. Abort. 2485 return false; 2486 } 2487 if (LangOpts.ObjCAutoRefCount && 2488 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2489 ToFunctionType)) 2490 return false; 2491 2492 ConvertedType = ToType; 2493 return true; 2494 } 2495 2496 enum { 2497 ft_default, 2498 ft_different_class, 2499 ft_parameter_arity, 2500 ft_parameter_mismatch, 2501 ft_return_type, 2502 ft_qualifer_mismatch 2503 }; 2504 2505 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2506 /// function types. Catches different number of parameter, mismatch in 2507 /// parameter types, and different return types. 2508 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2509 QualType FromType, QualType ToType) { 2510 // If either type is not valid, include no extra info. 2511 if (FromType.isNull() || ToType.isNull()) { 2512 PDiag << ft_default; 2513 return; 2514 } 2515 2516 // Get the function type from the pointers. 2517 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2518 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2519 *ToMember = ToType->getAs<MemberPointerType>(); 2520 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2521 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2522 << QualType(FromMember->getClass(), 0); 2523 return; 2524 } 2525 FromType = FromMember->getPointeeType(); 2526 ToType = ToMember->getPointeeType(); 2527 } 2528 2529 if (FromType->isPointerType()) 2530 FromType = FromType->getPointeeType(); 2531 if (ToType->isPointerType()) 2532 ToType = ToType->getPointeeType(); 2533 2534 // Remove references. 2535 FromType = FromType.getNonReferenceType(); 2536 ToType = ToType.getNonReferenceType(); 2537 2538 // Don't print extra info for non-specialized template functions. 2539 if (FromType->isInstantiationDependentType() && 2540 !FromType->getAs<TemplateSpecializationType>()) { 2541 PDiag << ft_default; 2542 return; 2543 } 2544 2545 // No extra info for same types. 2546 if (Context.hasSameType(FromType, ToType)) { 2547 PDiag << ft_default; 2548 return; 2549 } 2550 2551 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2552 *ToFunction = ToType->getAs<FunctionProtoType>(); 2553 2554 // Both types need to be function types. 2555 if (!FromFunction || !ToFunction) { 2556 PDiag << ft_default; 2557 return; 2558 } 2559 2560 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2561 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2562 << FromFunction->getNumParams(); 2563 return; 2564 } 2565 2566 // Handle different parameter types. 2567 unsigned ArgPos; 2568 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2569 PDiag << ft_parameter_mismatch << ArgPos + 1 2570 << ToFunction->getParamType(ArgPos) 2571 << FromFunction->getParamType(ArgPos); 2572 return; 2573 } 2574 2575 // Handle different return type. 2576 if (!Context.hasSameType(FromFunction->getReturnType(), 2577 ToFunction->getReturnType())) { 2578 PDiag << ft_return_type << ToFunction->getReturnType() 2579 << FromFunction->getReturnType(); 2580 return; 2581 } 2582 2583 unsigned FromQuals = FromFunction->getTypeQuals(), 2584 ToQuals = ToFunction->getTypeQuals(); 2585 if (FromQuals != ToQuals) { 2586 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2587 return; 2588 } 2589 2590 // Unable to find a difference, so add no extra info. 2591 PDiag << ft_default; 2592 } 2593 2594 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2595 /// for equality of their argument types. Caller has already checked that 2596 /// they have same number of arguments. If the parameters are different, 2597 /// ArgPos will have the parameter index of the first different parameter. 2598 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2599 const FunctionProtoType *NewType, 2600 unsigned *ArgPos) { 2601 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2602 N = NewType->param_type_begin(), 2603 E = OldType->param_type_end(); 2604 O && (O != E); ++O, ++N) { 2605 if (!Context.hasSameType(O->getUnqualifiedType(), 2606 N->getUnqualifiedType())) { 2607 if (ArgPos) 2608 *ArgPos = O - OldType->param_type_begin(); 2609 return false; 2610 } 2611 } 2612 return true; 2613 } 2614 2615 /// CheckPointerConversion - Check the pointer conversion from the 2616 /// expression From to the type ToType. This routine checks for 2617 /// ambiguous or inaccessible derived-to-base pointer 2618 /// conversions for which IsPointerConversion has already returned 2619 /// true. It returns true and produces a diagnostic if there was an 2620 /// error, or returns false otherwise. 2621 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2622 CastKind &Kind, 2623 CXXCastPath& BasePath, 2624 bool IgnoreBaseAccess) { 2625 QualType FromType = From->getType(); 2626 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2627 2628 Kind = CK_BitCast; 2629 2630 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2631 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2632 Expr::NPCK_ZeroExpression) { 2633 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2634 DiagRuntimeBehavior(From->getExprLoc(), From, 2635 PDiag(diag::warn_impcast_bool_to_null_pointer) 2636 << ToType << From->getSourceRange()); 2637 else if (!isUnevaluatedContext()) 2638 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2639 << ToType << From->getSourceRange(); 2640 } 2641 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2642 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2643 QualType FromPointeeType = FromPtrType->getPointeeType(), 2644 ToPointeeType = ToPtrType->getPointeeType(); 2645 2646 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2647 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2648 // We must have a derived-to-base conversion. Check an 2649 // ambiguous or inaccessible conversion. 2650 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2651 From->getExprLoc(), 2652 From->getSourceRange(), &BasePath, 2653 IgnoreBaseAccess)) 2654 return true; 2655 2656 // The conversion was successful. 2657 Kind = CK_DerivedToBase; 2658 } 2659 } 2660 } else if (const ObjCObjectPointerType *ToPtrType = 2661 ToType->getAs<ObjCObjectPointerType>()) { 2662 if (const ObjCObjectPointerType *FromPtrType = 2663 FromType->getAs<ObjCObjectPointerType>()) { 2664 // Objective-C++ conversions are always okay. 2665 // FIXME: We should have a different class of conversions for the 2666 // Objective-C++ implicit conversions. 2667 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2668 return false; 2669 } else if (FromType->isBlockPointerType()) { 2670 Kind = CK_BlockPointerToObjCPointerCast; 2671 } else { 2672 Kind = CK_CPointerToObjCPointerCast; 2673 } 2674 } else if (ToType->isBlockPointerType()) { 2675 if (!FromType->isBlockPointerType()) 2676 Kind = CK_AnyPointerToBlockPointerCast; 2677 } 2678 2679 // We shouldn't fall into this case unless it's valid for other 2680 // reasons. 2681 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2682 Kind = CK_NullToPointer; 2683 2684 return false; 2685 } 2686 2687 /// IsMemberPointerConversion - Determines whether the conversion of the 2688 /// expression From, which has the (possibly adjusted) type FromType, can be 2689 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2690 /// If so, returns true and places the converted type (that might differ from 2691 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2692 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2693 QualType ToType, 2694 bool InOverloadResolution, 2695 QualType &ConvertedType) { 2696 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2697 if (!ToTypePtr) 2698 return false; 2699 2700 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2701 if (From->isNullPointerConstant(Context, 2702 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2703 : Expr::NPC_ValueDependentIsNull)) { 2704 ConvertedType = ToType; 2705 return true; 2706 } 2707 2708 // Otherwise, both types have to be member pointers. 2709 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2710 if (!FromTypePtr) 2711 return false; 2712 2713 // A pointer to member of B can be converted to a pointer to member of D, 2714 // where D is derived from B (C++ 4.11p2). 2715 QualType FromClass(FromTypePtr->getClass(), 0); 2716 QualType ToClass(ToTypePtr->getClass(), 0); 2717 2718 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2719 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2720 IsDerivedFrom(ToClass, FromClass)) { 2721 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2722 ToClass.getTypePtr()); 2723 return true; 2724 } 2725 2726 return false; 2727 } 2728 2729 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2730 /// expression From to the type ToType. This routine checks for ambiguous or 2731 /// virtual or inaccessible base-to-derived member pointer conversions 2732 /// for which IsMemberPointerConversion has already returned true. It returns 2733 /// true and produces a diagnostic if there was an error, or returns false 2734 /// otherwise. 2735 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2736 CastKind &Kind, 2737 CXXCastPath &BasePath, 2738 bool IgnoreBaseAccess) { 2739 QualType FromType = From->getType(); 2740 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2741 if (!FromPtrType) { 2742 // This must be a null pointer to member pointer conversion 2743 assert(From->isNullPointerConstant(Context, 2744 Expr::NPC_ValueDependentIsNull) && 2745 "Expr must be null pointer constant!"); 2746 Kind = CK_NullToMemberPointer; 2747 return false; 2748 } 2749 2750 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2751 assert(ToPtrType && "No member pointer cast has a target type " 2752 "that is not a member pointer."); 2753 2754 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2755 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2756 2757 // FIXME: What about dependent types? 2758 assert(FromClass->isRecordType() && "Pointer into non-class."); 2759 assert(ToClass->isRecordType() && "Pointer into non-class."); 2760 2761 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2762 /*DetectVirtual=*/true); 2763 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2764 assert(DerivationOkay && 2765 "Should not have been called if derivation isn't OK."); 2766 (void)DerivationOkay; 2767 2768 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2769 getUnqualifiedType())) { 2770 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2771 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2772 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2773 return true; 2774 } 2775 2776 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2777 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2778 << FromClass << ToClass << QualType(VBase, 0) 2779 << From->getSourceRange(); 2780 return true; 2781 } 2782 2783 if (!IgnoreBaseAccess) 2784 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2785 Paths.front(), 2786 diag::err_downcast_from_inaccessible_base); 2787 2788 // Must be a base to derived member conversion. 2789 BuildBasePathArray(Paths, BasePath); 2790 Kind = CK_BaseToDerivedMemberPointer; 2791 return false; 2792 } 2793 2794 /// Determine whether the lifetime conversion between the two given 2795 /// qualifiers sets is nontrivial. 2796 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2797 Qualifiers ToQuals) { 2798 // Converting anything to const __unsafe_unretained is trivial. 2799 if (ToQuals.hasConst() && 2800 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2801 return false; 2802 2803 return true; 2804 } 2805 2806 /// IsQualificationConversion - Determines whether the conversion from 2807 /// an rvalue of type FromType to ToType is a qualification conversion 2808 /// (C++ 4.4). 2809 /// 2810 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2811 /// when the qualification conversion involves a change in the Objective-C 2812 /// object lifetime. 2813 bool 2814 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2815 bool CStyle, bool &ObjCLifetimeConversion) { 2816 FromType = Context.getCanonicalType(FromType); 2817 ToType = Context.getCanonicalType(ToType); 2818 ObjCLifetimeConversion = false; 2819 2820 // If FromType and ToType are the same type, this is not a 2821 // qualification conversion. 2822 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2823 return false; 2824 2825 // (C++ 4.4p4): 2826 // A conversion can add cv-qualifiers at levels other than the first 2827 // in multi-level pointers, subject to the following rules: [...] 2828 bool PreviousToQualsIncludeConst = true; 2829 bool UnwrappedAnyPointer = false; 2830 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2831 // Within each iteration of the loop, we check the qualifiers to 2832 // determine if this still looks like a qualification 2833 // conversion. Then, if all is well, we unwrap one more level of 2834 // pointers or pointers-to-members and do it all again 2835 // until there are no more pointers or pointers-to-members left to 2836 // unwrap. 2837 UnwrappedAnyPointer = true; 2838 2839 Qualifiers FromQuals = FromType.getQualifiers(); 2840 Qualifiers ToQuals = ToType.getQualifiers(); 2841 2842 // Objective-C ARC: 2843 // Check Objective-C lifetime conversions. 2844 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2845 UnwrappedAnyPointer) { 2846 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2847 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2848 ObjCLifetimeConversion = true; 2849 FromQuals.removeObjCLifetime(); 2850 ToQuals.removeObjCLifetime(); 2851 } else { 2852 // Qualification conversions cannot cast between different 2853 // Objective-C lifetime qualifiers. 2854 return false; 2855 } 2856 } 2857 2858 // Allow addition/removal of GC attributes but not changing GC attributes. 2859 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2860 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2861 FromQuals.removeObjCGCAttr(); 2862 ToQuals.removeObjCGCAttr(); 2863 } 2864 2865 // -- for every j > 0, if const is in cv 1,j then const is in cv 2866 // 2,j, and similarly for volatile. 2867 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2868 return false; 2869 2870 // -- if the cv 1,j and cv 2,j are different, then const is in 2871 // every cv for 0 < k < j. 2872 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2873 && !PreviousToQualsIncludeConst) 2874 return false; 2875 2876 // Keep track of whether all prior cv-qualifiers in the "to" type 2877 // include const. 2878 PreviousToQualsIncludeConst 2879 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2880 } 2881 2882 // We are left with FromType and ToType being the pointee types 2883 // after unwrapping the original FromType and ToType the same number 2884 // of types. If we unwrapped any pointers, and if FromType and 2885 // ToType have the same unqualified type (since we checked 2886 // qualifiers above), then this is a qualification conversion. 2887 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2888 } 2889 2890 /// \brief - Determine whether this is a conversion from a scalar type to an 2891 /// atomic type. 2892 /// 2893 /// If successful, updates \c SCS's second and third steps in the conversion 2894 /// sequence to finish the conversion. 2895 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2896 bool InOverloadResolution, 2897 StandardConversionSequence &SCS, 2898 bool CStyle) { 2899 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2900 if (!ToAtomic) 2901 return false; 2902 2903 StandardConversionSequence InnerSCS; 2904 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2905 InOverloadResolution, InnerSCS, 2906 CStyle, /*AllowObjCWritebackConversion=*/false)) 2907 return false; 2908 2909 SCS.Second = InnerSCS.Second; 2910 SCS.setToType(1, InnerSCS.getToType(1)); 2911 SCS.Third = InnerSCS.Third; 2912 SCS.QualificationIncludesObjCLifetime 2913 = InnerSCS.QualificationIncludesObjCLifetime; 2914 SCS.setToType(2, InnerSCS.getToType(2)); 2915 return true; 2916 } 2917 2918 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2919 CXXConstructorDecl *Constructor, 2920 QualType Type) { 2921 const FunctionProtoType *CtorType = 2922 Constructor->getType()->getAs<FunctionProtoType>(); 2923 if (CtorType->getNumParams() > 0) { 2924 QualType FirstArg = CtorType->getParamType(0); 2925 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2926 return true; 2927 } 2928 return false; 2929 } 2930 2931 static OverloadingResult 2932 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2933 CXXRecordDecl *To, 2934 UserDefinedConversionSequence &User, 2935 OverloadCandidateSet &CandidateSet, 2936 bool AllowExplicit) { 2937 DeclContext::lookup_result R = S.LookupConstructors(To); 2938 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2939 Con != ConEnd; ++Con) { 2940 NamedDecl *D = *Con; 2941 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2942 2943 // Find the constructor (which may be a template). 2944 CXXConstructorDecl *Constructor = nullptr; 2945 FunctionTemplateDecl *ConstructorTmpl 2946 = dyn_cast<FunctionTemplateDecl>(D); 2947 if (ConstructorTmpl) 2948 Constructor 2949 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2950 else 2951 Constructor = cast<CXXConstructorDecl>(D); 2952 2953 bool Usable = !Constructor->isInvalidDecl() && 2954 S.isInitListConstructor(Constructor) && 2955 (AllowExplicit || !Constructor->isExplicit()); 2956 if (Usable) { 2957 // If the first argument is (a reference to) the target type, 2958 // suppress conversions. 2959 bool SuppressUserConversions = 2960 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2961 if (ConstructorTmpl) 2962 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2963 /*ExplicitArgs*/ nullptr, 2964 From, CandidateSet, 2965 SuppressUserConversions); 2966 else 2967 S.AddOverloadCandidate(Constructor, FoundDecl, 2968 From, CandidateSet, 2969 SuppressUserConversions); 2970 } 2971 } 2972 2973 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2974 2975 OverloadCandidateSet::iterator Best; 2976 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2977 case OR_Success: { 2978 // Record the standard conversion we used and the conversion function. 2979 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2980 QualType ThisType = Constructor->getThisType(S.Context); 2981 // Initializer lists don't have conversions as such. 2982 User.Before.setAsIdentityConversion(); 2983 User.HadMultipleCandidates = HadMultipleCandidates; 2984 User.ConversionFunction = Constructor; 2985 User.FoundConversionFunction = Best->FoundDecl; 2986 User.After.setAsIdentityConversion(); 2987 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2988 User.After.setAllToTypes(ToType); 2989 return OR_Success; 2990 } 2991 2992 case OR_No_Viable_Function: 2993 return OR_No_Viable_Function; 2994 case OR_Deleted: 2995 return OR_Deleted; 2996 case OR_Ambiguous: 2997 return OR_Ambiguous; 2998 } 2999 3000 llvm_unreachable("Invalid OverloadResult!"); 3001 } 3002 3003 /// Determines whether there is a user-defined conversion sequence 3004 /// (C++ [over.ics.user]) that converts expression From to the type 3005 /// ToType. If such a conversion exists, User will contain the 3006 /// user-defined conversion sequence that performs such a conversion 3007 /// and this routine will return true. Otherwise, this routine returns 3008 /// false and User is unspecified. 3009 /// 3010 /// \param AllowExplicit true if the conversion should consider C++0x 3011 /// "explicit" conversion functions as well as non-explicit conversion 3012 /// functions (C++0x [class.conv.fct]p2). 3013 /// 3014 /// \param AllowObjCConversionOnExplicit true if the conversion should 3015 /// allow an extra Objective-C pointer conversion on uses of explicit 3016 /// constructors. Requires \c AllowExplicit to also be set. 3017 static OverloadingResult 3018 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3019 UserDefinedConversionSequence &User, 3020 OverloadCandidateSet &CandidateSet, 3021 bool AllowExplicit, 3022 bool AllowObjCConversionOnExplicit) { 3023 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3024 3025 // Whether we will only visit constructors. 3026 bool ConstructorsOnly = false; 3027 3028 // If the type we are conversion to is a class type, enumerate its 3029 // constructors. 3030 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3031 // C++ [over.match.ctor]p1: 3032 // When objects of class type are direct-initialized (8.5), or 3033 // copy-initialized from an expression of the same or a 3034 // derived class type (8.5), overload resolution selects the 3035 // constructor. [...] For copy-initialization, the candidate 3036 // functions are all the converting constructors (12.3.1) of 3037 // that class. The argument list is the expression-list within 3038 // the parentheses of the initializer. 3039 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3040 (From->getType()->getAs<RecordType>() && 3041 S.IsDerivedFrom(From->getType(), ToType))) 3042 ConstructorsOnly = true; 3043 3044 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3045 // RequireCompleteType may have returned true due to some invalid decl 3046 // during template instantiation, but ToType may be complete enough now 3047 // to try to recover. 3048 if (ToType->isIncompleteType()) { 3049 // We're not going to find any constructors. 3050 } else if (CXXRecordDecl *ToRecordDecl 3051 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3052 3053 Expr **Args = &From; 3054 unsigned NumArgs = 1; 3055 bool ListInitializing = false; 3056 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3057 // But first, see if there is an init-list-constructor that will work. 3058 OverloadingResult Result = IsInitializerListConstructorConversion( 3059 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3060 if (Result != OR_No_Viable_Function) 3061 return Result; 3062 // Never mind. 3063 CandidateSet.clear(); 3064 3065 // If we're list-initializing, we pass the individual elements as 3066 // arguments, not the entire list. 3067 Args = InitList->getInits(); 3068 NumArgs = InitList->getNumInits(); 3069 ListInitializing = true; 3070 } 3071 3072 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3073 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3074 Con != ConEnd; ++Con) { 3075 NamedDecl *D = *Con; 3076 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3077 3078 // Find the constructor (which may be a template). 3079 CXXConstructorDecl *Constructor = nullptr; 3080 FunctionTemplateDecl *ConstructorTmpl 3081 = dyn_cast<FunctionTemplateDecl>(D); 3082 if (ConstructorTmpl) 3083 Constructor 3084 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3085 else 3086 Constructor = cast<CXXConstructorDecl>(D); 3087 3088 bool Usable = !Constructor->isInvalidDecl(); 3089 if (ListInitializing) 3090 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3091 else 3092 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3093 if (Usable) { 3094 bool SuppressUserConversions = !ConstructorsOnly; 3095 if (SuppressUserConversions && ListInitializing) { 3096 SuppressUserConversions = false; 3097 if (NumArgs == 1) { 3098 // If the first argument is (a reference to) the target type, 3099 // suppress conversions. 3100 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3101 S.Context, Constructor, ToType); 3102 } 3103 } 3104 if (ConstructorTmpl) 3105 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3106 /*ExplicitArgs*/ nullptr, 3107 llvm::makeArrayRef(Args, NumArgs), 3108 CandidateSet, SuppressUserConversions); 3109 else 3110 // Allow one user-defined conversion when user specifies a 3111 // From->ToType conversion via an static cast (c-style, etc). 3112 S.AddOverloadCandidate(Constructor, FoundDecl, 3113 llvm::makeArrayRef(Args, NumArgs), 3114 CandidateSet, SuppressUserConversions); 3115 } 3116 } 3117 } 3118 } 3119 3120 // Enumerate conversion functions, if we're allowed to. 3121 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3122 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3123 // No conversion functions from incomplete types. 3124 } else if (const RecordType *FromRecordType 3125 = From->getType()->getAs<RecordType>()) { 3126 if (CXXRecordDecl *FromRecordDecl 3127 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3128 // Add all of the conversion functions as candidates. 3129 std::pair<CXXRecordDecl::conversion_iterator, 3130 CXXRecordDecl::conversion_iterator> 3131 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3132 for (CXXRecordDecl::conversion_iterator 3133 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3134 DeclAccessPair FoundDecl = I.getPair(); 3135 NamedDecl *D = FoundDecl.getDecl(); 3136 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3137 if (isa<UsingShadowDecl>(D)) 3138 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3139 3140 CXXConversionDecl *Conv; 3141 FunctionTemplateDecl *ConvTemplate; 3142 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3143 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3144 else 3145 Conv = cast<CXXConversionDecl>(D); 3146 3147 if (AllowExplicit || !Conv->isExplicit()) { 3148 if (ConvTemplate) 3149 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3150 ActingContext, From, ToType, 3151 CandidateSet, 3152 AllowObjCConversionOnExplicit); 3153 else 3154 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3155 From, ToType, CandidateSet, 3156 AllowObjCConversionOnExplicit); 3157 } 3158 } 3159 } 3160 } 3161 3162 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3163 3164 OverloadCandidateSet::iterator Best; 3165 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3166 case OR_Success: 3167 // Record the standard conversion we used and the conversion function. 3168 if (CXXConstructorDecl *Constructor 3169 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3170 // C++ [over.ics.user]p1: 3171 // If the user-defined conversion is specified by a 3172 // constructor (12.3.1), the initial standard conversion 3173 // sequence converts the source type to the type required by 3174 // the argument of the constructor. 3175 // 3176 QualType ThisType = Constructor->getThisType(S.Context); 3177 if (isa<InitListExpr>(From)) { 3178 // Initializer lists don't have conversions as such. 3179 User.Before.setAsIdentityConversion(); 3180 } else { 3181 if (Best->Conversions[0].isEllipsis()) 3182 User.EllipsisConversion = true; 3183 else { 3184 User.Before = Best->Conversions[0].Standard; 3185 User.EllipsisConversion = false; 3186 } 3187 } 3188 User.HadMultipleCandidates = HadMultipleCandidates; 3189 User.ConversionFunction = Constructor; 3190 User.FoundConversionFunction = Best->FoundDecl; 3191 User.After.setAsIdentityConversion(); 3192 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3193 User.After.setAllToTypes(ToType); 3194 return OR_Success; 3195 } 3196 if (CXXConversionDecl *Conversion 3197 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3198 // C++ [over.ics.user]p1: 3199 // 3200 // [...] If the user-defined conversion is specified by a 3201 // conversion function (12.3.2), the initial standard 3202 // conversion sequence converts the source type to the 3203 // implicit object parameter of the conversion function. 3204 User.Before = Best->Conversions[0].Standard; 3205 User.HadMultipleCandidates = HadMultipleCandidates; 3206 User.ConversionFunction = Conversion; 3207 User.FoundConversionFunction = Best->FoundDecl; 3208 User.EllipsisConversion = false; 3209 3210 // C++ [over.ics.user]p2: 3211 // The second standard conversion sequence converts the 3212 // result of the user-defined conversion to the target type 3213 // for the sequence. Since an implicit conversion sequence 3214 // is an initialization, the special rules for 3215 // initialization by user-defined conversion apply when 3216 // selecting the best user-defined conversion for a 3217 // user-defined conversion sequence (see 13.3.3 and 3218 // 13.3.3.1). 3219 User.After = Best->FinalConversion; 3220 return OR_Success; 3221 } 3222 llvm_unreachable("Not a constructor or conversion function?"); 3223 3224 case OR_No_Viable_Function: 3225 return OR_No_Viable_Function; 3226 case OR_Deleted: 3227 // No conversion here! We're done. 3228 return OR_Deleted; 3229 3230 case OR_Ambiguous: 3231 return OR_Ambiguous; 3232 } 3233 3234 llvm_unreachable("Invalid OverloadResult!"); 3235 } 3236 3237 bool 3238 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3239 ImplicitConversionSequence ICS; 3240 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3241 OverloadCandidateSet::CSK_Normal); 3242 OverloadingResult OvResult = 3243 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3244 CandidateSet, false, false); 3245 if (OvResult == OR_Ambiguous) 3246 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3247 << From->getType() << ToType << From->getSourceRange(); 3248 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3249 if (!RequireCompleteType(From->getLocStart(), ToType, 3250 diag::err_typecheck_nonviable_condition_incomplete, 3251 From->getType(), From->getSourceRange())) 3252 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3253 << From->getType() << From->getSourceRange() << ToType; 3254 } else 3255 return false; 3256 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3257 return true; 3258 } 3259 3260 /// \brief Compare the user-defined conversion functions or constructors 3261 /// of two user-defined conversion sequences to determine whether any ordering 3262 /// is possible. 3263 static ImplicitConversionSequence::CompareKind 3264 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3265 FunctionDecl *Function2) { 3266 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3267 return ImplicitConversionSequence::Indistinguishable; 3268 3269 // Objective-C++: 3270 // If both conversion functions are implicitly-declared conversions from 3271 // a lambda closure type to a function pointer and a block pointer, 3272 // respectively, always prefer the conversion to a function pointer, 3273 // because the function pointer is more lightweight and is more likely 3274 // to keep code working. 3275 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3276 if (!Conv1) 3277 return ImplicitConversionSequence::Indistinguishable; 3278 3279 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3280 if (!Conv2) 3281 return ImplicitConversionSequence::Indistinguishable; 3282 3283 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3284 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3285 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3286 if (Block1 != Block2) 3287 return Block1 ? ImplicitConversionSequence::Worse 3288 : ImplicitConversionSequence::Better; 3289 } 3290 3291 return ImplicitConversionSequence::Indistinguishable; 3292 } 3293 3294 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3295 const ImplicitConversionSequence &ICS) { 3296 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3297 (ICS.isUserDefined() && 3298 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3299 } 3300 3301 /// CompareImplicitConversionSequences - Compare two implicit 3302 /// conversion sequences to determine whether one is better than the 3303 /// other or if they are indistinguishable (C++ 13.3.3.2). 3304 static ImplicitConversionSequence::CompareKind 3305 CompareImplicitConversionSequences(Sema &S, 3306 const ImplicitConversionSequence& ICS1, 3307 const ImplicitConversionSequence& ICS2) 3308 { 3309 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3310 // conversion sequences (as defined in 13.3.3.1) 3311 // -- a standard conversion sequence (13.3.3.1.1) is a better 3312 // conversion sequence than a user-defined conversion sequence or 3313 // an ellipsis conversion sequence, and 3314 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3315 // conversion sequence than an ellipsis conversion sequence 3316 // (13.3.3.1.3). 3317 // 3318 // C++0x [over.best.ics]p10: 3319 // For the purpose of ranking implicit conversion sequences as 3320 // described in 13.3.3.2, the ambiguous conversion sequence is 3321 // treated as a user-defined sequence that is indistinguishable 3322 // from any other user-defined conversion sequence. 3323 3324 // String literal to 'char *' conversion has been deprecated in C++03. It has 3325 // been removed from C++11. We still accept this conversion, if it happens at 3326 // the best viable function. Otherwise, this conversion is considered worse 3327 // than ellipsis conversion. Consider this as an extension; this is not in the 3328 // standard. For example: 3329 // 3330 // int &f(...); // #1 3331 // void f(char*); // #2 3332 // void g() { int &r = f("foo"); } 3333 // 3334 // In C++03, we pick #2 as the best viable function. 3335 // In C++11, we pick #1 as the best viable function, because ellipsis 3336 // conversion is better than string-literal to char* conversion (since there 3337 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3338 // convert arguments, #2 would be the best viable function in C++11. 3339 // If the best viable function has this conversion, a warning will be issued 3340 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3341 3342 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3343 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3344 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3345 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3346 ? ImplicitConversionSequence::Worse 3347 : ImplicitConversionSequence::Better; 3348 3349 if (ICS1.getKindRank() < ICS2.getKindRank()) 3350 return ImplicitConversionSequence::Better; 3351 if (ICS2.getKindRank() < ICS1.getKindRank()) 3352 return ImplicitConversionSequence::Worse; 3353 3354 // The following checks require both conversion sequences to be of 3355 // the same kind. 3356 if (ICS1.getKind() != ICS2.getKind()) 3357 return ImplicitConversionSequence::Indistinguishable; 3358 3359 ImplicitConversionSequence::CompareKind Result = 3360 ImplicitConversionSequence::Indistinguishable; 3361 3362 // Two implicit conversion sequences of the same form are 3363 // indistinguishable conversion sequences unless one of the 3364 // following rules apply: (C++ 13.3.3.2p3): 3365 if (ICS1.isStandard()) 3366 Result = CompareStandardConversionSequences(S, 3367 ICS1.Standard, ICS2.Standard); 3368 else if (ICS1.isUserDefined()) { 3369 // User-defined conversion sequence U1 is a better conversion 3370 // sequence than another user-defined conversion sequence U2 if 3371 // they contain the same user-defined conversion function or 3372 // constructor and if the second standard conversion sequence of 3373 // U1 is better than the second standard conversion sequence of 3374 // U2 (C++ 13.3.3.2p3). 3375 if (ICS1.UserDefined.ConversionFunction == 3376 ICS2.UserDefined.ConversionFunction) 3377 Result = CompareStandardConversionSequences(S, 3378 ICS1.UserDefined.After, 3379 ICS2.UserDefined.After); 3380 else 3381 Result = compareConversionFunctions(S, 3382 ICS1.UserDefined.ConversionFunction, 3383 ICS2.UserDefined.ConversionFunction); 3384 } 3385 3386 // List-initialization sequence L1 is a better conversion sequence than 3387 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3388 // for some X and L2 does not. 3389 if (Result == ImplicitConversionSequence::Indistinguishable && 3390 !ICS1.isBad()) { 3391 if (ICS1.isStdInitializerListElement() && 3392 !ICS2.isStdInitializerListElement()) 3393 return ImplicitConversionSequence::Better; 3394 if (!ICS1.isStdInitializerListElement() && 3395 ICS2.isStdInitializerListElement()) 3396 return ImplicitConversionSequence::Worse; 3397 } 3398 3399 return Result; 3400 } 3401 3402 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3403 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3404 Qualifiers Quals; 3405 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3406 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3407 } 3408 3409 return Context.hasSameUnqualifiedType(T1, T2); 3410 } 3411 3412 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3413 // determine if one is a proper subset of the other. 3414 static ImplicitConversionSequence::CompareKind 3415 compareStandardConversionSubsets(ASTContext &Context, 3416 const StandardConversionSequence& SCS1, 3417 const StandardConversionSequence& SCS2) { 3418 ImplicitConversionSequence::CompareKind Result 3419 = ImplicitConversionSequence::Indistinguishable; 3420 3421 // the identity conversion sequence is considered to be a subsequence of 3422 // any non-identity conversion sequence 3423 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3424 return ImplicitConversionSequence::Better; 3425 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3426 return ImplicitConversionSequence::Worse; 3427 3428 if (SCS1.Second != SCS2.Second) { 3429 if (SCS1.Second == ICK_Identity) 3430 Result = ImplicitConversionSequence::Better; 3431 else if (SCS2.Second == ICK_Identity) 3432 Result = ImplicitConversionSequence::Worse; 3433 else 3434 return ImplicitConversionSequence::Indistinguishable; 3435 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3436 return ImplicitConversionSequence::Indistinguishable; 3437 3438 if (SCS1.Third == SCS2.Third) { 3439 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3440 : ImplicitConversionSequence::Indistinguishable; 3441 } 3442 3443 if (SCS1.Third == ICK_Identity) 3444 return Result == ImplicitConversionSequence::Worse 3445 ? ImplicitConversionSequence::Indistinguishable 3446 : ImplicitConversionSequence::Better; 3447 3448 if (SCS2.Third == ICK_Identity) 3449 return Result == ImplicitConversionSequence::Better 3450 ? ImplicitConversionSequence::Indistinguishable 3451 : ImplicitConversionSequence::Worse; 3452 3453 return ImplicitConversionSequence::Indistinguishable; 3454 } 3455 3456 /// \brief Determine whether one of the given reference bindings is better 3457 /// than the other based on what kind of bindings they are. 3458 static bool 3459 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3460 const StandardConversionSequence &SCS2) { 3461 // C++0x [over.ics.rank]p3b4: 3462 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3463 // implicit object parameter of a non-static member function declared 3464 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3465 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3466 // lvalue reference to a function lvalue and S2 binds an rvalue 3467 // reference*. 3468 // 3469 // FIXME: Rvalue references. We're going rogue with the above edits, 3470 // because the semantics in the current C++0x working paper (N3225 at the 3471 // time of this writing) break the standard definition of std::forward 3472 // and std::reference_wrapper when dealing with references to functions. 3473 // Proposed wording changes submitted to CWG for consideration. 3474 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3475 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3476 return false; 3477 3478 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3479 SCS2.IsLvalueReference) || 3480 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3481 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3482 } 3483 3484 /// CompareStandardConversionSequences - Compare two standard 3485 /// conversion sequences to determine whether one is better than the 3486 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3487 static ImplicitConversionSequence::CompareKind 3488 CompareStandardConversionSequences(Sema &S, 3489 const StandardConversionSequence& SCS1, 3490 const StandardConversionSequence& SCS2) 3491 { 3492 // Standard conversion sequence S1 is a better conversion sequence 3493 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3494 3495 // -- S1 is a proper subsequence of S2 (comparing the conversion 3496 // sequences in the canonical form defined by 13.3.3.1.1, 3497 // excluding any Lvalue Transformation; the identity conversion 3498 // sequence is considered to be a subsequence of any 3499 // non-identity conversion sequence) or, if not that, 3500 if (ImplicitConversionSequence::CompareKind CK 3501 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3502 return CK; 3503 3504 // -- the rank of S1 is better than the rank of S2 (by the rules 3505 // defined below), or, if not that, 3506 ImplicitConversionRank Rank1 = SCS1.getRank(); 3507 ImplicitConversionRank Rank2 = SCS2.getRank(); 3508 if (Rank1 < Rank2) 3509 return ImplicitConversionSequence::Better; 3510 else if (Rank2 < Rank1) 3511 return ImplicitConversionSequence::Worse; 3512 3513 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3514 // are indistinguishable unless one of the following rules 3515 // applies: 3516 3517 // A conversion that is not a conversion of a pointer, or 3518 // pointer to member, to bool is better than another conversion 3519 // that is such a conversion. 3520 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3521 return SCS2.isPointerConversionToBool() 3522 ? ImplicitConversionSequence::Better 3523 : ImplicitConversionSequence::Worse; 3524 3525 // C++ [over.ics.rank]p4b2: 3526 // 3527 // If class B is derived directly or indirectly from class A, 3528 // conversion of B* to A* is better than conversion of B* to 3529 // void*, and conversion of A* to void* is better than conversion 3530 // of B* to void*. 3531 bool SCS1ConvertsToVoid 3532 = SCS1.isPointerConversionToVoidPointer(S.Context); 3533 bool SCS2ConvertsToVoid 3534 = SCS2.isPointerConversionToVoidPointer(S.Context); 3535 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3536 // Exactly one of the conversion sequences is a conversion to 3537 // a void pointer; it's the worse conversion. 3538 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3539 : ImplicitConversionSequence::Worse; 3540 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3541 // Neither conversion sequence converts to a void pointer; compare 3542 // their derived-to-base conversions. 3543 if (ImplicitConversionSequence::CompareKind DerivedCK 3544 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3545 return DerivedCK; 3546 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3547 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3548 // Both conversion sequences are conversions to void 3549 // pointers. Compare the source types to determine if there's an 3550 // inheritance relationship in their sources. 3551 QualType FromType1 = SCS1.getFromType(); 3552 QualType FromType2 = SCS2.getFromType(); 3553 3554 // Adjust the types we're converting from via the array-to-pointer 3555 // conversion, if we need to. 3556 if (SCS1.First == ICK_Array_To_Pointer) 3557 FromType1 = S.Context.getArrayDecayedType(FromType1); 3558 if (SCS2.First == ICK_Array_To_Pointer) 3559 FromType2 = S.Context.getArrayDecayedType(FromType2); 3560 3561 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3562 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3563 3564 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3565 return ImplicitConversionSequence::Better; 3566 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3567 return ImplicitConversionSequence::Worse; 3568 3569 // Objective-C++: If one interface is more specific than the 3570 // other, it is the better one. 3571 const ObjCObjectPointerType* FromObjCPtr1 3572 = FromType1->getAs<ObjCObjectPointerType>(); 3573 const ObjCObjectPointerType* FromObjCPtr2 3574 = FromType2->getAs<ObjCObjectPointerType>(); 3575 if (FromObjCPtr1 && FromObjCPtr2) { 3576 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3577 FromObjCPtr2); 3578 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3579 FromObjCPtr1); 3580 if (AssignLeft != AssignRight) { 3581 return AssignLeft? ImplicitConversionSequence::Better 3582 : ImplicitConversionSequence::Worse; 3583 } 3584 } 3585 } 3586 3587 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3588 // bullet 3). 3589 if (ImplicitConversionSequence::CompareKind QualCK 3590 = CompareQualificationConversions(S, SCS1, SCS2)) 3591 return QualCK; 3592 3593 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3594 // Check for a better reference binding based on the kind of bindings. 3595 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3596 return ImplicitConversionSequence::Better; 3597 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3598 return ImplicitConversionSequence::Worse; 3599 3600 // C++ [over.ics.rank]p3b4: 3601 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3602 // which the references refer are the same type except for 3603 // top-level cv-qualifiers, and the type to which the reference 3604 // initialized by S2 refers is more cv-qualified than the type 3605 // to which the reference initialized by S1 refers. 3606 QualType T1 = SCS1.getToType(2); 3607 QualType T2 = SCS2.getToType(2); 3608 T1 = S.Context.getCanonicalType(T1); 3609 T2 = S.Context.getCanonicalType(T2); 3610 Qualifiers T1Quals, T2Quals; 3611 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3612 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3613 if (UnqualT1 == UnqualT2) { 3614 // Objective-C++ ARC: If the references refer to objects with different 3615 // lifetimes, prefer bindings that don't change lifetime. 3616 if (SCS1.ObjCLifetimeConversionBinding != 3617 SCS2.ObjCLifetimeConversionBinding) { 3618 return SCS1.ObjCLifetimeConversionBinding 3619 ? ImplicitConversionSequence::Worse 3620 : ImplicitConversionSequence::Better; 3621 } 3622 3623 // If the type is an array type, promote the element qualifiers to the 3624 // type for comparison. 3625 if (isa<ArrayType>(T1) && T1Quals) 3626 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3627 if (isa<ArrayType>(T2) && T2Quals) 3628 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3629 if (T2.isMoreQualifiedThan(T1)) 3630 return ImplicitConversionSequence::Better; 3631 else if (T1.isMoreQualifiedThan(T2)) 3632 return ImplicitConversionSequence::Worse; 3633 } 3634 } 3635 3636 // In Microsoft mode, prefer an integral conversion to a 3637 // floating-to-integral conversion if the integral conversion 3638 // is between types of the same size. 3639 // For example: 3640 // void f(float); 3641 // void f(int); 3642 // int main { 3643 // long a; 3644 // f(a); 3645 // } 3646 // Here, MSVC will call f(int) instead of generating a compile error 3647 // as clang will do in standard mode. 3648 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3649 SCS2.Second == ICK_Floating_Integral && 3650 S.Context.getTypeSize(SCS1.getFromType()) == 3651 S.Context.getTypeSize(SCS1.getToType(2))) 3652 return ImplicitConversionSequence::Better; 3653 3654 return ImplicitConversionSequence::Indistinguishable; 3655 } 3656 3657 /// CompareQualificationConversions - Compares two standard conversion 3658 /// sequences to determine whether they can be ranked based on their 3659 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3660 ImplicitConversionSequence::CompareKind 3661 CompareQualificationConversions(Sema &S, 3662 const StandardConversionSequence& SCS1, 3663 const StandardConversionSequence& SCS2) { 3664 // C++ 13.3.3.2p3: 3665 // -- S1 and S2 differ only in their qualification conversion and 3666 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3667 // cv-qualification signature of type T1 is a proper subset of 3668 // the cv-qualification signature of type T2, and S1 is not the 3669 // deprecated string literal array-to-pointer conversion (4.2). 3670 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3671 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3672 return ImplicitConversionSequence::Indistinguishable; 3673 3674 // FIXME: the example in the standard doesn't use a qualification 3675 // conversion (!) 3676 QualType T1 = SCS1.getToType(2); 3677 QualType T2 = SCS2.getToType(2); 3678 T1 = S.Context.getCanonicalType(T1); 3679 T2 = S.Context.getCanonicalType(T2); 3680 Qualifiers T1Quals, T2Quals; 3681 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3682 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3683 3684 // If the types are the same, we won't learn anything by unwrapped 3685 // them. 3686 if (UnqualT1 == UnqualT2) 3687 return ImplicitConversionSequence::Indistinguishable; 3688 3689 // If the type is an array type, promote the element qualifiers to the type 3690 // for comparison. 3691 if (isa<ArrayType>(T1) && T1Quals) 3692 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3693 if (isa<ArrayType>(T2) && T2Quals) 3694 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3695 3696 ImplicitConversionSequence::CompareKind Result 3697 = ImplicitConversionSequence::Indistinguishable; 3698 3699 // Objective-C++ ARC: 3700 // Prefer qualification conversions not involving a change in lifetime 3701 // to qualification conversions that do not change lifetime. 3702 if (SCS1.QualificationIncludesObjCLifetime != 3703 SCS2.QualificationIncludesObjCLifetime) { 3704 Result = SCS1.QualificationIncludesObjCLifetime 3705 ? ImplicitConversionSequence::Worse 3706 : ImplicitConversionSequence::Better; 3707 } 3708 3709 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3710 // Within each iteration of the loop, we check the qualifiers to 3711 // determine if this still looks like a qualification 3712 // conversion. Then, if all is well, we unwrap one more level of 3713 // pointers or pointers-to-members and do it all again 3714 // until there are no more pointers or pointers-to-members left 3715 // to unwrap. This essentially mimics what 3716 // IsQualificationConversion does, but here we're checking for a 3717 // strict subset of qualifiers. 3718 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3719 // The qualifiers are the same, so this doesn't tell us anything 3720 // about how the sequences rank. 3721 ; 3722 else if (T2.isMoreQualifiedThan(T1)) { 3723 // T1 has fewer qualifiers, so it could be the better sequence. 3724 if (Result == ImplicitConversionSequence::Worse) 3725 // Neither has qualifiers that are a subset of the other's 3726 // qualifiers. 3727 return ImplicitConversionSequence::Indistinguishable; 3728 3729 Result = ImplicitConversionSequence::Better; 3730 } else if (T1.isMoreQualifiedThan(T2)) { 3731 // T2 has fewer qualifiers, so it could be the better sequence. 3732 if (Result == ImplicitConversionSequence::Better) 3733 // Neither has qualifiers that are a subset of the other's 3734 // qualifiers. 3735 return ImplicitConversionSequence::Indistinguishable; 3736 3737 Result = ImplicitConversionSequence::Worse; 3738 } else { 3739 // Qualifiers are disjoint. 3740 return ImplicitConversionSequence::Indistinguishable; 3741 } 3742 3743 // If the types after this point are equivalent, we're done. 3744 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3745 break; 3746 } 3747 3748 // Check that the winning standard conversion sequence isn't using 3749 // the deprecated string literal array to pointer conversion. 3750 switch (Result) { 3751 case ImplicitConversionSequence::Better: 3752 if (SCS1.DeprecatedStringLiteralToCharPtr) 3753 Result = ImplicitConversionSequence::Indistinguishable; 3754 break; 3755 3756 case ImplicitConversionSequence::Indistinguishable: 3757 break; 3758 3759 case ImplicitConversionSequence::Worse: 3760 if (SCS2.DeprecatedStringLiteralToCharPtr) 3761 Result = ImplicitConversionSequence::Indistinguishable; 3762 break; 3763 } 3764 3765 return Result; 3766 } 3767 3768 /// CompareDerivedToBaseConversions - Compares two standard conversion 3769 /// sequences to determine whether they can be ranked based on their 3770 /// various kinds of derived-to-base conversions (C++ 3771 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3772 /// conversions between Objective-C interface types. 3773 ImplicitConversionSequence::CompareKind 3774 CompareDerivedToBaseConversions(Sema &S, 3775 const StandardConversionSequence& SCS1, 3776 const StandardConversionSequence& SCS2) { 3777 QualType FromType1 = SCS1.getFromType(); 3778 QualType ToType1 = SCS1.getToType(1); 3779 QualType FromType2 = SCS2.getFromType(); 3780 QualType ToType2 = SCS2.getToType(1); 3781 3782 // Adjust the types we're converting from via the array-to-pointer 3783 // conversion, if we need to. 3784 if (SCS1.First == ICK_Array_To_Pointer) 3785 FromType1 = S.Context.getArrayDecayedType(FromType1); 3786 if (SCS2.First == ICK_Array_To_Pointer) 3787 FromType2 = S.Context.getArrayDecayedType(FromType2); 3788 3789 // Canonicalize all of the types. 3790 FromType1 = S.Context.getCanonicalType(FromType1); 3791 ToType1 = S.Context.getCanonicalType(ToType1); 3792 FromType2 = S.Context.getCanonicalType(FromType2); 3793 ToType2 = S.Context.getCanonicalType(ToType2); 3794 3795 // C++ [over.ics.rank]p4b3: 3796 // 3797 // If class B is derived directly or indirectly from class A and 3798 // class C is derived directly or indirectly from B, 3799 // 3800 // Compare based on pointer conversions. 3801 if (SCS1.Second == ICK_Pointer_Conversion && 3802 SCS2.Second == ICK_Pointer_Conversion && 3803 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3804 FromType1->isPointerType() && FromType2->isPointerType() && 3805 ToType1->isPointerType() && ToType2->isPointerType()) { 3806 QualType FromPointee1 3807 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3808 QualType ToPointee1 3809 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3810 QualType FromPointee2 3811 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3812 QualType ToPointee2 3813 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3814 3815 // -- conversion of C* to B* is better than conversion of C* to A*, 3816 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3817 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3818 return ImplicitConversionSequence::Better; 3819 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3820 return ImplicitConversionSequence::Worse; 3821 } 3822 3823 // -- conversion of B* to A* is better than conversion of C* to A*, 3824 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3825 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3826 return ImplicitConversionSequence::Better; 3827 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3828 return ImplicitConversionSequence::Worse; 3829 } 3830 } else if (SCS1.Second == ICK_Pointer_Conversion && 3831 SCS2.Second == ICK_Pointer_Conversion) { 3832 const ObjCObjectPointerType *FromPtr1 3833 = FromType1->getAs<ObjCObjectPointerType>(); 3834 const ObjCObjectPointerType *FromPtr2 3835 = FromType2->getAs<ObjCObjectPointerType>(); 3836 const ObjCObjectPointerType *ToPtr1 3837 = ToType1->getAs<ObjCObjectPointerType>(); 3838 const ObjCObjectPointerType *ToPtr2 3839 = ToType2->getAs<ObjCObjectPointerType>(); 3840 3841 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3842 // Apply the same conversion ranking rules for Objective-C pointer types 3843 // that we do for C++ pointers to class types. However, we employ the 3844 // Objective-C pseudo-subtyping relationship used for assignment of 3845 // Objective-C pointer types. 3846 bool FromAssignLeft 3847 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3848 bool FromAssignRight 3849 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3850 bool ToAssignLeft 3851 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3852 bool ToAssignRight 3853 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3854 3855 // A conversion to an a non-id object pointer type or qualified 'id' 3856 // type is better than a conversion to 'id'. 3857 if (ToPtr1->isObjCIdType() && 3858 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3859 return ImplicitConversionSequence::Worse; 3860 if (ToPtr2->isObjCIdType() && 3861 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3862 return ImplicitConversionSequence::Better; 3863 3864 // A conversion to a non-id object pointer type is better than a 3865 // conversion to a qualified 'id' type 3866 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3867 return ImplicitConversionSequence::Worse; 3868 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3869 return ImplicitConversionSequence::Better; 3870 3871 // A conversion to an a non-Class object pointer type or qualified 'Class' 3872 // type is better than a conversion to 'Class'. 3873 if (ToPtr1->isObjCClassType() && 3874 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3875 return ImplicitConversionSequence::Worse; 3876 if (ToPtr2->isObjCClassType() && 3877 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3878 return ImplicitConversionSequence::Better; 3879 3880 // A conversion to a non-Class object pointer type is better than a 3881 // conversion to a qualified 'Class' type. 3882 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3883 return ImplicitConversionSequence::Worse; 3884 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3885 return ImplicitConversionSequence::Better; 3886 3887 // -- "conversion of C* to B* is better than conversion of C* to A*," 3888 if (S.Context.hasSameType(FromType1, FromType2) && 3889 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3890 (ToAssignLeft != ToAssignRight)) 3891 return ToAssignLeft? ImplicitConversionSequence::Worse 3892 : ImplicitConversionSequence::Better; 3893 3894 // -- "conversion of B* to A* is better than conversion of C* to A*," 3895 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3896 (FromAssignLeft != FromAssignRight)) 3897 return FromAssignLeft? ImplicitConversionSequence::Better 3898 : ImplicitConversionSequence::Worse; 3899 } 3900 } 3901 3902 // Ranking of member-pointer types. 3903 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3904 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3905 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3906 const MemberPointerType * FromMemPointer1 = 3907 FromType1->getAs<MemberPointerType>(); 3908 const MemberPointerType * ToMemPointer1 = 3909 ToType1->getAs<MemberPointerType>(); 3910 const MemberPointerType * FromMemPointer2 = 3911 FromType2->getAs<MemberPointerType>(); 3912 const MemberPointerType * ToMemPointer2 = 3913 ToType2->getAs<MemberPointerType>(); 3914 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3915 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3916 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3917 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3918 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3919 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3920 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3921 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3922 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3923 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3924 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3925 return ImplicitConversionSequence::Worse; 3926 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3927 return ImplicitConversionSequence::Better; 3928 } 3929 // conversion of B::* to C::* is better than conversion of A::* to C::* 3930 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3931 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3932 return ImplicitConversionSequence::Better; 3933 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3934 return ImplicitConversionSequence::Worse; 3935 } 3936 } 3937 3938 if (SCS1.Second == ICK_Derived_To_Base) { 3939 // -- conversion of C to B is better than conversion of C to A, 3940 // -- binding of an expression of type C to a reference of type 3941 // B& is better than binding an expression of type C to a 3942 // reference of type A&, 3943 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3944 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3945 if (S.IsDerivedFrom(ToType1, ToType2)) 3946 return ImplicitConversionSequence::Better; 3947 else if (S.IsDerivedFrom(ToType2, ToType1)) 3948 return ImplicitConversionSequence::Worse; 3949 } 3950 3951 // -- conversion of B to A is better than conversion of C to A. 3952 // -- binding of an expression of type B to a reference of type 3953 // A& is better than binding an expression of type C to a 3954 // reference of type A&, 3955 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3956 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3957 if (S.IsDerivedFrom(FromType2, FromType1)) 3958 return ImplicitConversionSequence::Better; 3959 else if (S.IsDerivedFrom(FromType1, FromType2)) 3960 return ImplicitConversionSequence::Worse; 3961 } 3962 } 3963 3964 return ImplicitConversionSequence::Indistinguishable; 3965 } 3966 3967 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3968 /// C++ class. 3969 static bool isTypeValid(QualType T) { 3970 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3971 return !Record->isInvalidDecl(); 3972 3973 return true; 3974 } 3975 3976 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3977 /// determine whether they are reference-related, 3978 /// reference-compatible, reference-compatible with added 3979 /// qualification, or incompatible, for use in C++ initialization by 3980 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3981 /// type, and the first type (T1) is the pointee type of the reference 3982 /// type being initialized. 3983 Sema::ReferenceCompareResult 3984 Sema::CompareReferenceRelationship(SourceLocation Loc, 3985 QualType OrigT1, QualType OrigT2, 3986 bool &DerivedToBase, 3987 bool &ObjCConversion, 3988 bool &ObjCLifetimeConversion) { 3989 assert(!OrigT1->isReferenceType() && 3990 "T1 must be the pointee type of the reference type"); 3991 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3992 3993 QualType T1 = Context.getCanonicalType(OrigT1); 3994 QualType T2 = Context.getCanonicalType(OrigT2); 3995 Qualifiers T1Quals, T2Quals; 3996 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3997 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3998 3999 // C++ [dcl.init.ref]p4: 4000 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4001 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4002 // T1 is a base class of T2. 4003 DerivedToBase = false; 4004 ObjCConversion = false; 4005 ObjCLifetimeConversion = false; 4006 if (UnqualT1 == UnqualT2) { 4007 // Nothing to do. 4008 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4009 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4010 IsDerivedFrom(UnqualT2, UnqualT1)) 4011 DerivedToBase = true; 4012 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4013 UnqualT2->isObjCObjectOrInterfaceType() && 4014 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4015 ObjCConversion = true; 4016 else 4017 return Ref_Incompatible; 4018 4019 // At this point, we know that T1 and T2 are reference-related (at 4020 // least). 4021 4022 // If the type is an array type, promote the element qualifiers to the type 4023 // for comparison. 4024 if (isa<ArrayType>(T1) && T1Quals) 4025 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4026 if (isa<ArrayType>(T2) && T2Quals) 4027 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4028 4029 // C++ [dcl.init.ref]p4: 4030 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4031 // reference-related to T2 and cv1 is the same cv-qualification 4032 // as, or greater cv-qualification than, cv2. For purposes of 4033 // overload resolution, cases for which cv1 is greater 4034 // cv-qualification than cv2 are identified as 4035 // reference-compatible with added qualification (see 13.3.3.2). 4036 // 4037 // Note that we also require equivalence of Objective-C GC and address-space 4038 // qualifiers when performing these computations, so that e.g., an int in 4039 // address space 1 is not reference-compatible with an int in address 4040 // space 2. 4041 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4042 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4043 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4044 ObjCLifetimeConversion = true; 4045 4046 T1Quals.removeObjCLifetime(); 4047 T2Quals.removeObjCLifetime(); 4048 } 4049 4050 if (T1Quals == T2Quals) 4051 return Ref_Compatible; 4052 else if (T1Quals.compatiblyIncludes(T2Quals)) 4053 return Ref_Compatible_With_Added_Qualification; 4054 else 4055 return Ref_Related; 4056 } 4057 4058 /// \brief Look for a user-defined conversion to an value reference-compatible 4059 /// with DeclType. Return true if something definite is found. 4060 static bool 4061 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4062 QualType DeclType, SourceLocation DeclLoc, 4063 Expr *Init, QualType T2, bool AllowRvalues, 4064 bool AllowExplicit) { 4065 assert(T2->isRecordType() && "Can only find conversions of record types."); 4066 CXXRecordDecl *T2RecordDecl 4067 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4068 4069 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4070 std::pair<CXXRecordDecl::conversion_iterator, 4071 CXXRecordDecl::conversion_iterator> 4072 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4073 for (CXXRecordDecl::conversion_iterator 4074 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4075 NamedDecl *D = *I; 4076 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4077 if (isa<UsingShadowDecl>(D)) 4078 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4079 4080 FunctionTemplateDecl *ConvTemplate 4081 = dyn_cast<FunctionTemplateDecl>(D); 4082 CXXConversionDecl *Conv; 4083 if (ConvTemplate) 4084 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4085 else 4086 Conv = cast<CXXConversionDecl>(D); 4087 4088 // If this is an explicit conversion, and we're not allowed to consider 4089 // explicit conversions, skip it. 4090 if (!AllowExplicit && Conv->isExplicit()) 4091 continue; 4092 4093 if (AllowRvalues) { 4094 bool DerivedToBase = false; 4095 bool ObjCConversion = false; 4096 bool ObjCLifetimeConversion = false; 4097 4098 // If we are initializing an rvalue reference, don't permit conversion 4099 // functions that return lvalues. 4100 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4101 const ReferenceType *RefType 4102 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4103 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4104 continue; 4105 } 4106 4107 if (!ConvTemplate && 4108 S.CompareReferenceRelationship( 4109 DeclLoc, 4110 Conv->getConversionType().getNonReferenceType() 4111 .getUnqualifiedType(), 4112 DeclType.getNonReferenceType().getUnqualifiedType(), 4113 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4114 Sema::Ref_Incompatible) 4115 continue; 4116 } else { 4117 // If the conversion function doesn't return a reference type, 4118 // it can't be considered for this conversion. An rvalue reference 4119 // is only acceptable if its referencee is a function type. 4120 4121 const ReferenceType *RefType = 4122 Conv->getConversionType()->getAs<ReferenceType>(); 4123 if (!RefType || 4124 (!RefType->isLValueReferenceType() && 4125 !RefType->getPointeeType()->isFunctionType())) 4126 continue; 4127 } 4128 4129 if (ConvTemplate) 4130 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4131 Init, DeclType, CandidateSet, 4132 /*AllowObjCConversionOnExplicit=*/false); 4133 else 4134 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4135 DeclType, CandidateSet, 4136 /*AllowObjCConversionOnExplicit=*/false); 4137 } 4138 4139 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4140 4141 OverloadCandidateSet::iterator Best; 4142 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4143 case OR_Success: 4144 // C++ [over.ics.ref]p1: 4145 // 4146 // [...] If the parameter binds directly to the result of 4147 // applying a conversion function to the argument 4148 // expression, the implicit conversion sequence is a 4149 // user-defined conversion sequence (13.3.3.1.2), with the 4150 // second standard conversion sequence either an identity 4151 // conversion or, if the conversion function returns an 4152 // entity of a type that is a derived class of the parameter 4153 // type, a derived-to-base Conversion. 4154 if (!Best->FinalConversion.DirectBinding) 4155 return false; 4156 4157 ICS.setUserDefined(); 4158 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4159 ICS.UserDefined.After = Best->FinalConversion; 4160 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4161 ICS.UserDefined.ConversionFunction = Best->Function; 4162 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4163 ICS.UserDefined.EllipsisConversion = false; 4164 assert(ICS.UserDefined.After.ReferenceBinding && 4165 ICS.UserDefined.After.DirectBinding && 4166 "Expected a direct reference binding!"); 4167 return true; 4168 4169 case OR_Ambiguous: 4170 ICS.setAmbiguous(); 4171 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4172 Cand != CandidateSet.end(); ++Cand) 4173 if (Cand->Viable) 4174 ICS.Ambiguous.addConversion(Cand->Function); 4175 return true; 4176 4177 case OR_No_Viable_Function: 4178 case OR_Deleted: 4179 // There was no suitable conversion, or we found a deleted 4180 // conversion; continue with other checks. 4181 return false; 4182 } 4183 4184 llvm_unreachable("Invalid OverloadResult!"); 4185 } 4186 4187 /// \brief Compute an implicit conversion sequence for reference 4188 /// initialization. 4189 static ImplicitConversionSequence 4190 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4191 SourceLocation DeclLoc, 4192 bool SuppressUserConversions, 4193 bool AllowExplicit) { 4194 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4195 4196 // Most paths end in a failed conversion. 4197 ImplicitConversionSequence ICS; 4198 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4199 4200 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4201 QualType T2 = Init->getType(); 4202 4203 // If the initializer is the address of an overloaded function, try 4204 // to resolve the overloaded function. If all goes well, T2 is the 4205 // type of the resulting function. 4206 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4207 DeclAccessPair Found; 4208 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4209 false, Found)) 4210 T2 = Fn->getType(); 4211 } 4212 4213 // Compute some basic properties of the types and the initializer. 4214 bool isRValRef = DeclType->isRValueReferenceType(); 4215 bool DerivedToBase = false; 4216 bool ObjCConversion = false; 4217 bool ObjCLifetimeConversion = false; 4218 Expr::Classification InitCategory = Init->Classify(S.Context); 4219 Sema::ReferenceCompareResult RefRelationship 4220 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4221 ObjCConversion, ObjCLifetimeConversion); 4222 4223 4224 // C++0x [dcl.init.ref]p5: 4225 // A reference to type "cv1 T1" is initialized by an expression 4226 // of type "cv2 T2" as follows: 4227 4228 // -- If reference is an lvalue reference and the initializer expression 4229 if (!isRValRef) { 4230 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4231 // reference-compatible with "cv2 T2," or 4232 // 4233 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4234 if (InitCategory.isLValue() && 4235 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4236 // C++ [over.ics.ref]p1: 4237 // When a parameter of reference type binds directly (8.5.3) 4238 // to an argument expression, the implicit conversion sequence 4239 // is the identity conversion, unless the argument expression 4240 // has a type that is a derived class of the parameter type, 4241 // in which case the implicit conversion sequence is a 4242 // derived-to-base Conversion (13.3.3.1). 4243 ICS.setStandard(); 4244 ICS.Standard.First = ICK_Identity; 4245 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4246 : ObjCConversion? ICK_Compatible_Conversion 4247 : ICK_Identity; 4248 ICS.Standard.Third = ICK_Identity; 4249 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4250 ICS.Standard.setToType(0, T2); 4251 ICS.Standard.setToType(1, T1); 4252 ICS.Standard.setToType(2, T1); 4253 ICS.Standard.ReferenceBinding = true; 4254 ICS.Standard.DirectBinding = true; 4255 ICS.Standard.IsLvalueReference = !isRValRef; 4256 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4257 ICS.Standard.BindsToRvalue = false; 4258 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4259 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4260 ICS.Standard.CopyConstructor = nullptr; 4261 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4262 4263 // Nothing more to do: the inaccessibility/ambiguity check for 4264 // derived-to-base conversions is suppressed when we're 4265 // computing the implicit conversion sequence (C++ 4266 // [over.best.ics]p2). 4267 return ICS; 4268 } 4269 4270 // -- has a class type (i.e., T2 is a class type), where T1 is 4271 // not reference-related to T2, and can be implicitly 4272 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4273 // is reference-compatible with "cv3 T3" 92) (this 4274 // conversion is selected by enumerating the applicable 4275 // conversion functions (13.3.1.6) and choosing the best 4276 // one through overload resolution (13.3)), 4277 if (!SuppressUserConversions && T2->isRecordType() && 4278 !S.RequireCompleteType(DeclLoc, T2, 0) && 4279 RefRelationship == Sema::Ref_Incompatible) { 4280 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4281 Init, T2, /*AllowRvalues=*/false, 4282 AllowExplicit)) 4283 return ICS; 4284 } 4285 } 4286 4287 // -- Otherwise, the reference shall be an lvalue reference to a 4288 // non-volatile const type (i.e., cv1 shall be const), or the reference 4289 // shall be an rvalue reference. 4290 // 4291 // We actually handle one oddity of C++ [over.ics.ref] at this 4292 // point, which is that, due to p2 (which short-circuits reference 4293 // binding by only attempting a simple conversion for non-direct 4294 // bindings) and p3's strange wording, we allow a const volatile 4295 // reference to bind to an rvalue. Hence the check for the presence 4296 // of "const" rather than checking for "const" being the only 4297 // qualifier. 4298 // This is also the point where rvalue references and lvalue inits no longer 4299 // go together. 4300 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4301 return ICS; 4302 4303 // -- If the initializer expression 4304 // 4305 // -- is an xvalue, class prvalue, array prvalue or function 4306 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4307 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4308 (InitCategory.isXValue() || 4309 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4310 (InitCategory.isLValue() && T2->isFunctionType()))) { 4311 ICS.setStandard(); 4312 ICS.Standard.First = ICK_Identity; 4313 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4314 : ObjCConversion? ICK_Compatible_Conversion 4315 : ICK_Identity; 4316 ICS.Standard.Third = ICK_Identity; 4317 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4318 ICS.Standard.setToType(0, T2); 4319 ICS.Standard.setToType(1, T1); 4320 ICS.Standard.setToType(2, T1); 4321 ICS.Standard.ReferenceBinding = true; 4322 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4323 // binding unless we're binding to a class prvalue. 4324 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4325 // allow the use of rvalue references in C++98/03 for the benefit of 4326 // standard library implementors; therefore, we need the xvalue check here. 4327 ICS.Standard.DirectBinding = 4328 S.getLangOpts().CPlusPlus11 || 4329 !(InitCategory.isPRValue() || T2->isRecordType()); 4330 ICS.Standard.IsLvalueReference = !isRValRef; 4331 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4332 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4333 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4334 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4335 ICS.Standard.CopyConstructor = nullptr; 4336 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4337 return ICS; 4338 } 4339 4340 // -- has a class type (i.e., T2 is a class type), where T1 is not 4341 // reference-related to T2, and can be implicitly converted to 4342 // an xvalue, class prvalue, or function lvalue of type 4343 // "cv3 T3", where "cv1 T1" is reference-compatible with 4344 // "cv3 T3", 4345 // 4346 // then the reference is bound to the value of the initializer 4347 // expression in the first case and to the result of the conversion 4348 // in the second case (or, in either case, to an appropriate base 4349 // class subobject). 4350 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4351 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4352 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4353 Init, T2, /*AllowRvalues=*/true, 4354 AllowExplicit)) { 4355 // In the second case, if the reference is an rvalue reference 4356 // and the second standard conversion sequence of the 4357 // user-defined conversion sequence includes an lvalue-to-rvalue 4358 // conversion, the program is ill-formed. 4359 if (ICS.isUserDefined() && isRValRef && 4360 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4361 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4362 4363 return ICS; 4364 } 4365 4366 // A temporary of function type cannot be created; don't even try. 4367 if (T1->isFunctionType()) 4368 return ICS; 4369 4370 // -- Otherwise, a temporary of type "cv1 T1" is created and 4371 // initialized from the initializer expression using the 4372 // rules for a non-reference copy initialization (8.5). The 4373 // reference is then bound to the temporary. If T1 is 4374 // reference-related to T2, cv1 must be the same 4375 // cv-qualification as, or greater cv-qualification than, 4376 // cv2; otherwise, the program is ill-formed. 4377 if (RefRelationship == Sema::Ref_Related) { 4378 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4379 // we would be reference-compatible or reference-compatible with 4380 // added qualification. But that wasn't the case, so the reference 4381 // initialization fails. 4382 // 4383 // Note that we only want to check address spaces and cvr-qualifiers here. 4384 // ObjC GC and lifetime qualifiers aren't important. 4385 Qualifiers T1Quals = T1.getQualifiers(); 4386 Qualifiers T2Quals = T2.getQualifiers(); 4387 T1Quals.removeObjCGCAttr(); 4388 T1Quals.removeObjCLifetime(); 4389 T2Quals.removeObjCGCAttr(); 4390 T2Quals.removeObjCLifetime(); 4391 if (!T1Quals.compatiblyIncludes(T2Quals)) 4392 return ICS; 4393 } 4394 4395 // If at least one of the types is a class type, the types are not 4396 // related, and we aren't allowed any user conversions, the 4397 // reference binding fails. This case is important for breaking 4398 // recursion, since TryImplicitConversion below will attempt to 4399 // create a temporary through the use of a copy constructor. 4400 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4401 (T1->isRecordType() || T2->isRecordType())) 4402 return ICS; 4403 4404 // If T1 is reference-related to T2 and the reference is an rvalue 4405 // reference, the initializer expression shall not be an lvalue. 4406 if (RefRelationship >= Sema::Ref_Related && 4407 isRValRef && Init->Classify(S.Context).isLValue()) 4408 return ICS; 4409 4410 // C++ [over.ics.ref]p2: 4411 // When a parameter of reference type is not bound directly to 4412 // an argument expression, the conversion sequence is the one 4413 // required to convert the argument expression to the 4414 // underlying type of the reference according to 4415 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4416 // to copy-initializing a temporary of the underlying type with 4417 // the argument expression. Any difference in top-level 4418 // cv-qualification is subsumed by the initialization itself 4419 // and does not constitute a conversion. 4420 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4421 /*AllowExplicit=*/false, 4422 /*InOverloadResolution=*/false, 4423 /*CStyle=*/false, 4424 /*AllowObjCWritebackConversion=*/false, 4425 /*AllowObjCConversionOnExplicit=*/false); 4426 4427 // Of course, that's still a reference binding. 4428 if (ICS.isStandard()) { 4429 ICS.Standard.ReferenceBinding = true; 4430 ICS.Standard.IsLvalueReference = !isRValRef; 4431 ICS.Standard.BindsToFunctionLvalue = false; 4432 ICS.Standard.BindsToRvalue = true; 4433 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4434 ICS.Standard.ObjCLifetimeConversionBinding = false; 4435 } else if (ICS.isUserDefined()) { 4436 const ReferenceType *LValRefType = 4437 ICS.UserDefined.ConversionFunction->getReturnType() 4438 ->getAs<LValueReferenceType>(); 4439 4440 // C++ [over.ics.ref]p3: 4441 // Except for an implicit object parameter, for which see 13.3.1, a 4442 // standard conversion sequence cannot be formed if it requires [...] 4443 // binding an rvalue reference to an lvalue other than a function 4444 // lvalue. 4445 // Note that the function case is not possible here. 4446 if (DeclType->isRValueReferenceType() && LValRefType) { 4447 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4448 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4449 // reference to an rvalue! 4450 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4451 return ICS; 4452 } 4453 4454 ICS.UserDefined.Before.setAsIdentityConversion(); 4455 ICS.UserDefined.After.ReferenceBinding = true; 4456 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4457 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4458 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4459 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4460 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4461 } 4462 4463 return ICS; 4464 } 4465 4466 static ImplicitConversionSequence 4467 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4468 bool SuppressUserConversions, 4469 bool InOverloadResolution, 4470 bool AllowObjCWritebackConversion, 4471 bool AllowExplicit = false); 4472 4473 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4474 /// initializer list From. 4475 static ImplicitConversionSequence 4476 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4477 bool SuppressUserConversions, 4478 bool InOverloadResolution, 4479 bool AllowObjCWritebackConversion) { 4480 // C++11 [over.ics.list]p1: 4481 // When an argument is an initializer list, it is not an expression and 4482 // special rules apply for converting it to a parameter type. 4483 4484 ImplicitConversionSequence Result; 4485 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4486 4487 // We need a complete type for what follows. Incomplete types can never be 4488 // initialized from init lists. 4489 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4490 return Result; 4491 4492 // C++11 [over.ics.list]p2: 4493 // If the parameter type is std::initializer_list<X> or "array of X" and 4494 // all the elements can be implicitly converted to X, the implicit 4495 // conversion sequence is the worst conversion necessary to convert an 4496 // element of the list to X. 4497 bool toStdInitializerList = false; 4498 QualType X; 4499 if (ToType->isArrayType()) 4500 X = S.Context.getAsArrayType(ToType)->getElementType(); 4501 else 4502 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4503 if (!X.isNull()) { 4504 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4505 Expr *Init = From->getInit(i); 4506 ImplicitConversionSequence ICS = 4507 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4508 InOverloadResolution, 4509 AllowObjCWritebackConversion); 4510 // If a single element isn't convertible, fail. 4511 if (ICS.isBad()) { 4512 Result = ICS; 4513 break; 4514 } 4515 // Otherwise, look for the worst conversion. 4516 if (Result.isBad() || 4517 CompareImplicitConversionSequences(S, ICS, Result) == 4518 ImplicitConversionSequence::Worse) 4519 Result = ICS; 4520 } 4521 4522 // For an empty list, we won't have computed any conversion sequence. 4523 // Introduce the identity conversion sequence. 4524 if (From->getNumInits() == 0) { 4525 Result.setStandard(); 4526 Result.Standard.setAsIdentityConversion(); 4527 Result.Standard.setFromType(ToType); 4528 Result.Standard.setAllToTypes(ToType); 4529 } 4530 4531 Result.setStdInitializerListElement(toStdInitializerList); 4532 return Result; 4533 } 4534 4535 // C++11 [over.ics.list]p3: 4536 // Otherwise, if the parameter is a non-aggregate class X and overload 4537 // resolution chooses a single best constructor [...] the implicit 4538 // conversion sequence is a user-defined conversion sequence. If multiple 4539 // constructors are viable but none is better than the others, the 4540 // implicit conversion sequence is a user-defined conversion sequence. 4541 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4542 // This function can deal with initializer lists. 4543 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4544 /*AllowExplicit=*/false, 4545 InOverloadResolution, /*CStyle=*/false, 4546 AllowObjCWritebackConversion, 4547 /*AllowObjCConversionOnExplicit=*/false); 4548 } 4549 4550 // C++11 [over.ics.list]p4: 4551 // Otherwise, if the parameter has an aggregate type which can be 4552 // initialized from the initializer list [...] the implicit conversion 4553 // sequence is a user-defined conversion sequence. 4554 if (ToType->isAggregateType()) { 4555 // Type is an aggregate, argument is an init list. At this point it comes 4556 // down to checking whether the initialization works. 4557 // FIXME: Find out whether this parameter is consumed or not. 4558 InitializedEntity Entity = 4559 InitializedEntity::InitializeParameter(S.Context, ToType, 4560 /*Consumed=*/false); 4561 if (S.CanPerformCopyInitialization(Entity, From)) { 4562 Result.setUserDefined(); 4563 Result.UserDefined.Before.setAsIdentityConversion(); 4564 // Initializer lists don't have a type. 4565 Result.UserDefined.Before.setFromType(QualType()); 4566 Result.UserDefined.Before.setAllToTypes(QualType()); 4567 4568 Result.UserDefined.After.setAsIdentityConversion(); 4569 Result.UserDefined.After.setFromType(ToType); 4570 Result.UserDefined.After.setAllToTypes(ToType); 4571 Result.UserDefined.ConversionFunction = nullptr; 4572 } 4573 return Result; 4574 } 4575 4576 // C++11 [over.ics.list]p5: 4577 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4578 if (ToType->isReferenceType()) { 4579 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4580 // mention initializer lists in any way. So we go by what list- 4581 // initialization would do and try to extrapolate from that. 4582 4583 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4584 4585 // If the initializer list has a single element that is reference-related 4586 // to the parameter type, we initialize the reference from that. 4587 if (From->getNumInits() == 1) { 4588 Expr *Init = From->getInit(0); 4589 4590 QualType T2 = Init->getType(); 4591 4592 // If the initializer is the address of an overloaded function, try 4593 // to resolve the overloaded function. If all goes well, T2 is the 4594 // type of the resulting function. 4595 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4596 DeclAccessPair Found; 4597 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4598 Init, ToType, false, Found)) 4599 T2 = Fn->getType(); 4600 } 4601 4602 // Compute some basic properties of the types and the initializer. 4603 bool dummy1 = false; 4604 bool dummy2 = false; 4605 bool dummy3 = false; 4606 Sema::ReferenceCompareResult RefRelationship 4607 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4608 dummy2, dummy3); 4609 4610 if (RefRelationship >= Sema::Ref_Related) { 4611 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4612 SuppressUserConversions, 4613 /*AllowExplicit=*/false); 4614 } 4615 } 4616 4617 // Otherwise, we bind the reference to a temporary created from the 4618 // initializer list. 4619 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4620 InOverloadResolution, 4621 AllowObjCWritebackConversion); 4622 if (Result.isFailure()) 4623 return Result; 4624 assert(!Result.isEllipsis() && 4625 "Sub-initialization cannot result in ellipsis conversion."); 4626 4627 // Can we even bind to a temporary? 4628 if (ToType->isRValueReferenceType() || 4629 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4630 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4631 Result.UserDefined.After; 4632 SCS.ReferenceBinding = true; 4633 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4634 SCS.BindsToRvalue = true; 4635 SCS.BindsToFunctionLvalue = false; 4636 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4637 SCS.ObjCLifetimeConversionBinding = false; 4638 } else 4639 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4640 From, ToType); 4641 return Result; 4642 } 4643 4644 // C++11 [over.ics.list]p6: 4645 // Otherwise, if the parameter type is not a class: 4646 if (!ToType->isRecordType()) { 4647 // - if the initializer list has one element, the implicit conversion 4648 // sequence is the one required to convert the element to the 4649 // parameter type. 4650 unsigned NumInits = From->getNumInits(); 4651 if (NumInits == 1) 4652 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4653 SuppressUserConversions, 4654 InOverloadResolution, 4655 AllowObjCWritebackConversion); 4656 // - if the initializer list has no elements, the implicit conversion 4657 // sequence is the identity conversion. 4658 else if (NumInits == 0) { 4659 Result.setStandard(); 4660 Result.Standard.setAsIdentityConversion(); 4661 Result.Standard.setFromType(ToType); 4662 Result.Standard.setAllToTypes(ToType); 4663 } 4664 return Result; 4665 } 4666 4667 // C++11 [over.ics.list]p7: 4668 // In all cases other than those enumerated above, no conversion is possible 4669 return Result; 4670 } 4671 4672 /// TryCopyInitialization - Try to copy-initialize a value of type 4673 /// ToType from the expression From. Return the implicit conversion 4674 /// sequence required to pass this argument, which may be a bad 4675 /// conversion sequence (meaning that the argument cannot be passed to 4676 /// a parameter of this type). If @p SuppressUserConversions, then we 4677 /// do not permit any user-defined conversion sequences. 4678 static ImplicitConversionSequence 4679 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4680 bool SuppressUserConversions, 4681 bool InOverloadResolution, 4682 bool AllowObjCWritebackConversion, 4683 bool AllowExplicit) { 4684 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4685 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4686 InOverloadResolution,AllowObjCWritebackConversion); 4687 4688 if (ToType->isReferenceType()) 4689 return TryReferenceInit(S, From, ToType, 4690 /*FIXME:*/From->getLocStart(), 4691 SuppressUserConversions, 4692 AllowExplicit); 4693 4694 return TryImplicitConversion(S, From, ToType, 4695 SuppressUserConversions, 4696 /*AllowExplicit=*/false, 4697 InOverloadResolution, 4698 /*CStyle=*/false, 4699 AllowObjCWritebackConversion, 4700 /*AllowObjCConversionOnExplicit=*/false); 4701 } 4702 4703 static bool TryCopyInitialization(const CanQualType FromQTy, 4704 const CanQualType ToQTy, 4705 Sema &S, 4706 SourceLocation Loc, 4707 ExprValueKind FromVK) { 4708 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4709 ImplicitConversionSequence ICS = 4710 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4711 4712 return !ICS.isBad(); 4713 } 4714 4715 /// TryObjectArgumentInitialization - Try to initialize the object 4716 /// parameter of the given member function (@c Method) from the 4717 /// expression @p From. 4718 static ImplicitConversionSequence 4719 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4720 Expr::Classification FromClassification, 4721 CXXMethodDecl *Method, 4722 CXXRecordDecl *ActingContext) { 4723 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4724 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4725 // const volatile object. 4726 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4727 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4728 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4729 4730 // Set up the conversion sequence as a "bad" conversion, to allow us 4731 // to exit early. 4732 ImplicitConversionSequence ICS; 4733 4734 // We need to have an object of class type. 4735 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4736 FromType = PT->getPointeeType(); 4737 4738 // When we had a pointer, it's implicitly dereferenced, so we 4739 // better have an lvalue. 4740 assert(FromClassification.isLValue()); 4741 } 4742 4743 assert(FromType->isRecordType()); 4744 4745 // C++0x [over.match.funcs]p4: 4746 // For non-static member functions, the type of the implicit object 4747 // parameter is 4748 // 4749 // - "lvalue reference to cv X" for functions declared without a 4750 // ref-qualifier or with the & ref-qualifier 4751 // - "rvalue reference to cv X" for functions declared with the && 4752 // ref-qualifier 4753 // 4754 // where X is the class of which the function is a member and cv is the 4755 // cv-qualification on the member function declaration. 4756 // 4757 // However, when finding an implicit conversion sequence for the argument, we 4758 // are not allowed to create temporaries or perform user-defined conversions 4759 // (C++ [over.match.funcs]p5). We perform a simplified version of 4760 // reference binding here, that allows class rvalues to bind to 4761 // non-constant references. 4762 4763 // First check the qualifiers. 4764 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4765 if (ImplicitParamType.getCVRQualifiers() 4766 != FromTypeCanon.getLocalCVRQualifiers() && 4767 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4768 ICS.setBad(BadConversionSequence::bad_qualifiers, 4769 FromType, ImplicitParamType); 4770 return ICS; 4771 } 4772 4773 // Check that we have either the same type or a derived type. It 4774 // affects the conversion rank. 4775 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4776 ImplicitConversionKind SecondKind; 4777 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4778 SecondKind = ICK_Identity; 4779 } else if (S.IsDerivedFrom(FromType, ClassType)) 4780 SecondKind = ICK_Derived_To_Base; 4781 else { 4782 ICS.setBad(BadConversionSequence::unrelated_class, 4783 FromType, ImplicitParamType); 4784 return ICS; 4785 } 4786 4787 // Check the ref-qualifier. 4788 switch (Method->getRefQualifier()) { 4789 case RQ_None: 4790 // Do nothing; we don't care about lvalueness or rvalueness. 4791 break; 4792 4793 case RQ_LValue: 4794 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4795 // non-const lvalue reference cannot bind to an rvalue 4796 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4797 ImplicitParamType); 4798 return ICS; 4799 } 4800 break; 4801 4802 case RQ_RValue: 4803 if (!FromClassification.isRValue()) { 4804 // rvalue reference cannot bind to an lvalue 4805 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4806 ImplicitParamType); 4807 return ICS; 4808 } 4809 break; 4810 } 4811 4812 // Success. Mark this as a reference binding. 4813 ICS.setStandard(); 4814 ICS.Standard.setAsIdentityConversion(); 4815 ICS.Standard.Second = SecondKind; 4816 ICS.Standard.setFromType(FromType); 4817 ICS.Standard.setAllToTypes(ImplicitParamType); 4818 ICS.Standard.ReferenceBinding = true; 4819 ICS.Standard.DirectBinding = true; 4820 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4821 ICS.Standard.BindsToFunctionLvalue = false; 4822 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4823 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4824 = (Method->getRefQualifier() == RQ_None); 4825 return ICS; 4826 } 4827 4828 /// PerformObjectArgumentInitialization - Perform initialization of 4829 /// the implicit object parameter for the given Method with the given 4830 /// expression. 4831 ExprResult 4832 Sema::PerformObjectArgumentInitialization(Expr *From, 4833 NestedNameSpecifier *Qualifier, 4834 NamedDecl *FoundDecl, 4835 CXXMethodDecl *Method) { 4836 QualType FromRecordType, DestType; 4837 QualType ImplicitParamRecordType = 4838 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4839 4840 Expr::Classification FromClassification; 4841 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4842 FromRecordType = PT->getPointeeType(); 4843 DestType = Method->getThisType(Context); 4844 FromClassification = Expr::Classification::makeSimpleLValue(); 4845 } else { 4846 FromRecordType = From->getType(); 4847 DestType = ImplicitParamRecordType; 4848 FromClassification = From->Classify(Context); 4849 } 4850 4851 // Note that we always use the true parent context when performing 4852 // the actual argument initialization. 4853 ImplicitConversionSequence ICS 4854 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4855 Method, Method->getParent()); 4856 if (ICS.isBad()) { 4857 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4858 Qualifiers FromQs = FromRecordType.getQualifiers(); 4859 Qualifiers ToQs = DestType.getQualifiers(); 4860 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4861 if (CVR) { 4862 Diag(From->getLocStart(), 4863 diag::err_member_function_call_bad_cvr) 4864 << Method->getDeclName() << FromRecordType << (CVR - 1) 4865 << From->getSourceRange(); 4866 Diag(Method->getLocation(), diag::note_previous_decl) 4867 << Method->getDeclName(); 4868 return ExprError(); 4869 } 4870 } 4871 4872 return Diag(From->getLocStart(), 4873 diag::err_implicit_object_parameter_init) 4874 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4875 } 4876 4877 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4878 ExprResult FromRes = 4879 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4880 if (FromRes.isInvalid()) 4881 return ExprError(); 4882 From = FromRes.get(); 4883 } 4884 4885 if (!Context.hasSameType(From->getType(), DestType)) 4886 From = ImpCastExprToType(From, DestType, CK_NoOp, 4887 From->getValueKind()).get(); 4888 return From; 4889 } 4890 4891 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4892 /// expression From to bool (C++0x [conv]p3). 4893 static ImplicitConversionSequence 4894 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4895 return TryImplicitConversion(S, From, S.Context.BoolTy, 4896 /*SuppressUserConversions=*/false, 4897 /*AllowExplicit=*/true, 4898 /*InOverloadResolution=*/false, 4899 /*CStyle=*/false, 4900 /*AllowObjCWritebackConversion=*/false, 4901 /*AllowObjCConversionOnExplicit=*/false); 4902 } 4903 4904 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4905 /// of the expression From to bool (C++0x [conv]p3). 4906 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4907 if (checkPlaceholderForOverload(*this, From)) 4908 return ExprError(); 4909 4910 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4911 if (!ICS.isBad()) 4912 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4913 4914 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4915 return Diag(From->getLocStart(), 4916 diag::err_typecheck_bool_condition) 4917 << From->getType() << From->getSourceRange(); 4918 return ExprError(); 4919 } 4920 4921 /// Check that the specified conversion is permitted in a converted constant 4922 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4923 /// is acceptable. 4924 static bool CheckConvertedConstantConversions(Sema &S, 4925 StandardConversionSequence &SCS) { 4926 // Since we know that the target type is an integral or unscoped enumeration 4927 // type, most conversion kinds are impossible. All possible First and Third 4928 // conversions are fine. 4929 switch (SCS.Second) { 4930 case ICK_Identity: 4931 case ICK_Integral_Promotion: 4932 case ICK_Integral_Conversion: 4933 case ICK_Zero_Event_Conversion: 4934 return true; 4935 4936 case ICK_Boolean_Conversion: 4937 // Conversion from an integral or unscoped enumeration type to bool is 4938 // classified as ICK_Boolean_Conversion, but it's also an integral 4939 // conversion, so it's permitted in a converted constant expression. 4940 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4941 SCS.getToType(2)->isBooleanType(); 4942 4943 case ICK_Floating_Integral: 4944 case ICK_Complex_Real: 4945 return false; 4946 4947 case ICK_Lvalue_To_Rvalue: 4948 case ICK_Array_To_Pointer: 4949 case ICK_Function_To_Pointer: 4950 case ICK_NoReturn_Adjustment: 4951 case ICK_Qualification: 4952 case ICK_Compatible_Conversion: 4953 case ICK_Vector_Conversion: 4954 case ICK_Vector_Splat: 4955 case ICK_Derived_To_Base: 4956 case ICK_Pointer_Conversion: 4957 case ICK_Pointer_Member: 4958 case ICK_Block_Pointer_Conversion: 4959 case ICK_Writeback_Conversion: 4960 case ICK_Floating_Promotion: 4961 case ICK_Complex_Promotion: 4962 case ICK_Complex_Conversion: 4963 case ICK_Floating_Conversion: 4964 case ICK_TransparentUnionConversion: 4965 llvm_unreachable("unexpected second conversion kind"); 4966 4967 case ICK_Num_Conversion_Kinds: 4968 break; 4969 } 4970 4971 llvm_unreachable("unknown conversion kind"); 4972 } 4973 4974 /// CheckConvertedConstantExpression - Check that the expression From is a 4975 /// converted constant expression of type T, perform the conversion and produce 4976 /// the converted expression, per C++11 [expr.const]p3. 4977 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4978 llvm::APSInt &Value, 4979 CCEKind CCE) { 4980 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4981 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4982 4983 if (checkPlaceholderForOverload(*this, From)) 4984 return ExprError(); 4985 4986 // C++11 [expr.const]p3 with proposed wording fixes: 4987 // A converted constant expression of type T is a core constant expression, 4988 // implicitly converted to a prvalue of type T, where the converted 4989 // expression is a literal constant expression and the implicit conversion 4990 // sequence contains only user-defined conversions, lvalue-to-rvalue 4991 // conversions, integral promotions, and integral conversions other than 4992 // narrowing conversions. 4993 ImplicitConversionSequence ICS = 4994 TryImplicitConversion(From, T, 4995 /*SuppressUserConversions=*/false, 4996 /*AllowExplicit=*/false, 4997 /*InOverloadResolution=*/false, 4998 /*CStyle=*/false, 4999 /*AllowObjcWritebackConversion=*/false); 5000 StandardConversionSequence *SCS = nullptr; 5001 switch (ICS.getKind()) { 5002 case ImplicitConversionSequence::StandardConversion: 5003 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 5004 return Diag(From->getLocStart(), 5005 diag::err_typecheck_converted_constant_expression_disallowed) 5006 << From->getType() << From->getSourceRange() << T; 5007 SCS = &ICS.Standard; 5008 break; 5009 case ImplicitConversionSequence::UserDefinedConversion: 5010 // We are converting from class type to an integral or enumeration type, so 5011 // the Before sequence must be trivial. 5012 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 5013 return Diag(From->getLocStart(), 5014 diag::err_typecheck_converted_constant_expression_disallowed) 5015 << From->getType() << From->getSourceRange() << T; 5016 SCS = &ICS.UserDefined.After; 5017 break; 5018 case ImplicitConversionSequence::AmbiguousConversion: 5019 case ImplicitConversionSequence::BadConversion: 5020 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 5021 return Diag(From->getLocStart(), 5022 diag::err_typecheck_converted_constant_expression) 5023 << From->getType() << From->getSourceRange() << T; 5024 return ExprError(); 5025 5026 case ImplicitConversionSequence::EllipsisConversion: 5027 llvm_unreachable("ellipsis conversion in converted constant expression"); 5028 } 5029 5030 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 5031 if (Result.isInvalid()) 5032 return Result; 5033 5034 // Check for a narrowing implicit conversion. 5035 APValue PreNarrowingValue; 5036 QualType PreNarrowingType; 5037 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5038 PreNarrowingType)) { 5039 case NK_Variable_Narrowing: 5040 // Implicit conversion to a narrower type, and the value is not a constant 5041 // expression. We'll diagnose this in a moment. 5042 case NK_Not_Narrowing: 5043 break; 5044 5045 case NK_Constant_Narrowing: 5046 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5047 << CCE << /*Constant*/1 5048 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5049 break; 5050 5051 case NK_Type_Narrowing: 5052 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5053 << CCE << /*Constant*/0 << From->getType() << T; 5054 break; 5055 } 5056 5057 // Check the expression is a constant expression. 5058 SmallVector<PartialDiagnosticAt, 8> Notes; 5059 Expr::EvalResult Eval; 5060 Eval.Diag = &Notes; 5061 5062 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5063 // The expression can't be folded, so we can't keep it at this position in 5064 // the AST. 5065 Result = ExprError(); 5066 } else { 5067 Value = Eval.Val.getInt(); 5068 5069 if (Notes.empty()) { 5070 // It's a constant expression. 5071 return Result; 5072 } 5073 } 5074 5075 // It's not a constant expression. Produce an appropriate diagnostic. 5076 if (Notes.size() == 1 && 5077 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5078 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5079 else { 5080 Diag(From->getLocStart(), diag::err_expr_not_cce) 5081 << CCE << From->getSourceRange(); 5082 for (unsigned I = 0; I < Notes.size(); ++I) 5083 Diag(Notes[I].first, Notes[I].second); 5084 } 5085 return Result; 5086 } 5087 5088 /// dropPointerConversions - If the given standard conversion sequence 5089 /// involves any pointer conversions, remove them. This may change 5090 /// the result type of the conversion sequence. 5091 static void dropPointerConversion(StandardConversionSequence &SCS) { 5092 if (SCS.Second == ICK_Pointer_Conversion) { 5093 SCS.Second = ICK_Identity; 5094 SCS.Third = ICK_Identity; 5095 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5096 } 5097 } 5098 5099 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5100 /// convert the expression From to an Objective-C pointer type. 5101 static ImplicitConversionSequence 5102 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5103 // Do an implicit conversion to 'id'. 5104 QualType Ty = S.Context.getObjCIdType(); 5105 ImplicitConversionSequence ICS 5106 = TryImplicitConversion(S, From, Ty, 5107 // FIXME: Are these flags correct? 5108 /*SuppressUserConversions=*/false, 5109 /*AllowExplicit=*/true, 5110 /*InOverloadResolution=*/false, 5111 /*CStyle=*/false, 5112 /*AllowObjCWritebackConversion=*/false, 5113 /*AllowObjCConversionOnExplicit=*/true); 5114 5115 // Strip off any final conversions to 'id'. 5116 switch (ICS.getKind()) { 5117 case ImplicitConversionSequence::BadConversion: 5118 case ImplicitConversionSequence::AmbiguousConversion: 5119 case ImplicitConversionSequence::EllipsisConversion: 5120 break; 5121 5122 case ImplicitConversionSequence::UserDefinedConversion: 5123 dropPointerConversion(ICS.UserDefined.After); 5124 break; 5125 5126 case ImplicitConversionSequence::StandardConversion: 5127 dropPointerConversion(ICS.Standard); 5128 break; 5129 } 5130 5131 return ICS; 5132 } 5133 5134 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5135 /// conversion of the expression From to an Objective-C pointer type. 5136 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5137 if (checkPlaceholderForOverload(*this, From)) 5138 return ExprError(); 5139 5140 QualType Ty = Context.getObjCIdType(); 5141 ImplicitConversionSequence ICS = 5142 TryContextuallyConvertToObjCPointer(*this, From); 5143 if (!ICS.isBad()) 5144 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5145 return ExprError(); 5146 } 5147 5148 /// Determine whether the provided type is an integral type, or an enumeration 5149 /// type of a permitted flavor. 5150 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5151 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5152 : T->isIntegralOrUnscopedEnumerationType(); 5153 } 5154 5155 static ExprResult 5156 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5157 Sema::ContextualImplicitConverter &Converter, 5158 QualType T, UnresolvedSetImpl &ViableConversions) { 5159 5160 if (Converter.Suppress) 5161 return ExprError(); 5162 5163 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5164 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5165 CXXConversionDecl *Conv = 5166 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5167 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5168 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5169 } 5170 return From; 5171 } 5172 5173 static bool 5174 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5175 Sema::ContextualImplicitConverter &Converter, 5176 QualType T, bool HadMultipleCandidates, 5177 UnresolvedSetImpl &ExplicitConversions) { 5178 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5179 DeclAccessPair Found = ExplicitConversions[0]; 5180 CXXConversionDecl *Conversion = 5181 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5182 5183 // The user probably meant to invoke the given explicit 5184 // conversion; use it. 5185 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5186 std::string TypeStr; 5187 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5188 5189 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5190 << FixItHint::CreateInsertion(From->getLocStart(), 5191 "static_cast<" + TypeStr + ">(") 5192 << FixItHint::CreateInsertion( 5193 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5194 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5195 5196 // If we aren't in a SFINAE context, build a call to the 5197 // explicit conversion function. 5198 if (SemaRef.isSFINAEContext()) 5199 return true; 5200 5201 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5202 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5203 HadMultipleCandidates); 5204 if (Result.isInvalid()) 5205 return true; 5206 // Record usage of conversion in an implicit cast. 5207 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5208 CK_UserDefinedConversion, Result.get(), 5209 nullptr, Result.get()->getValueKind()); 5210 } 5211 return false; 5212 } 5213 5214 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5215 Sema::ContextualImplicitConverter &Converter, 5216 QualType T, bool HadMultipleCandidates, 5217 DeclAccessPair &Found) { 5218 CXXConversionDecl *Conversion = 5219 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5220 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5221 5222 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5223 if (!Converter.SuppressConversion) { 5224 if (SemaRef.isSFINAEContext()) 5225 return true; 5226 5227 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5228 << From->getSourceRange(); 5229 } 5230 5231 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5232 HadMultipleCandidates); 5233 if (Result.isInvalid()) 5234 return true; 5235 // Record usage of conversion in an implicit cast. 5236 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5237 CK_UserDefinedConversion, Result.get(), 5238 nullptr, Result.get()->getValueKind()); 5239 return false; 5240 } 5241 5242 static ExprResult finishContextualImplicitConversion( 5243 Sema &SemaRef, SourceLocation Loc, Expr *From, 5244 Sema::ContextualImplicitConverter &Converter) { 5245 if (!Converter.match(From->getType()) && !Converter.Suppress) 5246 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5247 << From->getSourceRange(); 5248 5249 return SemaRef.DefaultLvalueConversion(From); 5250 } 5251 5252 static void 5253 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5254 UnresolvedSetImpl &ViableConversions, 5255 OverloadCandidateSet &CandidateSet) { 5256 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5257 DeclAccessPair FoundDecl = ViableConversions[I]; 5258 NamedDecl *D = FoundDecl.getDecl(); 5259 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5260 if (isa<UsingShadowDecl>(D)) 5261 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5262 5263 CXXConversionDecl *Conv; 5264 FunctionTemplateDecl *ConvTemplate; 5265 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5266 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5267 else 5268 Conv = cast<CXXConversionDecl>(D); 5269 5270 if (ConvTemplate) 5271 SemaRef.AddTemplateConversionCandidate( 5272 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5273 /*AllowObjCConversionOnExplicit=*/false); 5274 else 5275 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5276 ToType, CandidateSet, 5277 /*AllowObjCConversionOnExplicit=*/false); 5278 } 5279 } 5280 5281 /// \brief Attempt to convert the given expression to a type which is accepted 5282 /// by the given converter. 5283 /// 5284 /// This routine will attempt to convert an expression of class type to a 5285 /// type accepted by the specified converter. In C++11 and before, the class 5286 /// must have a single non-explicit conversion function converting to a matching 5287 /// type. In C++1y, there can be multiple such conversion functions, but only 5288 /// one target type. 5289 /// 5290 /// \param Loc The source location of the construct that requires the 5291 /// conversion. 5292 /// 5293 /// \param From The expression we're converting from. 5294 /// 5295 /// \param Converter Used to control and diagnose the conversion process. 5296 /// 5297 /// \returns The expression, converted to an integral or enumeration type if 5298 /// successful. 5299 ExprResult Sema::PerformContextualImplicitConversion( 5300 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5301 // We can't perform any more checking for type-dependent expressions. 5302 if (From->isTypeDependent()) 5303 return From; 5304 5305 // Process placeholders immediately. 5306 if (From->hasPlaceholderType()) { 5307 ExprResult result = CheckPlaceholderExpr(From); 5308 if (result.isInvalid()) 5309 return result; 5310 From = result.get(); 5311 } 5312 5313 // If the expression already has a matching type, we're golden. 5314 QualType T = From->getType(); 5315 if (Converter.match(T)) 5316 return DefaultLvalueConversion(From); 5317 5318 // FIXME: Check for missing '()' if T is a function type? 5319 5320 // We can only perform contextual implicit conversions on objects of class 5321 // type. 5322 const RecordType *RecordTy = T->getAs<RecordType>(); 5323 if (!RecordTy || !getLangOpts().CPlusPlus) { 5324 if (!Converter.Suppress) 5325 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5326 return From; 5327 } 5328 5329 // We must have a complete class type. 5330 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5331 ContextualImplicitConverter &Converter; 5332 Expr *From; 5333 5334 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5335 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5336 5337 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5338 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5339 } 5340 } IncompleteDiagnoser(Converter, From); 5341 5342 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5343 return From; 5344 5345 // Look for a conversion to an integral or enumeration type. 5346 UnresolvedSet<4> 5347 ViableConversions; // These are *potentially* viable in C++1y. 5348 UnresolvedSet<4> ExplicitConversions; 5349 std::pair<CXXRecordDecl::conversion_iterator, 5350 CXXRecordDecl::conversion_iterator> Conversions = 5351 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5352 5353 bool HadMultipleCandidates = 5354 (std::distance(Conversions.first, Conversions.second) > 1); 5355 5356 // To check that there is only one target type, in C++1y: 5357 QualType ToType; 5358 bool HasUniqueTargetType = true; 5359 5360 // Collect explicit or viable (potentially in C++1y) conversions. 5361 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5362 E = Conversions.second; 5363 I != E; ++I) { 5364 NamedDecl *D = (*I)->getUnderlyingDecl(); 5365 CXXConversionDecl *Conversion; 5366 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5367 if (ConvTemplate) { 5368 if (getLangOpts().CPlusPlus14) 5369 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5370 else 5371 continue; // C++11 does not consider conversion operator templates(?). 5372 } else 5373 Conversion = cast<CXXConversionDecl>(D); 5374 5375 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5376 "Conversion operator templates are considered potentially " 5377 "viable in C++1y"); 5378 5379 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5380 if (Converter.match(CurToType) || ConvTemplate) { 5381 5382 if (Conversion->isExplicit()) { 5383 // FIXME: For C++1y, do we need this restriction? 5384 // cf. diagnoseNoViableConversion() 5385 if (!ConvTemplate) 5386 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5387 } else { 5388 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5389 if (ToType.isNull()) 5390 ToType = CurToType.getUnqualifiedType(); 5391 else if (HasUniqueTargetType && 5392 (CurToType.getUnqualifiedType() != ToType)) 5393 HasUniqueTargetType = false; 5394 } 5395 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5396 } 5397 } 5398 } 5399 5400 if (getLangOpts().CPlusPlus14) { 5401 // C++1y [conv]p6: 5402 // ... An expression e of class type E appearing in such a context 5403 // is said to be contextually implicitly converted to a specified 5404 // type T and is well-formed if and only if e can be implicitly 5405 // converted to a type T that is determined as follows: E is searched 5406 // for conversion functions whose return type is cv T or reference to 5407 // cv T such that T is allowed by the context. There shall be 5408 // exactly one such T. 5409 5410 // If no unique T is found: 5411 if (ToType.isNull()) { 5412 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5413 HadMultipleCandidates, 5414 ExplicitConversions)) 5415 return ExprError(); 5416 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5417 } 5418 5419 // If more than one unique Ts are found: 5420 if (!HasUniqueTargetType) 5421 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5422 ViableConversions); 5423 5424 // If one unique T is found: 5425 // First, build a candidate set from the previously recorded 5426 // potentially viable conversions. 5427 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5428 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5429 CandidateSet); 5430 5431 // Then, perform overload resolution over the candidate set. 5432 OverloadCandidateSet::iterator Best; 5433 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5434 case OR_Success: { 5435 // Apply this conversion. 5436 DeclAccessPair Found = 5437 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5438 if (recordConversion(*this, Loc, From, Converter, T, 5439 HadMultipleCandidates, Found)) 5440 return ExprError(); 5441 break; 5442 } 5443 case OR_Ambiguous: 5444 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5445 ViableConversions); 5446 case OR_No_Viable_Function: 5447 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5448 HadMultipleCandidates, 5449 ExplicitConversions)) 5450 return ExprError(); 5451 // fall through 'OR_Deleted' case. 5452 case OR_Deleted: 5453 // We'll complain below about a non-integral condition type. 5454 break; 5455 } 5456 } else { 5457 switch (ViableConversions.size()) { 5458 case 0: { 5459 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5460 HadMultipleCandidates, 5461 ExplicitConversions)) 5462 return ExprError(); 5463 5464 // We'll complain below about a non-integral condition type. 5465 break; 5466 } 5467 case 1: { 5468 // Apply this conversion. 5469 DeclAccessPair Found = ViableConversions[0]; 5470 if (recordConversion(*this, Loc, From, Converter, T, 5471 HadMultipleCandidates, Found)) 5472 return ExprError(); 5473 break; 5474 } 5475 default: 5476 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5477 ViableConversions); 5478 } 5479 } 5480 5481 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5482 } 5483 5484 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5485 /// an acceptable non-member overloaded operator for a call whose 5486 /// arguments have types T1 (and, if non-empty, T2). This routine 5487 /// implements the check in C++ [over.match.oper]p3b2 concerning 5488 /// enumeration types. 5489 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5490 FunctionDecl *Fn, 5491 ArrayRef<Expr *> Args) { 5492 QualType T1 = Args[0]->getType(); 5493 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5494 5495 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5496 return true; 5497 5498 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5499 return true; 5500 5501 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5502 if (Proto->getNumParams() < 1) 5503 return false; 5504 5505 if (T1->isEnumeralType()) { 5506 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5507 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5508 return true; 5509 } 5510 5511 if (Proto->getNumParams() < 2) 5512 return false; 5513 5514 if (!T2.isNull() && T2->isEnumeralType()) { 5515 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5516 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5517 return true; 5518 } 5519 5520 return false; 5521 } 5522 5523 /// AddOverloadCandidate - Adds the given function to the set of 5524 /// candidate functions, using the given function call arguments. If 5525 /// @p SuppressUserConversions, then don't allow user-defined 5526 /// conversions via constructors or conversion operators. 5527 /// 5528 /// \param PartialOverloading true if we are performing "partial" overloading 5529 /// based on an incomplete set of function arguments. This feature is used by 5530 /// code completion. 5531 void 5532 Sema::AddOverloadCandidate(FunctionDecl *Function, 5533 DeclAccessPair FoundDecl, 5534 ArrayRef<Expr *> Args, 5535 OverloadCandidateSet &CandidateSet, 5536 bool SuppressUserConversions, 5537 bool PartialOverloading, 5538 bool AllowExplicit) { 5539 const FunctionProtoType *Proto 5540 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5541 assert(Proto && "Functions without a prototype cannot be overloaded"); 5542 assert(!Function->getDescribedFunctionTemplate() && 5543 "Use AddTemplateOverloadCandidate for function templates"); 5544 5545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5546 if (!isa<CXXConstructorDecl>(Method)) { 5547 // If we get here, it's because we're calling a member function 5548 // that is named without a member access expression (e.g., 5549 // "this->f") that was either written explicitly or created 5550 // implicitly. This can happen with a qualified call to a member 5551 // function, e.g., X::f(). We use an empty type for the implied 5552 // object argument (C++ [over.call.func]p3), and the acting context 5553 // is irrelevant. 5554 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5555 QualType(), Expr::Classification::makeSimpleLValue(), 5556 Args, CandidateSet, SuppressUserConversions); 5557 return; 5558 } 5559 // We treat a constructor like a non-member function, since its object 5560 // argument doesn't participate in overload resolution. 5561 } 5562 5563 if (!CandidateSet.isNewCandidate(Function)) 5564 return; 5565 5566 // C++ [over.match.oper]p3: 5567 // if no operand has a class type, only those non-member functions in the 5568 // lookup set that have a first parameter of type T1 or "reference to 5569 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5570 // is a right operand) a second parameter of type T2 or "reference to 5571 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5572 // candidate functions. 5573 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5574 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5575 return; 5576 5577 // C++11 [class.copy]p11: [DR1402] 5578 // A defaulted move constructor that is defined as deleted is ignored by 5579 // overload resolution. 5580 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5581 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5582 Constructor->isMoveConstructor()) 5583 return; 5584 5585 // Overload resolution is always an unevaluated context. 5586 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5587 5588 if (Constructor) { 5589 // C++ [class.copy]p3: 5590 // A member function template is never instantiated to perform the copy 5591 // of a class object to an object of its class type. 5592 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5593 if (Args.size() == 1 && 5594 Constructor->isSpecializationCopyingObject() && 5595 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5596 IsDerivedFrom(Args[0]->getType(), ClassType))) 5597 return; 5598 } 5599 5600 // Add this candidate 5601 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5602 Candidate.FoundDecl = FoundDecl; 5603 Candidate.Function = Function; 5604 Candidate.Viable = true; 5605 Candidate.IsSurrogate = false; 5606 Candidate.IgnoreObjectArgument = false; 5607 Candidate.ExplicitCallArguments = Args.size(); 5608 5609 unsigned NumParams = Proto->getNumParams(); 5610 5611 // (C++ 13.3.2p2): A candidate function having fewer than m 5612 // parameters is viable only if it has an ellipsis in its parameter 5613 // list (8.3.5). 5614 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams && 5615 !Proto->isVariadic()) { 5616 Candidate.Viable = false; 5617 Candidate.FailureKind = ovl_fail_too_many_arguments; 5618 return; 5619 } 5620 5621 // (C++ 13.3.2p2): A candidate function having more than m parameters 5622 // is viable only if the (m+1)st parameter has a default argument 5623 // (8.3.6). For the purposes of overload resolution, the 5624 // parameter list is truncated on the right, so that there are 5625 // exactly m parameters. 5626 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5627 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5628 // Not enough arguments. 5629 Candidate.Viable = false; 5630 Candidate.FailureKind = ovl_fail_too_few_arguments; 5631 return; 5632 } 5633 5634 // (CUDA B.1): Check for invalid calls between targets. 5635 if (getLangOpts().CUDA) 5636 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5637 // Skip the check for callers that are implicit members, because in this 5638 // case we may not yet know what the member's target is; the target is 5639 // inferred for the member automatically, based on the bases and fields of 5640 // the class. 5641 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5642 Candidate.Viable = false; 5643 Candidate.FailureKind = ovl_fail_bad_target; 5644 return; 5645 } 5646 5647 // Determine the implicit conversion sequences for each of the 5648 // arguments. 5649 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5650 if (ArgIdx < NumParams) { 5651 // (C++ 13.3.2p3): for F to be a viable function, there shall 5652 // exist for each argument an implicit conversion sequence 5653 // (13.3.3.1) that converts that argument to the corresponding 5654 // parameter of F. 5655 QualType ParamType = Proto->getParamType(ArgIdx); 5656 Candidate.Conversions[ArgIdx] 5657 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5658 SuppressUserConversions, 5659 /*InOverloadResolution=*/true, 5660 /*AllowObjCWritebackConversion=*/ 5661 getLangOpts().ObjCAutoRefCount, 5662 AllowExplicit); 5663 if (Candidate.Conversions[ArgIdx].isBad()) { 5664 Candidate.Viable = false; 5665 Candidate.FailureKind = ovl_fail_bad_conversion; 5666 return; 5667 } 5668 } else { 5669 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5670 // argument for which there is no corresponding parameter is 5671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5672 Candidate.Conversions[ArgIdx].setEllipsis(); 5673 } 5674 } 5675 5676 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5677 Candidate.Viable = false; 5678 Candidate.FailureKind = ovl_fail_enable_if; 5679 Candidate.DeductionFailure.Data = FailedAttr; 5680 return; 5681 } 5682 } 5683 5684 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5685 bool IsInstance) { 5686 SmallVector<ObjCMethodDecl*, 4> Methods; 5687 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5688 return nullptr; 5689 5690 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5691 bool Match = true; 5692 ObjCMethodDecl *Method = Methods[b]; 5693 unsigned NumNamedArgs = Sel.getNumArgs(); 5694 // Method might have more arguments than selector indicates. This is due 5695 // to addition of c-style arguments in method. 5696 if (Method->param_size() > NumNamedArgs) 5697 NumNamedArgs = Method->param_size(); 5698 if (Args.size() < NumNamedArgs) 5699 continue; 5700 5701 for (unsigned i = 0; i < NumNamedArgs; i++) { 5702 // We can't do any type-checking on a type-dependent argument. 5703 if (Args[i]->isTypeDependent()) { 5704 Match = false; 5705 break; 5706 } 5707 5708 ParmVarDecl *param = Method->parameters()[i]; 5709 Expr *argExpr = Args[i]; 5710 assert(argExpr && "SelectBestMethod(): missing expression"); 5711 5712 // Strip the unbridged-cast placeholder expression off unless it's 5713 // a consumed argument. 5714 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5715 !param->hasAttr<CFConsumedAttr>()) 5716 argExpr = stripARCUnbridgedCast(argExpr); 5717 5718 // If the parameter is __unknown_anytype, move on to the next method. 5719 if (param->getType() == Context.UnknownAnyTy) { 5720 Match = false; 5721 break; 5722 } 5723 5724 ImplicitConversionSequence ConversionState 5725 = TryCopyInitialization(*this, argExpr, param->getType(), 5726 /*SuppressUserConversions*/false, 5727 /*InOverloadResolution=*/true, 5728 /*AllowObjCWritebackConversion=*/ 5729 getLangOpts().ObjCAutoRefCount, 5730 /*AllowExplicit*/false); 5731 if (ConversionState.isBad()) { 5732 Match = false; 5733 break; 5734 } 5735 } 5736 // Promote additional arguments to variadic methods. 5737 if (Match && Method->isVariadic()) { 5738 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5739 if (Args[i]->isTypeDependent()) { 5740 Match = false; 5741 break; 5742 } 5743 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5744 nullptr); 5745 if (Arg.isInvalid()) { 5746 Match = false; 5747 break; 5748 } 5749 } 5750 } else { 5751 // Check for extra arguments to non-variadic methods. 5752 if (Args.size() != NumNamedArgs) 5753 Match = false; 5754 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5755 // Special case when selectors have no argument. In this case, select 5756 // one with the most general result type of 'id'. 5757 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5758 QualType ReturnT = Methods[b]->getReturnType(); 5759 if (ReturnT->isObjCIdType()) 5760 return Methods[b]; 5761 } 5762 } 5763 } 5764 5765 if (Match) 5766 return Method; 5767 } 5768 return nullptr; 5769 } 5770 5771 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5772 5773 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5774 bool MissingImplicitThis) { 5775 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5776 // we need to find the first failing one. 5777 if (!Function->hasAttrs()) 5778 return nullptr; 5779 AttrVec Attrs = Function->getAttrs(); 5780 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5781 IsNotEnableIfAttr); 5782 if (Attrs.begin() == E) 5783 return nullptr; 5784 std::reverse(Attrs.begin(), E); 5785 5786 SFINAETrap Trap(*this); 5787 5788 // Convert the arguments. 5789 SmallVector<Expr *, 16> ConvertedArgs; 5790 bool InitializationFailed = false; 5791 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5792 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5793 !cast<CXXMethodDecl>(Function)->isStatic() && 5794 !isa<CXXConstructorDecl>(Function)) { 5795 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5796 ExprResult R = 5797 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5798 Method, Method); 5799 if (R.isInvalid()) { 5800 InitializationFailed = true; 5801 break; 5802 } 5803 ConvertedArgs.push_back(R.get()); 5804 } else { 5805 ExprResult R = 5806 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5807 Context, 5808 Function->getParamDecl(i)), 5809 SourceLocation(), 5810 Args[i]); 5811 if (R.isInvalid()) { 5812 InitializationFailed = true; 5813 break; 5814 } 5815 ConvertedArgs.push_back(R.get()); 5816 } 5817 } 5818 5819 if (InitializationFailed || Trap.hasErrorOccurred()) 5820 return cast<EnableIfAttr>(Attrs[0]); 5821 5822 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5823 APValue Result; 5824 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5825 if (!EIA->getCond()->EvaluateWithSubstitution( 5826 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) || 5827 !Result.isInt() || !Result.getInt().getBoolValue()) { 5828 return EIA; 5829 } 5830 } 5831 return nullptr; 5832 } 5833 5834 /// \brief Add all of the function declarations in the given function set to 5835 /// the overload candidate set. 5836 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5837 ArrayRef<Expr *> Args, 5838 OverloadCandidateSet& CandidateSet, 5839 bool SuppressUserConversions, 5840 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5841 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5842 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5843 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5844 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5845 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5846 cast<CXXMethodDecl>(FD)->getParent(), 5847 Args[0]->getType(), Args[0]->Classify(Context), 5848 Args.slice(1), CandidateSet, 5849 SuppressUserConversions); 5850 else 5851 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5852 SuppressUserConversions); 5853 } else { 5854 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5855 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5856 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5857 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5858 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5859 ExplicitTemplateArgs, 5860 Args[0]->getType(), 5861 Args[0]->Classify(Context), Args.slice(1), 5862 CandidateSet, SuppressUserConversions); 5863 else 5864 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5865 ExplicitTemplateArgs, Args, 5866 CandidateSet, SuppressUserConversions); 5867 } 5868 } 5869 } 5870 5871 /// AddMethodCandidate - Adds a named decl (which is some kind of 5872 /// method) as a method candidate to the given overload set. 5873 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5874 QualType ObjectType, 5875 Expr::Classification ObjectClassification, 5876 ArrayRef<Expr *> Args, 5877 OverloadCandidateSet& CandidateSet, 5878 bool SuppressUserConversions) { 5879 NamedDecl *Decl = FoundDecl.getDecl(); 5880 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5881 5882 if (isa<UsingShadowDecl>(Decl)) 5883 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5884 5885 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5886 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5887 "Expected a member function template"); 5888 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5889 /*ExplicitArgs*/ nullptr, 5890 ObjectType, ObjectClassification, 5891 Args, CandidateSet, 5892 SuppressUserConversions); 5893 } else { 5894 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5895 ObjectType, ObjectClassification, 5896 Args, 5897 CandidateSet, SuppressUserConversions); 5898 } 5899 } 5900 5901 /// AddMethodCandidate - Adds the given C++ member function to the set 5902 /// of candidate functions, using the given function call arguments 5903 /// and the object argument (@c Object). For example, in a call 5904 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5905 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5906 /// allow user-defined conversions via constructors or conversion 5907 /// operators. 5908 void 5909 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5910 CXXRecordDecl *ActingContext, QualType ObjectType, 5911 Expr::Classification ObjectClassification, 5912 ArrayRef<Expr *> Args, 5913 OverloadCandidateSet &CandidateSet, 5914 bool SuppressUserConversions) { 5915 const FunctionProtoType *Proto 5916 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5917 assert(Proto && "Methods without a prototype cannot be overloaded"); 5918 assert(!isa<CXXConstructorDecl>(Method) && 5919 "Use AddOverloadCandidate for constructors"); 5920 5921 if (!CandidateSet.isNewCandidate(Method)) 5922 return; 5923 5924 // C++11 [class.copy]p23: [DR1402] 5925 // A defaulted move assignment operator that is defined as deleted is 5926 // ignored by overload resolution. 5927 if (Method->isDefaulted() && Method->isDeleted() && 5928 Method->isMoveAssignmentOperator()) 5929 return; 5930 5931 // Overload resolution is always an unevaluated context. 5932 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5933 5934 // Add this candidate 5935 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5936 Candidate.FoundDecl = FoundDecl; 5937 Candidate.Function = Method; 5938 Candidate.IsSurrogate = false; 5939 Candidate.IgnoreObjectArgument = false; 5940 Candidate.ExplicitCallArguments = Args.size(); 5941 5942 unsigned NumParams = Proto->getNumParams(); 5943 5944 // (C++ 13.3.2p2): A candidate function having fewer than m 5945 // parameters is viable only if it has an ellipsis in its parameter 5946 // list (8.3.5). 5947 if (Args.size() > NumParams && !Proto->isVariadic()) { 5948 Candidate.Viable = false; 5949 Candidate.FailureKind = ovl_fail_too_many_arguments; 5950 return; 5951 } 5952 5953 // (C++ 13.3.2p2): A candidate function having more than m parameters 5954 // is viable only if the (m+1)st parameter has a default argument 5955 // (8.3.6). For the purposes of overload resolution, the 5956 // parameter list is truncated on the right, so that there are 5957 // exactly m parameters. 5958 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5959 if (Args.size() < MinRequiredArgs) { 5960 // Not enough arguments. 5961 Candidate.Viable = false; 5962 Candidate.FailureKind = ovl_fail_too_few_arguments; 5963 return; 5964 } 5965 5966 Candidate.Viable = true; 5967 5968 if (Method->isStatic() || ObjectType.isNull()) 5969 // The implicit object argument is ignored. 5970 Candidate.IgnoreObjectArgument = true; 5971 else { 5972 // Determine the implicit conversion sequence for the object 5973 // parameter. 5974 Candidate.Conversions[0] 5975 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5976 Method, ActingContext); 5977 if (Candidate.Conversions[0].isBad()) { 5978 Candidate.Viable = false; 5979 Candidate.FailureKind = ovl_fail_bad_conversion; 5980 return; 5981 } 5982 } 5983 5984 // (CUDA B.1): Check for invalid calls between targets. 5985 if (getLangOpts().CUDA) 5986 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5987 if (CheckCUDATarget(Caller, Method)) { 5988 Candidate.Viable = false; 5989 Candidate.FailureKind = ovl_fail_bad_target; 5990 return; 5991 } 5992 5993 // Determine the implicit conversion sequences for each of the 5994 // arguments. 5995 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5996 if (ArgIdx < NumParams) { 5997 // (C++ 13.3.2p3): for F to be a viable function, there shall 5998 // exist for each argument an implicit conversion sequence 5999 // (13.3.3.1) that converts that argument to the corresponding 6000 // parameter of F. 6001 QualType ParamType = Proto->getParamType(ArgIdx); 6002 Candidate.Conversions[ArgIdx + 1] 6003 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6004 SuppressUserConversions, 6005 /*InOverloadResolution=*/true, 6006 /*AllowObjCWritebackConversion=*/ 6007 getLangOpts().ObjCAutoRefCount); 6008 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6009 Candidate.Viable = false; 6010 Candidate.FailureKind = ovl_fail_bad_conversion; 6011 return; 6012 } 6013 } else { 6014 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6015 // argument for which there is no corresponding parameter is 6016 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6017 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6018 } 6019 } 6020 6021 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6022 Candidate.Viable = false; 6023 Candidate.FailureKind = ovl_fail_enable_if; 6024 Candidate.DeductionFailure.Data = FailedAttr; 6025 return; 6026 } 6027 } 6028 6029 /// \brief Add a C++ member function template as a candidate to the candidate 6030 /// set, using template argument deduction to produce an appropriate member 6031 /// function template specialization. 6032 void 6033 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6034 DeclAccessPair FoundDecl, 6035 CXXRecordDecl *ActingContext, 6036 TemplateArgumentListInfo *ExplicitTemplateArgs, 6037 QualType ObjectType, 6038 Expr::Classification ObjectClassification, 6039 ArrayRef<Expr *> Args, 6040 OverloadCandidateSet& CandidateSet, 6041 bool SuppressUserConversions) { 6042 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6043 return; 6044 6045 // C++ [over.match.funcs]p7: 6046 // In each case where a candidate is a function template, candidate 6047 // function template specializations are generated using template argument 6048 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6049 // candidate functions in the usual way.113) A given name can refer to one 6050 // or more function templates and also to a set of overloaded non-template 6051 // functions. In such a case, the candidate functions generated from each 6052 // function template are combined with the set of non-template candidate 6053 // functions. 6054 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6055 FunctionDecl *Specialization = nullptr; 6056 if (TemplateDeductionResult Result 6057 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6058 Specialization, Info)) { 6059 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6060 Candidate.FoundDecl = FoundDecl; 6061 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6062 Candidate.Viable = false; 6063 Candidate.FailureKind = ovl_fail_bad_deduction; 6064 Candidate.IsSurrogate = false; 6065 Candidate.IgnoreObjectArgument = false; 6066 Candidate.ExplicitCallArguments = Args.size(); 6067 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6068 Info); 6069 return; 6070 } 6071 6072 // Add the function template specialization produced by template argument 6073 // deduction as a candidate. 6074 assert(Specialization && "Missing member function template specialization?"); 6075 assert(isa<CXXMethodDecl>(Specialization) && 6076 "Specialization is not a member function?"); 6077 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6078 ActingContext, ObjectType, ObjectClassification, Args, 6079 CandidateSet, SuppressUserConversions); 6080 } 6081 6082 /// \brief Add a C++ function template specialization as a candidate 6083 /// in the candidate set, using template argument deduction to produce 6084 /// an appropriate function template specialization. 6085 void 6086 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6087 DeclAccessPair FoundDecl, 6088 TemplateArgumentListInfo *ExplicitTemplateArgs, 6089 ArrayRef<Expr *> Args, 6090 OverloadCandidateSet& CandidateSet, 6091 bool SuppressUserConversions) { 6092 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6093 return; 6094 6095 // C++ [over.match.funcs]p7: 6096 // In each case where a candidate is a function template, candidate 6097 // function template specializations are generated using template argument 6098 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6099 // candidate functions in the usual way.113) A given name can refer to one 6100 // or more function templates and also to a set of overloaded non-template 6101 // functions. In such a case, the candidate functions generated from each 6102 // function template are combined with the set of non-template candidate 6103 // functions. 6104 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6105 FunctionDecl *Specialization = nullptr; 6106 if (TemplateDeductionResult Result 6107 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6108 Specialization, Info)) { 6109 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6110 Candidate.FoundDecl = FoundDecl; 6111 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6112 Candidate.Viable = false; 6113 Candidate.FailureKind = ovl_fail_bad_deduction; 6114 Candidate.IsSurrogate = false; 6115 Candidate.IgnoreObjectArgument = false; 6116 Candidate.ExplicitCallArguments = Args.size(); 6117 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6118 Info); 6119 return; 6120 } 6121 6122 // Add the function template specialization produced by template argument 6123 // deduction as a candidate. 6124 assert(Specialization && "Missing function template specialization?"); 6125 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6126 SuppressUserConversions); 6127 } 6128 6129 /// Determine whether this is an allowable conversion from the result 6130 /// of an explicit conversion operator to the expected type, per C++ 6131 /// [over.match.conv]p1 and [over.match.ref]p1. 6132 /// 6133 /// \param ConvType The return type of the conversion function. 6134 /// 6135 /// \param ToType The type we are converting to. 6136 /// 6137 /// \param AllowObjCPointerConversion Allow a conversion from one 6138 /// Objective-C pointer to another. 6139 /// 6140 /// \returns true if the conversion is allowable, false otherwise. 6141 static bool isAllowableExplicitConversion(Sema &S, 6142 QualType ConvType, QualType ToType, 6143 bool AllowObjCPointerConversion) { 6144 QualType ToNonRefType = ToType.getNonReferenceType(); 6145 6146 // Easy case: the types are the same. 6147 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6148 return true; 6149 6150 // Allow qualification conversions. 6151 bool ObjCLifetimeConversion; 6152 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6153 ObjCLifetimeConversion)) 6154 return true; 6155 6156 // If we're not allowed to consider Objective-C pointer conversions, 6157 // we're done. 6158 if (!AllowObjCPointerConversion) 6159 return false; 6160 6161 // Is this an Objective-C pointer conversion? 6162 bool IncompatibleObjC = false; 6163 QualType ConvertedType; 6164 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6165 IncompatibleObjC); 6166 } 6167 6168 /// AddConversionCandidate - Add a C++ conversion function as a 6169 /// candidate in the candidate set (C++ [over.match.conv], 6170 /// C++ [over.match.copy]). From is the expression we're converting from, 6171 /// and ToType is the type that we're eventually trying to convert to 6172 /// (which may or may not be the same type as the type that the 6173 /// conversion function produces). 6174 void 6175 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6176 DeclAccessPair FoundDecl, 6177 CXXRecordDecl *ActingContext, 6178 Expr *From, QualType ToType, 6179 OverloadCandidateSet& CandidateSet, 6180 bool AllowObjCConversionOnExplicit) { 6181 assert(!Conversion->getDescribedFunctionTemplate() && 6182 "Conversion function templates use AddTemplateConversionCandidate"); 6183 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6184 if (!CandidateSet.isNewCandidate(Conversion)) 6185 return; 6186 6187 // If the conversion function has an undeduced return type, trigger its 6188 // deduction now. 6189 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6190 if (DeduceReturnType(Conversion, From->getExprLoc())) 6191 return; 6192 ConvType = Conversion->getConversionType().getNonReferenceType(); 6193 } 6194 6195 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6196 // operator is only a candidate if its return type is the target type or 6197 // can be converted to the target type with a qualification conversion. 6198 if (Conversion->isExplicit() && 6199 !isAllowableExplicitConversion(*this, ConvType, ToType, 6200 AllowObjCConversionOnExplicit)) 6201 return; 6202 6203 // Overload resolution is always an unevaluated context. 6204 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6205 6206 // Add this candidate 6207 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6208 Candidate.FoundDecl = FoundDecl; 6209 Candidate.Function = Conversion; 6210 Candidate.IsSurrogate = false; 6211 Candidate.IgnoreObjectArgument = false; 6212 Candidate.FinalConversion.setAsIdentityConversion(); 6213 Candidate.FinalConversion.setFromType(ConvType); 6214 Candidate.FinalConversion.setAllToTypes(ToType); 6215 Candidate.Viable = true; 6216 Candidate.ExplicitCallArguments = 1; 6217 6218 // C++ [over.match.funcs]p4: 6219 // For conversion functions, the function is considered to be a member of 6220 // the class of the implicit implied object argument for the purpose of 6221 // defining the type of the implicit object parameter. 6222 // 6223 // Determine the implicit conversion sequence for the implicit 6224 // object parameter. 6225 QualType ImplicitParamType = From->getType(); 6226 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6227 ImplicitParamType = FromPtrType->getPointeeType(); 6228 CXXRecordDecl *ConversionContext 6229 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6230 6231 Candidate.Conversions[0] 6232 = TryObjectArgumentInitialization(*this, From->getType(), 6233 From->Classify(Context), 6234 Conversion, ConversionContext); 6235 6236 if (Candidate.Conversions[0].isBad()) { 6237 Candidate.Viable = false; 6238 Candidate.FailureKind = ovl_fail_bad_conversion; 6239 return; 6240 } 6241 6242 // We won't go through a user-defined type conversion function to convert a 6243 // derived to base as such conversions are given Conversion Rank. They only 6244 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6245 QualType FromCanon 6246 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6247 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6248 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6249 Candidate.Viable = false; 6250 Candidate.FailureKind = ovl_fail_trivial_conversion; 6251 return; 6252 } 6253 6254 // To determine what the conversion from the result of calling the 6255 // conversion function to the type we're eventually trying to 6256 // convert to (ToType), we need to synthesize a call to the 6257 // conversion function and attempt copy initialization from it. This 6258 // makes sure that we get the right semantics with respect to 6259 // lvalues/rvalues and the type. Fortunately, we can allocate this 6260 // call on the stack and we don't need its arguments to be 6261 // well-formed. 6262 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6263 VK_LValue, From->getLocStart()); 6264 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6265 Context.getPointerType(Conversion->getType()), 6266 CK_FunctionToPointerDecay, 6267 &ConversionRef, VK_RValue); 6268 6269 QualType ConversionType = Conversion->getConversionType(); 6270 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6271 Candidate.Viable = false; 6272 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6273 return; 6274 } 6275 6276 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6277 6278 // Note that it is safe to allocate CallExpr on the stack here because 6279 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6280 // allocator). 6281 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6282 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6283 From->getLocStart()); 6284 ImplicitConversionSequence ICS = 6285 TryCopyInitialization(*this, &Call, ToType, 6286 /*SuppressUserConversions=*/true, 6287 /*InOverloadResolution=*/false, 6288 /*AllowObjCWritebackConversion=*/false); 6289 6290 switch (ICS.getKind()) { 6291 case ImplicitConversionSequence::StandardConversion: 6292 Candidate.FinalConversion = ICS.Standard; 6293 6294 // C++ [over.ics.user]p3: 6295 // If the user-defined conversion is specified by a specialization of a 6296 // conversion function template, the second standard conversion sequence 6297 // shall have exact match rank. 6298 if (Conversion->getPrimaryTemplate() && 6299 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6300 Candidate.Viable = false; 6301 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6302 return; 6303 } 6304 6305 // C++0x [dcl.init.ref]p5: 6306 // In the second case, if the reference is an rvalue reference and 6307 // the second standard conversion sequence of the user-defined 6308 // conversion sequence includes an lvalue-to-rvalue conversion, the 6309 // program is ill-formed. 6310 if (ToType->isRValueReferenceType() && 6311 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6312 Candidate.Viable = false; 6313 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6314 return; 6315 } 6316 break; 6317 6318 case ImplicitConversionSequence::BadConversion: 6319 Candidate.Viable = false; 6320 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6321 return; 6322 6323 default: 6324 llvm_unreachable( 6325 "Can only end up with a standard conversion sequence or failure"); 6326 } 6327 6328 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6329 Candidate.Viable = false; 6330 Candidate.FailureKind = ovl_fail_enable_if; 6331 Candidate.DeductionFailure.Data = FailedAttr; 6332 return; 6333 } 6334 } 6335 6336 /// \brief Adds a conversion function template specialization 6337 /// candidate to the overload set, using template argument deduction 6338 /// to deduce the template arguments of the conversion function 6339 /// template from the type that we are converting to (C++ 6340 /// [temp.deduct.conv]). 6341 void 6342 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6343 DeclAccessPair FoundDecl, 6344 CXXRecordDecl *ActingDC, 6345 Expr *From, QualType ToType, 6346 OverloadCandidateSet &CandidateSet, 6347 bool AllowObjCConversionOnExplicit) { 6348 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6349 "Only conversion function templates permitted here"); 6350 6351 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6352 return; 6353 6354 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6355 CXXConversionDecl *Specialization = nullptr; 6356 if (TemplateDeductionResult Result 6357 = DeduceTemplateArguments(FunctionTemplate, ToType, 6358 Specialization, Info)) { 6359 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6360 Candidate.FoundDecl = FoundDecl; 6361 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6362 Candidate.Viable = false; 6363 Candidate.FailureKind = ovl_fail_bad_deduction; 6364 Candidate.IsSurrogate = false; 6365 Candidate.IgnoreObjectArgument = false; 6366 Candidate.ExplicitCallArguments = 1; 6367 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6368 Info); 6369 return; 6370 } 6371 6372 // Add the conversion function template specialization produced by 6373 // template argument deduction as a candidate. 6374 assert(Specialization && "Missing function template specialization?"); 6375 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6376 CandidateSet, AllowObjCConversionOnExplicit); 6377 } 6378 6379 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6380 /// converts the given @c Object to a function pointer via the 6381 /// conversion function @c Conversion, and then attempts to call it 6382 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6383 /// the type of function that we'll eventually be calling. 6384 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6385 DeclAccessPair FoundDecl, 6386 CXXRecordDecl *ActingContext, 6387 const FunctionProtoType *Proto, 6388 Expr *Object, 6389 ArrayRef<Expr *> Args, 6390 OverloadCandidateSet& CandidateSet) { 6391 if (!CandidateSet.isNewCandidate(Conversion)) 6392 return; 6393 6394 // Overload resolution is always an unevaluated context. 6395 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6396 6397 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6398 Candidate.FoundDecl = FoundDecl; 6399 Candidate.Function = nullptr; 6400 Candidate.Surrogate = Conversion; 6401 Candidate.Viable = true; 6402 Candidate.IsSurrogate = true; 6403 Candidate.IgnoreObjectArgument = false; 6404 Candidate.ExplicitCallArguments = Args.size(); 6405 6406 // Determine the implicit conversion sequence for the implicit 6407 // object parameter. 6408 ImplicitConversionSequence ObjectInit 6409 = TryObjectArgumentInitialization(*this, Object->getType(), 6410 Object->Classify(Context), 6411 Conversion, ActingContext); 6412 if (ObjectInit.isBad()) { 6413 Candidate.Viable = false; 6414 Candidate.FailureKind = ovl_fail_bad_conversion; 6415 Candidate.Conversions[0] = ObjectInit; 6416 return; 6417 } 6418 6419 // The first conversion is actually a user-defined conversion whose 6420 // first conversion is ObjectInit's standard conversion (which is 6421 // effectively a reference binding). Record it as such. 6422 Candidate.Conversions[0].setUserDefined(); 6423 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6424 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6425 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6426 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6427 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6428 Candidate.Conversions[0].UserDefined.After 6429 = Candidate.Conversions[0].UserDefined.Before; 6430 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6431 6432 // Find the 6433 unsigned NumParams = Proto->getNumParams(); 6434 6435 // (C++ 13.3.2p2): A candidate function having fewer than m 6436 // parameters is viable only if it has an ellipsis in its parameter 6437 // list (8.3.5). 6438 if (Args.size() > NumParams && !Proto->isVariadic()) { 6439 Candidate.Viable = false; 6440 Candidate.FailureKind = ovl_fail_too_many_arguments; 6441 return; 6442 } 6443 6444 // Function types don't have any default arguments, so just check if 6445 // we have enough arguments. 6446 if (Args.size() < NumParams) { 6447 // Not enough arguments. 6448 Candidate.Viable = false; 6449 Candidate.FailureKind = ovl_fail_too_few_arguments; 6450 return; 6451 } 6452 6453 // Determine the implicit conversion sequences for each of the 6454 // arguments. 6455 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6456 if (ArgIdx < NumParams) { 6457 // (C++ 13.3.2p3): for F to be a viable function, there shall 6458 // exist for each argument an implicit conversion sequence 6459 // (13.3.3.1) that converts that argument to the corresponding 6460 // parameter of F. 6461 QualType ParamType = Proto->getParamType(ArgIdx); 6462 Candidate.Conversions[ArgIdx + 1] 6463 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6464 /*SuppressUserConversions=*/false, 6465 /*InOverloadResolution=*/false, 6466 /*AllowObjCWritebackConversion=*/ 6467 getLangOpts().ObjCAutoRefCount); 6468 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6469 Candidate.Viable = false; 6470 Candidate.FailureKind = ovl_fail_bad_conversion; 6471 return; 6472 } 6473 } else { 6474 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6475 // argument for which there is no corresponding parameter is 6476 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6477 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6478 } 6479 } 6480 6481 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6482 Candidate.Viable = false; 6483 Candidate.FailureKind = ovl_fail_enable_if; 6484 Candidate.DeductionFailure.Data = FailedAttr; 6485 return; 6486 } 6487 } 6488 6489 /// \brief Add overload candidates for overloaded operators that are 6490 /// member functions. 6491 /// 6492 /// Add the overloaded operator candidates that are member functions 6493 /// for the operator Op that was used in an operator expression such 6494 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6495 /// CandidateSet will store the added overload candidates. (C++ 6496 /// [over.match.oper]). 6497 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6498 SourceLocation OpLoc, 6499 ArrayRef<Expr *> Args, 6500 OverloadCandidateSet& CandidateSet, 6501 SourceRange OpRange) { 6502 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6503 6504 // C++ [over.match.oper]p3: 6505 // For a unary operator @ with an operand of a type whose 6506 // cv-unqualified version is T1, and for a binary operator @ with 6507 // a left operand of a type whose cv-unqualified version is T1 and 6508 // a right operand of a type whose cv-unqualified version is T2, 6509 // three sets of candidate functions, designated member 6510 // candidates, non-member candidates and built-in candidates, are 6511 // constructed as follows: 6512 QualType T1 = Args[0]->getType(); 6513 6514 // -- If T1 is a complete class type or a class currently being 6515 // defined, the set of member candidates is the result of the 6516 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6517 // the set of member candidates is empty. 6518 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6519 // Complete the type if it can be completed. 6520 RequireCompleteType(OpLoc, T1, 0); 6521 // If the type is neither complete nor being defined, bail out now. 6522 if (!T1Rec->getDecl()->getDefinition()) 6523 return; 6524 6525 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6526 LookupQualifiedName(Operators, T1Rec->getDecl()); 6527 Operators.suppressDiagnostics(); 6528 6529 for (LookupResult::iterator Oper = Operators.begin(), 6530 OperEnd = Operators.end(); 6531 Oper != OperEnd; 6532 ++Oper) 6533 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6534 Args[0]->Classify(Context), 6535 Args.slice(1), 6536 CandidateSet, 6537 /* SuppressUserConversions = */ false); 6538 } 6539 } 6540 6541 /// AddBuiltinCandidate - Add a candidate for a built-in 6542 /// operator. ResultTy and ParamTys are the result and parameter types 6543 /// of the built-in candidate, respectively. Args and NumArgs are the 6544 /// arguments being passed to the candidate. IsAssignmentOperator 6545 /// should be true when this built-in candidate is an assignment 6546 /// operator. NumContextualBoolArguments is the number of arguments 6547 /// (at the beginning of the argument list) that will be contextually 6548 /// converted to bool. 6549 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6550 ArrayRef<Expr *> Args, 6551 OverloadCandidateSet& CandidateSet, 6552 bool IsAssignmentOperator, 6553 unsigned NumContextualBoolArguments) { 6554 // Overload resolution is always an unevaluated context. 6555 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6556 6557 // Add this candidate 6558 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6559 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6560 Candidate.Function = nullptr; 6561 Candidate.IsSurrogate = false; 6562 Candidate.IgnoreObjectArgument = false; 6563 Candidate.BuiltinTypes.ResultTy = ResultTy; 6564 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6565 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6566 6567 // Determine the implicit conversion sequences for each of the 6568 // arguments. 6569 Candidate.Viable = true; 6570 Candidate.ExplicitCallArguments = Args.size(); 6571 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6572 // C++ [over.match.oper]p4: 6573 // For the built-in assignment operators, conversions of the 6574 // left operand are restricted as follows: 6575 // -- no temporaries are introduced to hold the left operand, and 6576 // -- no user-defined conversions are applied to the left 6577 // operand to achieve a type match with the left-most 6578 // parameter of a built-in candidate. 6579 // 6580 // We block these conversions by turning off user-defined 6581 // conversions, since that is the only way that initialization of 6582 // a reference to a non-class type can occur from something that 6583 // is not of the same type. 6584 if (ArgIdx < NumContextualBoolArguments) { 6585 assert(ParamTys[ArgIdx] == Context.BoolTy && 6586 "Contextual conversion to bool requires bool type"); 6587 Candidate.Conversions[ArgIdx] 6588 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6589 } else { 6590 Candidate.Conversions[ArgIdx] 6591 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6592 ArgIdx == 0 && IsAssignmentOperator, 6593 /*InOverloadResolution=*/false, 6594 /*AllowObjCWritebackConversion=*/ 6595 getLangOpts().ObjCAutoRefCount); 6596 } 6597 if (Candidate.Conversions[ArgIdx].isBad()) { 6598 Candidate.Viable = false; 6599 Candidate.FailureKind = ovl_fail_bad_conversion; 6600 break; 6601 } 6602 } 6603 } 6604 6605 namespace { 6606 6607 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6608 /// candidate operator functions for built-in operators (C++ 6609 /// [over.built]). The types are separated into pointer types and 6610 /// enumeration types. 6611 class BuiltinCandidateTypeSet { 6612 /// TypeSet - A set of types. 6613 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6614 6615 /// PointerTypes - The set of pointer types that will be used in the 6616 /// built-in candidates. 6617 TypeSet PointerTypes; 6618 6619 /// MemberPointerTypes - The set of member pointer types that will be 6620 /// used in the built-in candidates. 6621 TypeSet MemberPointerTypes; 6622 6623 /// EnumerationTypes - The set of enumeration types that will be 6624 /// used in the built-in candidates. 6625 TypeSet EnumerationTypes; 6626 6627 /// \brief The set of vector types that will be used in the built-in 6628 /// candidates. 6629 TypeSet VectorTypes; 6630 6631 /// \brief A flag indicating non-record types are viable candidates 6632 bool HasNonRecordTypes; 6633 6634 /// \brief A flag indicating whether either arithmetic or enumeration types 6635 /// were present in the candidate set. 6636 bool HasArithmeticOrEnumeralTypes; 6637 6638 /// \brief A flag indicating whether the nullptr type was present in the 6639 /// candidate set. 6640 bool HasNullPtrType; 6641 6642 /// Sema - The semantic analysis instance where we are building the 6643 /// candidate type set. 6644 Sema &SemaRef; 6645 6646 /// Context - The AST context in which we will build the type sets. 6647 ASTContext &Context; 6648 6649 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6650 const Qualifiers &VisibleQuals); 6651 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6652 6653 public: 6654 /// iterator - Iterates through the types that are part of the set. 6655 typedef TypeSet::iterator iterator; 6656 6657 BuiltinCandidateTypeSet(Sema &SemaRef) 6658 : HasNonRecordTypes(false), 6659 HasArithmeticOrEnumeralTypes(false), 6660 HasNullPtrType(false), 6661 SemaRef(SemaRef), 6662 Context(SemaRef.Context) { } 6663 6664 void AddTypesConvertedFrom(QualType Ty, 6665 SourceLocation Loc, 6666 bool AllowUserConversions, 6667 bool AllowExplicitConversions, 6668 const Qualifiers &VisibleTypeConversionsQuals); 6669 6670 /// pointer_begin - First pointer type found; 6671 iterator pointer_begin() { return PointerTypes.begin(); } 6672 6673 /// pointer_end - Past the last pointer type found; 6674 iterator pointer_end() { return PointerTypes.end(); } 6675 6676 /// member_pointer_begin - First member pointer type found; 6677 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6678 6679 /// member_pointer_end - Past the last member pointer type found; 6680 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6681 6682 /// enumeration_begin - First enumeration type found; 6683 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6684 6685 /// enumeration_end - Past the last enumeration type found; 6686 iterator enumeration_end() { return EnumerationTypes.end(); } 6687 6688 iterator vector_begin() { return VectorTypes.begin(); } 6689 iterator vector_end() { return VectorTypes.end(); } 6690 6691 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6692 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6693 bool hasNullPtrType() const { return HasNullPtrType; } 6694 }; 6695 6696 } // end anonymous namespace 6697 6698 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6699 /// the set of pointer types along with any more-qualified variants of 6700 /// that type. For example, if @p Ty is "int const *", this routine 6701 /// will add "int const *", "int const volatile *", "int const 6702 /// restrict *", and "int const volatile restrict *" to the set of 6703 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6704 /// false otherwise. 6705 /// 6706 /// FIXME: what to do about extended qualifiers? 6707 bool 6708 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6709 const Qualifiers &VisibleQuals) { 6710 6711 // Insert this type. 6712 if (!PointerTypes.insert(Ty)) 6713 return false; 6714 6715 QualType PointeeTy; 6716 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6717 bool buildObjCPtr = false; 6718 if (!PointerTy) { 6719 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6720 PointeeTy = PTy->getPointeeType(); 6721 buildObjCPtr = true; 6722 } else { 6723 PointeeTy = PointerTy->getPointeeType(); 6724 } 6725 6726 // Don't add qualified variants of arrays. For one, they're not allowed 6727 // (the qualifier would sink to the element type), and for another, the 6728 // only overload situation where it matters is subscript or pointer +- int, 6729 // and those shouldn't have qualifier variants anyway. 6730 if (PointeeTy->isArrayType()) 6731 return true; 6732 6733 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6734 bool hasVolatile = VisibleQuals.hasVolatile(); 6735 bool hasRestrict = VisibleQuals.hasRestrict(); 6736 6737 // Iterate through all strict supersets of BaseCVR. 6738 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6739 if ((CVR | BaseCVR) != CVR) continue; 6740 // Skip over volatile if no volatile found anywhere in the types. 6741 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6742 6743 // Skip over restrict if no restrict found anywhere in the types, or if 6744 // the type cannot be restrict-qualified. 6745 if ((CVR & Qualifiers::Restrict) && 6746 (!hasRestrict || 6747 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6748 continue; 6749 6750 // Build qualified pointee type. 6751 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6752 6753 // Build qualified pointer type. 6754 QualType QPointerTy; 6755 if (!buildObjCPtr) 6756 QPointerTy = Context.getPointerType(QPointeeTy); 6757 else 6758 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6759 6760 // Insert qualified pointer type. 6761 PointerTypes.insert(QPointerTy); 6762 } 6763 6764 return true; 6765 } 6766 6767 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6768 /// to the set of pointer types along with any more-qualified variants of 6769 /// that type. For example, if @p Ty is "int const *", this routine 6770 /// will add "int const *", "int const volatile *", "int const 6771 /// restrict *", and "int const volatile restrict *" to the set of 6772 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6773 /// false otherwise. 6774 /// 6775 /// FIXME: what to do about extended qualifiers? 6776 bool 6777 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6778 QualType Ty) { 6779 // Insert this type. 6780 if (!MemberPointerTypes.insert(Ty)) 6781 return false; 6782 6783 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6784 assert(PointerTy && "type was not a member pointer type!"); 6785 6786 QualType PointeeTy = PointerTy->getPointeeType(); 6787 // Don't add qualified variants of arrays. For one, they're not allowed 6788 // (the qualifier would sink to the element type), and for another, the 6789 // only overload situation where it matters is subscript or pointer +- int, 6790 // and those shouldn't have qualifier variants anyway. 6791 if (PointeeTy->isArrayType()) 6792 return true; 6793 const Type *ClassTy = PointerTy->getClass(); 6794 6795 // Iterate through all strict supersets of the pointee type's CVR 6796 // qualifiers. 6797 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6798 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6799 if ((CVR | BaseCVR) != CVR) continue; 6800 6801 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6802 MemberPointerTypes.insert( 6803 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6804 } 6805 6806 return true; 6807 } 6808 6809 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6810 /// Ty can be implicit converted to the given set of @p Types. We're 6811 /// primarily interested in pointer types and enumeration types. We also 6812 /// take member pointer types, for the conditional operator. 6813 /// AllowUserConversions is true if we should look at the conversion 6814 /// functions of a class type, and AllowExplicitConversions if we 6815 /// should also include the explicit conversion functions of a class 6816 /// type. 6817 void 6818 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6819 SourceLocation Loc, 6820 bool AllowUserConversions, 6821 bool AllowExplicitConversions, 6822 const Qualifiers &VisibleQuals) { 6823 // Only deal with canonical types. 6824 Ty = Context.getCanonicalType(Ty); 6825 6826 // Look through reference types; they aren't part of the type of an 6827 // expression for the purposes of conversions. 6828 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6829 Ty = RefTy->getPointeeType(); 6830 6831 // If we're dealing with an array type, decay to the pointer. 6832 if (Ty->isArrayType()) 6833 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6834 6835 // Otherwise, we don't care about qualifiers on the type. 6836 Ty = Ty.getLocalUnqualifiedType(); 6837 6838 // Flag if we ever add a non-record type. 6839 const RecordType *TyRec = Ty->getAs<RecordType>(); 6840 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6841 6842 // Flag if we encounter an arithmetic type. 6843 HasArithmeticOrEnumeralTypes = 6844 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6845 6846 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6847 PointerTypes.insert(Ty); 6848 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6849 // Insert our type, and its more-qualified variants, into the set 6850 // of types. 6851 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6852 return; 6853 } else if (Ty->isMemberPointerType()) { 6854 // Member pointers are far easier, since the pointee can't be converted. 6855 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6856 return; 6857 } else if (Ty->isEnumeralType()) { 6858 HasArithmeticOrEnumeralTypes = true; 6859 EnumerationTypes.insert(Ty); 6860 } else if (Ty->isVectorType()) { 6861 // We treat vector types as arithmetic types in many contexts as an 6862 // extension. 6863 HasArithmeticOrEnumeralTypes = true; 6864 VectorTypes.insert(Ty); 6865 } else if (Ty->isNullPtrType()) { 6866 HasNullPtrType = true; 6867 } else if (AllowUserConversions && TyRec) { 6868 // No conversion functions in incomplete types. 6869 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6870 return; 6871 6872 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6873 std::pair<CXXRecordDecl::conversion_iterator, 6874 CXXRecordDecl::conversion_iterator> 6875 Conversions = ClassDecl->getVisibleConversionFunctions(); 6876 for (CXXRecordDecl::conversion_iterator 6877 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6878 NamedDecl *D = I.getDecl(); 6879 if (isa<UsingShadowDecl>(D)) 6880 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6881 6882 // Skip conversion function templates; they don't tell us anything 6883 // about which builtin types we can convert to. 6884 if (isa<FunctionTemplateDecl>(D)) 6885 continue; 6886 6887 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6888 if (AllowExplicitConversions || !Conv->isExplicit()) { 6889 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6890 VisibleQuals); 6891 } 6892 } 6893 } 6894 } 6895 6896 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6897 /// the volatile- and non-volatile-qualified assignment operators for the 6898 /// given type to the candidate set. 6899 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6900 QualType T, 6901 ArrayRef<Expr *> Args, 6902 OverloadCandidateSet &CandidateSet) { 6903 QualType ParamTypes[2]; 6904 6905 // T& operator=(T&, T) 6906 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6907 ParamTypes[1] = T; 6908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6909 /*IsAssignmentOperator=*/true); 6910 6911 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6912 // volatile T& operator=(volatile T&, T) 6913 ParamTypes[0] 6914 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6915 ParamTypes[1] = T; 6916 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6917 /*IsAssignmentOperator=*/true); 6918 } 6919 } 6920 6921 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6922 /// if any, found in visible type conversion functions found in ArgExpr's type. 6923 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6924 Qualifiers VRQuals; 6925 const RecordType *TyRec; 6926 if (const MemberPointerType *RHSMPType = 6927 ArgExpr->getType()->getAs<MemberPointerType>()) 6928 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6929 else 6930 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6931 if (!TyRec) { 6932 // Just to be safe, assume the worst case. 6933 VRQuals.addVolatile(); 6934 VRQuals.addRestrict(); 6935 return VRQuals; 6936 } 6937 6938 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6939 if (!ClassDecl->hasDefinition()) 6940 return VRQuals; 6941 6942 std::pair<CXXRecordDecl::conversion_iterator, 6943 CXXRecordDecl::conversion_iterator> 6944 Conversions = ClassDecl->getVisibleConversionFunctions(); 6945 6946 for (CXXRecordDecl::conversion_iterator 6947 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6948 NamedDecl *D = I.getDecl(); 6949 if (isa<UsingShadowDecl>(D)) 6950 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6951 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6952 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6953 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6954 CanTy = ResTypeRef->getPointeeType(); 6955 // Need to go down the pointer/mempointer chain and add qualifiers 6956 // as see them. 6957 bool done = false; 6958 while (!done) { 6959 if (CanTy.isRestrictQualified()) 6960 VRQuals.addRestrict(); 6961 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6962 CanTy = ResTypePtr->getPointeeType(); 6963 else if (const MemberPointerType *ResTypeMPtr = 6964 CanTy->getAs<MemberPointerType>()) 6965 CanTy = ResTypeMPtr->getPointeeType(); 6966 else 6967 done = true; 6968 if (CanTy.isVolatileQualified()) 6969 VRQuals.addVolatile(); 6970 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6971 return VRQuals; 6972 } 6973 } 6974 } 6975 return VRQuals; 6976 } 6977 6978 namespace { 6979 6980 /// \brief Helper class to manage the addition of builtin operator overload 6981 /// candidates. It provides shared state and utility methods used throughout 6982 /// the process, as well as a helper method to add each group of builtin 6983 /// operator overloads from the standard to a candidate set. 6984 class BuiltinOperatorOverloadBuilder { 6985 // Common instance state available to all overload candidate addition methods. 6986 Sema &S; 6987 ArrayRef<Expr *> Args; 6988 Qualifiers VisibleTypeConversionsQuals; 6989 bool HasArithmeticOrEnumeralCandidateType; 6990 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6991 OverloadCandidateSet &CandidateSet; 6992 6993 // Define some constants used to index and iterate over the arithemetic types 6994 // provided via the getArithmeticType() method below. 6995 // The "promoted arithmetic types" are the arithmetic 6996 // types are that preserved by promotion (C++ [over.built]p2). 6997 static const unsigned FirstIntegralType = 3; 6998 static const unsigned LastIntegralType = 20; 6999 static const unsigned FirstPromotedIntegralType = 3, 7000 LastPromotedIntegralType = 11; 7001 static const unsigned FirstPromotedArithmeticType = 0, 7002 LastPromotedArithmeticType = 11; 7003 static const unsigned NumArithmeticTypes = 20; 7004 7005 /// \brief Get the canonical type for a given arithmetic type index. 7006 CanQualType getArithmeticType(unsigned index) { 7007 assert(index < NumArithmeticTypes); 7008 static CanQualType ASTContext::* const 7009 ArithmeticTypes[NumArithmeticTypes] = { 7010 // Start of promoted types. 7011 &ASTContext::FloatTy, 7012 &ASTContext::DoubleTy, 7013 &ASTContext::LongDoubleTy, 7014 7015 // Start of integral types. 7016 &ASTContext::IntTy, 7017 &ASTContext::LongTy, 7018 &ASTContext::LongLongTy, 7019 &ASTContext::Int128Ty, 7020 &ASTContext::UnsignedIntTy, 7021 &ASTContext::UnsignedLongTy, 7022 &ASTContext::UnsignedLongLongTy, 7023 &ASTContext::UnsignedInt128Ty, 7024 // End of promoted types. 7025 7026 &ASTContext::BoolTy, 7027 &ASTContext::CharTy, 7028 &ASTContext::WCharTy, 7029 &ASTContext::Char16Ty, 7030 &ASTContext::Char32Ty, 7031 &ASTContext::SignedCharTy, 7032 &ASTContext::ShortTy, 7033 &ASTContext::UnsignedCharTy, 7034 &ASTContext::UnsignedShortTy, 7035 // End of integral types. 7036 // FIXME: What about complex? What about half? 7037 }; 7038 return S.Context.*ArithmeticTypes[index]; 7039 } 7040 7041 /// \brief Gets the canonical type resulting from the usual arithemetic 7042 /// converions for the given arithmetic types. 7043 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7044 // Accelerator table for performing the usual arithmetic conversions. 7045 // The rules are basically: 7046 // - if either is floating-point, use the wider floating-point 7047 // - if same signedness, use the higher rank 7048 // - if same size, use unsigned of the higher rank 7049 // - use the larger type 7050 // These rules, together with the axiom that higher ranks are 7051 // never smaller, are sufficient to precompute all of these results 7052 // *except* when dealing with signed types of higher rank. 7053 // (we could precompute SLL x UI for all known platforms, but it's 7054 // better not to make any assumptions). 7055 // We assume that int128 has a higher rank than long long on all platforms. 7056 enum PromotedType { 7057 Dep=-1, 7058 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7059 }; 7060 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7061 [LastPromotedArithmeticType] = { 7062 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7063 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7064 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7065 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7066 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7067 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7068 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7069 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7070 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7071 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7072 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7073 }; 7074 7075 assert(L < LastPromotedArithmeticType); 7076 assert(R < LastPromotedArithmeticType); 7077 int Idx = ConversionsTable[L][R]; 7078 7079 // Fast path: the table gives us a concrete answer. 7080 if (Idx != Dep) return getArithmeticType(Idx); 7081 7082 // Slow path: we need to compare widths. 7083 // An invariant is that the signed type has higher rank. 7084 CanQualType LT = getArithmeticType(L), 7085 RT = getArithmeticType(R); 7086 unsigned LW = S.Context.getIntWidth(LT), 7087 RW = S.Context.getIntWidth(RT); 7088 7089 // If they're different widths, use the signed type. 7090 if (LW > RW) return LT; 7091 else if (LW < RW) return RT; 7092 7093 // Otherwise, use the unsigned type of the signed type's rank. 7094 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7095 assert(L == SLL || R == SLL); 7096 return S.Context.UnsignedLongLongTy; 7097 } 7098 7099 /// \brief Helper method to factor out the common pattern of adding overloads 7100 /// for '++' and '--' builtin operators. 7101 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7102 bool HasVolatile, 7103 bool HasRestrict) { 7104 QualType ParamTypes[2] = { 7105 S.Context.getLValueReferenceType(CandidateTy), 7106 S.Context.IntTy 7107 }; 7108 7109 // Non-volatile version. 7110 if (Args.size() == 1) 7111 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7112 else 7113 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7114 7115 // Use a heuristic to reduce number of builtin candidates in the set: 7116 // add volatile version only if there are conversions to a volatile type. 7117 if (HasVolatile) { 7118 ParamTypes[0] = 7119 S.Context.getLValueReferenceType( 7120 S.Context.getVolatileType(CandidateTy)); 7121 if (Args.size() == 1) 7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7123 else 7124 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7125 } 7126 7127 // Add restrict version only if there are conversions to a restrict type 7128 // and our candidate type is a non-restrict-qualified pointer. 7129 if (HasRestrict && CandidateTy->isAnyPointerType() && 7130 !CandidateTy.isRestrictQualified()) { 7131 ParamTypes[0] 7132 = S.Context.getLValueReferenceType( 7133 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7134 if (Args.size() == 1) 7135 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7136 else 7137 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7138 7139 if (HasVolatile) { 7140 ParamTypes[0] 7141 = S.Context.getLValueReferenceType( 7142 S.Context.getCVRQualifiedType(CandidateTy, 7143 (Qualifiers::Volatile | 7144 Qualifiers::Restrict))); 7145 if (Args.size() == 1) 7146 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7147 else 7148 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7149 } 7150 } 7151 7152 } 7153 7154 public: 7155 BuiltinOperatorOverloadBuilder( 7156 Sema &S, ArrayRef<Expr *> Args, 7157 Qualifiers VisibleTypeConversionsQuals, 7158 bool HasArithmeticOrEnumeralCandidateType, 7159 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7160 OverloadCandidateSet &CandidateSet) 7161 : S(S), Args(Args), 7162 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7163 HasArithmeticOrEnumeralCandidateType( 7164 HasArithmeticOrEnumeralCandidateType), 7165 CandidateTypes(CandidateTypes), 7166 CandidateSet(CandidateSet) { 7167 // Validate some of our static helper constants in debug builds. 7168 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7169 "Invalid first promoted integral type"); 7170 assert(getArithmeticType(LastPromotedIntegralType - 1) 7171 == S.Context.UnsignedInt128Ty && 7172 "Invalid last promoted integral type"); 7173 assert(getArithmeticType(FirstPromotedArithmeticType) 7174 == S.Context.FloatTy && 7175 "Invalid first promoted arithmetic type"); 7176 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7177 == S.Context.UnsignedInt128Ty && 7178 "Invalid last promoted arithmetic type"); 7179 } 7180 7181 // C++ [over.built]p3: 7182 // 7183 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7184 // is either volatile or empty, there exist candidate operator 7185 // functions of the form 7186 // 7187 // VQ T& operator++(VQ T&); 7188 // T operator++(VQ T&, int); 7189 // 7190 // C++ [over.built]p4: 7191 // 7192 // For every pair (T, VQ), where T is an arithmetic type other 7193 // than bool, and VQ is either volatile or empty, there exist 7194 // candidate operator functions of the form 7195 // 7196 // VQ T& operator--(VQ T&); 7197 // T operator--(VQ T&, int); 7198 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7199 if (!HasArithmeticOrEnumeralCandidateType) 7200 return; 7201 7202 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7203 Arith < NumArithmeticTypes; ++Arith) { 7204 addPlusPlusMinusMinusStyleOverloads( 7205 getArithmeticType(Arith), 7206 VisibleTypeConversionsQuals.hasVolatile(), 7207 VisibleTypeConversionsQuals.hasRestrict()); 7208 } 7209 } 7210 7211 // C++ [over.built]p5: 7212 // 7213 // For every pair (T, VQ), where T is a cv-qualified or 7214 // cv-unqualified object type, and VQ is either volatile or 7215 // empty, there exist candidate operator functions of the form 7216 // 7217 // T*VQ& operator++(T*VQ&); 7218 // T*VQ& operator--(T*VQ&); 7219 // T* operator++(T*VQ&, int); 7220 // T* operator--(T*VQ&, int); 7221 void addPlusPlusMinusMinusPointerOverloads() { 7222 for (BuiltinCandidateTypeSet::iterator 7223 Ptr = CandidateTypes[0].pointer_begin(), 7224 PtrEnd = CandidateTypes[0].pointer_end(); 7225 Ptr != PtrEnd; ++Ptr) { 7226 // Skip pointer types that aren't pointers to object types. 7227 if (!(*Ptr)->getPointeeType()->isObjectType()) 7228 continue; 7229 7230 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7231 (!(*Ptr).isVolatileQualified() && 7232 VisibleTypeConversionsQuals.hasVolatile()), 7233 (!(*Ptr).isRestrictQualified() && 7234 VisibleTypeConversionsQuals.hasRestrict())); 7235 } 7236 } 7237 7238 // C++ [over.built]p6: 7239 // For every cv-qualified or cv-unqualified object type T, there 7240 // exist candidate operator functions of the form 7241 // 7242 // T& operator*(T*); 7243 // 7244 // C++ [over.built]p7: 7245 // For every function type T that does not have cv-qualifiers or a 7246 // ref-qualifier, there exist candidate operator functions of the form 7247 // T& operator*(T*); 7248 void addUnaryStarPointerOverloads() { 7249 for (BuiltinCandidateTypeSet::iterator 7250 Ptr = CandidateTypes[0].pointer_begin(), 7251 PtrEnd = CandidateTypes[0].pointer_end(); 7252 Ptr != PtrEnd; ++Ptr) { 7253 QualType ParamTy = *Ptr; 7254 QualType PointeeTy = ParamTy->getPointeeType(); 7255 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7256 continue; 7257 7258 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7259 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7260 continue; 7261 7262 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7263 &ParamTy, Args, CandidateSet); 7264 } 7265 } 7266 7267 // C++ [over.built]p9: 7268 // For every promoted arithmetic type T, there exist candidate 7269 // operator functions of the form 7270 // 7271 // T operator+(T); 7272 // T operator-(T); 7273 void addUnaryPlusOrMinusArithmeticOverloads() { 7274 if (!HasArithmeticOrEnumeralCandidateType) 7275 return; 7276 7277 for (unsigned Arith = FirstPromotedArithmeticType; 7278 Arith < LastPromotedArithmeticType; ++Arith) { 7279 QualType ArithTy = getArithmeticType(Arith); 7280 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7281 } 7282 7283 // Extension: We also add these operators for vector types. 7284 for (BuiltinCandidateTypeSet::iterator 7285 Vec = CandidateTypes[0].vector_begin(), 7286 VecEnd = CandidateTypes[0].vector_end(); 7287 Vec != VecEnd; ++Vec) { 7288 QualType VecTy = *Vec; 7289 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7290 } 7291 } 7292 7293 // C++ [over.built]p8: 7294 // For every type T, there exist candidate operator functions of 7295 // the form 7296 // 7297 // T* operator+(T*); 7298 void addUnaryPlusPointerOverloads() { 7299 for (BuiltinCandidateTypeSet::iterator 7300 Ptr = CandidateTypes[0].pointer_begin(), 7301 PtrEnd = CandidateTypes[0].pointer_end(); 7302 Ptr != PtrEnd; ++Ptr) { 7303 QualType ParamTy = *Ptr; 7304 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7305 } 7306 } 7307 7308 // C++ [over.built]p10: 7309 // For every promoted integral type T, there exist candidate 7310 // operator functions of the form 7311 // 7312 // T operator~(T); 7313 void addUnaryTildePromotedIntegralOverloads() { 7314 if (!HasArithmeticOrEnumeralCandidateType) 7315 return; 7316 7317 for (unsigned Int = FirstPromotedIntegralType; 7318 Int < LastPromotedIntegralType; ++Int) { 7319 QualType IntTy = getArithmeticType(Int); 7320 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7321 } 7322 7323 // Extension: We also add this operator for vector types. 7324 for (BuiltinCandidateTypeSet::iterator 7325 Vec = CandidateTypes[0].vector_begin(), 7326 VecEnd = CandidateTypes[0].vector_end(); 7327 Vec != VecEnd; ++Vec) { 7328 QualType VecTy = *Vec; 7329 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7330 } 7331 } 7332 7333 // C++ [over.match.oper]p16: 7334 // For every pointer to member type T, there exist candidate operator 7335 // functions of the form 7336 // 7337 // bool operator==(T,T); 7338 // bool operator!=(T,T); 7339 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7340 /// Set of (canonical) types that we've already handled. 7341 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7342 7343 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7344 for (BuiltinCandidateTypeSet::iterator 7345 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7346 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7347 MemPtr != MemPtrEnd; 7348 ++MemPtr) { 7349 // Don't add the same builtin candidate twice. 7350 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7351 continue; 7352 7353 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7354 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7355 } 7356 } 7357 } 7358 7359 // C++ [over.built]p15: 7360 // 7361 // For every T, where T is an enumeration type, a pointer type, or 7362 // std::nullptr_t, there exist candidate operator functions of the form 7363 // 7364 // bool operator<(T, T); 7365 // bool operator>(T, T); 7366 // bool operator<=(T, T); 7367 // bool operator>=(T, T); 7368 // bool operator==(T, T); 7369 // bool operator!=(T, T); 7370 void addRelationalPointerOrEnumeralOverloads() { 7371 // C++ [over.match.oper]p3: 7372 // [...]the built-in candidates include all of the candidate operator 7373 // functions defined in 13.6 that, compared to the given operator, [...] 7374 // do not have the same parameter-type-list as any non-template non-member 7375 // candidate. 7376 // 7377 // Note that in practice, this only affects enumeration types because there 7378 // aren't any built-in candidates of record type, and a user-defined operator 7379 // must have an operand of record or enumeration type. Also, the only other 7380 // overloaded operator with enumeration arguments, operator=, 7381 // cannot be overloaded for enumeration types, so this is the only place 7382 // where we must suppress candidates like this. 7383 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7384 UserDefinedBinaryOperators; 7385 7386 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7387 if (CandidateTypes[ArgIdx].enumeration_begin() != 7388 CandidateTypes[ArgIdx].enumeration_end()) { 7389 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7390 CEnd = CandidateSet.end(); 7391 C != CEnd; ++C) { 7392 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7393 continue; 7394 7395 if (C->Function->isFunctionTemplateSpecialization()) 7396 continue; 7397 7398 QualType FirstParamType = 7399 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7400 QualType SecondParamType = 7401 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7402 7403 // Skip if either parameter isn't of enumeral type. 7404 if (!FirstParamType->isEnumeralType() || 7405 !SecondParamType->isEnumeralType()) 7406 continue; 7407 7408 // Add this operator to the set of known user-defined operators. 7409 UserDefinedBinaryOperators.insert( 7410 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7411 S.Context.getCanonicalType(SecondParamType))); 7412 } 7413 } 7414 } 7415 7416 /// Set of (canonical) types that we've already handled. 7417 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7418 7419 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7420 for (BuiltinCandidateTypeSet::iterator 7421 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7422 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7423 Ptr != PtrEnd; ++Ptr) { 7424 // Don't add the same builtin candidate twice. 7425 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7426 continue; 7427 7428 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7429 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7430 } 7431 for (BuiltinCandidateTypeSet::iterator 7432 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7433 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7434 Enum != EnumEnd; ++Enum) { 7435 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7436 7437 // Don't add the same builtin candidate twice, or if a user defined 7438 // candidate exists. 7439 if (!AddedTypes.insert(CanonType) || 7440 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7441 CanonType))) 7442 continue; 7443 7444 QualType ParamTypes[2] = { *Enum, *Enum }; 7445 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7446 } 7447 7448 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7449 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7450 if (AddedTypes.insert(NullPtrTy) && 7451 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7452 NullPtrTy))) { 7453 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7454 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7455 CandidateSet); 7456 } 7457 } 7458 } 7459 } 7460 7461 // C++ [over.built]p13: 7462 // 7463 // For every cv-qualified or cv-unqualified object type T 7464 // there exist candidate operator functions of the form 7465 // 7466 // T* operator+(T*, ptrdiff_t); 7467 // T& operator[](T*, ptrdiff_t); [BELOW] 7468 // T* operator-(T*, ptrdiff_t); 7469 // T* operator+(ptrdiff_t, T*); 7470 // T& operator[](ptrdiff_t, T*); [BELOW] 7471 // 7472 // C++ [over.built]p14: 7473 // 7474 // For every T, where T is a pointer to object type, there 7475 // exist candidate operator functions of the form 7476 // 7477 // ptrdiff_t operator-(T, T); 7478 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7479 /// Set of (canonical) types that we've already handled. 7480 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7481 7482 for (int Arg = 0; Arg < 2; ++Arg) { 7483 QualType AsymetricParamTypes[2] = { 7484 S.Context.getPointerDiffType(), 7485 S.Context.getPointerDiffType(), 7486 }; 7487 for (BuiltinCandidateTypeSet::iterator 7488 Ptr = CandidateTypes[Arg].pointer_begin(), 7489 PtrEnd = CandidateTypes[Arg].pointer_end(); 7490 Ptr != PtrEnd; ++Ptr) { 7491 QualType PointeeTy = (*Ptr)->getPointeeType(); 7492 if (!PointeeTy->isObjectType()) 7493 continue; 7494 7495 AsymetricParamTypes[Arg] = *Ptr; 7496 if (Arg == 0 || Op == OO_Plus) { 7497 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7498 // T* operator+(ptrdiff_t, T*); 7499 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7500 } 7501 if (Op == OO_Minus) { 7502 // ptrdiff_t operator-(T, T); 7503 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7504 continue; 7505 7506 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7507 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7508 Args, CandidateSet); 7509 } 7510 } 7511 } 7512 } 7513 7514 // C++ [over.built]p12: 7515 // 7516 // For every pair of promoted arithmetic types L and R, there 7517 // exist candidate operator functions of the form 7518 // 7519 // LR operator*(L, R); 7520 // LR operator/(L, R); 7521 // LR operator+(L, R); 7522 // LR operator-(L, R); 7523 // bool operator<(L, R); 7524 // bool operator>(L, R); 7525 // bool operator<=(L, R); 7526 // bool operator>=(L, R); 7527 // bool operator==(L, R); 7528 // bool operator!=(L, R); 7529 // 7530 // where LR is the result of the usual arithmetic conversions 7531 // between types L and R. 7532 // 7533 // C++ [over.built]p24: 7534 // 7535 // For every pair of promoted arithmetic types L and R, there exist 7536 // candidate operator functions of the form 7537 // 7538 // LR operator?(bool, L, R); 7539 // 7540 // where LR is the result of the usual arithmetic conversions 7541 // between types L and R. 7542 // Our candidates ignore the first parameter. 7543 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7544 if (!HasArithmeticOrEnumeralCandidateType) 7545 return; 7546 7547 for (unsigned Left = FirstPromotedArithmeticType; 7548 Left < LastPromotedArithmeticType; ++Left) { 7549 for (unsigned Right = FirstPromotedArithmeticType; 7550 Right < LastPromotedArithmeticType; ++Right) { 7551 QualType LandR[2] = { getArithmeticType(Left), 7552 getArithmeticType(Right) }; 7553 QualType Result = 7554 isComparison ? S.Context.BoolTy 7555 : getUsualArithmeticConversions(Left, Right); 7556 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7557 } 7558 } 7559 7560 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7561 // conditional operator for vector types. 7562 for (BuiltinCandidateTypeSet::iterator 7563 Vec1 = CandidateTypes[0].vector_begin(), 7564 Vec1End = CandidateTypes[0].vector_end(); 7565 Vec1 != Vec1End; ++Vec1) { 7566 for (BuiltinCandidateTypeSet::iterator 7567 Vec2 = CandidateTypes[1].vector_begin(), 7568 Vec2End = CandidateTypes[1].vector_end(); 7569 Vec2 != Vec2End; ++Vec2) { 7570 QualType LandR[2] = { *Vec1, *Vec2 }; 7571 QualType Result = S.Context.BoolTy; 7572 if (!isComparison) { 7573 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7574 Result = *Vec1; 7575 else 7576 Result = *Vec2; 7577 } 7578 7579 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7580 } 7581 } 7582 } 7583 7584 // C++ [over.built]p17: 7585 // 7586 // For every pair of promoted integral types L and R, there 7587 // exist candidate operator functions of the form 7588 // 7589 // LR operator%(L, R); 7590 // LR operator&(L, R); 7591 // LR operator^(L, R); 7592 // LR operator|(L, R); 7593 // L operator<<(L, R); 7594 // L operator>>(L, R); 7595 // 7596 // where LR is the result of the usual arithmetic conversions 7597 // between types L and R. 7598 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7599 if (!HasArithmeticOrEnumeralCandidateType) 7600 return; 7601 7602 for (unsigned Left = FirstPromotedIntegralType; 7603 Left < LastPromotedIntegralType; ++Left) { 7604 for (unsigned Right = FirstPromotedIntegralType; 7605 Right < LastPromotedIntegralType; ++Right) { 7606 QualType LandR[2] = { getArithmeticType(Left), 7607 getArithmeticType(Right) }; 7608 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7609 ? LandR[0] 7610 : getUsualArithmeticConversions(Left, Right); 7611 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7612 } 7613 } 7614 } 7615 7616 // C++ [over.built]p20: 7617 // 7618 // For every pair (T, VQ), where T is an enumeration or 7619 // pointer to member type and VQ is either volatile or 7620 // empty, there exist candidate operator functions of the form 7621 // 7622 // VQ T& operator=(VQ T&, T); 7623 void addAssignmentMemberPointerOrEnumeralOverloads() { 7624 /// Set of (canonical) types that we've already handled. 7625 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7626 7627 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7628 for (BuiltinCandidateTypeSet::iterator 7629 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7630 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7631 Enum != EnumEnd; ++Enum) { 7632 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7633 continue; 7634 7635 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7636 } 7637 7638 for (BuiltinCandidateTypeSet::iterator 7639 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7640 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7641 MemPtr != MemPtrEnd; ++MemPtr) { 7642 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7643 continue; 7644 7645 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7646 } 7647 } 7648 } 7649 7650 // C++ [over.built]p19: 7651 // 7652 // For every pair (T, VQ), where T is any type and VQ is either 7653 // volatile or empty, there exist candidate operator functions 7654 // of the form 7655 // 7656 // T*VQ& operator=(T*VQ&, T*); 7657 // 7658 // C++ [over.built]p21: 7659 // 7660 // For every pair (T, VQ), where T is a cv-qualified or 7661 // cv-unqualified object type and VQ is either volatile or 7662 // empty, there exist candidate operator functions of the form 7663 // 7664 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7665 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7666 void addAssignmentPointerOverloads(bool isEqualOp) { 7667 /// Set of (canonical) types that we've already handled. 7668 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7669 7670 for (BuiltinCandidateTypeSet::iterator 7671 Ptr = CandidateTypes[0].pointer_begin(), 7672 PtrEnd = CandidateTypes[0].pointer_end(); 7673 Ptr != PtrEnd; ++Ptr) { 7674 // If this is operator=, keep track of the builtin candidates we added. 7675 if (isEqualOp) 7676 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7677 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7678 continue; 7679 7680 // non-volatile version 7681 QualType ParamTypes[2] = { 7682 S.Context.getLValueReferenceType(*Ptr), 7683 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7684 }; 7685 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7686 /*IsAssigmentOperator=*/ isEqualOp); 7687 7688 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7689 VisibleTypeConversionsQuals.hasVolatile(); 7690 if (NeedVolatile) { 7691 // volatile version 7692 ParamTypes[0] = 7693 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7695 /*IsAssigmentOperator=*/isEqualOp); 7696 } 7697 7698 if (!(*Ptr).isRestrictQualified() && 7699 VisibleTypeConversionsQuals.hasRestrict()) { 7700 // restrict version 7701 ParamTypes[0] 7702 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7703 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7704 /*IsAssigmentOperator=*/isEqualOp); 7705 7706 if (NeedVolatile) { 7707 // volatile restrict version 7708 ParamTypes[0] 7709 = S.Context.getLValueReferenceType( 7710 S.Context.getCVRQualifiedType(*Ptr, 7711 (Qualifiers::Volatile | 7712 Qualifiers::Restrict))); 7713 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7714 /*IsAssigmentOperator=*/isEqualOp); 7715 } 7716 } 7717 } 7718 7719 if (isEqualOp) { 7720 for (BuiltinCandidateTypeSet::iterator 7721 Ptr = CandidateTypes[1].pointer_begin(), 7722 PtrEnd = CandidateTypes[1].pointer_end(); 7723 Ptr != PtrEnd; ++Ptr) { 7724 // Make sure we don't add the same candidate twice. 7725 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7726 continue; 7727 7728 QualType ParamTypes[2] = { 7729 S.Context.getLValueReferenceType(*Ptr), 7730 *Ptr, 7731 }; 7732 7733 // non-volatile version 7734 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7735 /*IsAssigmentOperator=*/true); 7736 7737 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7738 VisibleTypeConversionsQuals.hasVolatile(); 7739 if (NeedVolatile) { 7740 // volatile version 7741 ParamTypes[0] = 7742 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7743 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7744 /*IsAssigmentOperator=*/true); 7745 } 7746 7747 if (!(*Ptr).isRestrictQualified() && 7748 VisibleTypeConversionsQuals.hasRestrict()) { 7749 // restrict version 7750 ParamTypes[0] 7751 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7752 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7753 /*IsAssigmentOperator=*/true); 7754 7755 if (NeedVolatile) { 7756 // volatile restrict version 7757 ParamTypes[0] 7758 = S.Context.getLValueReferenceType( 7759 S.Context.getCVRQualifiedType(*Ptr, 7760 (Qualifiers::Volatile | 7761 Qualifiers::Restrict))); 7762 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7763 /*IsAssigmentOperator=*/true); 7764 } 7765 } 7766 } 7767 } 7768 } 7769 7770 // C++ [over.built]p18: 7771 // 7772 // For every triple (L, VQ, R), where L is an arithmetic type, 7773 // VQ is either volatile or empty, and R is a promoted 7774 // arithmetic type, there exist candidate operator functions of 7775 // the form 7776 // 7777 // VQ L& operator=(VQ L&, R); 7778 // VQ L& operator*=(VQ L&, R); 7779 // VQ L& operator/=(VQ L&, R); 7780 // VQ L& operator+=(VQ L&, R); 7781 // VQ L& operator-=(VQ L&, R); 7782 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7783 if (!HasArithmeticOrEnumeralCandidateType) 7784 return; 7785 7786 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7787 for (unsigned Right = FirstPromotedArithmeticType; 7788 Right < LastPromotedArithmeticType; ++Right) { 7789 QualType ParamTypes[2]; 7790 ParamTypes[1] = getArithmeticType(Right); 7791 7792 // Add this built-in operator as a candidate (VQ is empty). 7793 ParamTypes[0] = 7794 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7795 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7796 /*IsAssigmentOperator=*/isEqualOp); 7797 7798 // Add this built-in operator as a candidate (VQ is 'volatile'). 7799 if (VisibleTypeConversionsQuals.hasVolatile()) { 7800 ParamTypes[0] = 7801 S.Context.getVolatileType(getArithmeticType(Left)); 7802 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7803 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7804 /*IsAssigmentOperator=*/isEqualOp); 7805 } 7806 } 7807 } 7808 7809 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7810 for (BuiltinCandidateTypeSet::iterator 7811 Vec1 = CandidateTypes[0].vector_begin(), 7812 Vec1End = CandidateTypes[0].vector_end(); 7813 Vec1 != Vec1End; ++Vec1) { 7814 for (BuiltinCandidateTypeSet::iterator 7815 Vec2 = CandidateTypes[1].vector_begin(), 7816 Vec2End = CandidateTypes[1].vector_end(); 7817 Vec2 != Vec2End; ++Vec2) { 7818 QualType ParamTypes[2]; 7819 ParamTypes[1] = *Vec2; 7820 // Add this built-in operator as a candidate (VQ is empty). 7821 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7823 /*IsAssigmentOperator=*/isEqualOp); 7824 7825 // Add this built-in operator as a candidate (VQ is 'volatile'). 7826 if (VisibleTypeConversionsQuals.hasVolatile()) { 7827 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7828 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7829 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7830 /*IsAssigmentOperator=*/isEqualOp); 7831 } 7832 } 7833 } 7834 } 7835 7836 // C++ [over.built]p22: 7837 // 7838 // For every triple (L, VQ, R), where L is an integral type, VQ 7839 // is either volatile or empty, and R is a promoted integral 7840 // type, there exist candidate operator functions of the form 7841 // 7842 // VQ L& operator%=(VQ L&, R); 7843 // VQ L& operator<<=(VQ L&, R); 7844 // VQ L& operator>>=(VQ L&, R); 7845 // VQ L& operator&=(VQ L&, R); 7846 // VQ L& operator^=(VQ L&, R); 7847 // VQ L& operator|=(VQ L&, R); 7848 void addAssignmentIntegralOverloads() { 7849 if (!HasArithmeticOrEnumeralCandidateType) 7850 return; 7851 7852 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7853 for (unsigned Right = FirstPromotedIntegralType; 7854 Right < LastPromotedIntegralType; ++Right) { 7855 QualType ParamTypes[2]; 7856 ParamTypes[1] = getArithmeticType(Right); 7857 7858 // Add this built-in operator as a candidate (VQ is empty). 7859 ParamTypes[0] = 7860 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7861 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7862 if (VisibleTypeConversionsQuals.hasVolatile()) { 7863 // Add this built-in operator as a candidate (VQ is 'volatile'). 7864 ParamTypes[0] = getArithmeticType(Left); 7865 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7866 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7867 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7868 } 7869 } 7870 } 7871 } 7872 7873 // C++ [over.operator]p23: 7874 // 7875 // There also exist candidate operator functions of the form 7876 // 7877 // bool operator!(bool); 7878 // bool operator&&(bool, bool); 7879 // bool operator||(bool, bool); 7880 void addExclaimOverload() { 7881 QualType ParamTy = S.Context.BoolTy; 7882 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7883 /*IsAssignmentOperator=*/false, 7884 /*NumContextualBoolArguments=*/1); 7885 } 7886 void addAmpAmpOrPipePipeOverload() { 7887 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7888 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7889 /*IsAssignmentOperator=*/false, 7890 /*NumContextualBoolArguments=*/2); 7891 } 7892 7893 // C++ [over.built]p13: 7894 // 7895 // For every cv-qualified or cv-unqualified object type T there 7896 // exist candidate operator functions of the form 7897 // 7898 // T* operator+(T*, ptrdiff_t); [ABOVE] 7899 // T& operator[](T*, ptrdiff_t); 7900 // T* operator-(T*, ptrdiff_t); [ABOVE] 7901 // T* operator+(ptrdiff_t, T*); [ABOVE] 7902 // T& operator[](ptrdiff_t, T*); 7903 void addSubscriptOverloads() { 7904 for (BuiltinCandidateTypeSet::iterator 7905 Ptr = CandidateTypes[0].pointer_begin(), 7906 PtrEnd = CandidateTypes[0].pointer_end(); 7907 Ptr != PtrEnd; ++Ptr) { 7908 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7909 QualType PointeeType = (*Ptr)->getPointeeType(); 7910 if (!PointeeType->isObjectType()) 7911 continue; 7912 7913 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7914 7915 // T& operator[](T*, ptrdiff_t) 7916 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7917 } 7918 7919 for (BuiltinCandidateTypeSet::iterator 7920 Ptr = CandidateTypes[1].pointer_begin(), 7921 PtrEnd = CandidateTypes[1].pointer_end(); 7922 Ptr != PtrEnd; ++Ptr) { 7923 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7924 QualType PointeeType = (*Ptr)->getPointeeType(); 7925 if (!PointeeType->isObjectType()) 7926 continue; 7927 7928 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7929 7930 // T& operator[](ptrdiff_t, T*) 7931 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7932 } 7933 } 7934 7935 // C++ [over.built]p11: 7936 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7937 // C1 is the same type as C2 or is a derived class of C2, T is an object 7938 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7939 // there exist candidate operator functions of the form 7940 // 7941 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7942 // 7943 // where CV12 is the union of CV1 and CV2. 7944 void addArrowStarOverloads() { 7945 for (BuiltinCandidateTypeSet::iterator 7946 Ptr = CandidateTypes[0].pointer_begin(), 7947 PtrEnd = CandidateTypes[0].pointer_end(); 7948 Ptr != PtrEnd; ++Ptr) { 7949 QualType C1Ty = (*Ptr); 7950 QualType C1; 7951 QualifierCollector Q1; 7952 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7953 if (!isa<RecordType>(C1)) 7954 continue; 7955 // heuristic to reduce number of builtin candidates in the set. 7956 // Add volatile/restrict version only if there are conversions to a 7957 // volatile/restrict type. 7958 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7959 continue; 7960 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7961 continue; 7962 for (BuiltinCandidateTypeSet::iterator 7963 MemPtr = CandidateTypes[1].member_pointer_begin(), 7964 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7965 MemPtr != MemPtrEnd; ++MemPtr) { 7966 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7967 QualType C2 = QualType(mptr->getClass(), 0); 7968 C2 = C2.getUnqualifiedType(); 7969 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7970 break; 7971 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7972 // build CV12 T& 7973 QualType T = mptr->getPointeeType(); 7974 if (!VisibleTypeConversionsQuals.hasVolatile() && 7975 T.isVolatileQualified()) 7976 continue; 7977 if (!VisibleTypeConversionsQuals.hasRestrict() && 7978 T.isRestrictQualified()) 7979 continue; 7980 T = Q1.apply(S.Context, T); 7981 QualType ResultTy = S.Context.getLValueReferenceType(T); 7982 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7983 } 7984 } 7985 } 7986 7987 // Note that we don't consider the first argument, since it has been 7988 // contextually converted to bool long ago. The candidates below are 7989 // therefore added as binary. 7990 // 7991 // C++ [over.built]p25: 7992 // For every type T, where T is a pointer, pointer-to-member, or scoped 7993 // enumeration type, there exist candidate operator functions of the form 7994 // 7995 // T operator?(bool, T, T); 7996 // 7997 void addConditionalOperatorOverloads() { 7998 /// Set of (canonical) types that we've already handled. 7999 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8000 8001 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8002 for (BuiltinCandidateTypeSet::iterator 8003 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8004 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8005 Ptr != PtrEnd; ++Ptr) { 8006 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 8007 continue; 8008 8009 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8010 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8011 } 8012 8013 for (BuiltinCandidateTypeSet::iterator 8014 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8015 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8016 MemPtr != MemPtrEnd; ++MemPtr) { 8017 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 8018 continue; 8019 8020 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8021 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8022 } 8023 8024 if (S.getLangOpts().CPlusPlus11) { 8025 for (BuiltinCandidateTypeSet::iterator 8026 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8027 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8028 Enum != EnumEnd; ++Enum) { 8029 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8030 continue; 8031 8032 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 8033 continue; 8034 8035 QualType ParamTypes[2] = { *Enum, *Enum }; 8036 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8037 } 8038 } 8039 } 8040 } 8041 }; 8042 8043 } // end anonymous namespace 8044 8045 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8046 /// operator overloads to the candidate set (C++ [over.built]), based 8047 /// on the operator @p Op and the arguments given. For example, if the 8048 /// operator is a binary '+', this routine might add "int 8049 /// operator+(int, int)" to cover integer addition. 8050 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8051 SourceLocation OpLoc, 8052 ArrayRef<Expr *> Args, 8053 OverloadCandidateSet &CandidateSet) { 8054 // Find all of the types that the arguments can convert to, but only 8055 // if the operator we're looking at has built-in operator candidates 8056 // that make use of these types. Also record whether we encounter non-record 8057 // candidate types or either arithmetic or enumeral candidate types. 8058 Qualifiers VisibleTypeConversionsQuals; 8059 VisibleTypeConversionsQuals.addConst(); 8060 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8061 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8062 8063 bool HasNonRecordCandidateType = false; 8064 bool HasArithmeticOrEnumeralCandidateType = false; 8065 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8066 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8067 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 8068 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8069 OpLoc, 8070 true, 8071 (Op == OO_Exclaim || 8072 Op == OO_AmpAmp || 8073 Op == OO_PipePipe), 8074 VisibleTypeConversionsQuals); 8075 HasNonRecordCandidateType = HasNonRecordCandidateType || 8076 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8077 HasArithmeticOrEnumeralCandidateType = 8078 HasArithmeticOrEnumeralCandidateType || 8079 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8080 } 8081 8082 // Exit early when no non-record types have been added to the candidate set 8083 // for any of the arguments to the operator. 8084 // 8085 // We can't exit early for !, ||, or &&, since there we have always have 8086 // 'bool' overloads. 8087 if (!HasNonRecordCandidateType && 8088 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8089 return; 8090 8091 // Setup an object to manage the common state for building overloads. 8092 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8093 VisibleTypeConversionsQuals, 8094 HasArithmeticOrEnumeralCandidateType, 8095 CandidateTypes, CandidateSet); 8096 8097 // Dispatch over the operation to add in only those overloads which apply. 8098 switch (Op) { 8099 case OO_None: 8100 case NUM_OVERLOADED_OPERATORS: 8101 llvm_unreachable("Expected an overloaded operator"); 8102 8103 case OO_New: 8104 case OO_Delete: 8105 case OO_Array_New: 8106 case OO_Array_Delete: 8107 case OO_Call: 8108 llvm_unreachable( 8109 "Special operators don't use AddBuiltinOperatorCandidates"); 8110 8111 case OO_Comma: 8112 case OO_Arrow: 8113 // C++ [over.match.oper]p3: 8114 // -- For the operator ',', the unary operator '&', or the 8115 // operator '->', the built-in candidates set is empty. 8116 break; 8117 8118 case OO_Plus: // '+' is either unary or binary 8119 if (Args.size() == 1) 8120 OpBuilder.addUnaryPlusPointerOverloads(); 8121 // Fall through. 8122 8123 case OO_Minus: // '-' is either unary or binary 8124 if (Args.size() == 1) { 8125 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8126 } else { 8127 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8128 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8129 } 8130 break; 8131 8132 case OO_Star: // '*' is either unary or binary 8133 if (Args.size() == 1) 8134 OpBuilder.addUnaryStarPointerOverloads(); 8135 else 8136 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8137 break; 8138 8139 case OO_Slash: 8140 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8141 break; 8142 8143 case OO_PlusPlus: 8144 case OO_MinusMinus: 8145 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8146 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8147 break; 8148 8149 case OO_EqualEqual: 8150 case OO_ExclaimEqual: 8151 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8152 // Fall through. 8153 8154 case OO_Less: 8155 case OO_Greater: 8156 case OO_LessEqual: 8157 case OO_GreaterEqual: 8158 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8159 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8160 break; 8161 8162 case OO_Percent: 8163 case OO_Caret: 8164 case OO_Pipe: 8165 case OO_LessLess: 8166 case OO_GreaterGreater: 8167 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8168 break; 8169 8170 case OO_Amp: // '&' is either unary or binary 8171 if (Args.size() == 1) 8172 // C++ [over.match.oper]p3: 8173 // -- For the operator ',', the unary operator '&', or the 8174 // operator '->', the built-in candidates set is empty. 8175 break; 8176 8177 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8178 break; 8179 8180 case OO_Tilde: 8181 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8182 break; 8183 8184 case OO_Equal: 8185 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8186 // Fall through. 8187 8188 case OO_PlusEqual: 8189 case OO_MinusEqual: 8190 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8191 // Fall through. 8192 8193 case OO_StarEqual: 8194 case OO_SlashEqual: 8195 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8196 break; 8197 8198 case OO_PercentEqual: 8199 case OO_LessLessEqual: 8200 case OO_GreaterGreaterEqual: 8201 case OO_AmpEqual: 8202 case OO_CaretEqual: 8203 case OO_PipeEqual: 8204 OpBuilder.addAssignmentIntegralOverloads(); 8205 break; 8206 8207 case OO_Exclaim: 8208 OpBuilder.addExclaimOverload(); 8209 break; 8210 8211 case OO_AmpAmp: 8212 case OO_PipePipe: 8213 OpBuilder.addAmpAmpOrPipePipeOverload(); 8214 break; 8215 8216 case OO_Subscript: 8217 OpBuilder.addSubscriptOverloads(); 8218 break; 8219 8220 case OO_ArrowStar: 8221 OpBuilder.addArrowStarOverloads(); 8222 break; 8223 8224 case OO_Conditional: 8225 OpBuilder.addConditionalOperatorOverloads(); 8226 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8227 break; 8228 } 8229 } 8230 8231 /// \brief Add function candidates found via argument-dependent lookup 8232 /// to the set of overloading candidates. 8233 /// 8234 /// This routine performs argument-dependent name lookup based on the 8235 /// given function name (which may also be an operator name) and adds 8236 /// all of the overload candidates found by ADL to the overload 8237 /// candidate set (C++ [basic.lookup.argdep]). 8238 void 8239 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8240 SourceLocation Loc, 8241 ArrayRef<Expr *> Args, 8242 TemplateArgumentListInfo *ExplicitTemplateArgs, 8243 OverloadCandidateSet& CandidateSet, 8244 bool PartialOverloading) { 8245 ADLResult Fns; 8246 8247 // FIXME: This approach for uniquing ADL results (and removing 8248 // redundant candidates from the set) relies on pointer-equality, 8249 // which means we need to key off the canonical decl. However, 8250 // always going back to the canonical decl might not get us the 8251 // right set of default arguments. What default arguments are 8252 // we supposed to consider on ADL candidates, anyway? 8253 8254 // FIXME: Pass in the explicit template arguments? 8255 ArgumentDependentLookup(Name, Loc, Args, Fns); 8256 8257 // Erase all of the candidates we already knew about. 8258 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8259 CandEnd = CandidateSet.end(); 8260 Cand != CandEnd; ++Cand) 8261 if (Cand->Function) { 8262 Fns.erase(Cand->Function); 8263 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8264 Fns.erase(FunTmpl); 8265 } 8266 8267 // For each of the ADL candidates we found, add it to the overload 8268 // set. 8269 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8270 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8272 if (ExplicitTemplateArgs) 8273 continue; 8274 8275 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8276 PartialOverloading); 8277 } else 8278 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8279 FoundDecl, ExplicitTemplateArgs, 8280 Args, CandidateSet); 8281 } 8282 } 8283 8284 /// isBetterOverloadCandidate - Determines whether the first overload 8285 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8286 bool 8287 isBetterOverloadCandidate(Sema &S, 8288 const OverloadCandidate &Cand1, 8289 const OverloadCandidate &Cand2, 8290 SourceLocation Loc, 8291 bool UserDefinedConversion) { 8292 // Define viable functions to be better candidates than non-viable 8293 // functions. 8294 if (!Cand2.Viable) 8295 return Cand1.Viable; 8296 else if (!Cand1.Viable) 8297 return false; 8298 8299 // C++ [over.match.best]p1: 8300 // 8301 // -- if F is a static member function, ICS1(F) is defined such 8302 // that ICS1(F) is neither better nor worse than ICS1(G) for 8303 // any function G, and, symmetrically, ICS1(G) is neither 8304 // better nor worse than ICS1(F). 8305 unsigned StartArg = 0; 8306 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8307 StartArg = 1; 8308 8309 // C++ [over.match.best]p1: 8310 // A viable function F1 is defined to be a better function than another 8311 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8312 // conversion sequence than ICSi(F2), and then... 8313 unsigned NumArgs = Cand1.NumConversions; 8314 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8315 bool HasBetterConversion = false; 8316 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8317 switch (CompareImplicitConversionSequences(S, 8318 Cand1.Conversions[ArgIdx], 8319 Cand2.Conversions[ArgIdx])) { 8320 case ImplicitConversionSequence::Better: 8321 // Cand1 has a better conversion sequence. 8322 HasBetterConversion = true; 8323 break; 8324 8325 case ImplicitConversionSequence::Worse: 8326 // Cand1 can't be better than Cand2. 8327 return false; 8328 8329 case ImplicitConversionSequence::Indistinguishable: 8330 // Do nothing. 8331 break; 8332 } 8333 } 8334 8335 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8336 // ICSj(F2), or, if not that, 8337 if (HasBetterConversion) 8338 return true; 8339 8340 // -- the context is an initialization by user-defined conversion 8341 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8342 // from the return type of F1 to the destination type (i.e., 8343 // the type of the entity being initialized) is a better 8344 // conversion sequence than the standard conversion sequence 8345 // from the return type of F2 to the destination type. 8346 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8347 isa<CXXConversionDecl>(Cand1.Function) && 8348 isa<CXXConversionDecl>(Cand2.Function)) { 8349 // First check whether we prefer one of the conversion functions over the 8350 // other. This only distinguishes the results in non-standard, extension 8351 // cases such as the conversion from a lambda closure type to a function 8352 // pointer or block. 8353 ImplicitConversionSequence::CompareKind Result = 8354 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8355 if (Result == ImplicitConversionSequence::Indistinguishable) 8356 Result = CompareStandardConversionSequences(S, 8357 Cand1.FinalConversion, 8358 Cand2.FinalConversion); 8359 8360 if (Result != ImplicitConversionSequence::Indistinguishable) 8361 return Result == ImplicitConversionSequence::Better; 8362 8363 // FIXME: Compare kind of reference binding if conversion functions 8364 // convert to a reference type used in direct reference binding, per 8365 // C++14 [over.match.best]p1 section 2 bullet 3. 8366 } 8367 8368 // -- F1 is a non-template function and F2 is a function template 8369 // specialization, or, if not that, 8370 bool Cand1IsSpecialization = Cand1.Function && 8371 Cand1.Function->getPrimaryTemplate(); 8372 bool Cand2IsSpecialization = Cand2.Function && 8373 Cand2.Function->getPrimaryTemplate(); 8374 if (Cand1IsSpecialization != Cand2IsSpecialization) 8375 return Cand2IsSpecialization; 8376 8377 // -- F1 and F2 are function template specializations, and the function 8378 // template for F1 is more specialized than the template for F2 8379 // according to the partial ordering rules described in 14.5.5.2, or, 8380 // if not that, 8381 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8382 if (FunctionTemplateDecl *BetterTemplate 8383 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8384 Cand2.Function->getPrimaryTemplate(), 8385 Loc, 8386 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8387 : TPOC_Call, 8388 Cand1.ExplicitCallArguments, 8389 Cand2.ExplicitCallArguments)) 8390 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8391 } 8392 8393 // Check for enable_if value-based overload resolution. 8394 if (Cand1.Function && Cand2.Function && 8395 (Cand1.Function->hasAttr<EnableIfAttr>() || 8396 Cand2.Function->hasAttr<EnableIfAttr>())) { 8397 // FIXME: The next several lines are just 8398 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8399 // instead of reverse order which is how they're stored in the AST. 8400 AttrVec Cand1Attrs; 8401 if (Cand1.Function->hasAttrs()) { 8402 Cand1Attrs = Cand1.Function->getAttrs(); 8403 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8404 IsNotEnableIfAttr), 8405 Cand1Attrs.end()); 8406 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end()); 8407 } 8408 8409 AttrVec Cand2Attrs; 8410 if (Cand2.Function->hasAttrs()) { 8411 Cand2Attrs = Cand2.Function->getAttrs(); 8412 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8413 IsNotEnableIfAttr), 8414 Cand2Attrs.end()); 8415 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end()); 8416 } 8417 8418 // Candidate 1 is better if it has strictly more attributes and 8419 // the common sequence is identical. 8420 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8421 return false; 8422 8423 auto Cand1I = Cand1Attrs.begin(); 8424 for (auto &Cand2A : Cand2Attrs) { 8425 auto &Cand1A = *Cand1I++; 8426 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8427 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID, 8428 S.getASTContext(), true); 8429 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID, 8430 S.getASTContext(), true); 8431 if (Cand1ID != Cand2ID) 8432 return false; 8433 } 8434 8435 return true; 8436 } 8437 8438 return false; 8439 } 8440 8441 /// \brief Computes the best viable function (C++ 13.3.3) 8442 /// within an overload candidate set. 8443 /// 8444 /// \param Loc The location of the function name (or operator symbol) for 8445 /// which overload resolution occurs. 8446 /// 8447 /// \param Best If overload resolution was successful or found a deleted 8448 /// function, \p Best points to the candidate function found. 8449 /// 8450 /// \returns The result of overload resolution. 8451 OverloadingResult 8452 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8453 iterator &Best, 8454 bool UserDefinedConversion) { 8455 // Find the best viable function. 8456 Best = end(); 8457 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8458 if (Cand->Viable) 8459 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8460 UserDefinedConversion)) 8461 Best = Cand; 8462 } 8463 8464 // If we didn't find any viable functions, abort. 8465 if (Best == end()) 8466 return OR_No_Viable_Function; 8467 8468 // Make sure that this function is better than every other viable 8469 // function. If not, we have an ambiguity. 8470 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8471 if (Cand->Viable && 8472 Cand != Best && 8473 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8474 UserDefinedConversion)) { 8475 Best = end(); 8476 return OR_Ambiguous; 8477 } 8478 } 8479 8480 // Best is the best viable function. 8481 if (Best->Function && 8482 (Best->Function->isDeleted() || 8483 S.isFunctionConsideredUnavailable(Best->Function))) 8484 return OR_Deleted; 8485 8486 return OR_Success; 8487 } 8488 8489 namespace { 8490 8491 enum OverloadCandidateKind { 8492 oc_function, 8493 oc_method, 8494 oc_constructor, 8495 oc_function_template, 8496 oc_method_template, 8497 oc_constructor_template, 8498 oc_implicit_default_constructor, 8499 oc_implicit_copy_constructor, 8500 oc_implicit_move_constructor, 8501 oc_implicit_copy_assignment, 8502 oc_implicit_move_assignment, 8503 oc_implicit_inherited_constructor 8504 }; 8505 8506 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8507 FunctionDecl *Fn, 8508 std::string &Description) { 8509 bool isTemplate = false; 8510 8511 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8512 isTemplate = true; 8513 Description = S.getTemplateArgumentBindingsText( 8514 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8515 } 8516 8517 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8518 if (!Ctor->isImplicit()) 8519 return isTemplate ? oc_constructor_template : oc_constructor; 8520 8521 if (Ctor->getInheritedConstructor()) 8522 return oc_implicit_inherited_constructor; 8523 8524 if (Ctor->isDefaultConstructor()) 8525 return oc_implicit_default_constructor; 8526 8527 if (Ctor->isMoveConstructor()) 8528 return oc_implicit_move_constructor; 8529 8530 assert(Ctor->isCopyConstructor() && 8531 "unexpected sort of implicit constructor"); 8532 return oc_implicit_copy_constructor; 8533 } 8534 8535 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8536 // This actually gets spelled 'candidate function' for now, but 8537 // it doesn't hurt to split it out. 8538 if (!Meth->isImplicit()) 8539 return isTemplate ? oc_method_template : oc_method; 8540 8541 if (Meth->isMoveAssignmentOperator()) 8542 return oc_implicit_move_assignment; 8543 8544 if (Meth->isCopyAssignmentOperator()) 8545 return oc_implicit_copy_assignment; 8546 8547 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8548 return oc_method; 8549 } 8550 8551 return isTemplate ? oc_function_template : oc_function; 8552 } 8553 8554 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8555 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8556 if (!Ctor) return; 8557 8558 Ctor = Ctor->getInheritedConstructor(); 8559 if (!Ctor) return; 8560 8561 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8562 } 8563 8564 } // end anonymous namespace 8565 8566 // Notes the location of an overload candidate. 8567 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8568 std::string FnDesc; 8569 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8570 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8571 << (unsigned) K << FnDesc; 8572 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8573 Diag(Fn->getLocation(), PD); 8574 MaybeEmitInheritedConstructorNote(*this, Fn); 8575 } 8576 8577 // Notes the location of all overload candidates designated through 8578 // OverloadedExpr 8579 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8580 assert(OverloadedExpr->getType() == Context.OverloadTy); 8581 8582 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8583 OverloadExpr *OvlExpr = Ovl.Expression; 8584 8585 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8586 IEnd = OvlExpr->decls_end(); 8587 I != IEnd; ++I) { 8588 if (FunctionTemplateDecl *FunTmpl = 8589 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8590 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8591 } else if (FunctionDecl *Fun 8592 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8593 NoteOverloadCandidate(Fun, DestType); 8594 } 8595 } 8596 } 8597 8598 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8599 /// "lead" diagnostic; it will be given two arguments, the source and 8600 /// target types of the conversion. 8601 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8602 Sema &S, 8603 SourceLocation CaretLoc, 8604 const PartialDiagnostic &PDiag) const { 8605 S.Diag(CaretLoc, PDiag) 8606 << Ambiguous.getFromType() << Ambiguous.getToType(); 8607 // FIXME: The note limiting machinery is borrowed from 8608 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8609 // refactoring here. 8610 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8611 unsigned CandsShown = 0; 8612 AmbiguousConversionSequence::const_iterator I, E; 8613 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8614 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8615 break; 8616 ++CandsShown; 8617 S.NoteOverloadCandidate(*I); 8618 } 8619 if (I != E) 8620 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8621 } 8622 8623 namespace { 8624 8625 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8626 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8627 assert(Conv.isBad()); 8628 assert(Cand->Function && "for now, candidate must be a function"); 8629 FunctionDecl *Fn = Cand->Function; 8630 8631 // There's a conversion slot for the object argument if this is a 8632 // non-constructor method. Note that 'I' corresponds the 8633 // conversion-slot index. 8634 bool isObjectArgument = false; 8635 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8636 if (I == 0) 8637 isObjectArgument = true; 8638 else 8639 I--; 8640 } 8641 8642 std::string FnDesc; 8643 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8644 8645 Expr *FromExpr = Conv.Bad.FromExpr; 8646 QualType FromTy = Conv.Bad.getFromType(); 8647 QualType ToTy = Conv.Bad.getToType(); 8648 8649 if (FromTy == S.Context.OverloadTy) { 8650 assert(FromExpr && "overload set argument came from implicit argument?"); 8651 Expr *E = FromExpr->IgnoreParens(); 8652 if (isa<UnaryOperator>(E)) 8653 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8654 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8655 8656 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8657 << (unsigned) FnKind << FnDesc 8658 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8659 << ToTy << Name << I+1; 8660 MaybeEmitInheritedConstructorNote(S, Fn); 8661 return; 8662 } 8663 8664 // Do some hand-waving analysis to see if the non-viability is due 8665 // to a qualifier mismatch. 8666 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8667 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8668 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8669 CToTy = RT->getPointeeType(); 8670 else { 8671 // TODO: detect and diagnose the full richness of const mismatches. 8672 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8673 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8674 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8675 } 8676 8677 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8678 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8679 Qualifiers FromQs = CFromTy.getQualifiers(); 8680 Qualifiers ToQs = CToTy.getQualifiers(); 8681 8682 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8684 << (unsigned) FnKind << FnDesc 8685 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8686 << FromTy 8687 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8688 << (unsigned) isObjectArgument << I+1; 8689 MaybeEmitInheritedConstructorNote(S, Fn); 8690 return; 8691 } 8692 8693 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8694 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8695 << (unsigned) FnKind << FnDesc 8696 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8697 << FromTy 8698 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8699 << (unsigned) isObjectArgument << I+1; 8700 MaybeEmitInheritedConstructorNote(S, Fn); 8701 return; 8702 } 8703 8704 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8705 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8706 << (unsigned) FnKind << FnDesc 8707 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8708 << FromTy 8709 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8710 << (unsigned) isObjectArgument << I+1; 8711 MaybeEmitInheritedConstructorNote(S, Fn); 8712 return; 8713 } 8714 8715 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8716 assert(CVR && "unexpected qualifiers mismatch"); 8717 8718 if (isObjectArgument) { 8719 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8720 << (unsigned) FnKind << FnDesc 8721 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8722 << FromTy << (CVR - 1); 8723 } else { 8724 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8725 << (unsigned) FnKind << FnDesc 8726 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8727 << FromTy << (CVR - 1) << I+1; 8728 } 8729 MaybeEmitInheritedConstructorNote(S, Fn); 8730 return; 8731 } 8732 8733 // Special diagnostic for failure to convert an initializer list, since 8734 // telling the user that it has type void is not useful. 8735 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8736 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8737 << (unsigned) FnKind << FnDesc 8738 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8739 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8740 MaybeEmitInheritedConstructorNote(S, Fn); 8741 return; 8742 } 8743 8744 // Diagnose references or pointers to incomplete types differently, 8745 // since it's far from impossible that the incompleteness triggered 8746 // the failure. 8747 QualType TempFromTy = FromTy.getNonReferenceType(); 8748 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8749 TempFromTy = PTy->getPointeeType(); 8750 if (TempFromTy->isIncompleteType()) { 8751 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8752 << (unsigned) FnKind << FnDesc 8753 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8754 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8755 MaybeEmitInheritedConstructorNote(S, Fn); 8756 return; 8757 } 8758 8759 // Diagnose base -> derived pointer conversions. 8760 unsigned BaseToDerivedConversion = 0; 8761 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8762 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8763 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8764 FromPtrTy->getPointeeType()) && 8765 !FromPtrTy->getPointeeType()->isIncompleteType() && 8766 !ToPtrTy->getPointeeType()->isIncompleteType() && 8767 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8768 FromPtrTy->getPointeeType())) 8769 BaseToDerivedConversion = 1; 8770 } 8771 } else if (const ObjCObjectPointerType *FromPtrTy 8772 = FromTy->getAs<ObjCObjectPointerType>()) { 8773 if (const ObjCObjectPointerType *ToPtrTy 8774 = ToTy->getAs<ObjCObjectPointerType>()) 8775 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8776 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8777 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8778 FromPtrTy->getPointeeType()) && 8779 FromIface->isSuperClassOf(ToIface)) 8780 BaseToDerivedConversion = 2; 8781 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8782 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8783 !FromTy->isIncompleteType() && 8784 !ToRefTy->getPointeeType()->isIncompleteType() && 8785 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8786 BaseToDerivedConversion = 3; 8787 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8788 ToTy.getNonReferenceType().getCanonicalType() == 8789 FromTy.getNonReferenceType().getCanonicalType()) { 8790 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8791 << (unsigned) FnKind << FnDesc 8792 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8793 << (unsigned) isObjectArgument << I + 1; 8794 MaybeEmitInheritedConstructorNote(S, Fn); 8795 return; 8796 } 8797 } 8798 8799 if (BaseToDerivedConversion) { 8800 S.Diag(Fn->getLocation(), 8801 diag::note_ovl_candidate_bad_base_to_derived_conv) 8802 << (unsigned) FnKind << FnDesc 8803 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8804 << (BaseToDerivedConversion - 1) 8805 << FromTy << ToTy << I+1; 8806 MaybeEmitInheritedConstructorNote(S, Fn); 8807 return; 8808 } 8809 8810 if (isa<ObjCObjectPointerType>(CFromTy) && 8811 isa<PointerType>(CToTy)) { 8812 Qualifiers FromQs = CFromTy.getQualifiers(); 8813 Qualifiers ToQs = CToTy.getQualifiers(); 8814 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8815 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8816 << (unsigned) FnKind << FnDesc 8817 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8818 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8819 MaybeEmitInheritedConstructorNote(S, Fn); 8820 return; 8821 } 8822 } 8823 8824 // Emit the generic diagnostic and, optionally, add the hints to it. 8825 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8826 FDiag << (unsigned) FnKind << FnDesc 8827 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8828 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8829 << (unsigned) (Cand->Fix.Kind); 8830 8831 // If we can fix the conversion, suggest the FixIts. 8832 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8833 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8834 FDiag << *HI; 8835 S.Diag(Fn->getLocation(), FDiag); 8836 8837 MaybeEmitInheritedConstructorNote(S, Fn); 8838 } 8839 8840 /// Additional arity mismatch diagnosis specific to a function overload 8841 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8842 /// over a candidate in any candidate set. 8843 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8844 unsigned NumArgs) { 8845 FunctionDecl *Fn = Cand->Function; 8846 unsigned MinParams = Fn->getMinRequiredArguments(); 8847 8848 // With invalid overloaded operators, it's possible that we think we 8849 // have an arity mismatch when in fact it looks like we have the 8850 // right number of arguments, because only overloaded operators have 8851 // the weird behavior of overloading member and non-member functions. 8852 // Just don't report anything. 8853 if (Fn->isInvalidDecl() && 8854 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8855 return true; 8856 8857 if (NumArgs < MinParams) { 8858 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8859 (Cand->FailureKind == ovl_fail_bad_deduction && 8860 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8861 } else { 8862 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8863 (Cand->FailureKind == ovl_fail_bad_deduction && 8864 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8865 } 8866 8867 return false; 8868 } 8869 8870 /// General arity mismatch diagnosis over a candidate in a candidate set. 8871 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8872 assert(isa<FunctionDecl>(D) && 8873 "The templated declaration should at least be a function" 8874 " when diagnosing bad template argument deduction due to too many" 8875 " or too few arguments"); 8876 8877 FunctionDecl *Fn = cast<FunctionDecl>(D); 8878 8879 // TODO: treat calls to a missing default constructor as a special case 8880 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8881 unsigned MinParams = Fn->getMinRequiredArguments(); 8882 8883 // at least / at most / exactly 8884 unsigned mode, modeCount; 8885 if (NumFormalArgs < MinParams) { 8886 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8887 FnTy->isTemplateVariadic()) 8888 mode = 0; // "at least" 8889 else 8890 mode = 2; // "exactly" 8891 modeCount = MinParams; 8892 } else { 8893 if (MinParams != FnTy->getNumParams()) 8894 mode = 1; // "at most" 8895 else 8896 mode = 2; // "exactly" 8897 modeCount = FnTy->getNumParams(); 8898 } 8899 8900 std::string Description; 8901 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8902 8903 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8905 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8906 << mode << Fn->getParamDecl(0) << NumFormalArgs; 8907 else 8908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8909 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8910 << mode << modeCount << NumFormalArgs; 8911 MaybeEmitInheritedConstructorNote(S, Fn); 8912 } 8913 8914 /// Arity mismatch diagnosis specific to a function overload candidate. 8915 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8916 unsigned NumFormalArgs) { 8917 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8918 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8919 } 8920 8921 TemplateDecl *getDescribedTemplate(Decl *Templated) { 8922 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8923 return FD->getDescribedFunctionTemplate(); 8924 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8925 return RD->getDescribedClassTemplate(); 8926 8927 llvm_unreachable("Unsupported: Getting the described template declaration" 8928 " for bad deduction diagnosis"); 8929 } 8930 8931 /// Diagnose a failed template-argument deduction. 8932 void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8933 DeductionFailureInfo &DeductionFailure, 8934 unsigned NumArgs) { 8935 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8936 NamedDecl *ParamD; 8937 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8938 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8939 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8940 switch (DeductionFailure.Result) { 8941 case Sema::TDK_Success: 8942 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8943 8944 case Sema::TDK_Incomplete: { 8945 assert(ParamD && "no parameter found for incomplete deduction result"); 8946 S.Diag(Templated->getLocation(), 8947 diag::note_ovl_candidate_incomplete_deduction) 8948 << ParamD->getDeclName(); 8949 MaybeEmitInheritedConstructorNote(S, Templated); 8950 return; 8951 } 8952 8953 case Sema::TDK_Underqualified: { 8954 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8955 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8956 8957 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8958 8959 // Param will have been canonicalized, but it should just be a 8960 // qualified version of ParamD, so move the qualifiers to that. 8961 QualifierCollector Qs; 8962 Qs.strip(Param); 8963 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8964 assert(S.Context.hasSameType(Param, NonCanonParam)); 8965 8966 // Arg has also been canonicalized, but there's nothing we can do 8967 // about that. It also doesn't matter as much, because it won't 8968 // have any template parameters in it (because deduction isn't 8969 // done on dependent types). 8970 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8971 8972 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8973 << ParamD->getDeclName() << Arg << NonCanonParam; 8974 MaybeEmitInheritedConstructorNote(S, Templated); 8975 return; 8976 } 8977 8978 case Sema::TDK_Inconsistent: { 8979 assert(ParamD && "no parameter found for inconsistent deduction result"); 8980 int which = 0; 8981 if (isa<TemplateTypeParmDecl>(ParamD)) 8982 which = 0; 8983 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8984 which = 1; 8985 else { 8986 which = 2; 8987 } 8988 8989 S.Diag(Templated->getLocation(), 8990 diag::note_ovl_candidate_inconsistent_deduction) 8991 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8992 << *DeductionFailure.getSecondArg(); 8993 MaybeEmitInheritedConstructorNote(S, Templated); 8994 return; 8995 } 8996 8997 case Sema::TDK_InvalidExplicitArguments: 8998 assert(ParamD && "no parameter found for invalid explicit arguments"); 8999 if (ParamD->getDeclName()) 9000 S.Diag(Templated->getLocation(), 9001 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9002 << ParamD->getDeclName(); 9003 else { 9004 int index = 0; 9005 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9006 index = TTP->getIndex(); 9007 else if (NonTypeTemplateParmDecl *NTTP 9008 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9009 index = NTTP->getIndex(); 9010 else 9011 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9012 S.Diag(Templated->getLocation(), 9013 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9014 << (index + 1); 9015 } 9016 MaybeEmitInheritedConstructorNote(S, Templated); 9017 return; 9018 9019 case Sema::TDK_TooManyArguments: 9020 case Sema::TDK_TooFewArguments: 9021 DiagnoseArityMismatch(S, Templated, NumArgs); 9022 return; 9023 9024 case Sema::TDK_InstantiationDepth: 9025 S.Diag(Templated->getLocation(), 9026 diag::note_ovl_candidate_instantiation_depth); 9027 MaybeEmitInheritedConstructorNote(S, Templated); 9028 return; 9029 9030 case Sema::TDK_SubstitutionFailure: { 9031 // Format the template argument list into the argument string. 9032 SmallString<128> TemplateArgString; 9033 if (TemplateArgumentList *Args = 9034 DeductionFailure.getTemplateArgumentList()) { 9035 TemplateArgString = " "; 9036 TemplateArgString += S.getTemplateArgumentBindingsText( 9037 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9038 } 9039 9040 // If this candidate was disabled by enable_if, say so. 9041 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9042 if (PDiag && PDiag->second.getDiagID() == 9043 diag::err_typename_nested_not_found_enable_if) { 9044 // FIXME: Use the source range of the condition, and the fully-qualified 9045 // name of the enable_if template. These are both present in PDiag. 9046 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9047 << "'enable_if'" << TemplateArgString; 9048 return; 9049 } 9050 9051 // Format the SFINAE diagnostic into the argument string. 9052 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9053 // formatted message in another diagnostic. 9054 SmallString<128> SFINAEArgString; 9055 SourceRange R; 9056 if (PDiag) { 9057 SFINAEArgString = ": "; 9058 R = SourceRange(PDiag->first, PDiag->first); 9059 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9060 } 9061 9062 S.Diag(Templated->getLocation(), 9063 diag::note_ovl_candidate_substitution_failure) 9064 << TemplateArgString << SFINAEArgString << R; 9065 MaybeEmitInheritedConstructorNote(S, Templated); 9066 return; 9067 } 9068 9069 case Sema::TDK_FailedOverloadResolution: { 9070 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9071 S.Diag(Templated->getLocation(), 9072 diag::note_ovl_candidate_failed_overload_resolution) 9073 << R.Expression->getName(); 9074 return; 9075 } 9076 9077 case Sema::TDK_NonDeducedMismatch: { 9078 // FIXME: Provide a source location to indicate what we couldn't match. 9079 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9080 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9081 if (FirstTA.getKind() == TemplateArgument::Template && 9082 SecondTA.getKind() == TemplateArgument::Template) { 9083 TemplateName FirstTN = FirstTA.getAsTemplate(); 9084 TemplateName SecondTN = SecondTA.getAsTemplate(); 9085 if (FirstTN.getKind() == TemplateName::Template && 9086 SecondTN.getKind() == TemplateName::Template) { 9087 if (FirstTN.getAsTemplateDecl()->getName() == 9088 SecondTN.getAsTemplateDecl()->getName()) { 9089 // FIXME: This fixes a bad diagnostic where both templates are named 9090 // the same. This particular case is a bit difficult since: 9091 // 1) It is passed as a string to the diagnostic printer. 9092 // 2) The diagnostic printer only attempts to find a better 9093 // name for types, not decls. 9094 // Ideally, this should folded into the diagnostic printer. 9095 S.Diag(Templated->getLocation(), 9096 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9097 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9098 return; 9099 } 9100 } 9101 } 9102 // FIXME: For generic lambda parameters, check if the function is a lambda 9103 // call operator, and if so, emit a prettier and more informative 9104 // diagnostic that mentions 'auto' and lambda in addition to 9105 // (or instead of?) the canonical template type parameters. 9106 S.Diag(Templated->getLocation(), 9107 diag::note_ovl_candidate_non_deduced_mismatch) 9108 << FirstTA << SecondTA; 9109 return; 9110 } 9111 // TODO: diagnose these individually, then kill off 9112 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9113 case Sema::TDK_MiscellaneousDeductionFailure: 9114 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9115 MaybeEmitInheritedConstructorNote(S, Templated); 9116 return; 9117 } 9118 } 9119 9120 /// Diagnose a failed template-argument deduction, for function calls. 9121 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 9122 unsigned TDK = Cand->DeductionFailure.Result; 9123 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9124 if (CheckArityMismatch(S, Cand, NumArgs)) 9125 return; 9126 } 9127 DiagnoseBadDeduction(S, Cand->Function, // pattern 9128 Cand->DeductionFailure, NumArgs); 9129 } 9130 9131 /// CUDA: diagnose an invalid call across targets. 9132 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9133 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9134 FunctionDecl *Callee = Cand->Function; 9135 9136 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9137 CalleeTarget = S.IdentifyCUDATarget(Callee); 9138 9139 std::string FnDesc; 9140 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9141 9142 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9143 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9144 9145 // This could be an implicit constructor for which we could not infer the 9146 // target due to a collsion. Diagnose that case. 9147 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9148 if (Meth != nullptr && Meth->isImplicit()) { 9149 CXXRecordDecl *ParentClass = Meth->getParent(); 9150 Sema::CXXSpecialMember CSM; 9151 9152 switch (FnKind) { 9153 default: 9154 return; 9155 case oc_implicit_default_constructor: 9156 CSM = Sema::CXXDefaultConstructor; 9157 break; 9158 case oc_implicit_copy_constructor: 9159 CSM = Sema::CXXCopyConstructor; 9160 break; 9161 case oc_implicit_move_constructor: 9162 CSM = Sema::CXXMoveConstructor; 9163 break; 9164 case oc_implicit_copy_assignment: 9165 CSM = Sema::CXXCopyAssignment; 9166 break; 9167 case oc_implicit_move_assignment: 9168 CSM = Sema::CXXMoveAssignment; 9169 break; 9170 }; 9171 9172 bool ConstRHS = false; 9173 if (Meth->getNumParams()) { 9174 if (const ReferenceType *RT = 9175 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9176 ConstRHS = RT->getPointeeType().isConstQualified(); 9177 } 9178 } 9179 9180 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9181 /* ConstRHS */ ConstRHS, 9182 /* Diagnose */ true); 9183 } 9184 } 9185 9186 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9187 FunctionDecl *Callee = Cand->Function; 9188 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9189 9190 S.Diag(Callee->getLocation(), 9191 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9192 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9193 } 9194 9195 /// Generates a 'note' diagnostic for an overload candidate. We've 9196 /// already generated a primary error at the call site. 9197 /// 9198 /// It really does need to be a single diagnostic with its caret 9199 /// pointed at the candidate declaration. Yes, this creates some 9200 /// major challenges of technical writing. Yes, this makes pointing 9201 /// out problems with specific arguments quite awkward. It's still 9202 /// better than generating twenty screens of text for every failed 9203 /// overload. 9204 /// 9205 /// It would be great to be able to express per-candidate problems 9206 /// more richly for those diagnostic clients that cared, but we'd 9207 /// still have to be just as careful with the default diagnostics. 9208 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9209 unsigned NumArgs) { 9210 FunctionDecl *Fn = Cand->Function; 9211 9212 // Note deleted candidates, but only if they're viable. 9213 if (Cand->Viable && (Fn->isDeleted() || 9214 S.isFunctionConsideredUnavailable(Fn))) { 9215 std::string FnDesc; 9216 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9217 9218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9219 << FnKind << FnDesc 9220 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9221 MaybeEmitInheritedConstructorNote(S, Fn); 9222 return; 9223 } 9224 9225 // We don't really have anything else to say about viable candidates. 9226 if (Cand->Viable) { 9227 S.NoteOverloadCandidate(Fn); 9228 return; 9229 } 9230 9231 switch (Cand->FailureKind) { 9232 case ovl_fail_too_many_arguments: 9233 case ovl_fail_too_few_arguments: 9234 return DiagnoseArityMismatch(S, Cand, NumArgs); 9235 9236 case ovl_fail_bad_deduction: 9237 return DiagnoseBadDeduction(S, Cand, NumArgs); 9238 9239 case ovl_fail_trivial_conversion: 9240 case ovl_fail_bad_final_conversion: 9241 case ovl_fail_final_conversion_not_exact: 9242 return S.NoteOverloadCandidate(Fn); 9243 9244 case ovl_fail_bad_conversion: { 9245 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9246 for (unsigned N = Cand->NumConversions; I != N; ++I) 9247 if (Cand->Conversions[I].isBad()) 9248 return DiagnoseBadConversion(S, Cand, I); 9249 9250 // FIXME: this currently happens when we're called from SemaInit 9251 // when user-conversion overload fails. Figure out how to handle 9252 // those conditions and diagnose them well. 9253 return S.NoteOverloadCandidate(Fn); 9254 } 9255 9256 case ovl_fail_bad_target: 9257 return DiagnoseBadTarget(S, Cand); 9258 9259 case ovl_fail_enable_if: 9260 return DiagnoseFailedEnableIfAttr(S, Cand); 9261 } 9262 } 9263 9264 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9265 // Desugar the type of the surrogate down to a function type, 9266 // retaining as many typedefs as possible while still showing 9267 // the function type (and, therefore, its parameter types). 9268 QualType FnType = Cand->Surrogate->getConversionType(); 9269 bool isLValueReference = false; 9270 bool isRValueReference = false; 9271 bool isPointer = false; 9272 if (const LValueReferenceType *FnTypeRef = 9273 FnType->getAs<LValueReferenceType>()) { 9274 FnType = FnTypeRef->getPointeeType(); 9275 isLValueReference = true; 9276 } else if (const RValueReferenceType *FnTypeRef = 9277 FnType->getAs<RValueReferenceType>()) { 9278 FnType = FnTypeRef->getPointeeType(); 9279 isRValueReference = true; 9280 } 9281 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9282 FnType = FnTypePtr->getPointeeType(); 9283 isPointer = true; 9284 } 9285 // Desugar down to a function type. 9286 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9287 // Reconstruct the pointer/reference as appropriate. 9288 if (isPointer) FnType = S.Context.getPointerType(FnType); 9289 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9290 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9291 9292 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9293 << FnType; 9294 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9295 } 9296 9297 void NoteBuiltinOperatorCandidate(Sema &S, 9298 StringRef Opc, 9299 SourceLocation OpLoc, 9300 OverloadCandidate *Cand) { 9301 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9302 std::string TypeStr("operator"); 9303 TypeStr += Opc; 9304 TypeStr += "("; 9305 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9306 if (Cand->NumConversions == 1) { 9307 TypeStr += ")"; 9308 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9309 } else { 9310 TypeStr += ", "; 9311 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9312 TypeStr += ")"; 9313 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9314 } 9315 } 9316 9317 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9318 OverloadCandidate *Cand) { 9319 unsigned NoOperands = Cand->NumConversions; 9320 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9321 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9322 if (ICS.isBad()) break; // all meaningless after first invalid 9323 if (!ICS.isAmbiguous()) continue; 9324 9325 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9326 S.PDiag(diag::note_ambiguous_type_conversion)); 9327 } 9328 } 9329 9330 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9331 if (Cand->Function) 9332 return Cand->Function->getLocation(); 9333 if (Cand->IsSurrogate) 9334 return Cand->Surrogate->getLocation(); 9335 return SourceLocation(); 9336 } 9337 9338 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9339 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9340 case Sema::TDK_Success: 9341 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9342 9343 case Sema::TDK_Invalid: 9344 case Sema::TDK_Incomplete: 9345 return 1; 9346 9347 case Sema::TDK_Underqualified: 9348 case Sema::TDK_Inconsistent: 9349 return 2; 9350 9351 case Sema::TDK_SubstitutionFailure: 9352 case Sema::TDK_NonDeducedMismatch: 9353 case Sema::TDK_MiscellaneousDeductionFailure: 9354 return 3; 9355 9356 case Sema::TDK_InstantiationDepth: 9357 case Sema::TDK_FailedOverloadResolution: 9358 return 4; 9359 9360 case Sema::TDK_InvalidExplicitArguments: 9361 return 5; 9362 9363 case Sema::TDK_TooManyArguments: 9364 case Sema::TDK_TooFewArguments: 9365 return 6; 9366 } 9367 llvm_unreachable("Unhandled deduction result"); 9368 } 9369 9370 struct CompareOverloadCandidatesForDisplay { 9371 Sema &S; 9372 size_t NumArgs; 9373 9374 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9375 : S(S), NumArgs(nArgs) {} 9376 9377 bool operator()(const OverloadCandidate *L, 9378 const OverloadCandidate *R) { 9379 // Fast-path this check. 9380 if (L == R) return false; 9381 9382 // Order first by viability. 9383 if (L->Viable) { 9384 if (!R->Viable) return true; 9385 9386 // TODO: introduce a tri-valued comparison for overload 9387 // candidates. Would be more worthwhile if we had a sort 9388 // that could exploit it. 9389 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9390 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9391 } else if (R->Viable) 9392 return false; 9393 9394 assert(L->Viable == R->Viable); 9395 9396 // Criteria by which we can sort non-viable candidates: 9397 if (!L->Viable) { 9398 // 1. Arity mismatches come after other candidates. 9399 if (L->FailureKind == ovl_fail_too_many_arguments || 9400 L->FailureKind == ovl_fail_too_few_arguments) { 9401 if (R->FailureKind == ovl_fail_too_many_arguments || 9402 R->FailureKind == ovl_fail_too_few_arguments) { 9403 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9404 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9405 if (LDist == RDist) { 9406 if (L->FailureKind == R->FailureKind) 9407 // Sort non-surrogates before surrogates. 9408 return !L->IsSurrogate && R->IsSurrogate; 9409 // Sort candidates requiring fewer parameters than there were 9410 // arguments given after candidates requiring more parameters 9411 // than there were arguments given. 9412 return L->FailureKind == ovl_fail_too_many_arguments; 9413 } 9414 return LDist < RDist; 9415 } 9416 return false; 9417 } 9418 if (R->FailureKind == ovl_fail_too_many_arguments || 9419 R->FailureKind == ovl_fail_too_few_arguments) 9420 return true; 9421 9422 // 2. Bad conversions come first and are ordered by the number 9423 // of bad conversions and quality of good conversions. 9424 if (L->FailureKind == ovl_fail_bad_conversion) { 9425 if (R->FailureKind != ovl_fail_bad_conversion) 9426 return true; 9427 9428 // The conversion that can be fixed with a smaller number of changes, 9429 // comes first. 9430 unsigned numLFixes = L->Fix.NumConversionsFixed; 9431 unsigned numRFixes = R->Fix.NumConversionsFixed; 9432 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9433 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9434 if (numLFixes != numRFixes) { 9435 if (numLFixes < numRFixes) 9436 return true; 9437 else 9438 return false; 9439 } 9440 9441 // If there's any ordering between the defined conversions... 9442 // FIXME: this might not be transitive. 9443 assert(L->NumConversions == R->NumConversions); 9444 9445 int leftBetter = 0; 9446 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9447 for (unsigned E = L->NumConversions; I != E; ++I) { 9448 switch (CompareImplicitConversionSequences(S, 9449 L->Conversions[I], 9450 R->Conversions[I])) { 9451 case ImplicitConversionSequence::Better: 9452 leftBetter++; 9453 break; 9454 9455 case ImplicitConversionSequence::Worse: 9456 leftBetter--; 9457 break; 9458 9459 case ImplicitConversionSequence::Indistinguishable: 9460 break; 9461 } 9462 } 9463 if (leftBetter > 0) return true; 9464 if (leftBetter < 0) return false; 9465 9466 } else if (R->FailureKind == ovl_fail_bad_conversion) 9467 return false; 9468 9469 if (L->FailureKind == ovl_fail_bad_deduction) { 9470 if (R->FailureKind != ovl_fail_bad_deduction) 9471 return true; 9472 9473 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9474 return RankDeductionFailure(L->DeductionFailure) 9475 < RankDeductionFailure(R->DeductionFailure); 9476 } else if (R->FailureKind == ovl_fail_bad_deduction) 9477 return false; 9478 9479 // TODO: others? 9480 } 9481 9482 // Sort everything else by location. 9483 SourceLocation LLoc = GetLocationForCandidate(L); 9484 SourceLocation RLoc = GetLocationForCandidate(R); 9485 9486 // Put candidates without locations (e.g. builtins) at the end. 9487 if (LLoc.isInvalid()) return false; 9488 if (RLoc.isInvalid()) return true; 9489 9490 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9491 } 9492 }; 9493 9494 /// CompleteNonViableCandidate - Normally, overload resolution only 9495 /// computes up to the first. Produces the FixIt set if possible. 9496 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9497 ArrayRef<Expr *> Args) { 9498 assert(!Cand->Viable); 9499 9500 // Don't do anything on failures other than bad conversion. 9501 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9502 9503 // We only want the FixIts if all the arguments can be corrected. 9504 bool Unfixable = false; 9505 // Use a implicit copy initialization to check conversion fixes. 9506 Cand->Fix.setConversionChecker(TryCopyInitialization); 9507 9508 // Skip forward to the first bad conversion. 9509 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9510 unsigned ConvCount = Cand->NumConversions; 9511 while (true) { 9512 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9513 ConvIdx++; 9514 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9515 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9516 break; 9517 } 9518 } 9519 9520 if (ConvIdx == ConvCount) 9521 return; 9522 9523 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9524 "remaining conversion is initialized?"); 9525 9526 // FIXME: this should probably be preserved from the overload 9527 // operation somehow. 9528 bool SuppressUserConversions = false; 9529 9530 const FunctionProtoType* Proto; 9531 unsigned ArgIdx = ConvIdx; 9532 9533 if (Cand->IsSurrogate) { 9534 QualType ConvType 9535 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9536 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9537 ConvType = ConvPtrType->getPointeeType(); 9538 Proto = ConvType->getAs<FunctionProtoType>(); 9539 ArgIdx--; 9540 } else if (Cand->Function) { 9541 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9542 if (isa<CXXMethodDecl>(Cand->Function) && 9543 !isa<CXXConstructorDecl>(Cand->Function)) 9544 ArgIdx--; 9545 } else { 9546 // Builtin binary operator with a bad first conversion. 9547 assert(ConvCount <= 3); 9548 for (; ConvIdx != ConvCount; ++ConvIdx) 9549 Cand->Conversions[ConvIdx] 9550 = TryCopyInitialization(S, Args[ConvIdx], 9551 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9552 SuppressUserConversions, 9553 /*InOverloadResolution*/ true, 9554 /*AllowObjCWritebackConversion=*/ 9555 S.getLangOpts().ObjCAutoRefCount); 9556 return; 9557 } 9558 9559 // Fill in the rest of the conversions. 9560 unsigned NumParams = Proto->getNumParams(); 9561 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9562 if (ArgIdx < NumParams) { 9563 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9564 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9565 /*InOverloadResolution=*/true, 9566 /*AllowObjCWritebackConversion=*/ 9567 S.getLangOpts().ObjCAutoRefCount); 9568 // Store the FixIt in the candidate if it exists. 9569 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9570 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9571 } 9572 else 9573 Cand->Conversions[ConvIdx].setEllipsis(); 9574 } 9575 } 9576 9577 } // end anonymous namespace 9578 9579 /// PrintOverloadCandidates - When overload resolution fails, prints 9580 /// diagnostic messages containing the candidates in the candidate 9581 /// set. 9582 void OverloadCandidateSet::NoteCandidates(Sema &S, 9583 OverloadCandidateDisplayKind OCD, 9584 ArrayRef<Expr *> Args, 9585 StringRef Opc, 9586 SourceLocation OpLoc) { 9587 // Sort the candidates by viability and position. Sorting directly would 9588 // be prohibitive, so we make a set of pointers and sort those. 9589 SmallVector<OverloadCandidate*, 32> Cands; 9590 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9591 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9592 if (Cand->Viable) 9593 Cands.push_back(Cand); 9594 else if (OCD == OCD_AllCandidates) { 9595 CompleteNonViableCandidate(S, Cand, Args); 9596 if (Cand->Function || Cand->IsSurrogate) 9597 Cands.push_back(Cand); 9598 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9599 // want to list every possible builtin candidate. 9600 } 9601 } 9602 9603 std::sort(Cands.begin(), Cands.end(), 9604 CompareOverloadCandidatesForDisplay(S, Args.size())); 9605 9606 bool ReportedAmbiguousConversions = false; 9607 9608 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9609 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9610 unsigned CandsShown = 0; 9611 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9612 OverloadCandidate *Cand = *I; 9613 9614 // Set an arbitrary limit on the number of candidate functions we'll spam 9615 // the user with. FIXME: This limit should depend on details of the 9616 // candidate list. 9617 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9618 break; 9619 } 9620 ++CandsShown; 9621 9622 if (Cand->Function) 9623 NoteFunctionCandidate(S, Cand, Args.size()); 9624 else if (Cand->IsSurrogate) 9625 NoteSurrogateCandidate(S, Cand); 9626 else { 9627 assert(Cand->Viable && 9628 "Non-viable built-in candidates are not added to Cands."); 9629 // Generally we only see ambiguities including viable builtin 9630 // operators if overload resolution got screwed up by an 9631 // ambiguous user-defined conversion. 9632 // 9633 // FIXME: It's quite possible for different conversions to see 9634 // different ambiguities, though. 9635 if (!ReportedAmbiguousConversions) { 9636 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9637 ReportedAmbiguousConversions = true; 9638 } 9639 9640 // If this is a viable builtin, print it. 9641 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9642 } 9643 } 9644 9645 if (I != E) 9646 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9647 } 9648 9649 static SourceLocation 9650 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9651 return Cand->Specialization ? Cand->Specialization->getLocation() 9652 : SourceLocation(); 9653 } 9654 9655 struct CompareTemplateSpecCandidatesForDisplay { 9656 Sema &S; 9657 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9658 9659 bool operator()(const TemplateSpecCandidate *L, 9660 const TemplateSpecCandidate *R) { 9661 // Fast-path this check. 9662 if (L == R) 9663 return false; 9664 9665 // Assuming that both candidates are not matches... 9666 9667 // Sort by the ranking of deduction failures. 9668 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9669 return RankDeductionFailure(L->DeductionFailure) < 9670 RankDeductionFailure(R->DeductionFailure); 9671 9672 // Sort everything else by location. 9673 SourceLocation LLoc = GetLocationForCandidate(L); 9674 SourceLocation RLoc = GetLocationForCandidate(R); 9675 9676 // Put candidates without locations (e.g. builtins) at the end. 9677 if (LLoc.isInvalid()) 9678 return false; 9679 if (RLoc.isInvalid()) 9680 return true; 9681 9682 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9683 } 9684 }; 9685 9686 /// Diagnose a template argument deduction failure. 9687 /// We are treating these failures as overload failures due to bad 9688 /// deductions. 9689 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9690 DiagnoseBadDeduction(S, Specialization, // pattern 9691 DeductionFailure, /*NumArgs=*/0); 9692 } 9693 9694 void TemplateSpecCandidateSet::destroyCandidates() { 9695 for (iterator i = begin(), e = end(); i != e; ++i) { 9696 i->DeductionFailure.Destroy(); 9697 } 9698 } 9699 9700 void TemplateSpecCandidateSet::clear() { 9701 destroyCandidates(); 9702 Candidates.clear(); 9703 } 9704 9705 /// NoteCandidates - When no template specialization match is found, prints 9706 /// diagnostic messages containing the non-matching specializations that form 9707 /// the candidate set. 9708 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9709 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9710 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9711 // Sort the candidates by position (assuming no candidate is a match). 9712 // Sorting directly would be prohibitive, so we make a set of pointers 9713 // and sort those. 9714 SmallVector<TemplateSpecCandidate *, 32> Cands; 9715 Cands.reserve(size()); 9716 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9717 if (Cand->Specialization) 9718 Cands.push_back(Cand); 9719 // Otherwise, this is a non-matching builtin candidate. We do not, 9720 // in general, want to list every possible builtin candidate. 9721 } 9722 9723 std::sort(Cands.begin(), Cands.end(), 9724 CompareTemplateSpecCandidatesForDisplay(S)); 9725 9726 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9727 // for generalization purposes (?). 9728 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9729 9730 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9731 unsigned CandsShown = 0; 9732 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9733 TemplateSpecCandidate *Cand = *I; 9734 9735 // Set an arbitrary limit on the number of candidates we'll spam 9736 // the user with. FIXME: This limit should depend on details of the 9737 // candidate list. 9738 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9739 break; 9740 ++CandsShown; 9741 9742 assert(Cand->Specialization && 9743 "Non-matching built-in candidates are not added to Cands."); 9744 Cand->NoteDeductionFailure(S); 9745 } 9746 9747 if (I != E) 9748 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9749 } 9750 9751 // [PossiblyAFunctionType] --> [Return] 9752 // NonFunctionType --> NonFunctionType 9753 // R (A) --> R(A) 9754 // R (*)(A) --> R (A) 9755 // R (&)(A) --> R (A) 9756 // R (S::*)(A) --> R (A) 9757 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9758 QualType Ret = PossiblyAFunctionType; 9759 if (const PointerType *ToTypePtr = 9760 PossiblyAFunctionType->getAs<PointerType>()) 9761 Ret = ToTypePtr->getPointeeType(); 9762 else if (const ReferenceType *ToTypeRef = 9763 PossiblyAFunctionType->getAs<ReferenceType>()) 9764 Ret = ToTypeRef->getPointeeType(); 9765 else if (const MemberPointerType *MemTypePtr = 9766 PossiblyAFunctionType->getAs<MemberPointerType>()) 9767 Ret = MemTypePtr->getPointeeType(); 9768 Ret = 9769 Context.getCanonicalType(Ret).getUnqualifiedType(); 9770 return Ret; 9771 } 9772 9773 // A helper class to help with address of function resolution 9774 // - allows us to avoid passing around all those ugly parameters 9775 class AddressOfFunctionResolver 9776 { 9777 Sema& S; 9778 Expr* SourceExpr; 9779 const QualType& TargetType; 9780 QualType TargetFunctionType; // Extracted function type from target type 9781 9782 bool Complain; 9783 //DeclAccessPair& ResultFunctionAccessPair; 9784 ASTContext& Context; 9785 9786 bool TargetTypeIsNonStaticMemberFunction; 9787 bool FoundNonTemplateFunction; 9788 bool StaticMemberFunctionFromBoundPointer; 9789 9790 OverloadExpr::FindResult OvlExprInfo; 9791 OverloadExpr *OvlExpr; 9792 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9793 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9794 TemplateSpecCandidateSet FailedCandidates; 9795 9796 public: 9797 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9798 const QualType &TargetType, bool Complain) 9799 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9800 Complain(Complain), Context(S.getASTContext()), 9801 TargetTypeIsNonStaticMemberFunction( 9802 !!TargetType->getAs<MemberPointerType>()), 9803 FoundNonTemplateFunction(false), 9804 StaticMemberFunctionFromBoundPointer(false), 9805 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9806 OvlExpr(OvlExprInfo.Expression), 9807 FailedCandidates(OvlExpr->getNameLoc()) { 9808 ExtractUnqualifiedFunctionTypeFromTargetType(); 9809 9810 if (TargetFunctionType->isFunctionType()) { 9811 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9812 if (!UME->isImplicitAccess() && 9813 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9814 StaticMemberFunctionFromBoundPointer = true; 9815 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9816 DeclAccessPair dap; 9817 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9818 OvlExpr, false, &dap)) { 9819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9820 if (!Method->isStatic()) { 9821 // If the target type is a non-function type and the function found 9822 // is a non-static member function, pretend as if that was the 9823 // target, it's the only possible type to end up with. 9824 TargetTypeIsNonStaticMemberFunction = true; 9825 9826 // And skip adding the function if its not in the proper form. 9827 // We'll diagnose this due to an empty set of functions. 9828 if (!OvlExprInfo.HasFormOfMemberPointer) 9829 return; 9830 } 9831 9832 Matches.push_back(std::make_pair(dap, Fn)); 9833 } 9834 return; 9835 } 9836 9837 if (OvlExpr->hasExplicitTemplateArgs()) 9838 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9839 9840 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9841 // C++ [over.over]p4: 9842 // If more than one function is selected, [...] 9843 if (Matches.size() > 1) { 9844 if (FoundNonTemplateFunction) 9845 EliminateAllTemplateMatches(); 9846 else 9847 EliminateAllExceptMostSpecializedTemplate(); 9848 } 9849 } 9850 } 9851 9852 private: 9853 bool isTargetTypeAFunction() const { 9854 return TargetFunctionType->isFunctionType(); 9855 } 9856 9857 // [ToType] [Return] 9858 9859 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9860 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9861 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9862 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9863 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9864 } 9865 9866 // return true if any matching specializations were found 9867 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9868 const DeclAccessPair& CurAccessFunPair) { 9869 if (CXXMethodDecl *Method 9870 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9871 // Skip non-static function templates when converting to pointer, and 9872 // static when converting to member pointer. 9873 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9874 return false; 9875 } 9876 else if (TargetTypeIsNonStaticMemberFunction) 9877 return false; 9878 9879 // C++ [over.over]p2: 9880 // If the name is a function template, template argument deduction is 9881 // done (14.8.2.2), and if the argument deduction succeeds, the 9882 // resulting template argument list is used to generate a single 9883 // function template specialization, which is added to the set of 9884 // overloaded functions considered. 9885 FunctionDecl *Specialization = nullptr; 9886 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9887 if (Sema::TemplateDeductionResult Result 9888 = S.DeduceTemplateArguments(FunctionTemplate, 9889 &OvlExplicitTemplateArgs, 9890 TargetFunctionType, Specialization, 9891 Info, /*InOverloadResolution=*/true)) { 9892 // Make a note of the failed deduction for diagnostics. 9893 FailedCandidates.addCandidate() 9894 .set(FunctionTemplate->getTemplatedDecl(), 9895 MakeDeductionFailureInfo(Context, Result, Info)); 9896 return false; 9897 } 9898 9899 // Template argument deduction ensures that we have an exact match or 9900 // compatible pointer-to-function arguments that would be adjusted by ICS. 9901 // This function template specicalization works. 9902 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9903 assert(S.isSameOrCompatibleFunctionType( 9904 Context.getCanonicalType(Specialization->getType()), 9905 Context.getCanonicalType(TargetFunctionType))); 9906 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9907 return true; 9908 } 9909 9910 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9911 const DeclAccessPair& CurAccessFunPair) { 9912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9913 // Skip non-static functions when converting to pointer, and static 9914 // when converting to member pointer. 9915 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9916 return false; 9917 } 9918 else if (TargetTypeIsNonStaticMemberFunction) 9919 return false; 9920 9921 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9922 if (S.getLangOpts().CUDA) 9923 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9924 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 9925 return false; 9926 9927 // If any candidate has a placeholder return type, trigger its deduction 9928 // now. 9929 if (S.getLangOpts().CPlusPlus14 && 9930 FunDecl->getReturnType()->isUndeducedType() && 9931 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9932 return false; 9933 9934 QualType ResultTy; 9935 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9936 FunDecl->getType()) || 9937 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9938 ResultTy)) { 9939 Matches.push_back(std::make_pair(CurAccessFunPair, 9940 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9941 FoundNonTemplateFunction = true; 9942 return true; 9943 } 9944 } 9945 9946 return false; 9947 } 9948 9949 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9950 bool Ret = false; 9951 9952 // If the overload expression doesn't have the form of a pointer to 9953 // member, don't try to convert it to a pointer-to-member type. 9954 if (IsInvalidFormOfPointerToMemberFunction()) 9955 return false; 9956 9957 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9958 E = OvlExpr->decls_end(); 9959 I != E; ++I) { 9960 // Look through any using declarations to find the underlying function. 9961 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9962 9963 // C++ [over.over]p3: 9964 // Non-member functions and static member functions match 9965 // targets of type "pointer-to-function" or "reference-to-function." 9966 // Nonstatic member functions match targets of 9967 // type "pointer-to-member-function." 9968 // Note that according to DR 247, the containing class does not matter. 9969 if (FunctionTemplateDecl *FunctionTemplate 9970 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9971 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9972 Ret = true; 9973 } 9974 // If we have explicit template arguments supplied, skip non-templates. 9975 else if (!OvlExpr->hasExplicitTemplateArgs() && 9976 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9977 Ret = true; 9978 } 9979 assert(Ret || Matches.empty()); 9980 return Ret; 9981 } 9982 9983 void EliminateAllExceptMostSpecializedTemplate() { 9984 // [...] and any given function template specialization F1 is 9985 // eliminated if the set contains a second function template 9986 // specialization whose function template is more specialized 9987 // than the function template of F1 according to the partial 9988 // ordering rules of 14.5.5.2. 9989 9990 // The algorithm specified above is quadratic. We instead use a 9991 // two-pass algorithm (similar to the one used to identify the 9992 // best viable function in an overload set) that identifies the 9993 // best function template (if it exists). 9994 9995 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9996 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9997 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9998 9999 // TODO: It looks like FailedCandidates does not serve much purpose 10000 // here, since the no_viable diagnostic has index 0. 10001 UnresolvedSetIterator Result = S.getMostSpecialized( 10002 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10003 SourceExpr->getLocStart(), S.PDiag(), 10004 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10005 .second->getDeclName(), 10006 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10007 Complain, TargetFunctionType); 10008 10009 if (Result != MatchesCopy.end()) { 10010 // Make it the first and only element 10011 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10012 Matches[0].second = cast<FunctionDecl>(*Result); 10013 Matches.resize(1); 10014 } 10015 } 10016 10017 void EliminateAllTemplateMatches() { 10018 // [...] any function template specializations in the set are 10019 // eliminated if the set also contains a non-template function, [...] 10020 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10021 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10022 ++I; 10023 else { 10024 Matches[I] = Matches[--N]; 10025 Matches.set_size(N); 10026 } 10027 } 10028 } 10029 10030 public: 10031 void ComplainNoMatchesFound() const { 10032 assert(Matches.empty()); 10033 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10034 << OvlExpr->getName() << TargetFunctionType 10035 << OvlExpr->getSourceRange(); 10036 if (FailedCandidates.empty()) 10037 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10038 else { 10039 // We have some deduction failure messages. Use them to diagnose 10040 // the function templates, and diagnose the non-template candidates 10041 // normally. 10042 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10043 IEnd = OvlExpr->decls_end(); 10044 I != IEnd; ++I) 10045 if (FunctionDecl *Fun = 10046 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10047 S.NoteOverloadCandidate(Fun, TargetFunctionType); 10048 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10049 } 10050 } 10051 10052 bool IsInvalidFormOfPointerToMemberFunction() const { 10053 return TargetTypeIsNonStaticMemberFunction && 10054 !OvlExprInfo.HasFormOfMemberPointer; 10055 } 10056 10057 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10058 // TODO: Should we condition this on whether any functions might 10059 // have matched, or is it more appropriate to do that in callers? 10060 // TODO: a fixit wouldn't hurt. 10061 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10062 << TargetType << OvlExpr->getSourceRange(); 10063 } 10064 10065 bool IsStaticMemberFunctionFromBoundPointer() const { 10066 return StaticMemberFunctionFromBoundPointer; 10067 } 10068 10069 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10070 S.Diag(OvlExpr->getLocStart(), 10071 diag::err_invalid_form_pointer_member_function) 10072 << OvlExpr->getSourceRange(); 10073 } 10074 10075 void ComplainOfInvalidConversion() const { 10076 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10077 << OvlExpr->getName() << TargetType; 10078 } 10079 10080 void ComplainMultipleMatchesFound() const { 10081 assert(Matches.size() > 1); 10082 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10083 << OvlExpr->getName() 10084 << OvlExpr->getSourceRange(); 10085 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10086 } 10087 10088 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10089 10090 int getNumMatches() const { return Matches.size(); } 10091 10092 FunctionDecl* getMatchingFunctionDecl() const { 10093 if (Matches.size() != 1) return nullptr; 10094 return Matches[0].second; 10095 } 10096 10097 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10098 if (Matches.size() != 1) return nullptr; 10099 return &Matches[0].first; 10100 } 10101 }; 10102 10103 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10104 /// an overloaded function (C++ [over.over]), where @p From is an 10105 /// expression with overloaded function type and @p ToType is the type 10106 /// we're trying to resolve to. For example: 10107 /// 10108 /// @code 10109 /// int f(double); 10110 /// int f(int); 10111 /// 10112 /// int (*pfd)(double) = f; // selects f(double) 10113 /// @endcode 10114 /// 10115 /// This routine returns the resulting FunctionDecl if it could be 10116 /// resolved, and NULL otherwise. When @p Complain is true, this 10117 /// routine will emit diagnostics if there is an error. 10118 FunctionDecl * 10119 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10120 QualType TargetType, 10121 bool Complain, 10122 DeclAccessPair &FoundResult, 10123 bool *pHadMultipleCandidates) { 10124 assert(AddressOfExpr->getType() == Context.OverloadTy); 10125 10126 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10127 Complain); 10128 int NumMatches = Resolver.getNumMatches(); 10129 FunctionDecl *Fn = nullptr; 10130 if (NumMatches == 0 && Complain) { 10131 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10132 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10133 else 10134 Resolver.ComplainNoMatchesFound(); 10135 } 10136 else if (NumMatches > 1 && Complain) 10137 Resolver.ComplainMultipleMatchesFound(); 10138 else if (NumMatches == 1) { 10139 Fn = Resolver.getMatchingFunctionDecl(); 10140 assert(Fn); 10141 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10142 if (Complain) { 10143 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10144 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10145 else 10146 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10147 } 10148 } 10149 10150 if (pHadMultipleCandidates) 10151 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10152 return Fn; 10153 } 10154 10155 /// \brief Given an expression that refers to an overloaded function, try to 10156 /// resolve that overloaded function expression down to a single function. 10157 /// 10158 /// This routine can only resolve template-ids that refer to a single function 10159 /// template, where that template-id refers to a single template whose template 10160 /// arguments are either provided by the template-id or have defaults, 10161 /// as described in C++0x [temp.arg.explicit]p3. 10162 /// 10163 /// If no template-ids are found, no diagnostics are emitted and NULL is 10164 /// returned. 10165 FunctionDecl * 10166 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10167 bool Complain, 10168 DeclAccessPair *FoundResult) { 10169 // C++ [over.over]p1: 10170 // [...] [Note: any redundant set of parentheses surrounding the 10171 // overloaded function name is ignored (5.1). ] 10172 // C++ [over.over]p1: 10173 // [...] The overloaded function name can be preceded by the & 10174 // operator. 10175 10176 // If we didn't actually find any template-ids, we're done. 10177 if (!ovl->hasExplicitTemplateArgs()) 10178 return nullptr; 10179 10180 TemplateArgumentListInfo ExplicitTemplateArgs; 10181 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10182 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10183 10184 // Look through all of the overloaded functions, searching for one 10185 // whose type matches exactly. 10186 FunctionDecl *Matched = nullptr; 10187 for (UnresolvedSetIterator I = ovl->decls_begin(), 10188 E = ovl->decls_end(); I != E; ++I) { 10189 // C++0x [temp.arg.explicit]p3: 10190 // [...] In contexts where deduction is done and fails, or in contexts 10191 // where deduction is not done, if a template argument list is 10192 // specified and it, along with any default template arguments, 10193 // identifies a single function template specialization, then the 10194 // template-id is an lvalue for the function template specialization. 10195 FunctionTemplateDecl *FunctionTemplate 10196 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10197 10198 // C++ [over.over]p2: 10199 // If the name is a function template, template argument deduction is 10200 // done (14.8.2.2), and if the argument deduction succeeds, the 10201 // resulting template argument list is used to generate a single 10202 // function template specialization, which is added to the set of 10203 // overloaded functions considered. 10204 FunctionDecl *Specialization = nullptr; 10205 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10206 if (TemplateDeductionResult Result 10207 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10208 Specialization, Info, 10209 /*InOverloadResolution=*/true)) { 10210 // Make a note of the failed deduction for diagnostics. 10211 // TODO: Actually use the failed-deduction info? 10212 FailedCandidates.addCandidate() 10213 .set(FunctionTemplate->getTemplatedDecl(), 10214 MakeDeductionFailureInfo(Context, Result, Info)); 10215 continue; 10216 } 10217 10218 assert(Specialization && "no specialization and no error?"); 10219 10220 // Multiple matches; we can't resolve to a single declaration. 10221 if (Matched) { 10222 if (Complain) { 10223 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10224 << ovl->getName(); 10225 NoteAllOverloadCandidates(ovl); 10226 } 10227 return nullptr; 10228 } 10229 10230 Matched = Specialization; 10231 if (FoundResult) *FoundResult = I.getPair(); 10232 } 10233 10234 if (Matched && getLangOpts().CPlusPlus14 && 10235 Matched->getReturnType()->isUndeducedType() && 10236 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10237 return nullptr; 10238 10239 return Matched; 10240 } 10241 10242 10243 10244 10245 // Resolve and fix an overloaded expression that can be resolved 10246 // because it identifies a single function template specialization. 10247 // 10248 // Last three arguments should only be supplied if Complain = true 10249 // 10250 // Return true if it was logically possible to so resolve the 10251 // expression, regardless of whether or not it succeeded. Always 10252 // returns true if 'complain' is set. 10253 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10254 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10255 bool complain, const SourceRange& OpRangeForComplaining, 10256 QualType DestTypeForComplaining, 10257 unsigned DiagIDForComplaining) { 10258 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10259 10260 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10261 10262 DeclAccessPair found; 10263 ExprResult SingleFunctionExpression; 10264 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10265 ovl.Expression, /*complain*/ false, &found)) { 10266 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10267 SrcExpr = ExprError(); 10268 return true; 10269 } 10270 10271 // It is only correct to resolve to an instance method if we're 10272 // resolving a form that's permitted to be a pointer to member. 10273 // Otherwise we'll end up making a bound member expression, which 10274 // is illegal in all the contexts we resolve like this. 10275 if (!ovl.HasFormOfMemberPointer && 10276 isa<CXXMethodDecl>(fn) && 10277 cast<CXXMethodDecl>(fn)->isInstance()) { 10278 if (!complain) return false; 10279 10280 Diag(ovl.Expression->getExprLoc(), 10281 diag::err_bound_member_function) 10282 << 0 << ovl.Expression->getSourceRange(); 10283 10284 // TODO: I believe we only end up here if there's a mix of 10285 // static and non-static candidates (otherwise the expression 10286 // would have 'bound member' type, not 'overload' type). 10287 // Ideally we would note which candidate was chosen and why 10288 // the static candidates were rejected. 10289 SrcExpr = ExprError(); 10290 return true; 10291 } 10292 10293 // Fix the expression to refer to 'fn'. 10294 SingleFunctionExpression = 10295 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10296 10297 // If desired, do function-to-pointer decay. 10298 if (doFunctionPointerConverion) { 10299 SingleFunctionExpression = 10300 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10301 if (SingleFunctionExpression.isInvalid()) { 10302 SrcExpr = ExprError(); 10303 return true; 10304 } 10305 } 10306 } 10307 10308 if (!SingleFunctionExpression.isUsable()) { 10309 if (complain) { 10310 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10311 << ovl.Expression->getName() 10312 << DestTypeForComplaining 10313 << OpRangeForComplaining 10314 << ovl.Expression->getQualifierLoc().getSourceRange(); 10315 NoteAllOverloadCandidates(SrcExpr.get()); 10316 10317 SrcExpr = ExprError(); 10318 return true; 10319 } 10320 10321 return false; 10322 } 10323 10324 SrcExpr = SingleFunctionExpression; 10325 return true; 10326 } 10327 10328 /// \brief Add a single candidate to the overload set. 10329 static void AddOverloadedCallCandidate(Sema &S, 10330 DeclAccessPair FoundDecl, 10331 TemplateArgumentListInfo *ExplicitTemplateArgs, 10332 ArrayRef<Expr *> Args, 10333 OverloadCandidateSet &CandidateSet, 10334 bool PartialOverloading, 10335 bool KnownValid) { 10336 NamedDecl *Callee = FoundDecl.getDecl(); 10337 if (isa<UsingShadowDecl>(Callee)) 10338 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10339 10340 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10341 if (ExplicitTemplateArgs) { 10342 assert(!KnownValid && "Explicit template arguments?"); 10343 return; 10344 } 10345 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 10346 PartialOverloading); 10347 return; 10348 } 10349 10350 if (FunctionTemplateDecl *FuncTemplate 10351 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10352 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10353 ExplicitTemplateArgs, Args, CandidateSet); 10354 return; 10355 } 10356 10357 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10358 } 10359 10360 /// \brief Add the overload candidates named by callee and/or found by argument 10361 /// dependent lookup to the given overload set. 10362 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10363 ArrayRef<Expr *> Args, 10364 OverloadCandidateSet &CandidateSet, 10365 bool PartialOverloading) { 10366 10367 #ifndef NDEBUG 10368 // Verify that ArgumentDependentLookup is consistent with the rules 10369 // in C++0x [basic.lookup.argdep]p3: 10370 // 10371 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10372 // and let Y be the lookup set produced by argument dependent 10373 // lookup (defined as follows). If X contains 10374 // 10375 // -- a declaration of a class member, or 10376 // 10377 // -- a block-scope function declaration that is not a 10378 // using-declaration, or 10379 // 10380 // -- a declaration that is neither a function or a function 10381 // template 10382 // 10383 // then Y is empty. 10384 10385 if (ULE->requiresADL()) { 10386 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10387 E = ULE->decls_end(); I != E; ++I) { 10388 assert(!(*I)->getDeclContext()->isRecord()); 10389 assert(isa<UsingShadowDecl>(*I) || 10390 !(*I)->getDeclContext()->isFunctionOrMethod()); 10391 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10392 } 10393 } 10394 #endif 10395 10396 // It would be nice to avoid this copy. 10397 TemplateArgumentListInfo TABuffer; 10398 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10399 if (ULE->hasExplicitTemplateArgs()) { 10400 ULE->copyTemplateArgumentsInto(TABuffer); 10401 ExplicitTemplateArgs = &TABuffer; 10402 } 10403 10404 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10405 E = ULE->decls_end(); I != E; ++I) 10406 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10407 CandidateSet, PartialOverloading, 10408 /*KnownValid*/ true); 10409 10410 if (ULE->requiresADL()) 10411 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10412 Args, ExplicitTemplateArgs, 10413 CandidateSet, PartialOverloading); 10414 } 10415 10416 /// Determine whether a declaration with the specified name could be moved into 10417 /// a different namespace. 10418 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10419 switch (Name.getCXXOverloadedOperator()) { 10420 case OO_New: case OO_Array_New: 10421 case OO_Delete: case OO_Array_Delete: 10422 return false; 10423 10424 default: 10425 return true; 10426 } 10427 } 10428 10429 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10430 /// template, where the non-dependent name was declared after the template 10431 /// was defined. This is common in code written for a compilers which do not 10432 /// correctly implement two-stage name lookup. 10433 /// 10434 /// Returns true if a viable candidate was found and a diagnostic was issued. 10435 static bool 10436 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10437 const CXXScopeSpec &SS, LookupResult &R, 10438 OverloadCandidateSet::CandidateSetKind CSK, 10439 TemplateArgumentListInfo *ExplicitTemplateArgs, 10440 ArrayRef<Expr *> Args) { 10441 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10442 return false; 10443 10444 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10445 if (DC->isTransparentContext()) 10446 continue; 10447 10448 SemaRef.LookupQualifiedName(R, DC); 10449 10450 if (!R.empty()) { 10451 R.suppressDiagnostics(); 10452 10453 if (isa<CXXRecordDecl>(DC)) { 10454 // Don't diagnose names we find in classes; we get much better 10455 // diagnostics for these from DiagnoseEmptyLookup. 10456 R.clear(); 10457 return false; 10458 } 10459 10460 OverloadCandidateSet Candidates(FnLoc, CSK); 10461 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10462 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10463 ExplicitTemplateArgs, Args, 10464 Candidates, false, /*KnownValid*/ false); 10465 10466 OverloadCandidateSet::iterator Best; 10467 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10468 // No viable functions. Don't bother the user with notes for functions 10469 // which don't work and shouldn't be found anyway. 10470 R.clear(); 10471 return false; 10472 } 10473 10474 // Find the namespaces where ADL would have looked, and suggest 10475 // declaring the function there instead. 10476 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10477 Sema::AssociatedClassSet AssociatedClasses; 10478 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10479 AssociatedNamespaces, 10480 AssociatedClasses); 10481 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10482 if (canBeDeclaredInNamespace(R.getLookupName())) { 10483 DeclContext *Std = SemaRef.getStdNamespace(); 10484 for (Sema::AssociatedNamespaceSet::iterator 10485 it = AssociatedNamespaces.begin(), 10486 end = AssociatedNamespaces.end(); it != end; ++it) { 10487 // Never suggest declaring a function within namespace 'std'. 10488 if (Std && Std->Encloses(*it)) 10489 continue; 10490 10491 // Never suggest declaring a function within a namespace with a 10492 // reserved name, like __gnu_cxx. 10493 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10494 if (NS && 10495 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10496 continue; 10497 10498 SuggestedNamespaces.insert(*it); 10499 } 10500 } 10501 10502 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10503 << R.getLookupName(); 10504 if (SuggestedNamespaces.empty()) { 10505 SemaRef.Diag(Best->Function->getLocation(), 10506 diag::note_not_found_by_two_phase_lookup) 10507 << R.getLookupName() << 0; 10508 } else if (SuggestedNamespaces.size() == 1) { 10509 SemaRef.Diag(Best->Function->getLocation(), 10510 diag::note_not_found_by_two_phase_lookup) 10511 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10512 } else { 10513 // FIXME: It would be useful to list the associated namespaces here, 10514 // but the diagnostics infrastructure doesn't provide a way to produce 10515 // a localized representation of a list of items. 10516 SemaRef.Diag(Best->Function->getLocation(), 10517 diag::note_not_found_by_two_phase_lookup) 10518 << R.getLookupName() << 2; 10519 } 10520 10521 // Try to recover by calling this function. 10522 return true; 10523 } 10524 10525 R.clear(); 10526 } 10527 10528 return false; 10529 } 10530 10531 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10532 /// template, where the non-dependent operator was declared after the template 10533 /// was defined. 10534 /// 10535 /// Returns true if a viable candidate was found and a diagnostic was issued. 10536 static bool 10537 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10538 SourceLocation OpLoc, 10539 ArrayRef<Expr *> Args) { 10540 DeclarationName OpName = 10541 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10542 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10543 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10544 OverloadCandidateSet::CSK_Operator, 10545 /*ExplicitTemplateArgs=*/nullptr, Args); 10546 } 10547 10548 namespace { 10549 class BuildRecoveryCallExprRAII { 10550 Sema &SemaRef; 10551 public: 10552 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10553 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10554 SemaRef.IsBuildingRecoveryCallExpr = true; 10555 } 10556 10557 ~BuildRecoveryCallExprRAII() { 10558 SemaRef.IsBuildingRecoveryCallExpr = false; 10559 } 10560 }; 10561 10562 } 10563 10564 /// Attempts to recover from a call where no functions were found. 10565 /// 10566 /// Returns true if new candidates were found. 10567 static ExprResult 10568 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10569 UnresolvedLookupExpr *ULE, 10570 SourceLocation LParenLoc, 10571 MutableArrayRef<Expr *> Args, 10572 SourceLocation RParenLoc, 10573 bool EmptyLookup, bool AllowTypoCorrection) { 10574 // Do not try to recover if it is already building a recovery call. 10575 // This stops infinite loops for template instantiations like 10576 // 10577 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10578 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10579 // 10580 if (SemaRef.IsBuildingRecoveryCallExpr) 10581 return ExprError(); 10582 BuildRecoveryCallExprRAII RCE(SemaRef); 10583 10584 CXXScopeSpec SS; 10585 SS.Adopt(ULE->getQualifierLoc()); 10586 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10587 10588 TemplateArgumentListInfo TABuffer; 10589 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10590 if (ULE->hasExplicitTemplateArgs()) { 10591 ULE->copyTemplateArgumentsInto(TABuffer); 10592 ExplicitTemplateArgs = &TABuffer; 10593 } 10594 10595 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10596 Sema::LookupOrdinaryName); 10597 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10598 ExplicitTemplateArgs != nullptr, 10599 dyn_cast<MemberExpr>(Fn)); 10600 NoTypoCorrectionCCC RejectAll; 10601 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10602 (CorrectionCandidateCallback*)&Validator : 10603 (CorrectionCandidateCallback*)&RejectAll; 10604 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10605 OverloadCandidateSet::CSK_Normal, 10606 ExplicitTemplateArgs, Args) && 10607 (!EmptyLookup || 10608 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10609 ExplicitTemplateArgs, Args))) 10610 return ExprError(); 10611 10612 assert(!R.empty() && "lookup results empty despite recovery"); 10613 10614 // Build an implicit member call if appropriate. Just drop the 10615 // casts and such from the call, we don't really care. 10616 ExprResult NewFn = ExprError(); 10617 if ((*R.begin())->isCXXClassMember()) 10618 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10619 R, ExplicitTemplateArgs); 10620 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10621 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10622 ExplicitTemplateArgs); 10623 else 10624 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10625 10626 if (NewFn.isInvalid()) 10627 return ExprError(); 10628 10629 // This shouldn't cause an infinite loop because we're giving it 10630 // an expression with viable lookup results, which should never 10631 // end up here. 10632 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10633 MultiExprArg(Args.data(), Args.size()), 10634 RParenLoc); 10635 } 10636 10637 /// \brief Constructs and populates an OverloadedCandidateSet from 10638 /// the given function. 10639 /// \returns true when an the ExprResult output parameter has been set. 10640 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10641 UnresolvedLookupExpr *ULE, 10642 MultiExprArg Args, 10643 SourceLocation RParenLoc, 10644 OverloadCandidateSet *CandidateSet, 10645 ExprResult *Result) { 10646 #ifndef NDEBUG 10647 if (ULE->requiresADL()) { 10648 // To do ADL, we must have found an unqualified name. 10649 assert(!ULE->getQualifier() && "qualified name with ADL"); 10650 10651 // We don't perform ADL for implicit declarations of builtins. 10652 // Verify that this was correctly set up. 10653 FunctionDecl *F; 10654 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10655 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10656 F->getBuiltinID() && F->isImplicit()) 10657 llvm_unreachable("performing ADL for builtin"); 10658 10659 // We don't perform ADL in C. 10660 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10661 } 10662 #endif 10663 10664 UnbridgedCastsSet UnbridgedCasts; 10665 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10666 *Result = ExprError(); 10667 return true; 10668 } 10669 10670 // Add the functions denoted by the callee to the set of candidate 10671 // functions, including those from argument-dependent lookup. 10672 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10673 10674 // If we found nothing, try to recover. 10675 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10676 // out if it fails. 10677 if (CandidateSet->empty()) { 10678 // In Microsoft mode, if we are inside a template class member function then 10679 // create a type dependent CallExpr. The goal is to postpone name lookup 10680 // to instantiation time to be able to search into type dependent base 10681 // classes. 10682 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10683 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10684 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10685 Context.DependentTy, VK_RValue, 10686 RParenLoc); 10687 CE->setTypeDependent(true); 10688 *Result = CE; 10689 return true; 10690 } 10691 return false; 10692 } 10693 10694 UnbridgedCasts.restore(); 10695 return false; 10696 } 10697 10698 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10699 /// the completed call expression. If overload resolution fails, emits 10700 /// diagnostics and returns ExprError() 10701 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10702 UnresolvedLookupExpr *ULE, 10703 SourceLocation LParenLoc, 10704 MultiExprArg Args, 10705 SourceLocation RParenLoc, 10706 Expr *ExecConfig, 10707 OverloadCandidateSet *CandidateSet, 10708 OverloadCandidateSet::iterator *Best, 10709 OverloadingResult OverloadResult, 10710 bool AllowTypoCorrection) { 10711 if (CandidateSet->empty()) 10712 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10713 RParenLoc, /*EmptyLookup=*/true, 10714 AllowTypoCorrection); 10715 10716 switch (OverloadResult) { 10717 case OR_Success: { 10718 FunctionDecl *FDecl = (*Best)->Function; 10719 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10720 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10721 return ExprError(); 10722 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10723 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10724 ExecConfig); 10725 } 10726 10727 case OR_No_Viable_Function: { 10728 // Try to recover by looking for viable functions which the user might 10729 // have meant to call. 10730 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10731 Args, RParenLoc, 10732 /*EmptyLookup=*/false, 10733 AllowTypoCorrection); 10734 if (!Recovery.isInvalid()) 10735 return Recovery; 10736 10737 SemaRef.Diag(Fn->getLocStart(), 10738 diag::err_ovl_no_viable_function_in_call) 10739 << ULE->getName() << Fn->getSourceRange(); 10740 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10741 break; 10742 } 10743 10744 case OR_Ambiguous: 10745 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10746 << ULE->getName() << Fn->getSourceRange(); 10747 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10748 break; 10749 10750 case OR_Deleted: { 10751 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10752 << (*Best)->Function->isDeleted() 10753 << ULE->getName() 10754 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10755 << Fn->getSourceRange(); 10756 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10757 10758 // We emitted an error for the unvailable/deleted function call but keep 10759 // the call in the AST. 10760 FunctionDecl *FDecl = (*Best)->Function; 10761 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10762 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10763 ExecConfig); 10764 } 10765 } 10766 10767 // Overload resolution failed. 10768 return ExprError(); 10769 } 10770 10771 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10772 /// (which eventually refers to the declaration Func) and the call 10773 /// arguments Args/NumArgs, attempt to resolve the function call down 10774 /// to a specific function. If overload resolution succeeds, returns 10775 /// the call expression produced by overload resolution. 10776 /// Otherwise, emits diagnostics and returns ExprError. 10777 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10778 UnresolvedLookupExpr *ULE, 10779 SourceLocation LParenLoc, 10780 MultiExprArg Args, 10781 SourceLocation RParenLoc, 10782 Expr *ExecConfig, 10783 bool AllowTypoCorrection) { 10784 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10785 OverloadCandidateSet::CSK_Normal); 10786 ExprResult result; 10787 10788 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10789 &result)) 10790 return result; 10791 10792 OverloadCandidateSet::iterator Best; 10793 OverloadingResult OverloadResult = 10794 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10795 10796 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10797 RParenLoc, ExecConfig, &CandidateSet, 10798 &Best, OverloadResult, 10799 AllowTypoCorrection); 10800 } 10801 10802 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10803 return Functions.size() > 1 || 10804 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10805 } 10806 10807 /// \brief Create a unary operation that may resolve to an overloaded 10808 /// operator. 10809 /// 10810 /// \param OpLoc The location of the operator itself (e.g., '*'). 10811 /// 10812 /// \param OpcIn The UnaryOperator::Opcode that describes this 10813 /// operator. 10814 /// 10815 /// \param Fns The set of non-member functions that will be 10816 /// considered by overload resolution. The caller needs to build this 10817 /// set based on the context using, e.g., 10818 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10819 /// set should not contain any member functions; those will be added 10820 /// by CreateOverloadedUnaryOp(). 10821 /// 10822 /// \param Input The input argument. 10823 ExprResult 10824 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10825 const UnresolvedSetImpl &Fns, 10826 Expr *Input) { 10827 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10828 10829 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10830 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10831 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10832 // TODO: provide better source location info. 10833 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10834 10835 if (checkPlaceholderForOverload(*this, Input)) 10836 return ExprError(); 10837 10838 Expr *Args[2] = { Input, nullptr }; 10839 unsigned NumArgs = 1; 10840 10841 // For post-increment and post-decrement, add the implicit '0' as 10842 // the second argument, so that we know this is a post-increment or 10843 // post-decrement. 10844 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10845 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10846 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10847 SourceLocation()); 10848 NumArgs = 2; 10849 } 10850 10851 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10852 10853 if (Input->isTypeDependent()) { 10854 if (Fns.empty()) 10855 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 10856 VK_RValue, OK_Ordinary, OpLoc); 10857 10858 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 10859 UnresolvedLookupExpr *Fn 10860 = UnresolvedLookupExpr::Create(Context, NamingClass, 10861 NestedNameSpecifierLoc(), OpNameInfo, 10862 /*ADL*/ true, IsOverloaded(Fns), 10863 Fns.begin(), Fns.end()); 10864 return new (Context) 10865 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 10866 VK_RValue, OpLoc, false); 10867 } 10868 10869 // Build an empty overload set. 10870 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10871 10872 // Add the candidates from the given function set. 10873 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10874 10875 // Add operator candidates that are member functions. 10876 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10877 10878 // Add candidates from ADL. 10879 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10880 /*ExplicitTemplateArgs*/nullptr, 10881 CandidateSet); 10882 10883 // Add builtin operator candidates. 10884 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10885 10886 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10887 10888 // Perform overload resolution. 10889 OverloadCandidateSet::iterator Best; 10890 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10891 case OR_Success: { 10892 // We found a built-in operator or an overloaded operator. 10893 FunctionDecl *FnDecl = Best->Function; 10894 10895 if (FnDecl) { 10896 // We matched an overloaded operator. Build a call to that 10897 // operator. 10898 10899 // Convert the arguments. 10900 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10901 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 10902 10903 ExprResult InputRes = 10904 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 10905 Best->FoundDecl, Method); 10906 if (InputRes.isInvalid()) 10907 return ExprError(); 10908 Input = InputRes.get(); 10909 } else { 10910 // Convert the arguments. 10911 ExprResult InputInit 10912 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10913 Context, 10914 FnDecl->getParamDecl(0)), 10915 SourceLocation(), 10916 Input); 10917 if (InputInit.isInvalid()) 10918 return ExprError(); 10919 Input = InputInit.get(); 10920 } 10921 10922 // Build the actual expression node. 10923 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10924 HadMultipleCandidates, OpLoc); 10925 if (FnExpr.isInvalid()) 10926 return ExprError(); 10927 10928 // Determine the result type. 10929 QualType ResultTy = FnDecl->getReturnType(); 10930 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10931 ResultTy = ResultTy.getNonLValueExprType(Context); 10932 10933 Args[0] = Input; 10934 CallExpr *TheCall = 10935 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 10936 ResultTy, VK, OpLoc, false); 10937 10938 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 10939 return ExprError(); 10940 10941 return MaybeBindToTemporary(TheCall); 10942 } else { 10943 // We matched a built-in operator. Convert the arguments, then 10944 // break out so that we will build the appropriate built-in 10945 // operator node. 10946 ExprResult InputRes = 10947 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10948 Best->Conversions[0], AA_Passing); 10949 if (InputRes.isInvalid()) 10950 return ExprError(); 10951 Input = InputRes.get(); 10952 break; 10953 } 10954 } 10955 10956 case OR_No_Viable_Function: 10957 // This is an erroneous use of an operator which can be overloaded by 10958 // a non-member function. Check for non-member operators which were 10959 // defined too late to be candidates. 10960 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10961 // FIXME: Recover by calling the found function. 10962 return ExprError(); 10963 10964 // No viable function; fall through to handling this as a 10965 // built-in operator, which will produce an error message for us. 10966 break; 10967 10968 case OR_Ambiguous: 10969 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10970 << UnaryOperator::getOpcodeStr(Opc) 10971 << Input->getType() 10972 << Input->getSourceRange(); 10973 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10974 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10975 return ExprError(); 10976 10977 case OR_Deleted: 10978 Diag(OpLoc, diag::err_ovl_deleted_oper) 10979 << Best->Function->isDeleted() 10980 << UnaryOperator::getOpcodeStr(Opc) 10981 << getDeletedOrUnavailableSuffix(Best->Function) 10982 << Input->getSourceRange(); 10983 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10984 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10985 return ExprError(); 10986 } 10987 10988 // Either we found no viable overloaded operator or we matched a 10989 // built-in operator. In either case, fall through to trying to 10990 // build a built-in operation. 10991 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10992 } 10993 10994 /// \brief Create a binary operation that may resolve to an overloaded 10995 /// operator. 10996 /// 10997 /// \param OpLoc The location of the operator itself (e.g., '+'). 10998 /// 10999 /// \param OpcIn The BinaryOperator::Opcode that describes this 11000 /// operator. 11001 /// 11002 /// \param Fns The set of non-member functions that will be 11003 /// considered by overload resolution. The caller needs to build this 11004 /// set based on the context using, e.g., 11005 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11006 /// set should not contain any member functions; those will be added 11007 /// by CreateOverloadedBinOp(). 11008 /// 11009 /// \param LHS Left-hand argument. 11010 /// \param RHS Right-hand argument. 11011 ExprResult 11012 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11013 unsigned OpcIn, 11014 const UnresolvedSetImpl &Fns, 11015 Expr *LHS, Expr *RHS) { 11016 Expr *Args[2] = { LHS, RHS }; 11017 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11018 11019 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11020 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11021 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11022 11023 // If either side is type-dependent, create an appropriate dependent 11024 // expression. 11025 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11026 if (Fns.empty()) { 11027 // If there are no functions to store, just build a dependent 11028 // BinaryOperator or CompoundAssignment. 11029 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11030 return new (Context) BinaryOperator( 11031 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11032 OpLoc, FPFeatures.fp_contract); 11033 11034 return new (Context) CompoundAssignOperator( 11035 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11036 Context.DependentTy, Context.DependentTy, OpLoc, 11037 FPFeatures.fp_contract); 11038 } 11039 11040 // FIXME: save results of ADL from here? 11041 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11042 // TODO: provide better source location info in DNLoc component. 11043 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11044 UnresolvedLookupExpr *Fn 11045 = UnresolvedLookupExpr::Create(Context, NamingClass, 11046 NestedNameSpecifierLoc(), OpNameInfo, 11047 /*ADL*/ true, IsOverloaded(Fns), 11048 Fns.begin(), Fns.end()); 11049 return new (Context) 11050 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11051 VK_RValue, OpLoc, FPFeatures.fp_contract); 11052 } 11053 11054 // Always do placeholder-like conversions on the RHS. 11055 if (checkPlaceholderForOverload(*this, Args[1])) 11056 return ExprError(); 11057 11058 // Do placeholder-like conversion on the LHS; note that we should 11059 // not get here with a PseudoObject LHS. 11060 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11061 if (checkPlaceholderForOverload(*this, Args[0])) 11062 return ExprError(); 11063 11064 // If this is the assignment operator, we only perform overload resolution 11065 // if the left-hand side is a class or enumeration type. This is actually 11066 // a hack. The standard requires that we do overload resolution between the 11067 // various built-in candidates, but as DR507 points out, this can lead to 11068 // problems. So we do it this way, which pretty much follows what GCC does. 11069 // Note that we go the traditional code path for compound assignment forms. 11070 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11071 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11072 11073 // If this is the .* operator, which is not overloadable, just 11074 // create a built-in binary operator. 11075 if (Opc == BO_PtrMemD) 11076 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11077 11078 // Build an empty overload set. 11079 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11080 11081 // Add the candidates from the given function set. 11082 AddFunctionCandidates(Fns, Args, CandidateSet, false); 11083 11084 // Add operator candidates that are member functions. 11085 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11086 11087 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11088 // performed for an assignment operator (nor for operator[] nor operator->, 11089 // which don't get here). 11090 if (Opc != BO_Assign) 11091 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11092 /*ExplicitTemplateArgs*/ nullptr, 11093 CandidateSet); 11094 11095 // Add builtin operator candidates. 11096 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11097 11098 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11099 11100 // Perform overload resolution. 11101 OverloadCandidateSet::iterator Best; 11102 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11103 case OR_Success: { 11104 // We found a built-in operator or an overloaded operator. 11105 FunctionDecl *FnDecl = Best->Function; 11106 11107 if (FnDecl) { 11108 // We matched an overloaded operator. Build a call to that 11109 // operator. 11110 11111 // Convert the arguments. 11112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11113 // Best->Access is only meaningful for class members. 11114 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11115 11116 ExprResult Arg1 = 11117 PerformCopyInitialization( 11118 InitializedEntity::InitializeParameter(Context, 11119 FnDecl->getParamDecl(0)), 11120 SourceLocation(), Args[1]); 11121 if (Arg1.isInvalid()) 11122 return ExprError(); 11123 11124 ExprResult Arg0 = 11125 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11126 Best->FoundDecl, Method); 11127 if (Arg0.isInvalid()) 11128 return ExprError(); 11129 Args[0] = Arg0.getAs<Expr>(); 11130 Args[1] = RHS = Arg1.getAs<Expr>(); 11131 } else { 11132 // Convert the arguments. 11133 ExprResult Arg0 = PerformCopyInitialization( 11134 InitializedEntity::InitializeParameter(Context, 11135 FnDecl->getParamDecl(0)), 11136 SourceLocation(), Args[0]); 11137 if (Arg0.isInvalid()) 11138 return ExprError(); 11139 11140 ExprResult Arg1 = 11141 PerformCopyInitialization( 11142 InitializedEntity::InitializeParameter(Context, 11143 FnDecl->getParamDecl(1)), 11144 SourceLocation(), Args[1]); 11145 if (Arg1.isInvalid()) 11146 return ExprError(); 11147 Args[0] = LHS = Arg0.getAs<Expr>(); 11148 Args[1] = RHS = Arg1.getAs<Expr>(); 11149 } 11150 11151 // Build the actual expression node. 11152 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11153 Best->FoundDecl, 11154 HadMultipleCandidates, OpLoc); 11155 if (FnExpr.isInvalid()) 11156 return ExprError(); 11157 11158 // Determine the result type. 11159 QualType ResultTy = FnDecl->getReturnType(); 11160 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11161 ResultTy = ResultTy.getNonLValueExprType(Context); 11162 11163 CXXOperatorCallExpr *TheCall = 11164 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11165 Args, ResultTy, VK, OpLoc, 11166 FPFeatures.fp_contract); 11167 11168 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11169 FnDecl)) 11170 return ExprError(); 11171 11172 ArrayRef<const Expr *> ArgsArray(Args, 2); 11173 // Cut off the implicit 'this'. 11174 if (isa<CXXMethodDecl>(FnDecl)) 11175 ArgsArray = ArgsArray.slice(1); 11176 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 11177 TheCall->getSourceRange(), VariadicDoesNotApply); 11178 11179 return MaybeBindToTemporary(TheCall); 11180 } else { 11181 // We matched a built-in operator. Convert the arguments, then 11182 // break out so that we will build the appropriate built-in 11183 // operator node. 11184 ExprResult ArgsRes0 = 11185 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11186 Best->Conversions[0], AA_Passing); 11187 if (ArgsRes0.isInvalid()) 11188 return ExprError(); 11189 Args[0] = ArgsRes0.get(); 11190 11191 ExprResult ArgsRes1 = 11192 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11193 Best->Conversions[1], AA_Passing); 11194 if (ArgsRes1.isInvalid()) 11195 return ExprError(); 11196 Args[1] = ArgsRes1.get(); 11197 break; 11198 } 11199 } 11200 11201 case OR_No_Viable_Function: { 11202 // C++ [over.match.oper]p9: 11203 // If the operator is the operator , [...] and there are no 11204 // viable functions, then the operator is assumed to be the 11205 // built-in operator and interpreted according to clause 5. 11206 if (Opc == BO_Comma) 11207 break; 11208 11209 // For class as left operand for assignment or compound assigment 11210 // operator do not fall through to handling in built-in, but report that 11211 // no overloaded assignment operator found 11212 ExprResult Result = ExprError(); 11213 if (Args[0]->getType()->isRecordType() && 11214 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11215 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11216 << BinaryOperator::getOpcodeStr(Opc) 11217 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11218 if (Args[0]->getType()->isIncompleteType()) { 11219 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11220 << Args[0]->getType() 11221 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11222 } 11223 } else { 11224 // This is an erroneous use of an operator which can be overloaded by 11225 // a non-member function. Check for non-member operators which were 11226 // defined too late to be candidates. 11227 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11228 // FIXME: Recover by calling the found function. 11229 return ExprError(); 11230 11231 // No viable function; try to create a built-in operation, which will 11232 // produce an error. Then, show the non-viable candidates. 11233 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11234 } 11235 assert(Result.isInvalid() && 11236 "C++ binary operator overloading is missing candidates!"); 11237 if (Result.isInvalid()) 11238 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11239 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11240 return Result; 11241 } 11242 11243 case OR_Ambiguous: 11244 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11245 << BinaryOperator::getOpcodeStr(Opc) 11246 << Args[0]->getType() << Args[1]->getType() 11247 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11248 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11249 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11250 return ExprError(); 11251 11252 case OR_Deleted: 11253 if (isImplicitlyDeleted(Best->Function)) { 11254 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11255 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11256 << Context.getRecordType(Method->getParent()) 11257 << getSpecialMember(Method); 11258 11259 // The user probably meant to call this special member. Just 11260 // explain why it's deleted. 11261 NoteDeletedFunction(Method); 11262 return ExprError(); 11263 } else { 11264 Diag(OpLoc, diag::err_ovl_deleted_oper) 11265 << Best->Function->isDeleted() 11266 << BinaryOperator::getOpcodeStr(Opc) 11267 << getDeletedOrUnavailableSuffix(Best->Function) 11268 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11269 } 11270 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11271 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11272 return ExprError(); 11273 } 11274 11275 // We matched a built-in operator; build it. 11276 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11277 } 11278 11279 ExprResult 11280 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11281 SourceLocation RLoc, 11282 Expr *Base, Expr *Idx) { 11283 Expr *Args[2] = { Base, Idx }; 11284 DeclarationName OpName = 11285 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11286 11287 // If either side is type-dependent, create an appropriate dependent 11288 // expression. 11289 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11290 11291 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11292 // CHECKME: no 'operator' keyword? 11293 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11294 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11295 UnresolvedLookupExpr *Fn 11296 = UnresolvedLookupExpr::Create(Context, NamingClass, 11297 NestedNameSpecifierLoc(), OpNameInfo, 11298 /*ADL*/ true, /*Overloaded*/ false, 11299 UnresolvedSetIterator(), 11300 UnresolvedSetIterator()); 11301 // Can't add any actual overloads yet 11302 11303 return new (Context) 11304 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11305 Context.DependentTy, VK_RValue, RLoc, false); 11306 } 11307 11308 // Handle placeholders on both operands. 11309 if (checkPlaceholderForOverload(*this, Args[0])) 11310 return ExprError(); 11311 if (checkPlaceholderForOverload(*this, Args[1])) 11312 return ExprError(); 11313 11314 // Build an empty overload set. 11315 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11316 11317 // Subscript can only be overloaded as a member function. 11318 11319 // Add operator candidates that are member functions. 11320 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11321 11322 // Add builtin operator candidates. 11323 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11324 11325 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11326 11327 // Perform overload resolution. 11328 OverloadCandidateSet::iterator Best; 11329 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11330 case OR_Success: { 11331 // We found a built-in operator or an overloaded operator. 11332 FunctionDecl *FnDecl = Best->Function; 11333 11334 if (FnDecl) { 11335 // We matched an overloaded operator. Build a call to that 11336 // operator. 11337 11338 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11339 11340 // Convert the arguments. 11341 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11342 ExprResult Arg0 = 11343 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11344 Best->FoundDecl, Method); 11345 if (Arg0.isInvalid()) 11346 return ExprError(); 11347 Args[0] = Arg0.get(); 11348 11349 // Convert the arguments. 11350 ExprResult InputInit 11351 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11352 Context, 11353 FnDecl->getParamDecl(0)), 11354 SourceLocation(), 11355 Args[1]); 11356 if (InputInit.isInvalid()) 11357 return ExprError(); 11358 11359 Args[1] = InputInit.getAs<Expr>(); 11360 11361 // Build the actual expression node. 11362 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11363 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11364 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11365 Best->FoundDecl, 11366 HadMultipleCandidates, 11367 OpLocInfo.getLoc(), 11368 OpLocInfo.getInfo()); 11369 if (FnExpr.isInvalid()) 11370 return ExprError(); 11371 11372 // Determine the result type 11373 QualType ResultTy = FnDecl->getReturnType(); 11374 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11375 ResultTy = ResultTy.getNonLValueExprType(Context); 11376 11377 CXXOperatorCallExpr *TheCall = 11378 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11379 FnExpr.get(), Args, 11380 ResultTy, VK, RLoc, 11381 false); 11382 11383 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11384 return ExprError(); 11385 11386 return MaybeBindToTemporary(TheCall); 11387 } else { 11388 // We matched a built-in operator. Convert the arguments, then 11389 // break out so that we will build the appropriate built-in 11390 // operator node. 11391 ExprResult ArgsRes0 = 11392 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11393 Best->Conversions[0], AA_Passing); 11394 if (ArgsRes0.isInvalid()) 11395 return ExprError(); 11396 Args[0] = ArgsRes0.get(); 11397 11398 ExprResult ArgsRes1 = 11399 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11400 Best->Conversions[1], AA_Passing); 11401 if (ArgsRes1.isInvalid()) 11402 return ExprError(); 11403 Args[1] = ArgsRes1.get(); 11404 11405 break; 11406 } 11407 } 11408 11409 case OR_No_Viable_Function: { 11410 if (CandidateSet.empty()) 11411 Diag(LLoc, diag::err_ovl_no_oper) 11412 << Args[0]->getType() << /*subscript*/ 0 11413 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11414 else 11415 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11416 << Args[0]->getType() 11417 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11418 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11419 "[]", LLoc); 11420 return ExprError(); 11421 } 11422 11423 case OR_Ambiguous: 11424 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11425 << "[]" 11426 << Args[0]->getType() << Args[1]->getType() 11427 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11428 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11429 "[]", LLoc); 11430 return ExprError(); 11431 11432 case OR_Deleted: 11433 Diag(LLoc, diag::err_ovl_deleted_oper) 11434 << Best->Function->isDeleted() << "[]" 11435 << getDeletedOrUnavailableSuffix(Best->Function) 11436 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11437 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11438 "[]", LLoc); 11439 return ExprError(); 11440 } 11441 11442 // We matched a built-in operator; build it. 11443 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11444 } 11445 11446 /// BuildCallToMemberFunction - Build a call to a member 11447 /// function. MemExpr is the expression that refers to the member 11448 /// function (and includes the object parameter), Args/NumArgs are the 11449 /// arguments to the function call (not including the object 11450 /// parameter). The caller needs to validate that the member 11451 /// expression refers to a non-static member function or an overloaded 11452 /// member function. 11453 ExprResult 11454 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11455 SourceLocation LParenLoc, 11456 MultiExprArg Args, 11457 SourceLocation RParenLoc) { 11458 assert(MemExprE->getType() == Context.BoundMemberTy || 11459 MemExprE->getType() == Context.OverloadTy); 11460 11461 // Dig out the member expression. This holds both the object 11462 // argument and the member function we're referring to. 11463 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11464 11465 // Determine whether this is a call to a pointer-to-member function. 11466 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11467 assert(op->getType() == Context.BoundMemberTy); 11468 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11469 11470 QualType fnType = 11471 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11472 11473 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11474 QualType resultType = proto->getCallResultType(Context); 11475 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11476 11477 // Check that the object type isn't more qualified than the 11478 // member function we're calling. 11479 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11480 11481 QualType objectType = op->getLHS()->getType(); 11482 if (op->getOpcode() == BO_PtrMemI) 11483 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11484 Qualifiers objectQuals = objectType.getQualifiers(); 11485 11486 Qualifiers difference = objectQuals - funcQuals; 11487 difference.removeObjCGCAttr(); 11488 difference.removeAddressSpace(); 11489 if (difference) { 11490 std::string qualsString = difference.getAsString(); 11491 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11492 << fnType.getUnqualifiedType() 11493 << qualsString 11494 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11495 } 11496 11497 if (resultType->isMemberPointerType()) 11498 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11499 RequireCompleteType(LParenLoc, resultType, 0); 11500 11501 CXXMemberCallExpr *call 11502 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11503 resultType, valueKind, RParenLoc); 11504 11505 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11506 call, nullptr)) 11507 return ExprError(); 11508 11509 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11510 return ExprError(); 11511 11512 if (CheckOtherCall(call, proto)) 11513 return ExprError(); 11514 11515 return MaybeBindToTemporary(call); 11516 } 11517 11518 UnbridgedCastsSet UnbridgedCasts; 11519 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11520 return ExprError(); 11521 11522 MemberExpr *MemExpr; 11523 CXXMethodDecl *Method = nullptr; 11524 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11525 NestedNameSpecifier *Qualifier = nullptr; 11526 if (isa<MemberExpr>(NakedMemExpr)) { 11527 MemExpr = cast<MemberExpr>(NakedMemExpr); 11528 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11529 FoundDecl = MemExpr->getFoundDecl(); 11530 Qualifier = MemExpr->getQualifier(); 11531 UnbridgedCasts.restore(); 11532 } else { 11533 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11534 Qualifier = UnresExpr->getQualifier(); 11535 11536 QualType ObjectType = UnresExpr->getBaseType(); 11537 Expr::Classification ObjectClassification 11538 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11539 : UnresExpr->getBase()->Classify(Context); 11540 11541 // Add overload candidates 11542 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11543 OverloadCandidateSet::CSK_Normal); 11544 11545 // FIXME: avoid copy. 11546 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11547 if (UnresExpr->hasExplicitTemplateArgs()) { 11548 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11549 TemplateArgs = &TemplateArgsBuffer; 11550 } 11551 11552 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11553 E = UnresExpr->decls_end(); I != E; ++I) { 11554 11555 NamedDecl *Func = *I; 11556 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11557 if (isa<UsingShadowDecl>(Func)) 11558 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11559 11560 11561 // Microsoft supports direct constructor calls. 11562 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11563 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11564 Args, CandidateSet); 11565 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11566 // If explicit template arguments were provided, we can't call a 11567 // non-template member function. 11568 if (TemplateArgs) 11569 continue; 11570 11571 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11572 ObjectClassification, Args, CandidateSet, 11573 /*SuppressUserConversions=*/false); 11574 } else { 11575 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11576 I.getPair(), ActingDC, TemplateArgs, 11577 ObjectType, ObjectClassification, 11578 Args, CandidateSet, 11579 /*SuppressUsedConversions=*/false); 11580 } 11581 } 11582 11583 DeclarationName DeclName = UnresExpr->getMemberName(); 11584 11585 UnbridgedCasts.restore(); 11586 11587 OverloadCandidateSet::iterator Best; 11588 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11589 Best)) { 11590 case OR_Success: 11591 Method = cast<CXXMethodDecl>(Best->Function); 11592 FoundDecl = Best->FoundDecl; 11593 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11594 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11595 return ExprError(); 11596 // If FoundDecl is different from Method (such as if one is a template 11597 // and the other a specialization), make sure DiagnoseUseOfDecl is 11598 // called on both. 11599 // FIXME: This would be more comprehensively addressed by modifying 11600 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11601 // being used. 11602 if (Method != FoundDecl.getDecl() && 11603 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11604 return ExprError(); 11605 break; 11606 11607 case OR_No_Viable_Function: 11608 Diag(UnresExpr->getMemberLoc(), 11609 diag::err_ovl_no_viable_member_function_in_call) 11610 << DeclName << MemExprE->getSourceRange(); 11611 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11612 // FIXME: Leaking incoming expressions! 11613 return ExprError(); 11614 11615 case OR_Ambiguous: 11616 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11617 << DeclName << MemExprE->getSourceRange(); 11618 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11619 // FIXME: Leaking incoming expressions! 11620 return ExprError(); 11621 11622 case OR_Deleted: 11623 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11624 << Best->Function->isDeleted() 11625 << DeclName 11626 << getDeletedOrUnavailableSuffix(Best->Function) 11627 << MemExprE->getSourceRange(); 11628 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11629 // FIXME: Leaking incoming expressions! 11630 return ExprError(); 11631 } 11632 11633 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11634 11635 // If overload resolution picked a static member, build a 11636 // non-member call based on that function. 11637 if (Method->isStatic()) { 11638 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11639 RParenLoc); 11640 } 11641 11642 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11643 } 11644 11645 QualType ResultType = Method->getReturnType(); 11646 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11647 ResultType = ResultType.getNonLValueExprType(Context); 11648 11649 assert(Method && "Member call to something that isn't a method?"); 11650 CXXMemberCallExpr *TheCall = 11651 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11652 ResultType, VK, RParenLoc); 11653 11654 // (CUDA B.1): Check for invalid calls between targets. 11655 if (getLangOpts().CUDA) { 11656 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11657 if (CheckCUDATarget(Caller, Method)) { 11658 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11659 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11660 << IdentifyCUDATarget(Caller); 11661 return ExprError(); 11662 } 11663 } 11664 } 11665 11666 // Check for a valid return type. 11667 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11668 TheCall, Method)) 11669 return ExprError(); 11670 11671 // Convert the object argument (for a non-static member function call). 11672 // We only need to do this if there was actually an overload; otherwise 11673 // it was done at lookup. 11674 if (!Method->isStatic()) { 11675 ExprResult ObjectArg = 11676 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11677 FoundDecl, Method); 11678 if (ObjectArg.isInvalid()) 11679 return ExprError(); 11680 MemExpr->setBase(ObjectArg.get()); 11681 } 11682 11683 // Convert the rest of the arguments 11684 const FunctionProtoType *Proto = 11685 Method->getType()->getAs<FunctionProtoType>(); 11686 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11687 RParenLoc)) 11688 return ExprError(); 11689 11690 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11691 11692 if (CheckFunctionCall(Method, TheCall, Proto)) 11693 return ExprError(); 11694 11695 if ((isa<CXXConstructorDecl>(CurContext) || 11696 isa<CXXDestructorDecl>(CurContext)) && 11697 TheCall->getMethodDecl()->isPure()) { 11698 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11699 11700 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11701 Diag(MemExpr->getLocStart(), 11702 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11703 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11704 << MD->getParent()->getDeclName(); 11705 11706 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11707 } 11708 } 11709 return MaybeBindToTemporary(TheCall); 11710 } 11711 11712 /// BuildCallToObjectOfClassType - Build a call to an object of class 11713 /// type (C++ [over.call.object]), which can end up invoking an 11714 /// overloaded function call operator (@c operator()) or performing a 11715 /// user-defined conversion on the object argument. 11716 ExprResult 11717 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11718 SourceLocation LParenLoc, 11719 MultiExprArg Args, 11720 SourceLocation RParenLoc) { 11721 if (checkPlaceholderForOverload(*this, Obj)) 11722 return ExprError(); 11723 ExprResult Object = Obj; 11724 11725 UnbridgedCastsSet UnbridgedCasts; 11726 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11727 return ExprError(); 11728 11729 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11730 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11731 11732 // C++ [over.call.object]p1: 11733 // If the primary-expression E in the function call syntax 11734 // evaluates to a class object of type "cv T", then the set of 11735 // candidate functions includes at least the function call 11736 // operators of T. The function call operators of T are obtained by 11737 // ordinary lookup of the name operator() in the context of 11738 // (E).operator(). 11739 OverloadCandidateSet CandidateSet(LParenLoc, 11740 OverloadCandidateSet::CSK_Operator); 11741 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11742 11743 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11744 diag::err_incomplete_object_call, Object.get())) 11745 return true; 11746 11747 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11748 LookupQualifiedName(R, Record->getDecl()); 11749 R.suppressDiagnostics(); 11750 11751 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11752 Oper != OperEnd; ++Oper) { 11753 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11754 Object.get()->Classify(Context), 11755 Args, CandidateSet, 11756 /*SuppressUserConversions=*/ false); 11757 } 11758 11759 // C++ [over.call.object]p2: 11760 // In addition, for each (non-explicit in C++0x) conversion function 11761 // declared in T of the form 11762 // 11763 // operator conversion-type-id () cv-qualifier; 11764 // 11765 // where cv-qualifier is the same cv-qualification as, or a 11766 // greater cv-qualification than, cv, and where conversion-type-id 11767 // denotes the type "pointer to function of (P1,...,Pn) returning 11768 // R", or the type "reference to pointer to function of 11769 // (P1,...,Pn) returning R", or the type "reference to function 11770 // of (P1,...,Pn) returning R", a surrogate call function [...] 11771 // is also considered as a candidate function. Similarly, 11772 // surrogate call functions are added to the set of candidate 11773 // functions for each conversion function declared in an 11774 // accessible base class provided the function is not hidden 11775 // within T by another intervening declaration. 11776 std::pair<CXXRecordDecl::conversion_iterator, 11777 CXXRecordDecl::conversion_iterator> Conversions 11778 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11779 for (CXXRecordDecl::conversion_iterator 11780 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11781 NamedDecl *D = *I; 11782 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11783 if (isa<UsingShadowDecl>(D)) 11784 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11785 11786 // Skip over templated conversion functions; they aren't 11787 // surrogates. 11788 if (isa<FunctionTemplateDecl>(D)) 11789 continue; 11790 11791 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11792 if (!Conv->isExplicit()) { 11793 // Strip the reference type (if any) and then the pointer type (if 11794 // any) to get down to what might be a function type. 11795 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11796 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11797 ConvType = ConvPtrType->getPointeeType(); 11798 11799 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11800 { 11801 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11802 Object.get(), Args, CandidateSet); 11803 } 11804 } 11805 } 11806 11807 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11808 11809 // Perform overload resolution. 11810 OverloadCandidateSet::iterator Best; 11811 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11812 Best)) { 11813 case OR_Success: 11814 // Overload resolution succeeded; we'll build the appropriate call 11815 // below. 11816 break; 11817 11818 case OR_No_Viable_Function: 11819 if (CandidateSet.empty()) 11820 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11821 << Object.get()->getType() << /*call*/ 1 11822 << Object.get()->getSourceRange(); 11823 else 11824 Diag(Object.get()->getLocStart(), 11825 diag::err_ovl_no_viable_object_call) 11826 << Object.get()->getType() << Object.get()->getSourceRange(); 11827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11828 break; 11829 11830 case OR_Ambiguous: 11831 Diag(Object.get()->getLocStart(), 11832 diag::err_ovl_ambiguous_object_call) 11833 << Object.get()->getType() << Object.get()->getSourceRange(); 11834 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11835 break; 11836 11837 case OR_Deleted: 11838 Diag(Object.get()->getLocStart(), 11839 diag::err_ovl_deleted_object_call) 11840 << Best->Function->isDeleted() 11841 << Object.get()->getType() 11842 << getDeletedOrUnavailableSuffix(Best->Function) 11843 << Object.get()->getSourceRange(); 11844 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11845 break; 11846 } 11847 11848 if (Best == CandidateSet.end()) 11849 return true; 11850 11851 UnbridgedCasts.restore(); 11852 11853 if (Best->Function == nullptr) { 11854 // Since there is no function declaration, this is one of the 11855 // surrogate candidates. Dig out the conversion function. 11856 CXXConversionDecl *Conv 11857 = cast<CXXConversionDecl>( 11858 Best->Conversions[0].UserDefined.ConversionFunction); 11859 11860 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 11861 Best->FoundDecl); 11862 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11863 return ExprError(); 11864 assert(Conv == Best->FoundDecl.getDecl() && 11865 "Found Decl & conversion-to-functionptr should be same, right?!"); 11866 // We selected one of the surrogate functions that converts the 11867 // object parameter to a function pointer. Perform the conversion 11868 // on the object argument, then let ActOnCallExpr finish the job. 11869 11870 // Create an implicit member expr to refer to the conversion operator. 11871 // and then call it. 11872 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11873 Conv, HadMultipleCandidates); 11874 if (Call.isInvalid()) 11875 return ExprError(); 11876 // Record usage of conversion in an implicit cast. 11877 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 11878 CK_UserDefinedConversion, Call.get(), 11879 nullptr, VK_RValue); 11880 11881 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11882 } 11883 11884 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 11885 11886 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11887 // that calls this method, using Object for the implicit object 11888 // parameter and passing along the remaining arguments. 11889 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11890 11891 // An error diagnostic has already been printed when parsing the declaration. 11892 if (Method->isInvalidDecl()) 11893 return ExprError(); 11894 11895 const FunctionProtoType *Proto = 11896 Method->getType()->getAs<FunctionProtoType>(); 11897 11898 unsigned NumParams = Proto->getNumParams(); 11899 11900 DeclarationNameInfo OpLocInfo( 11901 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11902 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11903 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11904 HadMultipleCandidates, 11905 OpLocInfo.getLoc(), 11906 OpLocInfo.getInfo()); 11907 if (NewFn.isInvalid()) 11908 return true; 11909 11910 // Build the full argument list for the method call (the implicit object 11911 // parameter is placed at the beginning of the list). 11912 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11913 MethodArgs[0] = Object.get(); 11914 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11915 11916 // Once we've built TheCall, all of the expressions are properly 11917 // owned. 11918 QualType ResultTy = Method->getReturnType(); 11919 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11920 ResultTy = ResultTy.getNonLValueExprType(Context); 11921 11922 CXXOperatorCallExpr *TheCall = new (Context) 11923 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 11924 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11925 ResultTy, VK, RParenLoc, false); 11926 MethodArgs.reset(); 11927 11928 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 11929 return true; 11930 11931 // We may have default arguments. If so, we need to allocate more 11932 // slots in the call for them. 11933 if (Args.size() < NumParams) 11934 TheCall->setNumArgs(Context, NumParams + 1); 11935 11936 bool IsError = false; 11937 11938 // Initialize the implicit object parameter. 11939 ExprResult ObjRes = 11940 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 11941 Best->FoundDecl, Method); 11942 if (ObjRes.isInvalid()) 11943 IsError = true; 11944 else 11945 Object = ObjRes; 11946 TheCall->setArg(0, Object.get()); 11947 11948 // Check the argument types. 11949 for (unsigned i = 0; i != NumParams; i++) { 11950 Expr *Arg; 11951 if (i < Args.size()) { 11952 Arg = Args[i]; 11953 11954 // Pass the argument. 11955 11956 ExprResult InputInit 11957 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11958 Context, 11959 Method->getParamDecl(i)), 11960 SourceLocation(), Arg); 11961 11962 IsError |= InputInit.isInvalid(); 11963 Arg = InputInit.getAs<Expr>(); 11964 } else { 11965 ExprResult DefArg 11966 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11967 if (DefArg.isInvalid()) { 11968 IsError = true; 11969 break; 11970 } 11971 11972 Arg = DefArg.getAs<Expr>(); 11973 } 11974 11975 TheCall->setArg(i + 1, Arg); 11976 } 11977 11978 // If this is a variadic call, handle args passed through "...". 11979 if (Proto->isVariadic()) { 11980 // Promote the arguments (C99 6.5.2.2p7). 11981 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 11982 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 11983 nullptr); 11984 IsError |= Arg.isInvalid(); 11985 TheCall->setArg(i + 1, Arg.get()); 11986 } 11987 } 11988 11989 if (IsError) return true; 11990 11991 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11992 11993 if (CheckFunctionCall(Method, TheCall, Proto)) 11994 return true; 11995 11996 return MaybeBindToTemporary(TheCall); 11997 } 11998 11999 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12000 /// (if one exists), where @c Base is an expression of class type and 12001 /// @c Member is the name of the member we're trying to find. 12002 ExprResult 12003 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12004 bool *NoArrowOperatorFound) { 12005 assert(Base->getType()->isRecordType() && 12006 "left-hand side must have class type"); 12007 12008 if (checkPlaceholderForOverload(*this, Base)) 12009 return ExprError(); 12010 12011 SourceLocation Loc = Base->getExprLoc(); 12012 12013 // C++ [over.ref]p1: 12014 // 12015 // [...] An expression x->m is interpreted as (x.operator->())->m 12016 // for a class object x of type T if T::operator->() exists and if 12017 // the operator is selected as the best match function by the 12018 // overload resolution mechanism (13.3). 12019 DeclarationName OpName = 12020 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12021 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12022 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12023 12024 if (RequireCompleteType(Loc, Base->getType(), 12025 diag::err_typecheck_incomplete_tag, Base)) 12026 return ExprError(); 12027 12028 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12029 LookupQualifiedName(R, BaseRecord->getDecl()); 12030 R.suppressDiagnostics(); 12031 12032 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12033 Oper != OperEnd; ++Oper) { 12034 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12035 None, CandidateSet, /*SuppressUserConversions=*/false); 12036 } 12037 12038 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12039 12040 // Perform overload resolution. 12041 OverloadCandidateSet::iterator Best; 12042 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12043 case OR_Success: 12044 // Overload resolution succeeded; we'll build the call below. 12045 break; 12046 12047 case OR_No_Viable_Function: 12048 if (CandidateSet.empty()) { 12049 QualType BaseType = Base->getType(); 12050 if (NoArrowOperatorFound) { 12051 // Report this specific error to the caller instead of emitting a 12052 // diagnostic, as requested. 12053 *NoArrowOperatorFound = true; 12054 return ExprError(); 12055 } 12056 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12057 << BaseType << Base->getSourceRange(); 12058 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12059 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12060 << FixItHint::CreateReplacement(OpLoc, "."); 12061 } 12062 } else 12063 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12064 << "operator->" << Base->getSourceRange(); 12065 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12066 return ExprError(); 12067 12068 case OR_Ambiguous: 12069 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12070 << "->" << Base->getType() << Base->getSourceRange(); 12071 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12072 return ExprError(); 12073 12074 case OR_Deleted: 12075 Diag(OpLoc, diag::err_ovl_deleted_oper) 12076 << Best->Function->isDeleted() 12077 << "->" 12078 << getDeletedOrUnavailableSuffix(Best->Function) 12079 << Base->getSourceRange(); 12080 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12081 return ExprError(); 12082 } 12083 12084 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12085 12086 // Convert the object parameter. 12087 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12088 ExprResult BaseResult = 12089 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12090 Best->FoundDecl, Method); 12091 if (BaseResult.isInvalid()) 12092 return ExprError(); 12093 Base = BaseResult.get(); 12094 12095 // Build the operator call. 12096 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12097 HadMultipleCandidates, OpLoc); 12098 if (FnExpr.isInvalid()) 12099 return ExprError(); 12100 12101 QualType ResultTy = Method->getReturnType(); 12102 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12103 ResultTy = ResultTy.getNonLValueExprType(Context); 12104 CXXOperatorCallExpr *TheCall = 12105 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12106 Base, ResultTy, VK, OpLoc, false); 12107 12108 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12109 return ExprError(); 12110 12111 return MaybeBindToTemporary(TheCall); 12112 } 12113 12114 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12115 /// a literal operator described by the provided lookup results. 12116 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12117 DeclarationNameInfo &SuffixInfo, 12118 ArrayRef<Expr*> Args, 12119 SourceLocation LitEndLoc, 12120 TemplateArgumentListInfo *TemplateArgs) { 12121 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12122 12123 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12124 OverloadCandidateSet::CSK_Normal); 12125 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 12126 TemplateArgs); 12127 12128 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12129 12130 // Perform overload resolution. This will usually be trivial, but might need 12131 // to perform substitutions for a literal operator template. 12132 OverloadCandidateSet::iterator Best; 12133 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12134 case OR_Success: 12135 case OR_Deleted: 12136 break; 12137 12138 case OR_No_Viable_Function: 12139 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12140 << R.getLookupName(); 12141 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12142 return ExprError(); 12143 12144 case OR_Ambiguous: 12145 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12146 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12147 return ExprError(); 12148 } 12149 12150 FunctionDecl *FD = Best->Function; 12151 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12152 HadMultipleCandidates, 12153 SuffixInfo.getLoc(), 12154 SuffixInfo.getInfo()); 12155 if (Fn.isInvalid()) 12156 return true; 12157 12158 // Check the argument types. This should almost always be a no-op, except 12159 // that array-to-pointer decay is applied to string literals. 12160 Expr *ConvArgs[2]; 12161 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12162 ExprResult InputInit = PerformCopyInitialization( 12163 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12164 SourceLocation(), Args[ArgIdx]); 12165 if (InputInit.isInvalid()) 12166 return true; 12167 ConvArgs[ArgIdx] = InputInit.get(); 12168 } 12169 12170 QualType ResultTy = FD->getReturnType(); 12171 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12172 ResultTy = ResultTy.getNonLValueExprType(Context); 12173 12174 UserDefinedLiteral *UDL = 12175 new (Context) UserDefinedLiteral(Context, Fn.get(), 12176 llvm::makeArrayRef(ConvArgs, Args.size()), 12177 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12178 12179 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12180 return ExprError(); 12181 12182 if (CheckFunctionCall(FD, UDL, nullptr)) 12183 return ExprError(); 12184 12185 return MaybeBindToTemporary(UDL); 12186 } 12187 12188 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12189 /// given LookupResult is non-empty, it is assumed to describe a member which 12190 /// will be invoked. Otherwise, the function will be found via argument 12191 /// dependent lookup. 12192 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12193 /// otherwise CallExpr is set to ExprError() and some non-success value 12194 /// is returned. 12195 Sema::ForRangeStatus 12196 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12197 SourceLocation RangeLoc, VarDecl *Decl, 12198 BeginEndFunction BEF, 12199 const DeclarationNameInfo &NameInfo, 12200 LookupResult &MemberLookup, 12201 OverloadCandidateSet *CandidateSet, 12202 Expr *Range, ExprResult *CallExpr) { 12203 CandidateSet->clear(); 12204 if (!MemberLookup.empty()) { 12205 ExprResult MemberRef = 12206 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12207 /*IsPtr=*/false, CXXScopeSpec(), 12208 /*TemplateKWLoc=*/SourceLocation(), 12209 /*FirstQualifierInScope=*/nullptr, 12210 MemberLookup, 12211 /*TemplateArgs=*/nullptr); 12212 if (MemberRef.isInvalid()) { 12213 *CallExpr = ExprError(); 12214 Diag(Range->getLocStart(), diag::note_in_for_range) 12215 << RangeLoc << BEF << Range->getType(); 12216 return FRS_DiagnosticIssued; 12217 } 12218 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12219 if (CallExpr->isInvalid()) { 12220 *CallExpr = ExprError(); 12221 Diag(Range->getLocStart(), diag::note_in_for_range) 12222 << RangeLoc << BEF << Range->getType(); 12223 return FRS_DiagnosticIssued; 12224 } 12225 } else { 12226 UnresolvedSet<0> FoundNames; 12227 UnresolvedLookupExpr *Fn = 12228 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12229 NestedNameSpecifierLoc(), NameInfo, 12230 /*NeedsADL=*/true, /*Overloaded=*/false, 12231 FoundNames.begin(), FoundNames.end()); 12232 12233 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12234 CandidateSet, CallExpr); 12235 if (CandidateSet->empty() || CandidateSetError) { 12236 *CallExpr = ExprError(); 12237 return FRS_NoViableFunction; 12238 } 12239 OverloadCandidateSet::iterator Best; 12240 OverloadingResult OverloadResult = 12241 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12242 12243 if (OverloadResult == OR_No_Viable_Function) { 12244 *CallExpr = ExprError(); 12245 return FRS_NoViableFunction; 12246 } 12247 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12248 Loc, nullptr, CandidateSet, &Best, 12249 OverloadResult, 12250 /*AllowTypoCorrection=*/false); 12251 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12252 *CallExpr = ExprError(); 12253 Diag(Range->getLocStart(), diag::note_in_for_range) 12254 << RangeLoc << BEF << Range->getType(); 12255 return FRS_DiagnosticIssued; 12256 } 12257 } 12258 return FRS_Success; 12259 } 12260 12261 12262 /// FixOverloadedFunctionReference - E is an expression that refers to 12263 /// a C++ overloaded function (possibly with some parentheses and 12264 /// perhaps a '&' around it). We have resolved the overloaded function 12265 /// to the function declaration Fn, so patch up the expression E to 12266 /// refer (possibly indirectly) to Fn. Returns the new expr. 12267 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12268 FunctionDecl *Fn) { 12269 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12270 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12271 Found, Fn); 12272 if (SubExpr == PE->getSubExpr()) 12273 return PE; 12274 12275 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12276 } 12277 12278 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12279 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12280 Found, Fn); 12281 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12282 SubExpr->getType()) && 12283 "Implicit cast type cannot be determined from overload"); 12284 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12285 if (SubExpr == ICE->getSubExpr()) 12286 return ICE; 12287 12288 return ImplicitCastExpr::Create(Context, ICE->getType(), 12289 ICE->getCastKind(), 12290 SubExpr, nullptr, 12291 ICE->getValueKind()); 12292 } 12293 12294 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12295 assert(UnOp->getOpcode() == UO_AddrOf && 12296 "Can only take the address of an overloaded function"); 12297 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12298 if (Method->isStatic()) { 12299 // Do nothing: static member functions aren't any different 12300 // from non-member functions. 12301 } else { 12302 // Fix the subexpression, which really has to be an 12303 // UnresolvedLookupExpr holding an overloaded member function 12304 // or template. 12305 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12306 Found, Fn); 12307 if (SubExpr == UnOp->getSubExpr()) 12308 return UnOp; 12309 12310 assert(isa<DeclRefExpr>(SubExpr) 12311 && "fixed to something other than a decl ref"); 12312 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12313 && "fixed to a member ref with no nested name qualifier"); 12314 12315 // We have taken the address of a pointer to member 12316 // function. Perform the computation here so that we get the 12317 // appropriate pointer to member type. 12318 QualType ClassType 12319 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12320 QualType MemPtrType 12321 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12322 12323 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12324 VK_RValue, OK_Ordinary, 12325 UnOp->getOperatorLoc()); 12326 } 12327 } 12328 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12329 Found, Fn); 12330 if (SubExpr == UnOp->getSubExpr()) 12331 return UnOp; 12332 12333 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12334 Context.getPointerType(SubExpr->getType()), 12335 VK_RValue, OK_Ordinary, 12336 UnOp->getOperatorLoc()); 12337 } 12338 12339 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12340 // FIXME: avoid copy. 12341 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12342 if (ULE->hasExplicitTemplateArgs()) { 12343 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12344 TemplateArgs = &TemplateArgsBuffer; 12345 } 12346 12347 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12348 ULE->getQualifierLoc(), 12349 ULE->getTemplateKeywordLoc(), 12350 Fn, 12351 /*enclosing*/ false, // FIXME? 12352 ULE->getNameLoc(), 12353 Fn->getType(), 12354 VK_LValue, 12355 Found.getDecl(), 12356 TemplateArgs); 12357 MarkDeclRefReferenced(DRE); 12358 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12359 return DRE; 12360 } 12361 12362 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12363 // FIXME: avoid copy. 12364 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12365 if (MemExpr->hasExplicitTemplateArgs()) { 12366 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12367 TemplateArgs = &TemplateArgsBuffer; 12368 } 12369 12370 Expr *Base; 12371 12372 // If we're filling in a static method where we used to have an 12373 // implicit member access, rewrite to a simple decl ref. 12374 if (MemExpr->isImplicitAccess()) { 12375 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12376 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12377 MemExpr->getQualifierLoc(), 12378 MemExpr->getTemplateKeywordLoc(), 12379 Fn, 12380 /*enclosing*/ false, 12381 MemExpr->getMemberLoc(), 12382 Fn->getType(), 12383 VK_LValue, 12384 Found.getDecl(), 12385 TemplateArgs); 12386 MarkDeclRefReferenced(DRE); 12387 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12388 return DRE; 12389 } else { 12390 SourceLocation Loc = MemExpr->getMemberLoc(); 12391 if (MemExpr->getQualifier()) 12392 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12393 CheckCXXThisCapture(Loc); 12394 Base = new (Context) CXXThisExpr(Loc, 12395 MemExpr->getBaseType(), 12396 /*isImplicit=*/true); 12397 } 12398 } else 12399 Base = MemExpr->getBase(); 12400 12401 ExprValueKind valueKind; 12402 QualType type; 12403 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12404 valueKind = VK_LValue; 12405 type = Fn->getType(); 12406 } else { 12407 valueKind = VK_RValue; 12408 type = Context.BoundMemberTy; 12409 } 12410 12411 MemberExpr *ME = MemberExpr::Create(Context, Base, 12412 MemExpr->isArrow(), 12413 MemExpr->getQualifierLoc(), 12414 MemExpr->getTemplateKeywordLoc(), 12415 Fn, 12416 Found, 12417 MemExpr->getMemberNameInfo(), 12418 TemplateArgs, 12419 type, valueKind, OK_Ordinary); 12420 ME->setHadMultipleCandidates(true); 12421 MarkMemberReferenced(ME); 12422 return ME; 12423 } 12424 12425 llvm_unreachable("Invalid reference to overloaded function"); 12426 } 12427 12428 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12429 DeclAccessPair Found, 12430 FunctionDecl *Fn) { 12431 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12432 } 12433 12434 } // end namespace clang 12435