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 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return std::any_of(FD->param_begin(), FD->param_end(), 43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 44 } 45 46 /// A convenience routine for creating a decayed reference to a function. 47 static ExprResult 48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 49 bool HadMultipleCandidates, 50 SourceLocation Loc = SourceLocation(), 51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 52 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 53 return ExprError(); 54 // If FoundDecl is different from Fn (such as if one is a template 55 // and the other a specialization), make sure DiagnoseUseOfDecl is 56 // called on both. 57 // FIXME: This would be more comprehensively addressed by modifying 58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 59 // being used. 60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 61 return ExprError(); 62 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 63 VK_LValue, Loc, LocInfo); 64 if (HadMultipleCandidates) 65 DRE->setHadMultipleCandidates(true); 66 67 S.MarkDeclRefReferenced(DRE); 68 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 69 CK_FunctionToPointerDecay); 70 } 71 72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 73 bool InOverloadResolution, 74 StandardConversionSequence &SCS, 75 bool CStyle, 76 bool AllowObjCWritebackConversion); 77 78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 79 QualType &ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle); 83 static OverloadingResult 84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 85 UserDefinedConversionSequence& User, 86 OverloadCandidateSet& Conversions, 87 bool AllowExplicit, 88 bool AllowObjCConversionOnExplicit); 89 90 91 static ImplicitConversionSequence::CompareKind 92 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 93 const StandardConversionSequence& SCS1, 94 const StandardConversionSequence& SCS2); 95 96 static ImplicitConversionSequence::CompareKind 97 CompareQualificationConversions(Sema &S, 98 const StandardConversionSequence& SCS1, 99 const StandardConversionSequence& SCS2); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 /// GetConversionRank - Retrieve the implicit conversion rank 107 /// corresponding to the given implicit conversion kind. 108 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 109 static const ImplicitConversionRank 110 Rank[(int)ICK_Num_Conversion_Kinds] = { 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Promotion, 120 ICR_Conversion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Complex_Real_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Writeback_Conversion, 135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 136 // it was omitted by the patch that added 137 // ICK_Zero_Event_Conversion 138 ICR_C_Conversion 139 }; 140 return Rank[(int)Kind]; 141 } 142 143 /// GetImplicitConversionName - Return the name of this kind of 144 /// implicit conversion. 145 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 147 "No conversion", 148 "Lvalue-to-rvalue", 149 "Array-to-pointer", 150 "Function-to-pointer", 151 "Noreturn adjustment", 152 "Qualification", 153 "Integral promotion", 154 "Floating point promotion", 155 "Complex promotion", 156 "Integral conversion", 157 "Floating conversion", 158 "Complex conversion", 159 "Floating-integral conversion", 160 "Pointer conversion", 161 "Pointer-to-member conversion", 162 "Boolean conversion", 163 "Compatible-types conversion", 164 "Derived-to-base conversion", 165 "Vector conversion", 166 "Vector splat", 167 "Complex-real conversion", 168 "Block Pointer conversion", 169 "Transparent Union Conversion", 170 "Writeback conversion", 171 "OpenCL Zero Event Conversion", 172 "C specific type conversion" 173 }; 174 return Name[Kind]; 175 } 176 177 /// StandardConversionSequence - Set the standard conversion 178 /// sequence to the identity conversion. 179 void StandardConversionSequence::setAsIdentityConversion() { 180 First = ICK_Identity; 181 Second = ICK_Identity; 182 Third = ICK_Identity; 183 DeprecatedStringLiteralToCharPtr = false; 184 QualificationIncludesObjCLifetime = false; 185 ReferenceBinding = false; 186 DirectBinding = false; 187 IsLvalueReference = true; 188 BindsToFunctionLvalue = false; 189 BindsToRvalue = false; 190 BindsImplicitObjectArgumentWithoutRefQualifier = false; 191 ObjCLifetimeConversionBinding = false; 192 CopyConstructor = nullptr; 193 } 194 195 /// getRank - Retrieve the rank of this standard conversion sequence 196 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 197 /// implicit conversions. 198 ImplicitConversionRank StandardConversionSequence::getRank() const { 199 ImplicitConversionRank Rank = ICR_Exact_Match; 200 if (GetConversionRank(First) > Rank) 201 Rank = GetConversionRank(First); 202 if (GetConversionRank(Second) > Rank) 203 Rank = GetConversionRank(Second); 204 if (GetConversionRank(Third) > Rank) 205 Rank = GetConversionRank(Third); 206 return Rank; 207 } 208 209 /// isPointerConversionToBool - Determines whether this conversion is 210 /// a conversion of a pointer or pointer-to-member to bool. This is 211 /// used as part of the ranking of standard conversion sequences 212 /// (C++ 13.3.3.2p4). 213 bool StandardConversionSequence::isPointerConversionToBool() const { 214 // Note that FromType has not necessarily been transformed by the 215 // array-to-pointer or function-to-pointer implicit conversions, so 216 // check for their presence as well as checking whether FromType is 217 // a pointer. 218 if (getToType(1)->isBooleanType() && 219 (getFromType()->isPointerType() || 220 getFromType()->isObjCObjectPointerType() || 221 getFromType()->isBlockPointerType() || 222 getFromType()->isNullPtrType() || 223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 224 return true; 225 226 return false; 227 } 228 229 /// isPointerConversionToVoidPointer - Determines whether this 230 /// conversion is a conversion of a pointer to a void pointer. This is 231 /// used as part of the ranking of standard conversion sequences (C++ 232 /// 13.3.3.2p4). 233 bool 234 StandardConversionSequence:: 235 isPointerConversionToVoidPointer(ASTContext& Context) const { 236 QualType FromType = getFromType(); 237 QualType ToType = getToType(1); 238 239 // Note that FromType has not necessarily been transformed by the 240 // array-to-pointer implicit conversion, so check for its presence 241 // and redo the conversion to get a pointer. 242 if (First == ICK_Array_To_Pointer) 243 FromType = Context.getArrayDecayedType(FromType); 244 245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 247 return ToPtrType->getPointeeType()->isVoidType(); 248 249 return false; 250 } 251 252 /// Skip any implicit casts which could be either part of a narrowing conversion 253 /// or after one in an implicit conversion. 254 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 256 switch (ICE->getCastKind()) { 257 case CK_NoOp: 258 case CK_IntegralCast: 259 case CK_IntegralToBoolean: 260 case CK_IntegralToFloating: 261 case CK_FloatingToIntegral: 262 case CK_FloatingToBoolean: 263 case CK_FloatingCast: 264 Converted = ICE->getSubExpr(); 265 continue; 266 267 default: 268 return Converted; 269 } 270 } 271 272 return Converted; 273 } 274 275 /// Check if this standard conversion sequence represents a narrowing 276 /// conversion, according to C++11 [dcl.init.list]p7. 277 /// 278 /// \param Ctx The AST context. 279 /// \param Converted The result of applying this standard conversion sequence. 280 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 281 /// value of the expression prior to the narrowing conversion. 282 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 283 /// type of the expression prior to the narrowing conversion. 284 NarrowingKind 285 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 286 const Expr *Converted, 287 APValue &ConstantValue, 288 QualType &ConstantType) const { 289 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 290 291 // C++11 [dcl.init.list]p7: 292 // A narrowing conversion is an implicit conversion ... 293 QualType FromType = getToType(0); 294 QualType ToType = getToType(1); 295 switch (Second) { 296 // 'bool' is an integral type; dispatch to the right place to handle it. 297 case ICK_Boolean_Conversion: 298 if (FromType->isRealFloatingType()) 299 goto FloatingIntegralConversion; 300 if (FromType->isIntegralOrUnscopedEnumerationType()) 301 goto IntegralConversion; 302 // Boolean conversions can be from pointers and pointers to members 303 // [conv.bool], and those aren't considered narrowing conversions. 304 return NK_Not_Narrowing; 305 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 FloatingIntegralConversion: 314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 315 return NK_Type_Narrowing; 316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 317 llvm::APSInt IntConstantValue; 318 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 319 if (Initializer && 320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 321 // Convert the integer to the floating type. 322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 324 llvm::APFloat::rmNearestTiesToEven); 325 // And back. 326 llvm::APSInt ConvertedValue = IntConstantValue; 327 bool ignored; 328 Result.convertToInteger(ConvertedValue, 329 llvm::APFloat::rmTowardZero, &ignored); 330 // If the resulting value is different, this was a narrowing conversion. 331 if (IntConstantValue != ConvertedValue) { 332 ConstantValue = APValue(IntConstantValue); 333 ConstantType = Initializer->getType(); 334 return NK_Constant_Narrowing; 335 } 336 } else { 337 // Variables are always narrowings. 338 return NK_Variable_Narrowing; 339 } 340 } 341 return NK_Not_Narrowing; 342 343 // -- from long double to double or float, or from double to float, except 344 // where the source is a constant expression and the actual value after 345 // conversion is within the range of values that can be represented (even 346 // if it cannot be represented exactly), or 347 case ICK_Floating_Conversion: 348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 350 // FromType is larger than ToType. 351 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 353 // Constant! 354 assert(ConstantValue.isFloat()); 355 llvm::APFloat FloatVal = ConstantValue.getFloat(); 356 // Convert the source value into the target type. 357 bool ignored; 358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 359 Ctx.getFloatTypeSemantics(ToType), 360 llvm::APFloat::rmNearestTiesToEven, &ignored); 361 // If there was no overflow, the source value is within the range of 362 // values that can be represented. 363 if (ConvertStatus & llvm::APFloat::opOverflow) { 364 ConstantType = Initializer->getType(); 365 return NK_Constant_Narrowing; 366 } 367 } else { 368 return NK_Variable_Narrowing; 369 } 370 } 371 return NK_Not_Narrowing; 372 373 // -- from an integer type or unscoped enumeration type to an integer type 374 // that cannot represent all the values of the original type, except where 375 // the source is a constant expression and the actual value after 376 // conversion will fit into the target type and will produce the original 377 // value when converted back to the original type. 378 case ICK_Integral_Conversion: 379 IntegralConversion: { 380 assert(FromType->isIntegralOrUnscopedEnumerationType()); 381 assert(ToType->isIntegralOrUnscopedEnumerationType()); 382 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 383 const unsigned FromWidth = Ctx.getIntWidth(FromType); 384 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 385 const unsigned ToWidth = Ctx.getIntWidth(ToType); 386 387 if (FromWidth > ToWidth || 388 (FromWidth == ToWidth && FromSigned != ToSigned) || 389 (FromSigned && !ToSigned)) { 390 // Not all values of FromType can be represented in ToType. 391 llvm::APSInt InitializerValue; 392 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 393 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 394 // Such conversions on variables are always narrowing. 395 return NK_Variable_Narrowing; 396 } 397 bool Narrowing = false; 398 if (FromWidth < ToWidth) { 399 // Negative -> unsigned is narrowing. Otherwise, more bits is never 400 // narrowing. 401 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 402 Narrowing = true; 403 } else { 404 // Add a bit to the InitializerValue so we don't have to worry about 405 // signed vs. unsigned comparisons. 406 InitializerValue = InitializerValue.extend( 407 InitializerValue.getBitWidth() + 1); 408 // Convert the initializer to and from the target width and signed-ness. 409 llvm::APSInt ConvertedValue = InitializerValue; 410 ConvertedValue = ConvertedValue.trunc(ToWidth); 411 ConvertedValue.setIsSigned(ToSigned); 412 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 413 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 414 // If the result is different, this was a narrowing conversion. 415 if (ConvertedValue != InitializerValue) 416 Narrowing = true; 417 } 418 if (Narrowing) { 419 ConstantType = Initializer->getType(); 420 ConstantValue = APValue(InitializerValue); 421 return NK_Constant_Narrowing; 422 } 423 } 424 return NK_Not_Narrowing; 425 } 426 427 default: 428 // Other kinds of conversions are not narrowings. 429 return NK_Not_Narrowing; 430 } 431 } 432 433 /// dump - Print this standard conversion sequence to standard 434 /// error. Useful for debugging overloading issues. 435 void StandardConversionSequence::dump() const { 436 raw_ostream &OS = llvm::errs(); 437 bool PrintedSomething = false; 438 if (First != ICK_Identity) { 439 OS << GetImplicitConversionName(First); 440 PrintedSomething = true; 441 } 442 443 if (Second != ICK_Identity) { 444 if (PrintedSomething) { 445 OS << " -> "; 446 } 447 OS << GetImplicitConversionName(Second); 448 449 if (CopyConstructor) { 450 OS << " (by copy constructor)"; 451 } else if (DirectBinding) { 452 OS << " (direct reference binding)"; 453 } else if (ReferenceBinding) { 454 OS << " (reference binding)"; 455 } 456 PrintedSomething = true; 457 } 458 459 if (Third != ICK_Identity) { 460 if (PrintedSomething) { 461 OS << " -> "; 462 } 463 OS << GetImplicitConversionName(Third); 464 PrintedSomething = true; 465 } 466 467 if (!PrintedSomething) { 468 OS << "No conversions required"; 469 } 470 } 471 472 /// dump - Print this user-defined conversion sequence to standard 473 /// error. Useful for debugging overloading issues. 474 void UserDefinedConversionSequence::dump() const { 475 raw_ostream &OS = llvm::errs(); 476 if (Before.First || Before.Second || Before.Third) { 477 Before.dump(); 478 OS << " -> "; 479 } 480 if (ConversionFunction) 481 OS << '\'' << *ConversionFunction << '\''; 482 else 483 OS << "aggregate initialization"; 484 if (After.First || After.Second || After.Third) { 485 OS << " -> "; 486 After.dump(); 487 } 488 } 489 490 /// dump - Print this implicit conversion sequence to standard 491 /// error. Useful for debugging overloading issues. 492 void ImplicitConversionSequence::dump() const { 493 raw_ostream &OS = llvm::errs(); 494 if (isStdInitializerListElement()) 495 OS << "Worst std::initializer_list element conversion: "; 496 switch (ConversionKind) { 497 case StandardConversion: 498 OS << "Standard conversion: "; 499 Standard.dump(); 500 break; 501 case UserDefinedConversion: 502 OS << "User-defined conversion: "; 503 UserDefined.dump(); 504 break; 505 case EllipsisConversion: 506 OS << "Ellipsis conversion"; 507 break; 508 case AmbiguousConversion: 509 OS << "Ambiguous conversion"; 510 break; 511 case BadConversion: 512 OS << "Bad conversion"; 513 break; 514 } 515 516 OS << "\n"; 517 } 518 519 void AmbiguousConversionSequence::construct() { 520 new (&conversions()) ConversionSet(); 521 } 522 523 void AmbiguousConversionSequence::destruct() { 524 conversions().~ConversionSet(); 525 } 526 527 void 528 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 529 FromTypePtr = O.FromTypePtr; 530 ToTypePtr = O.ToTypePtr; 531 new (&conversions()) ConversionSet(O.conversions()); 532 } 533 534 namespace { 535 // Structure used by DeductionFailureInfo to store 536 // template argument information. 537 struct DFIArguments { 538 TemplateArgument FirstArg; 539 TemplateArgument SecondArg; 540 }; 541 // Structure used by DeductionFailureInfo to store 542 // template parameter and template argument information. 543 struct DFIParamWithArguments : DFIArguments { 544 TemplateParameter Param; 545 }; 546 } 547 548 /// \brief Convert from Sema's representation of template deduction information 549 /// to the form used in overload-candidate information. 550 DeductionFailureInfo 551 clang::MakeDeductionFailureInfo(ASTContext &Context, 552 Sema::TemplateDeductionResult TDK, 553 TemplateDeductionInfo &Info) { 554 DeductionFailureInfo Result; 555 Result.Result = static_cast<unsigned>(TDK); 556 Result.HasDiagnostic = false; 557 Result.Data = nullptr; 558 switch (TDK) { 559 case Sema::TDK_Success: 560 case Sema::TDK_Invalid: 561 case Sema::TDK_InstantiationDepth: 562 case Sema::TDK_TooManyArguments: 563 case Sema::TDK_TooFewArguments: 564 break; 565 566 case Sema::TDK_Incomplete: 567 case Sema::TDK_InvalidExplicitArguments: 568 Result.Data = Info.Param.getOpaqueValue(); 569 break; 570 571 case Sema::TDK_NonDeducedMismatch: { 572 // FIXME: Should allocate from normal heap so that we can free this later. 573 DFIArguments *Saved = new (Context) DFIArguments; 574 Saved->FirstArg = Info.FirstArg; 575 Saved->SecondArg = Info.SecondArg; 576 Result.Data = Saved; 577 break; 578 } 579 580 case Sema::TDK_Inconsistent: 581 case Sema::TDK_Underqualified: { 582 // FIXME: Should allocate from normal heap so that we can free this later. 583 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 584 Saved->Param = Info.Param; 585 Saved->FirstArg = Info.FirstArg; 586 Saved->SecondArg = Info.SecondArg; 587 Result.Data = Saved; 588 break; 589 } 590 591 case Sema::TDK_SubstitutionFailure: 592 Result.Data = Info.take(); 593 if (Info.hasSFINAEDiagnostic()) { 594 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 595 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 596 Info.takeSFINAEDiagnostic(*Diag); 597 Result.HasDiagnostic = true; 598 } 599 break; 600 601 case Sema::TDK_FailedOverloadResolution: 602 Result.Data = Info.Expression; 603 break; 604 605 case Sema::TDK_MiscellaneousDeductionFailure: 606 break; 607 } 608 609 return Result; 610 } 611 612 void DeductionFailureInfo::Destroy() { 613 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 614 case Sema::TDK_Success: 615 case Sema::TDK_Invalid: 616 case Sema::TDK_InstantiationDepth: 617 case Sema::TDK_Incomplete: 618 case Sema::TDK_TooManyArguments: 619 case Sema::TDK_TooFewArguments: 620 case Sema::TDK_InvalidExplicitArguments: 621 case Sema::TDK_FailedOverloadResolution: 622 break; 623 624 case Sema::TDK_Inconsistent: 625 case Sema::TDK_Underqualified: 626 case Sema::TDK_NonDeducedMismatch: 627 // FIXME: Destroy the data? 628 Data = nullptr; 629 break; 630 631 case Sema::TDK_SubstitutionFailure: 632 // FIXME: Destroy the template argument list? 633 Data = nullptr; 634 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 635 Diag->~PartialDiagnosticAt(); 636 HasDiagnostic = false; 637 } 638 break; 639 640 // Unhandled 641 case Sema::TDK_MiscellaneousDeductionFailure: 642 break; 643 } 644 } 645 646 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 647 if (HasDiagnostic) 648 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 649 return nullptr; 650 } 651 652 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 654 case Sema::TDK_Success: 655 case Sema::TDK_Invalid: 656 case Sema::TDK_InstantiationDepth: 657 case Sema::TDK_TooManyArguments: 658 case Sema::TDK_TooFewArguments: 659 case Sema::TDK_SubstitutionFailure: 660 case Sema::TDK_NonDeducedMismatch: 661 case Sema::TDK_FailedOverloadResolution: 662 return TemplateParameter(); 663 664 case Sema::TDK_Incomplete: 665 case Sema::TDK_InvalidExplicitArguments: 666 return TemplateParameter::getFromOpaqueValue(Data); 667 668 case Sema::TDK_Inconsistent: 669 case Sema::TDK_Underqualified: 670 return static_cast<DFIParamWithArguments*>(Data)->Param; 671 672 // Unhandled 673 case Sema::TDK_MiscellaneousDeductionFailure: 674 break; 675 } 676 677 return TemplateParameter(); 678 } 679 680 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 681 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 682 case Sema::TDK_Success: 683 case Sema::TDK_Invalid: 684 case Sema::TDK_InstantiationDepth: 685 case Sema::TDK_TooManyArguments: 686 case Sema::TDK_TooFewArguments: 687 case Sema::TDK_Incomplete: 688 case Sema::TDK_InvalidExplicitArguments: 689 case Sema::TDK_Inconsistent: 690 case Sema::TDK_Underqualified: 691 case Sema::TDK_NonDeducedMismatch: 692 case Sema::TDK_FailedOverloadResolution: 693 return nullptr; 694 695 case Sema::TDK_SubstitutionFailure: 696 return static_cast<TemplateArgumentList*>(Data); 697 698 // Unhandled 699 case Sema::TDK_MiscellaneousDeductionFailure: 700 break; 701 } 702 703 return nullptr; 704 } 705 706 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 708 case Sema::TDK_Success: 709 case Sema::TDK_Invalid: 710 case Sema::TDK_InstantiationDepth: 711 case Sema::TDK_Incomplete: 712 case Sema::TDK_TooManyArguments: 713 case Sema::TDK_TooFewArguments: 714 case Sema::TDK_InvalidExplicitArguments: 715 case Sema::TDK_SubstitutionFailure: 716 case Sema::TDK_FailedOverloadResolution: 717 return nullptr; 718 719 case Sema::TDK_Inconsistent: 720 case Sema::TDK_Underqualified: 721 case Sema::TDK_NonDeducedMismatch: 722 return &static_cast<DFIArguments*>(Data)->FirstArg; 723 724 // Unhandled 725 case Sema::TDK_MiscellaneousDeductionFailure: 726 break; 727 } 728 729 return nullptr; 730 } 731 732 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 733 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 734 case Sema::TDK_Success: 735 case Sema::TDK_Invalid: 736 case Sema::TDK_InstantiationDepth: 737 case Sema::TDK_Incomplete: 738 case Sema::TDK_TooManyArguments: 739 case Sema::TDK_TooFewArguments: 740 case Sema::TDK_InvalidExplicitArguments: 741 case Sema::TDK_SubstitutionFailure: 742 case Sema::TDK_FailedOverloadResolution: 743 return nullptr; 744 745 case Sema::TDK_Inconsistent: 746 case Sema::TDK_Underqualified: 747 case Sema::TDK_NonDeducedMismatch: 748 return &static_cast<DFIArguments*>(Data)->SecondArg; 749 750 // Unhandled 751 case Sema::TDK_MiscellaneousDeductionFailure: 752 break; 753 } 754 755 return nullptr; 756 } 757 758 Expr *DeductionFailureInfo::getExpr() { 759 if (static_cast<Sema::TemplateDeductionResult>(Result) == 760 Sema::TDK_FailedOverloadResolution) 761 return static_cast<Expr*>(Data); 762 763 return nullptr; 764 } 765 766 void OverloadCandidateSet::destroyCandidates() { 767 for (iterator i = begin(), e = end(); i != e; ++i) { 768 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 769 i->Conversions[ii].~ImplicitConversionSequence(); 770 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 771 i->DeductionFailure.Destroy(); 772 } 773 } 774 775 void OverloadCandidateSet::clear() { 776 destroyCandidates(); 777 NumInlineSequences = 0; 778 Candidates.clear(); 779 Functions.clear(); 780 } 781 782 namespace { 783 class UnbridgedCastsSet { 784 struct Entry { 785 Expr **Addr; 786 Expr *Saved; 787 }; 788 SmallVector<Entry, 2> Entries; 789 790 public: 791 void save(Sema &S, Expr *&E) { 792 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 793 Entry entry = { &E, E }; 794 Entries.push_back(entry); 795 E = S.stripARCUnbridgedCast(E); 796 } 797 798 void restore() { 799 for (SmallVectorImpl<Entry>::iterator 800 i = Entries.begin(), e = Entries.end(); i != e; ++i) 801 *i->Addr = i->Saved; 802 } 803 }; 804 } 805 806 /// checkPlaceholderForOverload - Do any interesting placeholder-like 807 /// preprocessing on the given expression. 808 /// 809 /// \param unbridgedCasts a collection to which to add unbridged casts; 810 /// without this, they will be immediately diagnosed as errors 811 /// 812 /// Return true on unrecoverable error. 813 static bool 814 checkPlaceholderForOverload(Sema &S, Expr *&E, 815 UnbridgedCastsSet *unbridgedCasts = nullptr) { 816 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 817 // We can't handle overloaded expressions here because overload 818 // resolution might reasonably tweak them. 819 if (placeholder->getKind() == BuiltinType::Overload) return false; 820 821 // If the context potentially accepts unbridged ARC casts, strip 822 // the unbridged cast and add it to the collection for later restoration. 823 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 824 unbridgedCasts) { 825 unbridgedCasts->save(S, E); 826 return false; 827 } 828 829 // Go ahead and check everything else. 830 ExprResult result = S.CheckPlaceholderExpr(E); 831 if (result.isInvalid()) 832 return true; 833 834 E = result.get(); 835 return false; 836 } 837 838 // Nothing to do. 839 return false; 840 } 841 842 /// checkArgPlaceholdersForOverload - Check a set of call operands for 843 /// placeholders. 844 static bool checkArgPlaceholdersForOverload(Sema &S, 845 MultiExprArg Args, 846 UnbridgedCastsSet &unbridged) { 847 for (unsigned i = 0, e = Args.size(); i != e; ++i) 848 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 849 return true; 850 851 return false; 852 } 853 854 // IsOverload - Determine whether the given New declaration is an 855 // overload of the declarations in Old. This routine returns false if 856 // New and Old cannot be overloaded, e.g., if New has the same 857 // signature as some function in Old (C++ 1.3.10) or if the Old 858 // declarations aren't functions (or function templates) at all. When 859 // it does return false, MatchedDecl will point to the decl that New 860 // cannot be overloaded with. This decl may be a UsingShadowDecl on 861 // top of the underlying declaration. 862 // 863 // Example: Given the following input: 864 // 865 // void f(int, float); // #1 866 // void f(int, int); // #2 867 // int f(int, int); // #3 868 // 869 // When we process #1, there is no previous declaration of "f", 870 // so IsOverload will not be used. 871 // 872 // When we process #2, Old contains only the FunctionDecl for #1. By 873 // comparing the parameter types, we see that #1 and #2 are overloaded 874 // (since they have different signatures), so this routine returns 875 // false; MatchedDecl is unchanged. 876 // 877 // When we process #3, Old is an overload set containing #1 and #2. We 878 // compare the signatures of #3 to #1 (they're overloaded, so we do 879 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 880 // identical (return types of functions are not part of the 881 // signature), IsOverload returns false and MatchedDecl will be set to 882 // point to the FunctionDecl for #2. 883 // 884 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 885 // into a class by a using declaration. The rules for whether to hide 886 // shadow declarations ignore some properties which otherwise figure 887 // into a function template's signature. 888 Sema::OverloadKind 889 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 890 NamedDecl *&Match, bool NewIsUsingDecl) { 891 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 892 I != E; ++I) { 893 NamedDecl *OldD = *I; 894 895 bool OldIsUsingDecl = false; 896 if (isa<UsingShadowDecl>(OldD)) { 897 OldIsUsingDecl = true; 898 899 // We can always introduce two using declarations into the same 900 // context, even if they have identical signatures. 901 if (NewIsUsingDecl) continue; 902 903 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 904 } 905 906 // A using-declaration does not conflict with another declaration 907 // if one of them is hidden. 908 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 909 continue; 910 911 // If either declaration was introduced by a using declaration, 912 // we'll need to use slightly different rules for matching. 913 // Essentially, these rules are the normal rules, except that 914 // function templates hide function templates with different 915 // return types or template parameter lists. 916 bool UseMemberUsingDeclRules = 917 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 918 !New->getFriendObjectKind(); 919 920 if (FunctionDecl *OldF = OldD->getAsFunction()) { 921 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 922 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 923 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 924 continue; 925 } 926 927 if (!isa<FunctionTemplateDecl>(OldD) && 928 !shouldLinkPossiblyHiddenDecl(*I, New)) 929 continue; 930 931 Match = *I; 932 return Ovl_Match; 933 } 934 } else if (isa<UsingDecl>(OldD)) { 935 // We can overload with these, which can show up when doing 936 // redeclaration checks for UsingDecls. 937 assert(Old.getLookupKind() == LookupUsingDeclName); 938 } else if (isa<TagDecl>(OldD)) { 939 // We can always overload with tags by hiding them. 940 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 941 // Optimistically assume that an unresolved using decl will 942 // overload; if it doesn't, we'll have to diagnose during 943 // template instantiation. 944 } else { 945 // (C++ 13p1): 946 // Only function declarations can be overloaded; object and type 947 // declarations cannot be overloaded. 948 Match = *I; 949 return Ovl_NonFunction; 950 } 951 } 952 953 return Ovl_Overload; 954 } 955 956 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 957 bool UseUsingDeclRules) { 958 // C++ [basic.start.main]p2: This function shall not be overloaded. 959 if (New->isMain()) 960 return false; 961 962 // MSVCRT user defined entry points cannot be overloaded. 963 if (New->isMSVCRTEntryPoint()) 964 return false; 965 966 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 967 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 968 969 // C++ [temp.fct]p2: 970 // A function template can be overloaded with other function templates 971 // and with normal (non-template) functions. 972 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 973 return true; 974 975 // Is the function New an overload of the function Old? 976 QualType OldQType = Context.getCanonicalType(Old->getType()); 977 QualType NewQType = Context.getCanonicalType(New->getType()); 978 979 // Compare the signatures (C++ 1.3.10) of the two functions to 980 // determine whether they are overloads. If we find any mismatch 981 // in the signature, they are overloads. 982 983 // If either of these functions is a K&R-style function (no 984 // prototype), then we consider them to have matching signatures. 985 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 986 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 987 return false; 988 989 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 990 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 991 992 // The signature of a function includes the types of its 993 // parameters (C++ 1.3.10), which includes the presence or absence 994 // of the ellipsis; see C++ DR 357). 995 if (OldQType != NewQType && 996 (OldType->getNumParams() != NewType->getNumParams() || 997 OldType->isVariadic() != NewType->isVariadic() || 998 !FunctionParamTypesAreEqual(OldType, NewType))) 999 return true; 1000 1001 // C++ [temp.over.link]p4: 1002 // The signature of a function template consists of its function 1003 // signature, its return type and its template parameter list. The names 1004 // of the template parameters are significant only for establishing the 1005 // relationship between the template parameters and the rest of the 1006 // signature. 1007 // 1008 // We check the return type and template parameter lists for function 1009 // templates first; the remaining checks follow. 1010 // 1011 // However, we don't consider either of these when deciding whether 1012 // a member introduced by a shadow declaration is hidden. 1013 if (!UseUsingDeclRules && NewTemplate && 1014 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1015 OldTemplate->getTemplateParameters(), 1016 false, TPL_TemplateMatch) || 1017 OldType->getReturnType() != NewType->getReturnType())) 1018 return true; 1019 1020 // If the function is a class member, its signature includes the 1021 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1022 // 1023 // As part of this, also check whether one of the member functions 1024 // is static, in which case they are not overloads (C++ 1025 // 13.1p2). While not part of the definition of the signature, 1026 // this check is important to determine whether these functions 1027 // can be overloaded. 1028 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1029 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1030 if (OldMethod && NewMethod && 1031 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1032 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1033 if (!UseUsingDeclRules && 1034 (OldMethod->getRefQualifier() == RQ_None || 1035 NewMethod->getRefQualifier() == RQ_None)) { 1036 // C++0x [over.load]p2: 1037 // - Member function declarations with the same name and the same 1038 // parameter-type-list as well as member function template 1039 // declarations with the same name, the same parameter-type-list, and 1040 // the same template parameter lists cannot be overloaded if any of 1041 // them, but not all, have a ref-qualifier (8.3.5). 1042 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1043 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1044 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1045 } 1046 return true; 1047 } 1048 1049 // We may not have applied the implicit const for a constexpr member 1050 // function yet (because we haven't yet resolved whether this is a static 1051 // or non-static member function). Add it now, on the assumption that this 1052 // is a redeclaration of OldMethod. 1053 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1054 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1055 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1056 !isa<CXXConstructorDecl>(NewMethod)) 1057 NewQuals |= Qualifiers::Const; 1058 1059 // We do not allow overloading based off of '__restrict'. 1060 OldQuals &= ~Qualifiers::Restrict; 1061 NewQuals &= ~Qualifiers::Restrict; 1062 if (OldQuals != NewQuals) 1063 return true; 1064 } 1065 1066 // Though pass_object_size is placed on parameters and takes an argument, we 1067 // consider it to be a function-level modifier for the sake of function 1068 // identity. Either the function has one or more parameters with 1069 // pass_object_size or it doesn't. 1070 if (functionHasPassObjectSizeParams(New) != 1071 functionHasPassObjectSizeParams(Old)) 1072 return true; 1073 1074 // enable_if attributes are an order-sensitive part of the signature. 1075 for (specific_attr_iterator<EnableIfAttr> 1076 NewI = New->specific_attr_begin<EnableIfAttr>(), 1077 NewE = New->specific_attr_end<EnableIfAttr>(), 1078 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1079 OldE = Old->specific_attr_end<EnableIfAttr>(); 1080 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1081 if (NewI == NewE || OldI == OldE) 1082 return true; 1083 llvm::FoldingSetNodeID NewID, OldID; 1084 NewI->getCond()->Profile(NewID, Context, true); 1085 OldI->getCond()->Profile(OldID, Context, true); 1086 if (NewID != OldID) 1087 return true; 1088 } 1089 1090 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1091 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1092 OldTarget = IdentifyCUDATarget(Old); 1093 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1094 return false; 1095 1096 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1097 1098 // Don't allow mixing of HD with other kinds. This guarantees that 1099 // we have only one viable function with this signature on any 1100 // side of CUDA compilation . 1101 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1102 return false; 1103 1104 // Allow overloading of functions with same signature, but 1105 // different CUDA target attributes. 1106 return NewTarget != OldTarget; 1107 } 1108 1109 // The signatures match; this is not an overload. 1110 return false; 1111 } 1112 1113 /// \brief Checks availability of the function depending on the current 1114 /// function context. Inside an unavailable function, unavailability is ignored. 1115 /// 1116 /// \returns true if \arg FD is unavailable and current context is inside 1117 /// an available function, false otherwise. 1118 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1119 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1120 } 1121 1122 /// \brief Tries a user-defined conversion from From to ToType. 1123 /// 1124 /// Produces an implicit conversion sequence for when a standard conversion 1125 /// is not an option. See TryImplicitConversion for more information. 1126 static ImplicitConversionSequence 1127 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1128 bool SuppressUserConversions, 1129 bool AllowExplicit, 1130 bool InOverloadResolution, 1131 bool CStyle, 1132 bool AllowObjCWritebackConversion, 1133 bool AllowObjCConversionOnExplicit) { 1134 ImplicitConversionSequence ICS; 1135 1136 if (SuppressUserConversions) { 1137 // We're not in the case above, so there is no conversion that 1138 // we can perform. 1139 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1140 return ICS; 1141 } 1142 1143 // Attempt user-defined conversion. 1144 OverloadCandidateSet Conversions(From->getExprLoc(), 1145 OverloadCandidateSet::CSK_Normal); 1146 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1147 Conversions, AllowExplicit, 1148 AllowObjCConversionOnExplicit)) { 1149 case OR_Success: 1150 case OR_Deleted: 1151 ICS.setUserDefined(); 1152 ICS.UserDefined.Before.setAsIdentityConversion(); 1153 // C++ [over.ics.user]p4: 1154 // A conversion of an expression of class type to the same class 1155 // type is given Exact Match rank, and a conversion of an 1156 // expression of class type to a base class of that type is 1157 // given Conversion rank, in spite of the fact that a copy 1158 // constructor (i.e., a user-defined conversion function) is 1159 // called for those cases. 1160 if (CXXConstructorDecl *Constructor 1161 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1162 QualType FromCanon 1163 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1164 QualType ToCanon 1165 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1166 if (Constructor->isCopyConstructor() && 1167 (FromCanon == ToCanon || 1168 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1169 // Turn this into a "standard" conversion sequence, so that it 1170 // gets ranked with standard conversion sequences. 1171 ICS.setStandard(); 1172 ICS.Standard.setAsIdentityConversion(); 1173 ICS.Standard.setFromType(From->getType()); 1174 ICS.Standard.setAllToTypes(ToType); 1175 ICS.Standard.CopyConstructor = Constructor; 1176 if (ToCanon != FromCanon) 1177 ICS.Standard.Second = ICK_Derived_To_Base; 1178 } 1179 } 1180 break; 1181 1182 case OR_Ambiguous: 1183 ICS.setAmbiguous(); 1184 ICS.Ambiguous.setFromType(From->getType()); 1185 ICS.Ambiguous.setToType(ToType); 1186 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1187 Cand != Conversions.end(); ++Cand) 1188 if (Cand->Viable) 1189 ICS.Ambiguous.addConversion(Cand->Function); 1190 break; 1191 1192 // Fall through. 1193 case OR_No_Viable_Function: 1194 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1195 break; 1196 } 1197 1198 return ICS; 1199 } 1200 1201 /// TryImplicitConversion - Attempt to perform an implicit conversion 1202 /// from the given expression (Expr) to the given type (ToType). This 1203 /// function returns an implicit conversion sequence that can be used 1204 /// to perform the initialization. Given 1205 /// 1206 /// void f(float f); 1207 /// void g(int i) { f(i); } 1208 /// 1209 /// this routine would produce an implicit conversion sequence to 1210 /// describe the initialization of f from i, which will be a standard 1211 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1212 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1213 // 1214 /// Note that this routine only determines how the conversion can be 1215 /// performed; it does not actually perform the conversion. As such, 1216 /// it will not produce any diagnostics if no conversion is available, 1217 /// but will instead return an implicit conversion sequence of kind 1218 /// "BadConversion". 1219 /// 1220 /// If @p SuppressUserConversions, then user-defined conversions are 1221 /// not permitted. 1222 /// If @p AllowExplicit, then explicit user-defined conversions are 1223 /// permitted. 1224 /// 1225 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1226 /// writeback conversion, which allows __autoreleasing id* parameters to 1227 /// be initialized with __strong id* or __weak id* arguments. 1228 static ImplicitConversionSequence 1229 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1230 bool SuppressUserConversions, 1231 bool AllowExplicit, 1232 bool InOverloadResolution, 1233 bool CStyle, 1234 bool AllowObjCWritebackConversion, 1235 bool AllowObjCConversionOnExplicit) { 1236 ImplicitConversionSequence ICS; 1237 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1238 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1239 ICS.setStandard(); 1240 return ICS; 1241 } 1242 1243 if (!S.getLangOpts().CPlusPlus) { 1244 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1245 return ICS; 1246 } 1247 1248 // C++ [over.ics.user]p4: 1249 // A conversion of an expression of class type to the same class 1250 // type is given Exact Match rank, and a conversion of an 1251 // expression of class type to a base class of that type is 1252 // given Conversion rank, in spite of the fact that a copy/move 1253 // constructor (i.e., a user-defined conversion function) is 1254 // called for those cases. 1255 QualType FromType = From->getType(); 1256 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1257 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1258 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1259 ICS.setStandard(); 1260 ICS.Standard.setAsIdentityConversion(); 1261 ICS.Standard.setFromType(FromType); 1262 ICS.Standard.setAllToTypes(ToType); 1263 1264 // We don't actually check at this point whether there is a valid 1265 // copy/move constructor, since overloading just assumes that it 1266 // exists. When we actually perform initialization, we'll find the 1267 // appropriate constructor to copy the returned object, if needed. 1268 ICS.Standard.CopyConstructor = nullptr; 1269 1270 // Determine whether this is considered a derived-to-base conversion. 1271 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1272 ICS.Standard.Second = ICK_Derived_To_Base; 1273 1274 return ICS; 1275 } 1276 1277 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1278 AllowExplicit, InOverloadResolution, CStyle, 1279 AllowObjCWritebackConversion, 1280 AllowObjCConversionOnExplicit); 1281 } 1282 1283 ImplicitConversionSequence 1284 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1285 bool SuppressUserConversions, 1286 bool AllowExplicit, 1287 bool InOverloadResolution, 1288 bool CStyle, 1289 bool AllowObjCWritebackConversion) { 1290 return ::TryImplicitConversion(*this, From, ToType, 1291 SuppressUserConversions, AllowExplicit, 1292 InOverloadResolution, CStyle, 1293 AllowObjCWritebackConversion, 1294 /*AllowObjCConversionOnExplicit=*/false); 1295 } 1296 1297 /// PerformImplicitConversion - Perform an implicit conversion of the 1298 /// expression From to the type ToType. Returns the 1299 /// converted expression. Flavor is the kind of conversion we're 1300 /// performing, used in the error message. If @p AllowExplicit, 1301 /// explicit user-defined conversions are permitted. 1302 ExprResult 1303 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1304 AssignmentAction Action, bool AllowExplicit) { 1305 ImplicitConversionSequence ICS; 1306 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1307 } 1308 1309 ExprResult 1310 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1311 AssignmentAction Action, bool AllowExplicit, 1312 ImplicitConversionSequence& ICS) { 1313 if (checkPlaceholderForOverload(*this, From)) 1314 return ExprError(); 1315 1316 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1317 bool AllowObjCWritebackConversion 1318 = getLangOpts().ObjCAutoRefCount && 1319 (Action == AA_Passing || Action == AA_Sending); 1320 if (getLangOpts().ObjC1) 1321 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1322 ToType, From->getType(), From); 1323 ICS = ::TryImplicitConversion(*this, From, ToType, 1324 /*SuppressUserConversions=*/false, 1325 AllowExplicit, 1326 /*InOverloadResolution=*/false, 1327 /*CStyle=*/false, 1328 AllowObjCWritebackConversion, 1329 /*AllowObjCConversionOnExplicit=*/false); 1330 return PerformImplicitConversion(From, ToType, ICS, Action); 1331 } 1332 1333 /// \brief Determine whether the conversion from FromType to ToType is a valid 1334 /// conversion that strips "noreturn" off the nested function type. 1335 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1336 QualType &ResultTy) { 1337 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1338 return false; 1339 1340 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1341 // where F adds one of the following at most once: 1342 // - a pointer 1343 // - a member pointer 1344 // - a block pointer 1345 CanQualType CanTo = Context.getCanonicalType(ToType); 1346 CanQualType CanFrom = Context.getCanonicalType(FromType); 1347 Type::TypeClass TyClass = CanTo->getTypeClass(); 1348 if (TyClass != CanFrom->getTypeClass()) return false; 1349 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1350 if (TyClass == Type::Pointer) { 1351 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1352 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1353 } else if (TyClass == Type::BlockPointer) { 1354 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1355 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1356 } else if (TyClass == Type::MemberPointer) { 1357 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1358 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1359 } else { 1360 return false; 1361 } 1362 1363 TyClass = CanTo->getTypeClass(); 1364 if (TyClass != CanFrom->getTypeClass()) return false; 1365 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1366 return false; 1367 } 1368 1369 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1370 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1371 if (!EInfo.getNoReturn()) return false; 1372 1373 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1374 assert(QualType(FromFn, 0).isCanonical()); 1375 if (QualType(FromFn, 0) != CanTo) return false; 1376 1377 ResultTy = ToType; 1378 return true; 1379 } 1380 1381 /// \brief Determine whether the conversion from FromType to ToType is a valid 1382 /// vector conversion. 1383 /// 1384 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1385 /// conversion. 1386 static bool IsVectorConversion(Sema &S, QualType FromType, 1387 QualType ToType, ImplicitConversionKind &ICK) { 1388 // We need at least one of these types to be a vector type to have a vector 1389 // conversion. 1390 if (!ToType->isVectorType() && !FromType->isVectorType()) 1391 return false; 1392 1393 // Identical types require no conversions. 1394 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1395 return false; 1396 1397 // There are no conversions between extended vector types, only identity. 1398 if (ToType->isExtVectorType()) { 1399 // There are no conversions between extended vector types other than the 1400 // identity conversion. 1401 if (FromType->isExtVectorType()) 1402 return false; 1403 1404 // Vector splat from any arithmetic type to a vector. 1405 if (FromType->isArithmeticType()) { 1406 ICK = ICK_Vector_Splat; 1407 return true; 1408 } 1409 } 1410 1411 // We can perform the conversion between vector types in the following cases: 1412 // 1)vector types are equivalent AltiVec and GCC vector types 1413 // 2)lax vector conversions are permitted and the vector types are of the 1414 // same size 1415 if (ToType->isVectorType() && FromType->isVectorType()) { 1416 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1417 S.isLaxVectorConversion(FromType, ToType)) { 1418 ICK = ICK_Vector_Conversion; 1419 return true; 1420 } 1421 } 1422 1423 return false; 1424 } 1425 1426 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1427 bool InOverloadResolution, 1428 StandardConversionSequence &SCS, 1429 bool CStyle); 1430 1431 /// IsStandardConversion - Determines whether there is a standard 1432 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1433 /// expression From to the type ToType. Standard conversion sequences 1434 /// only consider non-class types; for conversions that involve class 1435 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1436 /// contain the standard conversion sequence required to perform this 1437 /// conversion and this routine will return true. Otherwise, this 1438 /// routine will return false and the value of SCS is unspecified. 1439 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1440 bool InOverloadResolution, 1441 StandardConversionSequence &SCS, 1442 bool CStyle, 1443 bool AllowObjCWritebackConversion) { 1444 QualType FromType = From->getType(); 1445 1446 // Standard conversions (C++ [conv]) 1447 SCS.setAsIdentityConversion(); 1448 SCS.IncompatibleObjC = false; 1449 SCS.setFromType(FromType); 1450 SCS.CopyConstructor = nullptr; 1451 1452 // There are no standard conversions for class types in C++, so 1453 // abort early. When overloading in C, however, we do permit them. 1454 if (S.getLangOpts().CPlusPlus && 1455 (FromType->isRecordType() || ToType->isRecordType())) 1456 return false; 1457 1458 // The first conversion can be an lvalue-to-rvalue conversion, 1459 // array-to-pointer conversion, or function-to-pointer conversion 1460 // (C++ 4p1). 1461 1462 if (FromType == S.Context.OverloadTy) { 1463 DeclAccessPair AccessPair; 1464 if (FunctionDecl *Fn 1465 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1466 AccessPair)) { 1467 // We were able to resolve the address of the overloaded function, 1468 // so we can convert to the type of that function. 1469 FromType = Fn->getType(); 1470 SCS.setFromType(FromType); 1471 1472 // we can sometimes resolve &foo<int> regardless of ToType, so check 1473 // if the type matches (identity) or we are converting to bool 1474 if (!S.Context.hasSameUnqualifiedType( 1475 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1476 QualType resultTy; 1477 // if the function type matches except for [[noreturn]], it's ok 1478 if (!S.IsNoReturnConversion(FromType, 1479 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1480 // otherwise, only a boolean conversion is standard 1481 if (!ToType->isBooleanType()) 1482 return false; 1483 } 1484 1485 // Check if the "from" expression is taking the address of an overloaded 1486 // function and recompute the FromType accordingly. Take advantage of the 1487 // fact that non-static member functions *must* have such an address-of 1488 // expression. 1489 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1490 if (Method && !Method->isStatic()) { 1491 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1492 "Non-unary operator on non-static member address"); 1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1494 == UO_AddrOf && 1495 "Non-address-of operator on non-static member address"); 1496 const Type *ClassType 1497 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1498 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1499 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1500 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1501 UO_AddrOf && 1502 "Non-address-of operator for overloaded function expression"); 1503 FromType = S.Context.getPointerType(FromType); 1504 } 1505 1506 // Check that we've computed the proper type after overload resolution. 1507 assert(S.Context.hasSameType( 1508 FromType, 1509 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1510 } else { 1511 return false; 1512 } 1513 } 1514 // Lvalue-to-rvalue conversion (C++11 4.1): 1515 // A glvalue (3.10) of a non-function, non-array type T can 1516 // be converted to a prvalue. 1517 bool argIsLValue = From->isGLValue(); 1518 if (argIsLValue && 1519 !FromType->isFunctionType() && !FromType->isArrayType() && 1520 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1521 SCS.First = ICK_Lvalue_To_Rvalue; 1522 1523 // C11 6.3.2.1p2: 1524 // ... if the lvalue has atomic type, the value has the non-atomic version 1525 // of the type of the lvalue ... 1526 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1527 FromType = Atomic->getValueType(); 1528 1529 // If T is a non-class type, the type of the rvalue is the 1530 // cv-unqualified version of T. Otherwise, the type of the rvalue 1531 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1532 // just strip the qualifiers because they don't matter. 1533 FromType = FromType.getUnqualifiedType(); 1534 } else if (FromType->isArrayType()) { 1535 // Array-to-pointer conversion (C++ 4.2) 1536 SCS.First = ICK_Array_To_Pointer; 1537 1538 // An lvalue or rvalue of type "array of N T" or "array of unknown 1539 // bound of T" can be converted to an rvalue of type "pointer to 1540 // T" (C++ 4.2p1). 1541 FromType = S.Context.getArrayDecayedType(FromType); 1542 1543 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1544 // This conversion is deprecated in C++03 (D.4) 1545 SCS.DeprecatedStringLiteralToCharPtr = true; 1546 1547 // For the purpose of ranking in overload resolution 1548 // (13.3.3.1.1), this conversion is considered an 1549 // array-to-pointer conversion followed by a qualification 1550 // conversion (4.4). (C++ 4.2p2) 1551 SCS.Second = ICK_Identity; 1552 SCS.Third = ICK_Qualification; 1553 SCS.QualificationIncludesObjCLifetime = false; 1554 SCS.setAllToTypes(FromType); 1555 return true; 1556 } 1557 } else if (FromType->isFunctionType() && argIsLValue) { 1558 // Function-to-pointer conversion (C++ 4.3). 1559 SCS.First = ICK_Function_To_Pointer; 1560 1561 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1562 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1563 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1564 return false; 1565 1566 // An lvalue of function type T can be converted to an rvalue of 1567 // type "pointer to T." The result is a pointer to the 1568 // function. (C++ 4.3p1). 1569 FromType = S.Context.getPointerType(FromType); 1570 } else { 1571 // We don't require any conversions for the first step. 1572 SCS.First = ICK_Identity; 1573 } 1574 SCS.setToType(0, FromType); 1575 1576 // The second conversion can be an integral promotion, floating 1577 // point promotion, integral conversion, floating point conversion, 1578 // floating-integral conversion, pointer conversion, 1579 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1580 // For overloading in C, this can also be a "compatible-type" 1581 // conversion. 1582 bool IncompatibleObjC = false; 1583 ImplicitConversionKind SecondICK = ICK_Identity; 1584 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1585 // The unqualified versions of the types are the same: there's no 1586 // conversion to do. 1587 SCS.Second = ICK_Identity; 1588 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1589 // Integral promotion (C++ 4.5). 1590 SCS.Second = ICK_Integral_Promotion; 1591 FromType = ToType.getUnqualifiedType(); 1592 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1593 // Floating point promotion (C++ 4.6). 1594 SCS.Second = ICK_Floating_Promotion; 1595 FromType = ToType.getUnqualifiedType(); 1596 } else if (S.IsComplexPromotion(FromType, ToType)) { 1597 // Complex promotion (Clang extension) 1598 SCS.Second = ICK_Complex_Promotion; 1599 FromType = ToType.getUnqualifiedType(); 1600 } else if (ToType->isBooleanType() && 1601 (FromType->isArithmeticType() || 1602 FromType->isAnyPointerType() || 1603 FromType->isBlockPointerType() || 1604 FromType->isMemberPointerType() || 1605 FromType->isNullPtrType())) { 1606 // Boolean conversions (C++ 4.12). 1607 SCS.Second = ICK_Boolean_Conversion; 1608 FromType = S.Context.BoolTy; 1609 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1610 ToType->isIntegralType(S.Context)) { 1611 // Integral conversions (C++ 4.7). 1612 SCS.Second = ICK_Integral_Conversion; 1613 FromType = ToType.getUnqualifiedType(); 1614 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1615 // Complex conversions (C99 6.3.1.6) 1616 SCS.Second = ICK_Complex_Conversion; 1617 FromType = ToType.getUnqualifiedType(); 1618 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1619 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1620 // Complex-real conversions (C99 6.3.1.7) 1621 SCS.Second = ICK_Complex_Real; 1622 FromType = ToType.getUnqualifiedType(); 1623 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1624 // Floating point conversions (C++ 4.8). 1625 SCS.Second = ICK_Floating_Conversion; 1626 FromType = ToType.getUnqualifiedType(); 1627 } else if ((FromType->isRealFloatingType() && 1628 ToType->isIntegralType(S.Context)) || 1629 (FromType->isIntegralOrUnscopedEnumerationType() && 1630 ToType->isRealFloatingType())) { 1631 // Floating-integral conversions (C++ 4.9). 1632 SCS.Second = ICK_Floating_Integral; 1633 FromType = ToType.getUnqualifiedType(); 1634 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1635 SCS.Second = ICK_Block_Pointer_Conversion; 1636 } else if (AllowObjCWritebackConversion && 1637 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1638 SCS.Second = ICK_Writeback_Conversion; 1639 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1640 FromType, IncompatibleObjC)) { 1641 // Pointer conversions (C++ 4.10). 1642 SCS.Second = ICK_Pointer_Conversion; 1643 SCS.IncompatibleObjC = IncompatibleObjC; 1644 FromType = FromType.getUnqualifiedType(); 1645 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1646 InOverloadResolution, FromType)) { 1647 // Pointer to member conversions (4.11). 1648 SCS.Second = ICK_Pointer_Member; 1649 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1650 SCS.Second = SecondICK; 1651 FromType = ToType.getUnqualifiedType(); 1652 } else if (!S.getLangOpts().CPlusPlus && 1653 S.Context.typesAreCompatible(ToType, FromType)) { 1654 // Compatible conversions (Clang extension for C function overloading) 1655 SCS.Second = ICK_Compatible_Conversion; 1656 FromType = ToType.getUnqualifiedType(); 1657 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1658 // Treat a conversion that strips "noreturn" as an identity conversion. 1659 SCS.Second = ICK_NoReturn_Adjustment; 1660 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1661 InOverloadResolution, 1662 SCS, CStyle)) { 1663 SCS.Second = ICK_TransparentUnionConversion; 1664 FromType = ToType; 1665 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1666 CStyle)) { 1667 // tryAtomicConversion has updated the standard conversion sequence 1668 // appropriately. 1669 return true; 1670 } else if (ToType->isEventT() && 1671 From->isIntegerConstantExpr(S.getASTContext()) && 1672 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1673 SCS.Second = ICK_Zero_Event_Conversion; 1674 FromType = ToType; 1675 } else { 1676 // No second conversion required. 1677 SCS.Second = ICK_Identity; 1678 } 1679 SCS.setToType(1, FromType); 1680 1681 QualType CanonFrom; 1682 QualType CanonTo; 1683 // The third conversion can be a qualification conversion (C++ 4p1). 1684 bool ObjCLifetimeConversion; 1685 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1686 ObjCLifetimeConversion)) { 1687 SCS.Third = ICK_Qualification; 1688 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1689 FromType = ToType; 1690 CanonFrom = S.Context.getCanonicalType(FromType); 1691 CanonTo = S.Context.getCanonicalType(ToType); 1692 } else { 1693 // No conversion required 1694 SCS.Third = ICK_Identity; 1695 1696 // C++ [over.best.ics]p6: 1697 // [...] Any difference in top-level cv-qualification is 1698 // subsumed by the initialization itself and does not constitute 1699 // a conversion. [...] 1700 CanonFrom = S.Context.getCanonicalType(FromType); 1701 CanonTo = S.Context.getCanonicalType(ToType); 1702 if (CanonFrom.getLocalUnqualifiedType() 1703 == CanonTo.getLocalUnqualifiedType() && 1704 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1705 FromType = ToType; 1706 CanonFrom = CanonTo; 1707 } 1708 } 1709 SCS.setToType(2, FromType); 1710 1711 if (CanonFrom == CanonTo) 1712 return true; 1713 1714 // If we have not converted the argument type to the parameter type, 1715 // this is a bad conversion sequence, unless we're resolving an overload in C. 1716 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1717 return false; 1718 1719 ExprResult ER = ExprResult{From}; 1720 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1721 /*Diagnose=*/false, 1722 /*DiagnoseCFAudited=*/false, 1723 /*ConvertRHS=*/false); 1724 if (Conv != Sema::Compatible) 1725 return false; 1726 1727 SCS.setAllToTypes(ToType); 1728 // We need to set all three because we want this conversion to rank terribly, 1729 // and we don't know what conversions it may overlap with. 1730 SCS.First = ICK_C_Only_Conversion; 1731 SCS.Second = ICK_C_Only_Conversion; 1732 SCS.Third = ICK_C_Only_Conversion; 1733 return true; 1734 } 1735 1736 static bool 1737 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1738 QualType &ToType, 1739 bool InOverloadResolution, 1740 StandardConversionSequence &SCS, 1741 bool CStyle) { 1742 1743 const RecordType *UT = ToType->getAsUnionType(); 1744 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1745 return false; 1746 // The field to initialize within the transparent union. 1747 RecordDecl *UD = UT->getDecl(); 1748 // It's compatible if the expression matches any of the fields. 1749 for (const auto *it : UD->fields()) { 1750 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1751 CStyle, /*ObjCWritebackConversion=*/false)) { 1752 ToType = it->getType(); 1753 return true; 1754 } 1755 } 1756 return false; 1757 } 1758 1759 /// IsIntegralPromotion - Determines whether the conversion from the 1760 /// expression From (whose potentially-adjusted type is FromType) to 1761 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1762 /// sets PromotedType to the promoted type. 1763 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1764 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1765 // All integers are built-in. 1766 if (!To) { 1767 return false; 1768 } 1769 1770 // An rvalue of type char, signed char, unsigned char, short int, or 1771 // unsigned short int can be converted to an rvalue of type int if 1772 // int can represent all the values of the source type; otherwise, 1773 // the source rvalue can be converted to an rvalue of type unsigned 1774 // int (C++ 4.5p1). 1775 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1776 !FromType->isEnumeralType()) { 1777 if (// We can promote any signed, promotable integer type to an int 1778 (FromType->isSignedIntegerType() || 1779 // We can promote any unsigned integer type whose size is 1780 // less than int to an int. 1781 (!FromType->isSignedIntegerType() && 1782 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1783 return To->getKind() == BuiltinType::Int; 1784 } 1785 1786 return To->getKind() == BuiltinType::UInt; 1787 } 1788 1789 // C++11 [conv.prom]p3: 1790 // A prvalue of an unscoped enumeration type whose underlying type is not 1791 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1792 // following types that can represent all the values of the enumeration 1793 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1794 // unsigned int, long int, unsigned long int, long long int, or unsigned 1795 // long long int. If none of the types in that list can represent all the 1796 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1797 // type can be converted to an rvalue a prvalue of the extended integer type 1798 // with lowest integer conversion rank (4.13) greater than the rank of long 1799 // long in which all the values of the enumeration can be represented. If 1800 // there are two such extended types, the signed one is chosen. 1801 // C++11 [conv.prom]p4: 1802 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1803 // can be converted to a prvalue of its underlying type. Moreover, if 1804 // integral promotion can be applied to its underlying type, a prvalue of an 1805 // unscoped enumeration type whose underlying type is fixed can also be 1806 // converted to a prvalue of the promoted underlying type. 1807 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1808 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1809 // provided for a scoped enumeration. 1810 if (FromEnumType->getDecl()->isScoped()) 1811 return false; 1812 1813 // We can perform an integral promotion to the underlying type of the enum, 1814 // even if that's not the promoted type. Note that the check for promoting 1815 // the underlying type is based on the type alone, and does not consider 1816 // the bitfield-ness of the actual source expression. 1817 if (FromEnumType->getDecl()->isFixed()) { 1818 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1819 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1820 IsIntegralPromotion(nullptr, Underlying, ToType); 1821 } 1822 1823 // We have already pre-calculated the promotion type, so this is trivial. 1824 if (ToType->isIntegerType() && 1825 isCompleteType(From->getLocStart(), FromType)) 1826 return Context.hasSameUnqualifiedType( 1827 ToType, FromEnumType->getDecl()->getPromotionType()); 1828 } 1829 1830 // C++0x [conv.prom]p2: 1831 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1832 // to an rvalue a prvalue of the first of the following types that can 1833 // represent all the values of its underlying type: int, unsigned int, 1834 // long int, unsigned long int, long long int, or unsigned long long int. 1835 // If none of the types in that list can represent all the values of its 1836 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1837 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1838 // type. 1839 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1840 ToType->isIntegerType()) { 1841 // Determine whether the type we're converting from is signed or 1842 // unsigned. 1843 bool FromIsSigned = FromType->isSignedIntegerType(); 1844 uint64_t FromSize = Context.getTypeSize(FromType); 1845 1846 // The types we'll try to promote to, in the appropriate 1847 // order. Try each of these types. 1848 QualType PromoteTypes[6] = { 1849 Context.IntTy, Context.UnsignedIntTy, 1850 Context.LongTy, Context.UnsignedLongTy , 1851 Context.LongLongTy, Context.UnsignedLongLongTy 1852 }; 1853 for (int Idx = 0; Idx < 6; ++Idx) { 1854 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1855 if (FromSize < ToSize || 1856 (FromSize == ToSize && 1857 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1858 // We found the type that we can promote to. If this is the 1859 // type we wanted, we have a promotion. Otherwise, no 1860 // promotion. 1861 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1862 } 1863 } 1864 } 1865 1866 // An rvalue for an integral bit-field (9.6) can be converted to an 1867 // rvalue of type int if int can represent all the values of the 1868 // bit-field; otherwise, it can be converted to unsigned int if 1869 // unsigned int can represent all the values of the bit-field. If 1870 // the bit-field is larger yet, no integral promotion applies to 1871 // it. If the bit-field has an enumerated type, it is treated as any 1872 // other value of that type for promotion purposes (C++ 4.5p3). 1873 // FIXME: We should delay checking of bit-fields until we actually perform the 1874 // conversion. 1875 if (From) { 1876 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1877 llvm::APSInt BitWidth; 1878 if (FromType->isIntegralType(Context) && 1879 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1880 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1881 ToSize = Context.getTypeSize(ToType); 1882 1883 // Are we promoting to an int from a bitfield that fits in an int? 1884 if (BitWidth < ToSize || 1885 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1886 return To->getKind() == BuiltinType::Int; 1887 } 1888 1889 // Are we promoting to an unsigned int from an unsigned bitfield 1890 // that fits into an unsigned int? 1891 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1892 return To->getKind() == BuiltinType::UInt; 1893 } 1894 1895 return false; 1896 } 1897 } 1898 } 1899 1900 // An rvalue of type bool can be converted to an rvalue of type int, 1901 // with false becoming zero and true becoming one (C++ 4.5p4). 1902 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1903 return true; 1904 } 1905 1906 return false; 1907 } 1908 1909 /// IsFloatingPointPromotion - Determines whether the conversion from 1910 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1911 /// returns true and sets PromotedType to the promoted type. 1912 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1913 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1914 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1915 /// An rvalue of type float can be converted to an rvalue of type 1916 /// double. (C++ 4.6p1). 1917 if (FromBuiltin->getKind() == BuiltinType::Float && 1918 ToBuiltin->getKind() == BuiltinType::Double) 1919 return true; 1920 1921 // C99 6.3.1.5p1: 1922 // When a float is promoted to double or long double, or a 1923 // double is promoted to long double [...]. 1924 if (!getLangOpts().CPlusPlus && 1925 (FromBuiltin->getKind() == BuiltinType::Float || 1926 FromBuiltin->getKind() == BuiltinType::Double) && 1927 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1928 return true; 1929 1930 // Half can be promoted to float. 1931 if (!getLangOpts().NativeHalfType && 1932 FromBuiltin->getKind() == BuiltinType::Half && 1933 ToBuiltin->getKind() == BuiltinType::Float) 1934 return true; 1935 } 1936 1937 return false; 1938 } 1939 1940 /// \brief Determine if a conversion is a complex promotion. 1941 /// 1942 /// A complex promotion is defined as a complex -> complex conversion 1943 /// where the conversion between the underlying real types is a 1944 /// floating-point or integral promotion. 1945 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1946 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1947 if (!FromComplex) 1948 return false; 1949 1950 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1951 if (!ToComplex) 1952 return false; 1953 1954 return IsFloatingPointPromotion(FromComplex->getElementType(), 1955 ToComplex->getElementType()) || 1956 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1957 ToComplex->getElementType()); 1958 } 1959 1960 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1961 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1962 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1963 /// if non-empty, will be a pointer to ToType that may or may not have 1964 /// the right set of qualifiers on its pointee. 1965 /// 1966 static QualType 1967 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1968 QualType ToPointee, QualType ToType, 1969 ASTContext &Context, 1970 bool StripObjCLifetime = false) { 1971 assert((FromPtr->getTypeClass() == Type::Pointer || 1972 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1973 "Invalid similarly-qualified pointer type"); 1974 1975 /// Conversions to 'id' subsume cv-qualifier conversions. 1976 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1977 return ToType.getUnqualifiedType(); 1978 1979 QualType CanonFromPointee 1980 = Context.getCanonicalType(FromPtr->getPointeeType()); 1981 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1982 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1983 1984 if (StripObjCLifetime) 1985 Quals.removeObjCLifetime(); 1986 1987 // Exact qualifier match -> return the pointer type we're converting to. 1988 if (CanonToPointee.getLocalQualifiers() == Quals) { 1989 // ToType is exactly what we need. Return it. 1990 if (!ToType.isNull()) 1991 return ToType.getUnqualifiedType(); 1992 1993 // Build a pointer to ToPointee. It has the right qualifiers 1994 // already. 1995 if (isa<ObjCObjectPointerType>(ToType)) 1996 return Context.getObjCObjectPointerType(ToPointee); 1997 return Context.getPointerType(ToPointee); 1998 } 1999 2000 // Just build a canonical type that has the right qualifiers. 2001 QualType QualifiedCanonToPointee 2002 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2003 2004 if (isa<ObjCObjectPointerType>(ToType)) 2005 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2006 return Context.getPointerType(QualifiedCanonToPointee); 2007 } 2008 2009 static bool isNullPointerConstantForConversion(Expr *Expr, 2010 bool InOverloadResolution, 2011 ASTContext &Context) { 2012 // Handle value-dependent integral null pointer constants correctly. 2013 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2014 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2015 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2016 return !InOverloadResolution; 2017 2018 return Expr->isNullPointerConstant(Context, 2019 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2020 : Expr::NPC_ValueDependentIsNull); 2021 } 2022 2023 /// IsPointerConversion - Determines whether the conversion of the 2024 /// expression From, which has the (possibly adjusted) type FromType, 2025 /// can be converted to the type ToType via a pointer conversion (C++ 2026 /// 4.10). If so, returns true and places the converted type (that 2027 /// might differ from ToType in its cv-qualifiers at some level) into 2028 /// ConvertedType. 2029 /// 2030 /// This routine also supports conversions to and from block pointers 2031 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2032 /// pointers to interfaces. FIXME: Once we've determined the 2033 /// appropriate overloading rules for Objective-C, we may want to 2034 /// split the Objective-C checks into a different routine; however, 2035 /// GCC seems to consider all of these conversions to be pointer 2036 /// conversions, so for now they live here. IncompatibleObjC will be 2037 /// set if the conversion is an allowed Objective-C conversion that 2038 /// should result in a warning. 2039 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2040 bool InOverloadResolution, 2041 QualType& ConvertedType, 2042 bool &IncompatibleObjC) { 2043 IncompatibleObjC = false; 2044 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2045 IncompatibleObjC)) 2046 return true; 2047 2048 // Conversion from a null pointer constant to any Objective-C pointer type. 2049 if (ToType->isObjCObjectPointerType() && 2050 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2051 ConvertedType = ToType; 2052 return true; 2053 } 2054 2055 // Blocks: Block pointers can be converted to void*. 2056 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2057 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2058 ConvertedType = ToType; 2059 return true; 2060 } 2061 // Blocks: A null pointer constant can be converted to a block 2062 // pointer type. 2063 if (ToType->isBlockPointerType() && 2064 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2065 ConvertedType = ToType; 2066 return true; 2067 } 2068 2069 // If the left-hand-side is nullptr_t, the right side can be a null 2070 // pointer constant. 2071 if (ToType->isNullPtrType() && 2072 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2073 ConvertedType = ToType; 2074 return true; 2075 } 2076 2077 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2078 if (!ToTypePtr) 2079 return false; 2080 2081 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2082 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2083 ConvertedType = ToType; 2084 return true; 2085 } 2086 2087 // Beyond this point, both types need to be pointers 2088 // , including objective-c pointers. 2089 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2090 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2091 !getLangOpts().ObjCAutoRefCount) { 2092 ConvertedType = BuildSimilarlyQualifiedPointerType( 2093 FromType->getAs<ObjCObjectPointerType>(), 2094 ToPointeeType, 2095 ToType, Context); 2096 return true; 2097 } 2098 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2099 if (!FromTypePtr) 2100 return false; 2101 2102 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2103 2104 // If the unqualified pointee types are the same, this can't be a 2105 // pointer conversion, so don't do all of the work below. 2106 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2107 return false; 2108 2109 // An rvalue of type "pointer to cv T," where T is an object type, 2110 // can be converted to an rvalue of type "pointer to cv void" (C++ 2111 // 4.10p2). 2112 if (FromPointeeType->isIncompleteOrObjectType() && 2113 ToPointeeType->isVoidType()) { 2114 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2115 ToPointeeType, 2116 ToType, Context, 2117 /*StripObjCLifetime=*/true); 2118 return true; 2119 } 2120 2121 // MSVC allows implicit function to void* type conversion. 2122 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2123 ToPointeeType->isVoidType()) { 2124 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2125 ToPointeeType, 2126 ToType, Context); 2127 return true; 2128 } 2129 2130 // When we're overloading in C, we allow a special kind of pointer 2131 // conversion for compatible-but-not-identical pointee types. 2132 if (!getLangOpts().CPlusPlus && 2133 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2134 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2135 ToPointeeType, 2136 ToType, Context); 2137 return true; 2138 } 2139 2140 // C++ [conv.ptr]p3: 2141 // 2142 // An rvalue of type "pointer to cv D," where D is a class type, 2143 // can be converted to an rvalue of type "pointer to cv B," where 2144 // B is a base class (clause 10) of D. If B is an inaccessible 2145 // (clause 11) or ambiguous (10.2) base class of D, a program that 2146 // necessitates this conversion is ill-formed. The result of the 2147 // conversion is a pointer to the base class sub-object of the 2148 // derived class object. The null pointer value is converted to 2149 // the null pointer value of the destination type. 2150 // 2151 // Note that we do not check for ambiguity or inaccessibility 2152 // here. That is handled by CheckPointerConversion. 2153 if (getLangOpts().CPlusPlus && 2154 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2155 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2156 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2158 ToPointeeType, 2159 ToType, Context); 2160 return true; 2161 } 2162 2163 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2164 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2166 ToPointeeType, 2167 ToType, Context); 2168 return true; 2169 } 2170 2171 return false; 2172 } 2173 2174 /// \brief Adopt the given qualifiers for the given type. 2175 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2176 Qualifiers TQs = T.getQualifiers(); 2177 2178 // Check whether qualifiers already match. 2179 if (TQs == Qs) 2180 return T; 2181 2182 if (Qs.compatiblyIncludes(TQs)) 2183 return Context.getQualifiedType(T, Qs); 2184 2185 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2186 } 2187 2188 /// isObjCPointerConversion - Determines whether this is an 2189 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2190 /// with the same arguments and return values. 2191 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2192 QualType& ConvertedType, 2193 bool &IncompatibleObjC) { 2194 if (!getLangOpts().ObjC1) 2195 return false; 2196 2197 // The set of qualifiers on the type we're converting from. 2198 Qualifiers FromQualifiers = FromType.getQualifiers(); 2199 2200 // First, we handle all conversions on ObjC object pointer types. 2201 const ObjCObjectPointerType* ToObjCPtr = 2202 ToType->getAs<ObjCObjectPointerType>(); 2203 const ObjCObjectPointerType *FromObjCPtr = 2204 FromType->getAs<ObjCObjectPointerType>(); 2205 2206 if (ToObjCPtr && FromObjCPtr) { 2207 // If the pointee types are the same (ignoring qualifications), 2208 // then this is not a pointer conversion. 2209 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2210 FromObjCPtr->getPointeeType())) 2211 return false; 2212 2213 // Conversion between Objective-C pointers. 2214 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2215 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2216 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2217 if (getLangOpts().CPlusPlus && LHS && RHS && 2218 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2219 FromObjCPtr->getPointeeType())) 2220 return false; 2221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2222 ToObjCPtr->getPointeeType(), 2223 ToType, Context); 2224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2225 return true; 2226 } 2227 2228 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2229 // Okay: this is some kind of implicit downcast of Objective-C 2230 // interfaces, which is permitted. However, we're going to 2231 // complain about it. 2232 IncompatibleObjC = true; 2233 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2234 ToObjCPtr->getPointeeType(), 2235 ToType, Context); 2236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2237 return true; 2238 } 2239 } 2240 // Beyond this point, both types need to be C pointers or block pointers. 2241 QualType ToPointeeType; 2242 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2243 ToPointeeType = ToCPtr->getPointeeType(); 2244 else if (const BlockPointerType *ToBlockPtr = 2245 ToType->getAs<BlockPointerType>()) { 2246 // Objective C++: We're able to convert from a pointer to any object 2247 // to a block pointer type. 2248 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2249 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2250 return true; 2251 } 2252 ToPointeeType = ToBlockPtr->getPointeeType(); 2253 } 2254 else if (FromType->getAs<BlockPointerType>() && 2255 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2256 // Objective C++: We're able to convert from a block pointer type to a 2257 // pointer to any object. 2258 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2259 return true; 2260 } 2261 else 2262 return false; 2263 2264 QualType FromPointeeType; 2265 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2266 FromPointeeType = FromCPtr->getPointeeType(); 2267 else if (const BlockPointerType *FromBlockPtr = 2268 FromType->getAs<BlockPointerType>()) 2269 FromPointeeType = FromBlockPtr->getPointeeType(); 2270 else 2271 return false; 2272 2273 // If we have pointers to pointers, recursively check whether this 2274 // is an Objective-C conversion. 2275 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2277 IncompatibleObjC)) { 2278 // We always complain about this conversion. 2279 IncompatibleObjC = true; 2280 ConvertedType = Context.getPointerType(ConvertedType); 2281 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2282 return true; 2283 } 2284 // Allow conversion of pointee being objective-c pointer to another one; 2285 // as in I* to id. 2286 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2287 ToPointeeType->getAs<ObjCObjectPointerType>() && 2288 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2289 IncompatibleObjC)) { 2290 2291 ConvertedType = Context.getPointerType(ConvertedType); 2292 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2293 return true; 2294 } 2295 2296 // If we have pointers to functions or blocks, check whether the only 2297 // differences in the argument and result types are in Objective-C 2298 // pointer conversions. If so, we permit the conversion (but 2299 // complain about it). 2300 const FunctionProtoType *FromFunctionType 2301 = FromPointeeType->getAs<FunctionProtoType>(); 2302 const FunctionProtoType *ToFunctionType 2303 = ToPointeeType->getAs<FunctionProtoType>(); 2304 if (FromFunctionType && ToFunctionType) { 2305 // If the function types are exactly the same, this isn't an 2306 // Objective-C pointer conversion. 2307 if (Context.getCanonicalType(FromPointeeType) 2308 == Context.getCanonicalType(ToPointeeType)) 2309 return false; 2310 2311 // Perform the quick checks that will tell us whether these 2312 // function types are obviously different. 2313 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2314 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2315 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2316 return false; 2317 2318 bool HasObjCConversion = false; 2319 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2320 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2321 // Okay, the types match exactly. Nothing to do. 2322 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2323 ToFunctionType->getReturnType(), 2324 ConvertedType, IncompatibleObjC)) { 2325 // Okay, we have an Objective-C pointer conversion. 2326 HasObjCConversion = true; 2327 } else { 2328 // Function types are too different. Abort. 2329 return false; 2330 } 2331 2332 // Check argument types. 2333 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2334 ArgIdx != NumArgs; ++ArgIdx) { 2335 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2336 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2337 if (Context.getCanonicalType(FromArgType) 2338 == Context.getCanonicalType(ToArgType)) { 2339 // Okay, the types match exactly. Nothing to do. 2340 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2341 ConvertedType, IncompatibleObjC)) { 2342 // Okay, we have an Objective-C pointer conversion. 2343 HasObjCConversion = true; 2344 } else { 2345 // Argument types are too different. Abort. 2346 return false; 2347 } 2348 } 2349 2350 if (HasObjCConversion) { 2351 // We had an Objective-C conversion. Allow this pointer 2352 // conversion, but complain about it. 2353 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2354 IncompatibleObjC = true; 2355 return true; 2356 } 2357 } 2358 2359 return false; 2360 } 2361 2362 /// \brief Determine whether this is an Objective-C writeback conversion, 2363 /// used for parameter passing when performing automatic reference counting. 2364 /// 2365 /// \param FromType The type we're converting form. 2366 /// 2367 /// \param ToType The type we're converting to. 2368 /// 2369 /// \param ConvertedType The type that will be produced after applying 2370 /// this conversion. 2371 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2372 QualType &ConvertedType) { 2373 if (!getLangOpts().ObjCAutoRefCount || 2374 Context.hasSameUnqualifiedType(FromType, ToType)) 2375 return false; 2376 2377 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2378 QualType ToPointee; 2379 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2380 ToPointee = ToPointer->getPointeeType(); 2381 else 2382 return false; 2383 2384 Qualifiers ToQuals = ToPointee.getQualifiers(); 2385 if (!ToPointee->isObjCLifetimeType() || 2386 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2387 !ToQuals.withoutObjCLifetime().empty()) 2388 return false; 2389 2390 // Argument must be a pointer to __strong to __weak. 2391 QualType FromPointee; 2392 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2393 FromPointee = FromPointer->getPointeeType(); 2394 else 2395 return false; 2396 2397 Qualifiers FromQuals = FromPointee.getQualifiers(); 2398 if (!FromPointee->isObjCLifetimeType() || 2399 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2400 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2401 return false; 2402 2403 // Make sure that we have compatible qualifiers. 2404 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2405 if (!ToQuals.compatiblyIncludes(FromQuals)) 2406 return false; 2407 2408 // Remove qualifiers from the pointee type we're converting from; they 2409 // aren't used in the compatibility check belong, and we'll be adding back 2410 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2411 FromPointee = FromPointee.getUnqualifiedType(); 2412 2413 // The unqualified form of the pointee types must be compatible. 2414 ToPointee = ToPointee.getUnqualifiedType(); 2415 bool IncompatibleObjC; 2416 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2417 FromPointee = ToPointee; 2418 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2419 IncompatibleObjC)) 2420 return false; 2421 2422 /// \brief Construct the type we're converting to, which is a pointer to 2423 /// __autoreleasing pointee. 2424 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2425 ConvertedType = Context.getPointerType(FromPointee); 2426 return true; 2427 } 2428 2429 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2430 QualType& ConvertedType) { 2431 QualType ToPointeeType; 2432 if (const BlockPointerType *ToBlockPtr = 2433 ToType->getAs<BlockPointerType>()) 2434 ToPointeeType = ToBlockPtr->getPointeeType(); 2435 else 2436 return false; 2437 2438 QualType FromPointeeType; 2439 if (const BlockPointerType *FromBlockPtr = 2440 FromType->getAs<BlockPointerType>()) 2441 FromPointeeType = FromBlockPtr->getPointeeType(); 2442 else 2443 return false; 2444 // We have pointer to blocks, check whether the only 2445 // differences in the argument and result types are in Objective-C 2446 // pointer conversions. If so, we permit the conversion. 2447 2448 const FunctionProtoType *FromFunctionType 2449 = FromPointeeType->getAs<FunctionProtoType>(); 2450 const FunctionProtoType *ToFunctionType 2451 = ToPointeeType->getAs<FunctionProtoType>(); 2452 2453 if (!FromFunctionType || !ToFunctionType) 2454 return false; 2455 2456 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2457 return true; 2458 2459 // Perform the quick checks that will tell us whether these 2460 // function types are obviously different. 2461 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2462 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2463 return false; 2464 2465 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2466 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2467 if (FromEInfo != ToEInfo) 2468 return false; 2469 2470 bool IncompatibleObjC = false; 2471 if (Context.hasSameType(FromFunctionType->getReturnType(), 2472 ToFunctionType->getReturnType())) { 2473 // Okay, the types match exactly. Nothing to do. 2474 } else { 2475 QualType RHS = FromFunctionType->getReturnType(); 2476 QualType LHS = ToFunctionType->getReturnType(); 2477 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2478 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2479 LHS = LHS.getUnqualifiedType(); 2480 2481 if (Context.hasSameType(RHS,LHS)) { 2482 // OK exact match. 2483 } else if (isObjCPointerConversion(RHS, LHS, 2484 ConvertedType, IncompatibleObjC)) { 2485 if (IncompatibleObjC) 2486 return false; 2487 // Okay, we have an Objective-C pointer conversion. 2488 } 2489 else 2490 return false; 2491 } 2492 2493 // Check argument types. 2494 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2495 ArgIdx != NumArgs; ++ArgIdx) { 2496 IncompatibleObjC = false; 2497 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2498 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2499 if (Context.hasSameType(FromArgType, ToArgType)) { 2500 // Okay, the types match exactly. Nothing to do. 2501 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2502 ConvertedType, IncompatibleObjC)) { 2503 if (IncompatibleObjC) 2504 return false; 2505 // Okay, we have an Objective-C pointer conversion. 2506 } else 2507 // Argument types are too different. Abort. 2508 return false; 2509 } 2510 if (LangOpts.ObjCAutoRefCount && 2511 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2512 ToFunctionType)) 2513 return false; 2514 2515 ConvertedType = ToType; 2516 return true; 2517 } 2518 2519 enum { 2520 ft_default, 2521 ft_different_class, 2522 ft_parameter_arity, 2523 ft_parameter_mismatch, 2524 ft_return_type, 2525 ft_qualifer_mismatch 2526 }; 2527 2528 /// Attempts to get the FunctionProtoType from a Type. Handles 2529 /// MemberFunctionPointers properly. 2530 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2531 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2532 return FPT; 2533 2534 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2535 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2536 2537 return nullptr; 2538 } 2539 2540 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2541 /// function types. Catches different number of parameter, mismatch in 2542 /// parameter types, and different return types. 2543 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2544 QualType FromType, QualType ToType) { 2545 // If either type is not valid, include no extra info. 2546 if (FromType.isNull() || ToType.isNull()) { 2547 PDiag << ft_default; 2548 return; 2549 } 2550 2551 // Get the function type from the pointers. 2552 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2553 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2554 *ToMember = ToType->getAs<MemberPointerType>(); 2555 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2556 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2557 << QualType(FromMember->getClass(), 0); 2558 return; 2559 } 2560 FromType = FromMember->getPointeeType(); 2561 ToType = ToMember->getPointeeType(); 2562 } 2563 2564 if (FromType->isPointerType()) 2565 FromType = FromType->getPointeeType(); 2566 if (ToType->isPointerType()) 2567 ToType = ToType->getPointeeType(); 2568 2569 // Remove references. 2570 FromType = FromType.getNonReferenceType(); 2571 ToType = ToType.getNonReferenceType(); 2572 2573 // Don't print extra info for non-specialized template functions. 2574 if (FromType->isInstantiationDependentType() && 2575 !FromType->getAs<TemplateSpecializationType>()) { 2576 PDiag << ft_default; 2577 return; 2578 } 2579 2580 // No extra info for same types. 2581 if (Context.hasSameType(FromType, ToType)) { 2582 PDiag << ft_default; 2583 return; 2584 } 2585 2586 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2587 *ToFunction = tryGetFunctionProtoType(ToType); 2588 2589 // Both types need to be function types. 2590 if (!FromFunction || !ToFunction) { 2591 PDiag << ft_default; 2592 return; 2593 } 2594 2595 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2596 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2597 << FromFunction->getNumParams(); 2598 return; 2599 } 2600 2601 // Handle different parameter types. 2602 unsigned ArgPos; 2603 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2604 PDiag << ft_parameter_mismatch << ArgPos + 1 2605 << ToFunction->getParamType(ArgPos) 2606 << FromFunction->getParamType(ArgPos); 2607 return; 2608 } 2609 2610 // Handle different return type. 2611 if (!Context.hasSameType(FromFunction->getReturnType(), 2612 ToFunction->getReturnType())) { 2613 PDiag << ft_return_type << ToFunction->getReturnType() 2614 << FromFunction->getReturnType(); 2615 return; 2616 } 2617 2618 unsigned FromQuals = FromFunction->getTypeQuals(), 2619 ToQuals = ToFunction->getTypeQuals(); 2620 if (FromQuals != ToQuals) { 2621 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2622 return; 2623 } 2624 2625 // Unable to find a difference, so add no extra info. 2626 PDiag << ft_default; 2627 } 2628 2629 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2630 /// for equality of their argument types. Caller has already checked that 2631 /// they have same number of arguments. If the parameters are different, 2632 /// ArgPos will have the parameter index of the first different parameter. 2633 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2634 const FunctionProtoType *NewType, 2635 unsigned *ArgPos) { 2636 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2637 N = NewType->param_type_begin(), 2638 E = OldType->param_type_end(); 2639 O && (O != E); ++O, ++N) { 2640 if (!Context.hasSameType(O->getUnqualifiedType(), 2641 N->getUnqualifiedType())) { 2642 if (ArgPos) 2643 *ArgPos = O - OldType->param_type_begin(); 2644 return false; 2645 } 2646 } 2647 return true; 2648 } 2649 2650 /// CheckPointerConversion - Check the pointer conversion from the 2651 /// expression From to the type ToType. This routine checks for 2652 /// ambiguous or inaccessible derived-to-base pointer 2653 /// conversions for which IsPointerConversion has already returned 2654 /// true. It returns true and produces a diagnostic if there was an 2655 /// error, or returns false otherwise. 2656 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2657 CastKind &Kind, 2658 CXXCastPath& BasePath, 2659 bool IgnoreBaseAccess) { 2660 QualType FromType = From->getType(); 2661 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2662 2663 Kind = CK_BitCast; 2664 2665 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2666 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2667 Expr::NPCK_ZeroExpression) { 2668 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2669 DiagRuntimeBehavior(From->getExprLoc(), From, 2670 PDiag(diag::warn_impcast_bool_to_null_pointer) 2671 << ToType << From->getSourceRange()); 2672 else if (!isUnevaluatedContext()) 2673 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2674 << ToType << From->getSourceRange(); 2675 } 2676 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2677 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2678 QualType FromPointeeType = FromPtrType->getPointeeType(), 2679 ToPointeeType = ToPtrType->getPointeeType(); 2680 2681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2683 // We must have a derived-to-base conversion. Check an 2684 // ambiguous or inaccessible conversion. 2685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2686 From->getExprLoc(), 2687 From->getSourceRange(), &BasePath, 2688 IgnoreBaseAccess)) 2689 return true; 2690 2691 // The conversion was successful. 2692 Kind = CK_DerivedToBase; 2693 } 2694 2695 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() && 2696 ToPointeeType->isVoidType()) { 2697 assert(getLangOpts().MSVCCompat && 2698 "this should only be possible with MSVCCompat!"); 2699 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2700 << From->getSourceRange(); 2701 } 2702 } 2703 } else if (const ObjCObjectPointerType *ToPtrType = 2704 ToType->getAs<ObjCObjectPointerType>()) { 2705 if (const ObjCObjectPointerType *FromPtrType = 2706 FromType->getAs<ObjCObjectPointerType>()) { 2707 // Objective-C++ conversions are always okay. 2708 // FIXME: We should have a different class of conversions for the 2709 // Objective-C++ implicit conversions. 2710 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2711 return false; 2712 } else if (FromType->isBlockPointerType()) { 2713 Kind = CK_BlockPointerToObjCPointerCast; 2714 } else { 2715 Kind = CK_CPointerToObjCPointerCast; 2716 } 2717 } else if (ToType->isBlockPointerType()) { 2718 if (!FromType->isBlockPointerType()) 2719 Kind = CK_AnyPointerToBlockPointerCast; 2720 } 2721 2722 // We shouldn't fall into this case unless it's valid for other 2723 // reasons. 2724 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2725 Kind = CK_NullToPointer; 2726 2727 return false; 2728 } 2729 2730 /// IsMemberPointerConversion - Determines whether the conversion of the 2731 /// expression From, which has the (possibly adjusted) type FromType, can be 2732 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2733 /// If so, returns true and places the converted type (that might differ from 2734 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2735 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2736 QualType ToType, 2737 bool InOverloadResolution, 2738 QualType &ConvertedType) { 2739 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2740 if (!ToTypePtr) 2741 return false; 2742 2743 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2744 if (From->isNullPointerConstant(Context, 2745 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2746 : Expr::NPC_ValueDependentIsNull)) { 2747 ConvertedType = ToType; 2748 return true; 2749 } 2750 2751 // Otherwise, both types have to be member pointers. 2752 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2753 if (!FromTypePtr) 2754 return false; 2755 2756 // A pointer to member of B can be converted to a pointer to member of D, 2757 // where D is derived from B (C++ 4.11p2). 2758 QualType FromClass(FromTypePtr->getClass(), 0); 2759 QualType ToClass(ToTypePtr->getClass(), 0); 2760 2761 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2762 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2763 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2764 ToClass.getTypePtr()); 2765 return true; 2766 } 2767 2768 return false; 2769 } 2770 2771 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2772 /// expression From to the type ToType. This routine checks for ambiguous or 2773 /// virtual or inaccessible base-to-derived member pointer conversions 2774 /// for which IsMemberPointerConversion has already returned true. It returns 2775 /// true and produces a diagnostic if there was an error, or returns false 2776 /// otherwise. 2777 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2778 CastKind &Kind, 2779 CXXCastPath &BasePath, 2780 bool IgnoreBaseAccess) { 2781 QualType FromType = From->getType(); 2782 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2783 if (!FromPtrType) { 2784 // This must be a null pointer to member pointer conversion 2785 assert(From->isNullPointerConstant(Context, 2786 Expr::NPC_ValueDependentIsNull) && 2787 "Expr must be null pointer constant!"); 2788 Kind = CK_NullToMemberPointer; 2789 return false; 2790 } 2791 2792 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2793 assert(ToPtrType && "No member pointer cast has a target type " 2794 "that is not a member pointer."); 2795 2796 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2797 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2798 2799 // FIXME: What about dependent types? 2800 assert(FromClass->isRecordType() && "Pointer into non-class."); 2801 assert(ToClass->isRecordType() && "Pointer into non-class."); 2802 2803 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2804 /*DetectVirtual=*/true); 2805 bool DerivationOkay = 2806 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2807 assert(DerivationOkay && 2808 "Should not have been called if derivation isn't OK."); 2809 (void)DerivationOkay; 2810 2811 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2812 getUnqualifiedType())) { 2813 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2814 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2815 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2816 return true; 2817 } 2818 2819 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2820 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2821 << FromClass << ToClass << QualType(VBase, 0) 2822 << From->getSourceRange(); 2823 return true; 2824 } 2825 2826 if (!IgnoreBaseAccess) 2827 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2828 Paths.front(), 2829 diag::err_downcast_from_inaccessible_base); 2830 2831 // Must be a base to derived member conversion. 2832 BuildBasePathArray(Paths, BasePath); 2833 Kind = CK_BaseToDerivedMemberPointer; 2834 return false; 2835 } 2836 2837 /// Determine whether the lifetime conversion between the two given 2838 /// qualifiers sets is nontrivial. 2839 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2840 Qualifiers ToQuals) { 2841 // Converting anything to const __unsafe_unretained is trivial. 2842 if (ToQuals.hasConst() && 2843 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2844 return false; 2845 2846 return true; 2847 } 2848 2849 /// IsQualificationConversion - Determines whether the conversion from 2850 /// an rvalue of type FromType to ToType is a qualification conversion 2851 /// (C++ 4.4). 2852 /// 2853 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2854 /// when the qualification conversion involves a change in the Objective-C 2855 /// object lifetime. 2856 bool 2857 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2858 bool CStyle, bool &ObjCLifetimeConversion) { 2859 FromType = Context.getCanonicalType(FromType); 2860 ToType = Context.getCanonicalType(ToType); 2861 ObjCLifetimeConversion = false; 2862 2863 // If FromType and ToType are the same type, this is not a 2864 // qualification conversion. 2865 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2866 return false; 2867 2868 // (C++ 4.4p4): 2869 // A conversion can add cv-qualifiers at levels other than the first 2870 // in multi-level pointers, subject to the following rules: [...] 2871 bool PreviousToQualsIncludeConst = true; 2872 bool UnwrappedAnyPointer = false; 2873 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2874 // Within each iteration of the loop, we check the qualifiers to 2875 // determine if this still looks like a qualification 2876 // conversion. Then, if all is well, we unwrap one more level of 2877 // pointers or pointers-to-members and do it all again 2878 // until there are no more pointers or pointers-to-members left to 2879 // unwrap. 2880 UnwrappedAnyPointer = true; 2881 2882 Qualifiers FromQuals = FromType.getQualifiers(); 2883 Qualifiers ToQuals = ToType.getQualifiers(); 2884 2885 // Objective-C ARC: 2886 // Check Objective-C lifetime conversions. 2887 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2888 UnwrappedAnyPointer) { 2889 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2890 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2891 ObjCLifetimeConversion = true; 2892 FromQuals.removeObjCLifetime(); 2893 ToQuals.removeObjCLifetime(); 2894 } else { 2895 // Qualification conversions cannot cast between different 2896 // Objective-C lifetime qualifiers. 2897 return false; 2898 } 2899 } 2900 2901 // Allow addition/removal of GC attributes but not changing GC attributes. 2902 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2903 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2904 FromQuals.removeObjCGCAttr(); 2905 ToQuals.removeObjCGCAttr(); 2906 } 2907 2908 // -- for every j > 0, if const is in cv 1,j then const is in cv 2909 // 2,j, and similarly for volatile. 2910 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2911 return false; 2912 2913 // -- if the cv 1,j and cv 2,j are different, then const is in 2914 // every cv for 0 < k < j. 2915 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2916 && !PreviousToQualsIncludeConst) 2917 return false; 2918 2919 // Keep track of whether all prior cv-qualifiers in the "to" type 2920 // include const. 2921 PreviousToQualsIncludeConst 2922 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2923 } 2924 2925 // We are left with FromType and ToType being the pointee types 2926 // after unwrapping the original FromType and ToType the same number 2927 // of types. If we unwrapped any pointers, and if FromType and 2928 // ToType have the same unqualified type (since we checked 2929 // qualifiers above), then this is a qualification conversion. 2930 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2931 } 2932 2933 /// \brief - Determine whether this is a conversion from a scalar type to an 2934 /// atomic type. 2935 /// 2936 /// If successful, updates \c SCS's second and third steps in the conversion 2937 /// sequence to finish the conversion. 2938 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2939 bool InOverloadResolution, 2940 StandardConversionSequence &SCS, 2941 bool CStyle) { 2942 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2943 if (!ToAtomic) 2944 return false; 2945 2946 StandardConversionSequence InnerSCS; 2947 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2948 InOverloadResolution, InnerSCS, 2949 CStyle, /*AllowObjCWritebackConversion=*/false)) 2950 return false; 2951 2952 SCS.Second = InnerSCS.Second; 2953 SCS.setToType(1, InnerSCS.getToType(1)); 2954 SCS.Third = InnerSCS.Third; 2955 SCS.QualificationIncludesObjCLifetime 2956 = InnerSCS.QualificationIncludesObjCLifetime; 2957 SCS.setToType(2, InnerSCS.getToType(2)); 2958 return true; 2959 } 2960 2961 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2962 CXXConstructorDecl *Constructor, 2963 QualType Type) { 2964 const FunctionProtoType *CtorType = 2965 Constructor->getType()->getAs<FunctionProtoType>(); 2966 if (CtorType->getNumParams() > 0) { 2967 QualType FirstArg = CtorType->getParamType(0); 2968 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2969 return true; 2970 } 2971 return false; 2972 } 2973 2974 static OverloadingResult 2975 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2976 CXXRecordDecl *To, 2977 UserDefinedConversionSequence &User, 2978 OverloadCandidateSet &CandidateSet, 2979 bool AllowExplicit) { 2980 DeclContext::lookup_result R = S.LookupConstructors(To); 2981 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2982 Con != ConEnd; ++Con) { 2983 NamedDecl *D = *Con; 2984 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2985 2986 // Find the constructor (which may be a template). 2987 CXXConstructorDecl *Constructor = nullptr; 2988 FunctionTemplateDecl *ConstructorTmpl 2989 = dyn_cast<FunctionTemplateDecl>(D); 2990 if (ConstructorTmpl) 2991 Constructor 2992 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2993 else 2994 Constructor = cast<CXXConstructorDecl>(D); 2995 2996 bool Usable = !Constructor->isInvalidDecl() && 2997 S.isInitListConstructor(Constructor) && 2998 (AllowExplicit || !Constructor->isExplicit()); 2999 if (Usable) { 3000 // If the first argument is (a reference to) the target type, 3001 // suppress conversions. 3002 bool SuppressUserConversions = 3003 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 3004 if (ConstructorTmpl) 3005 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3006 /*ExplicitArgs*/ nullptr, 3007 From, CandidateSet, 3008 SuppressUserConversions); 3009 else 3010 S.AddOverloadCandidate(Constructor, FoundDecl, 3011 From, CandidateSet, 3012 SuppressUserConversions); 3013 } 3014 } 3015 3016 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3017 3018 OverloadCandidateSet::iterator Best; 3019 switch (auto Result = 3020 CandidateSet.BestViableFunction(S, From->getLocStart(), 3021 Best, true)) { 3022 case OR_Deleted: 3023 case OR_Success: { 3024 // Record the standard conversion we used and the conversion function. 3025 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3026 QualType ThisType = Constructor->getThisType(S.Context); 3027 // Initializer lists don't have conversions as such. 3028 User.Before.setAsIdentityConversion(); 3029 User.HadMultipleCandidates = HadMultipleCandidates; 3030 User.ConversionFunction = Constructor; 3031 User.FoundConversionFunction = Best->FoundDecl; 3032 User.After.setAsIdentityConversion(); 3033 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3034 User.After.setAllToTypes(ToType); 3035 return Result; 3036 } 3037 3038 case OR_No_Viable_Function: 3039 return OR_No_Viable_Function; 3040 case OR_Ambiguous: 3041 return OR_Ambiguous; 3042 } 3043 3044 llvm_unreachable("Invalid OverloadResult!"); 3045 } 3046 3047 /// Determines whether there is a user-defined conversion sequence 3048 /// (C++ [over.ics.user]) that converts expression From to the type 3049 /// ToType. If such a conversion exists, User will contain the 3050 /// user-defined conversion sequence that performs such a conversion 3051 /// and this routine will return true. Otherwise, this routine returns 3052 /// false and User is unspecified. 3053 /// 3054 /// \param AllowExplicit true if the conversion should consider C++0x 3055 /// "explicit" conversion functions as well as non-explicit conversion 3056 /// functions (C++0x [class.conv.fct]p2). 3057 /// 3058 /// \param AllowObjCConversionOnExplicit true if the conversion should 3059 /// allow an extra Objective-C pointer conversion on uses of explicit 3060 /// constructors. Requires \c AllowExplicit to also be set. 3061 static OverloadingResult 3062 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3063 UserDefinedConversionSequence &User, 3064 OverloadCandidateSet &CandidateSet, 3065 bool AllowExplicit, 3066 bool AllowObjCConversionOnExplicit) { 3067 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3068 3069 // Whether we will only visit constructors. 3070 bool ConstructorsOnly = false; 3071 3072 // If the type we are conversion to is a class type, enumerate its 3073 // constructors. 3074 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3075 // C++ [over.match.ctor]p1: 3076 // When objects of class type are direct-initialized (8.5), or 3077 // copy-initialized from an expression of the same or a 3078 // derived class type (8.5), overload resolution selects the 3079 // constructor. [...] For copy-initialization, the candidate 3080 // functions are all the converting constructors (12.3.1) of 3081 // that class. The argument list is the expression-list within 3082 // the parentheses of the initializer. 3083 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3084 (From->getType()->getAs<RecordType>() && 3085 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3086 ConstructorsOnly = true; 3087 3088 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3089 // We're not going to find any constructors. 3090 } else if (CXXRecordDecl *ToRecordDecl 3091 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3092 3093 Expr **Args = &From; 3094 unsigned NumArgs = 1; 3095 bool ListInitializing = false; 3096 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3097 // But first, see if there is an init-list-constructor that will work. 3098 OverloadingResult Result = IsInitializerListConstructorConversion( 3099 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3100 if (Result != OR_No_Viable_Function) 3101 return Result; 3102 // Never mind. 3103 CandidateSet.clear(); 3104 3105 // If we're list-initializing, we pass the individual elements as 3106 // arguments, not the entire list. 3107 Args = InitList->getInits(); 3108 NumArgs = InitList->getNumInits(); 3109 ListInitializing = true; 3110 } 3111 3112 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3113 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3114 Con != ConEnd; ++Con) { 3115 NamedDecl *D = *Con; 3116 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3117 3118 // Find the constructor (which may be a template). 3119 CXXConstructorDecl *Constructor = nullptr; 3120 FunctionTemplateDecl *ConstructorTmpl 3121 = dyn_cast<FunctionTemplateDecl>(D); 3122 if (ConstructorTmpl) 3123 Constructor 3124 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3125 else 3126 Constructor = cast<CXXConstructorDecl>(D); 3127 3128 bool Usable = !Constructor->isInvalidDecl(); 3129 if (ListInitializing) 3130 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3131 else 3132 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3133 if (Usable) { 3134 bool SuppressUserConversions = !ConstructorsOnly; 3135 if (SuppressUserConversions && ListInitializing) { 3136 SuppressUserConversions = false; 3137 if (NumArgs == 1) { 3138 // If the first argument is (a reference to) the target type, 3139 // suppress conversions. 3140 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3141 S.Context, Constructor, ToType); 3142 } 3143 } 3144 if (ConstructorTmpl) 3145 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3146 /*ExplicitArgs*/ nullptr, 3147 llvm::makeArrayRef(Args, NumArgs), 3148 CandidateSet, SuppressUserConversions); 3149 else 3150 // Allow one user-defined conversion when user specifies a 3151 // From->ToType conversion via an static cast (c-style, etc). 3152 S.AddOverloadCandidate(Constructor, FoundDecl, 3153 llvm::makeArrayRef(Args, NumArgs), 3154 CandidateSet, SuppressUserConversions); 3155 } 3156 } 3157 } 3158 } 3159 3160 // Enumerate conversion functions, if we're allowed to. 3161 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3162 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3163 // No conversion functions from incomplete types. 3164 } else if (const RecordType *FromRecordType 3165 = From->getType()->getAs<RecordType>()) { 3166 if (CXXRecordDecl *FromRecordDecl 3167 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3168 // Add all of the conversion functions as candidates. 3169 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3170 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3171 DeclAccessPair FoundDecl = I.getPair(); 3172 NamedDecl *D = FoundDecl.getDecl(); 3173 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3174 if (isa<UsingShadowDecl>(D)) 3175 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3176 3177 CXXConversionDecl *Conv; 3178 FunctionTemplateDecl *ConvTemplate; 3179 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3180 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3181 else 3182 Conv = cast<CXXConversionDecl>(D); 3183 3184 if (AllowExplicit || !Conv->isExplicit()) { 3185 if (ConvTemplate) 3186 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3187 ActingContext, From, ToType, 3188 CandidateSet, 3189 AllowObjCConversionOnExplicit); 3190 else 3191 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3192 From, ToType, CandidateSet, 3193 AllowObjCConversionOnExplicit); 3194 } 3195 } 3196 } 3197 } 3198 3199 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3200 3201 OverloadCandidateSet::iterator Best; 3202 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3203 Best, true)) { 3204 case OR_Success: 3205 case OR_Deleted: 3206 // Record the standard conversion we used and the conversion function. 3207 if (CXXConstructorDecl *Constructor 3208 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3209 // C++ [over.ics.user]p1: 3210 // If the user-defined conversion is specified by a 3211 // constructor (12.3.1), the initial standard conversion 3212 // sequence converts the source type to the type required by 3213 // the argument of the constructor. 3214 // 3215 QualType ThisType = Constructor->getThisType(S.Context); 3216 if (isa<InitListExpr>(From)) { 3217 // Initializer lists don't have conversions as such. 3218 User.Before.setAsIdentityConversion(); 3219 } else { 3220 if (Best->Conversions[0].isEllipsis()) 3221 User.EllipsisConversion = true; 3222 else { 3223 User.Before = Best->Conversions[0].Standard; 3224 User.EllipsisConversion = false; 3225 } 3226 } 3227 User.HadMultipleCandidates = HadMultipleCandidates; 3228 User.ConversionFunction = Constructor; 3229 User.FoundConversionFunction = Best->FoundDecl; 3230 User.After.setAsIdentityConversion(); 3231 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3232 User.After.setAllToTypes(ToType); 3233 return Result; 3234 } 3235 if (CXXConversionDecl *Conversion 3236 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3237 // C++ [over.ics.user]p1: 3238 // 3239 // [...] If the user-defined conversion is specified by a 3240 // conversion function (12.3.2), the initial standard 3241 // conversion sequence converts the source type to the 3242 // implicit object parameter of the conversion function. 3243 User.Before = Best->Conversions[0].Standard; 3244 User.HadMultipleCandidates = HadMultipleCandidates; 3245 User.ConversionFunction = Conversion; 3246 User.FoundConversionFunction = Best->FoundDecl; 3247 User.EllipsisConversion = false; 3248 3249 // C++ [over.ics.user]p2: 3250 // The second standard conversion sequence converts the 3251 // result of the user-defined conversion to the target type 3252 // for the sequence. Since an implicit conversion sequence 3253 // is an initialization, the special rules for 3254 // initialization by user-defined conversion apply when 3255 // selecting the best user-defined conversion for a 3256 // user-defined conversion sequence (see 13.3.3 and 3257 // 13.3.3.1). 3258 User.After = Best->FinalConversion; 3259 return Result; 3260 } 3261 llvm_unreachable("Not a constructor or conversion function?"); 3262 3263 case OR_No_Viable_Function: 3264 return OR_No_Viable_Function; 3265 3266 case OR_Ambiguous: 3267 return OR_Ambiguous; 3268 } 3269 3270 llvm_unreachable("Invalid OverloadResult!"); 3271 } 3272 3273 bool 3274 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3275 ImplicitConversionSequence ICS; 3276 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3277 OverloadCandidateSet::CSK_Normal); 3278 OverloadingResult OvResult = 3279 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3280 CandidateSet, false, false); 3281 if (OvResult == OR_Ambiguous) 3282 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3283 << From->getType() << ToType << From->getSourceRange(); 3284 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3285 if (!RequireCompleteType(From->getLocStart(), ToType, 3286 diag::err_typecheck_nonviable_condition_incomplete, 3287 From->getType(), From->getSourceRange())) 3288 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3289 << false << From->getType() << From->getSourceRange() << ToType; 3290 } else 3291 return false; 3292 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3293 return true; 3294 } 3295 3296 /// \brief Compare the user-defined conversion functions or constructors 3297 /// of two user-defined conversion sequences to determine whether any ordering 3298 /// is possible. 3299 static ImplicitConversionSequence::CompareKind 3300 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3301 FunctionDecl *Function2) { 3302 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3303 return ImplicitConversionSequence::Indistinguishable; 3304 3305 // Objective-C++: 3306 // If both conversion functions are implicitly-declared conversions from 3307 // a lambda closure type to a function pointer and a block pointer, 3308 // respectively, always prefer the conversion to a function pointer, 3309 // because the function pointer is more lightweight and is more likely 3310 // to keep code working. 3311 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3312 if (!Conv1) 3313 return ImplicitConversionSequence::Indistinguishable; 3314 3315 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3316 if (!Conv2) 3317 return ImplicitConversionSequence::Indistinguishable; 3318 3319 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3320 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3321 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3322 if (Block1 != Block2) 3323 return Block1 ? ImplicitConversionSequence::Worse 3324 : ImplicitConversionSequence::Better; 3325 } 3326 3327 return ImplicitConversionSequence::Indistinguishable; 3328 } 3329 3330 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3331 const ImplicitConversionSequence &ICS) { 3332 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3333 (ICS.isUserDefined() && 3334 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3335 } 3336 3337 /// CompareImplicitConversionSequences - Compare two implicit 3338 /// conversion sequences to determine whether one is better than the 3339 /// other or if they are indistinguishable (C++ 13.3.3.2). 3340 static ImplicitConversionSequence::CompareKind 3341 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3342 const ImplicitConversionSequence& ICS1, 3343 const ImplicitConversionSequence& ICS2) 3344 { 3345 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3346 // conversion sequences (as defined in 13.3.3.1) 3347 // -- a standard conversion sequence (13.3.3.1.1) is a better 3348 // conversion sequence than a user-defined conversion sequence or 3349 // an ellipsis conversion sequence, and 3350 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3351 // conversion sequence than an ellipsis conversion sequence 3352 // (13.3.3.1.3). 3353 // 3354 // C++0x [over.best.ics]p10: 3355 // For the purpose of ranking implicit conversion sequences as 3356 // described in 13.3.3.2, the ambiguous conversion sequence is 3357 // treated as a user-defined sequence that is indistinguishable 3358 // from any other user-defined conversion sequence. 3359 3360 // String literal to 'char *' conversion has been deprecated in C++03. It has 3361 // been removed from C++11. We still accept this conversion, if it happens at 3362 // the best viable function. Otherwise, this conversion is considered worse 3363 // than ellipsis conversion. Consider this as an extension; this is not in the 3364 // standard. For example: 3365 // 3366 // int &f(...); // #1 3367 // void f(char*); // #2 3368 // void g() { int &r = f("foo"); } 3369 // 3370 // In C++03, we pick #2 as the best viable function. 3371 // In C++11, we pick #1 as the best viable function, because ellipsis 3372 // conversion is better than string-literal to char* conversion (since there 3373 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3374 // convert arguments, #2 would be the best viable function in C++11. 3375 // If the best viable function has this conversion, a warning will be issued 3376 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3377 3378 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3379 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3380 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3381 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3382 ? ImplicitConversionSequence::Worse 3383 : ImplicitConversionSequence::Better; 3384 3385 if (ICS1.getKindRank() < ICS2.getKindRank()) 3386 return ImplicitConversionSequence::Better; 3387 if (ICS2.getKindRank() < ICS1.getKindRank()) 3388 return ImplicitConversionSequence::Worse; 3389 3390 // The following checks require both conversion sequences to be of 3391 // the same kind. 3392 if (ICS1.getKind() != ICS2.getKind()) 3393 return ImplicitConversionSequence::Indistinguishable; 3394 3395 ImplicitConversionSequence::CompareKind Result = 3396 ImplicitConversionSequence::Indistinguishable; 3397 3398 // Two implicit conversion sequences of the same form are 3399 // indistinguishable conversion sequences unless one of the 3400 // following rules apply: (C++ 13.3.3.2p3): 3401 3402 // List-initialization sequence L1 is a better conversion sequence than 3403 // list-initialization sequence L2 if: 3404 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3405 // if not that, 3406 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3407 // and N1 is smaller than N2., 3408 // even if one of the other rules in this paragraph would otherwise apply. 3409 if (!ICS1.isBad()) { 3410 if (ICS1.isStdInitializerListElement() && 3411 !ICS2.isStdInitializerListElement()) 3412 return ImplicitConversionSequence::Better; 3413 if (!ICS1.isStdInitializerListElement() && 3414 ICS2.isStdInitializerListElement()) 3415 return ImplicitConversionSequence::Worse; 3416 } 3417 3418 if (ICS1.isStandard()) 3419 // Standard conversion sequence S1 is a better conversion sequence than 3420 // standard conversion sequence S2 if [...] 3421 Result = CompareStandardConversionSequences(S, Loc, 3422 ICS1.Standard, ICS2.Standard); 3423 else if (ICS1.isUserDefined()) { 3424 // User-defined conversion sequence U1 is a better conversion 3425 // sequence than another user-defined conversion sequence U2 if 3426 // they contain the same user-defined conversion function or 3427 // constructor and if the second standard conversion sequence of 3428 // U1 is better than the second standard conversion sequence of 3429 // U2 (C++ 13.3.3.2p3). 3430 if (ICS1.UserDefined.ConversionFunction == 3431 ICS2.UserDefined.ConversionFunction) 3432 Result = CompareStandardConversionSequences(S, Loc, 3433 ICS1.UserDefined.After, 3434 ICS2.UserDefined.After); 3435 else 3436 Result = compareConversionFunctions(S, 3437 ICS1.UserDefined.ConversionFunction, 3438 ICS2.UserDefined.ConversionFunction); 3439 } 3440 3441 return Result; 3442 } 3443 3444 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3445 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3446 Qualifiers Quals; 3447 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3448 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3449 } 3450 3451 return Context.hasSameUnqualifiedType(T1, T2); 3452 } 3453 3454 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3455 // determine if one is a proper subset of the other. 3456 static ImplicitConversionSequence::CompareKind 3457 compareStandardConversionSubsets(ASTContext &Context, 3458 const StandardConversionSequence& SCS1, 3459 const StandardConversionSequence& SCS2) { 3460 ImplicitConversionSequence::CompareKind Result 3461 = ImplicitConversionSequence::Indistinguishable; 3462 3463 // the identity conversion sequence is considered to be a subsequence of 3464 // any non-identity conversion sequence 3465 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3466 return ImplicitConversionSequence::Better; 3467 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3468 return ImplicitConversionSequence::Worse; 3469 3470 if (SCS1.Second != SCS2.Second) { 3471 if (SCS1.Second == ICK_Identity) 3472 Result = ImplicitConversionSequence::Better; 3473 else if (SCS2.Second == ICK_Identity) 3474 Result = ImplicitConversionSequence::Worse; 3475 else 3476 return ImplicitConversionSequence::Indistinguishable; 3477 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3478 return ImplicitConversionSequence::Indistinguishable; 3479 3480 if (SCS1.Third == SCS2.Third) { 3481 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3482 : ImplicitConversionSequence::Indistinguishable; 3483 } 3484 3485 if (SCS1.Third == ICK_Identity) 3486 return Result == ImplicitConversionSequence::Worse 3487 ? ImplicitConversionSequence::Indistinguishable 3488 : ImplicitConversionSequence::Better; 3489 3490 if (SCS2.Third == ICK_Identity) 3491 return Result == ImplicitConversionSequence::Better 3492 ? ImplicitConversionSequence::Indistinguishable 3493 : ImplicitConversionSequence::Worse; 3494 3495 return ImplicitConversionSequence::Indistinguishable; 3496 } 3497 3498 /// \brief Determine whether one of the given reference bindings is better 3499 /// than the other based on what kind of bindings they are. 3500 static bool 3501 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3502 const StandardConversionSequence &SCS2) { 3503 // C++0x [over.ics.rank]p3b4: 3504 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3505 // implicit object parameter of a non-static member function declared 3506 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3507 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3508 // lvalue reference to a function lvalue and S2 binds an rvalue 3509 // reference*. 3510 // 3511 // FIXME: Rvalue references. We're going rogue with the above edits, 3512 // because the semantics in the current C++0x working paper (N3225 at the 3513 // time of this writing) break the standard definition of std::forward 3514 // and std::reference_wrapper when dealing with references to functions. 3515 // Proposed wording changes submitted to CWG for consideration. 3516 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3517 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3518 return false; 3519 3520 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3521 SCS2.IsLvalueReference) || 3522 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3523 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3524 } 3525 3526 /// CompareStandardConversionSequences - Compare two standard 3527 /// conversion sequences to determine whether one is better than the 3528 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3529 static ImplicitConversionSequence::CompareKind 3530 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3531 const StandardConversionSequence& SCS1, 3532 const StandardConversionSequence& SCS2) 3533 { 3534 // Standard conversion sequence S1 is a better conversion sequence 3535 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3536 3537 // -- S1 is a proper subsequence of S2 (comparing the conversion 3538 // sequences in the canonical form defined by 13.3.3.1.1, 3539 // excluding any Lvalue Transformation; the identity conversion 3540 // sequence is considered to be a subsequence of any 3541 // non-identity conversion sequence) or, if not that, 3542 if (ImplicitConversionSequence::CompareKind CK 3543 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3544 return CK; 3545 3546 // -- the rank of S1 is better than the rank of S2 (by the rules 3547 // defined below), or, if not that, 3548 ImplicitConversionRank Rank1 = SCS1.getRank(); 3549 ImplicitConversionRank Rank2 = SCS2.getRank(); 3550 if (Rank1 < Rank2) 3551 return ImplicitConversionSequence::Better; 3552 else if (Rank2 < Rank1) 3553 return ImplicitConversionSequence::Worse; 3554 3555 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3556 // are indistinguishable unless one of the following rules 3557 // applies: 3558 3559 // A conversion that is not a conversion of a pointer, or 3560 // pointer to member, to bool is better than another conversion 3561 // that is such a conversion. 3562 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3563 return SCS2.isPointerConversionToBool() 3564 ? ImplicitConversionSequence::Better 3565 : ImplicitConversionSequence::Worse; 3566 3567 // C++ [over.ics.rank]p4b2: 3568 // 3569 // If class B is derived directly or indirectly from class A, 3570 // conversion of B* to A* is better than conversion of B* to 3571 // void*, and conversion of A* to void* is better than conversion 3572 // of B* to void*. 3573 bool SCS1ConvertsToVoid 3574 = SCS1.isPointerConversionToVoidPointer(S.Context); 3575 bool SCS2ConvertsToVoid 3576 = SCS2.isPointerConversionToVoidPointer(S.Context); 3577 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3578 // Exactly one of the conversion sequences is a conversion to 3579 // a void pointer; it's the worse conversion. 3580 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3581 : ImplicitConversionSequence::Worse; 3582 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3583 // Neither conversion sequence converts to a void pointer; compare 3584 // their derived-to-base conversions. 3585 if (ImplicitConversionSequence::CompareKind DerivedCK 3586 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3587 return DerivedCK; 3588 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3589 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3590 // Both conversion sequences are conversions to void 3591 // pointers. Compare the source types to determine if there's an 3592 // inheritance relationship in their sources. 3593 QualType FromType1 = SCS1.getFromType(); 3594 QualType FromType2 = SCS2.getFromType(); 3595 3596 // Adjust the types we're converting from via the array-to-pointer 3597 // conversion, if we need to. 3598 if (SCS1.First == ICK_Array_To_Pointer) 3599 FromType1 = S.Context.getArrayDecayedType(FromType1); 3600 if (SCS2.First == ICK_Array_To_Pointer) 3601 FromType2 = S.Context.getArrayDecayedType(FromType2); 3602 3603 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3604 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3605 3606 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3607 return ImplicitConversionSequence::Better; 3608 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3609 return ImplicitConversionSequence::Worse; 3610 3611 // Objective-C++: If one interface is more specific than the 3612 // other, it is the better one. 3613 const ObjCObjectPointerType* FromObjCPtr1 3614 = FromType1->getAs<ObjCObjectPointerType>(); 3615 const ObjCObjectPointerType* FromObjCPtr2 3616 = FromType2->getAs<ObjCObjectPointerType>(); 3617 if (FromObjCPtr1 && FromObjCPtr2) { 3618 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3619 FromObjCPtr2); 3620 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3621 FromObjCPtr1); 3622 if (AssignLeft != AssignRight) { 3623 return AssignLeft? ImplicitConversionSequence::Better 3624 : ImplicitConversionSequence::Worse; 3625 } 3626 } 3627 } 3628 3629 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3630 // bullet 3). 3631 if (ImplicitConversionSequence::CompareKind QualCK 3632 = CompareQualificationConversions(S, SCS1, SCS2)) 3633 return QualCK; 3634 3635 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3636 // Check for a better reference binding based on the kind of bindings. 3637 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3638 return ImplicitConversionSequence::Better; 3639 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3640 return ImplicitConversionSequence::Worse; 3641 3642 // C++ [over.ics.rank]p3b4: 3643 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3644 // which the references refer are the same type except for 3645 // top-level cv-qualifiers, and the type to which the reference 3646 // initialized by S2 refers is more cv-qualified than the type 3647 // to which the reference initialized by S1 refers. 3648 QualType T1 = SCS1.getToType(2); 3649 QualType T2 = SCS2.getToType(2); 3650 T1 = S.Context.getCanonicalType(T1); 3651 T2 = S.Context.getCanonicalType(T2); 3652 Qualifiers T1Quals, T2Quals; 3653 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3654 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3655 if (UnqualT1 == UnqualT2) { 3656 // Objective-C++ ARC: If the references refer to objects with different 3657 // lifetimes, prefer bindings that don't change lifetime. 3658 if (SCS1.ObjCLifetimeConversionBinding != 3659 SCS2.ObjCLifetimeConversionBinding) { 3660 return SCS1.ObjCLifetimeConversionBinding 3661 ? ImplicitConversionSequence::Worse 3662 : ImplicitConversionSequence::Better; 3663 } 3664 3665 // If the type is an array type, promote the element qualifiers to the 3666 // type for comparison. 3667 if (isa<ArrayType>(T1) && T1Quals) 3668 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3669 if (isa<ArrayType>(T2) && T2Quals) 3670 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3671 if (T2.isMoreQualifiedThan(T1)) 3672 return ImplicitConversionSequence::Better; 3673 else if (T1.isMoreQualifiedThan(T2)) 3674 return ImplicitConversionSequence::Worse; 3675 } 3676 } 3677 3678 // In Microsoft mode, prefer an integral conversion to a 3679 // floating-to-integral conversion if the integral conversion 3680 // is between types of the same size. 3681 // For example: 3682 // void f(float); 3683 // void f(int); 3684 // int main { 3685 // long a; 3686 // f(a); 3687 // } 3688 // Here, MSVC will call f(int) instead of generating a compile error 3689 // as clang will do in standard mode. 3690 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3691 SCS2.Second == ICK_Floating_Integral && 3692 S.Context.getTypeSize(SCS1.getFromType()) == 3693 S.Context.getTypeSize(SCS1.getToType(2))) 3694 return ImplicitConversionSequence::Better; 3695 3696 return ImplicitConversionSequence::Indistinguishable; 3697 } 3698 3699 /// CompareQualificationConversions - Compares two standard conversion 3700 /// sequences to determine whether they can be ranked based on their 3701 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3702 static ImplicitConversionSequence::CompareKind 3703 CompareQualificationConversions(Sema &S, 3704 const StandardConversionSequence& SCS1, 3705 const StandardConversionSequence& SCS2) { 3706 // C++ 13.3.3.2p3: 3707 // -- S1 and S2 differ only in their qualification conversion and 3708 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3709 // cv-qualification signature of type T1 is a proper subset of 3710 // the cv-qualification signature of type T2, and S1 is not the 3711 // deprecated string literal array-to-pointer conversion (4.2). 3712 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3713 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3714 return ImplicitConversionSequence::Indistinguishable; 3715 3716 // FIXME: the example in the standard doesn't use a qualification 3717 // conversion (!) 3718 QualType T1 = SCS1.getToType(2); 3719 QualType T2 = SCS2.getToType(2); 3720 T1 = S.Context.getCanonicalType(T1); 3721 T2 = S.Context.getCanonicalType(T2); 3722 Qualifiers T1Quals, T2Quals; 3723 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3724 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3725 3726 // If the types are the same, we won't learn anything by unwrapped 3727 // them. 3728 if (UnqualT1 == UnqualT2) 3729 return ImplicitConversionSequence::Indistinguishable; 3730 3731 // If the type is an array type, promote the element qualifiers to the type 3732 // for comparison. 3733 if (isa<ArrayType>(T1) && T1Quals) 3734 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3735 if (isa<ArrayType>(T2) && T2Quals) 3736 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3737 3738 ImplicitConversionSequence::CompareKind Result 3739 = ImplicitConversionSequence::Indistinguishable; 3740 3741 // Objective-C++ ARC: 3742 // Prefer qualification conversions not involving a change in lifetime 3743 // to qualification conversions that do not change lifetime. 3744 if (SCS1.QualificationIncludesObjCLifetime != 3745 SCS2.QualificationIncludesObjCLifetime) { 3746 Result = SCS1.QualificationIncludesObjCLifetime 3747 ? ImplicitConversionSequence::Worse 3748 : ImplicitConversionSequence::Better; 3749 } 3750 3751 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3752 // Within each iteration of the loop, we check the qualifiers to 3753 // determine if this still looks like a qualification 3754 // conversion. Then, if all is well, we unwrap one more level of 3755 // pointers or pointers-to-members and do it all again 3756 // until there are no more pointers or pointers-to-members left 3757 // to unwrap. This essentially mimics what 3758 // IsQualificationConversion does, but here we're checking for a 3759 // strict subset of qualifiers. 3760 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3761 // The qualifiers are the same, so this doesn't tell us anything 3762 // about how the sequences rank. 3763 ; 3764 else if (T2.isMoreQualifiedThan(T1)) { 3765 // T1 has fewer qualifiers, so it could be the better sequence. 3766 if (Result == ImplicitConversionSequence::Worse) 3767 // Neither has qualifiers that are a subset of the other's 3768 // qualifiers. 3769 return ImplicitConversionSequence::Indistinguishable; 3770 3771 Result = ImplicitConversionSequence::Better; 3772 } else if (T1.isMoreQualifiedThan(T2)) { 3773 // T2 has fewer qualifiers, so it could be the better sequence. 3774 if (Result == ImplicitConversionSequence::Better) 3775 // Neither has qualifiers that are a subset of the other's 3776 // qualifiers. 3777 return ImplicitConversionSequence::Indistinguishable; 3778 3779 Result = ImplicitConversionSequence::Worse; 3780 } else { 3781 // Qualifiers are disjoint. 3782 return ImplicitConversionSequence::Indistinguishable; 3783 } 3784 3785 // If the types after this point are equivalent, we're done. 3786 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3787 break; 3788 } 3789 3790 // Check that the winning standard conversion sequence isn't using 3791 // the deprecated string literal array to pointer conversion. 3792 switch (Result) { 3793 case ImplicitConversionSequence::Better: 3794 if (SCS1.DeprecatedStringLiteralToCharPtr) 3795 Result = ImplicitConversionSequence::Indistinguishable; 3796 break; 3797 3798 case ImplicitConversionSequence::Indistinguishable: 3799 break; 3800 3801 case ImplicitConversionSequence::Worse: 3802 if (SCS2.DeprecatedStringLiteralToCharPtr) 3803 Result = ImplicitConversionSequence::Indistinguishable; 3804 break; 3805 } 3806 3807 return Result; 3808 } 3809 3810 /// CompareDerivedToBaseConversions - Compares two standard conversion 3811 /// sequences to determine whether they can be ranked based on their 3812 /// various kinds of derived-to-base conversions (C++ 3813 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3814 /// conversions between Objective-C interface types. 3815 static ImplicitConversionSequence::CompareKind 3816 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3817 const StandardConversionSequence& SCS1, 3818 const StandardConversionSequence& SCS2) { 3819 QualType FromType1 = SCS1.getFromType(); 3820 QualType ToType1 = SCS1.getToType(1); 3821 QualType FromType2 = SCS2.getFromType(); 3822 QualType ToType2 = SCS2.getToType(1); 3823 3824 // Adjust the types we're converting from via the array-to-pointer 3825 // conversion, if we need to. 3826 if (SCS1.First == ICK_Array_To_Pointer) 3827 FromType1 = S.Context.getArrayDecayedType(FromType1); 3828 if (SCS2.First == ICK_Array_To_Pointer) 3829 FromType2 = S.Context.getArrayDecayedType(FromType2); 3830 3831 // Canonicalize all of the types. 3832 FromType1 = S.Context.getCanonicalType(FromType1); 3833 ToType1 = S.Context.getCanonicalType(ToType1); 3834 FromType2 = S.Context.getCanonicalType(FromType2); 3835 ToType2 = S.Context.getCanonicalType(ToType2); 3836 3837 // C++ [over.ics.rank]p4b3: 3838 // 3839 // If class B is derived directly or indirectly from class A and 3840 // class C is derived directly or indirectly from B, 3841 // 3842 // Compare based on pointer conversions. 3843 if (SCS1.Second == ICK_Pointer_Conversion && 3844 SCS2.Second == ICK_Pointer_Conversion && 3845 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3846 FromType1->isPointerType() && FromType2->isPointerType() && 3847 ToType1->isPointerType() && ToType2->isPointerType()) { 3848 QualType FromPointee1 3849 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3850 QualType ToPointee1 3851 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3852 QualType FromPointee2 3853 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3854 QualType ToPointee2 3855 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3856 3857 // -- conversion of C* to B* is better than conversion of C* to A*, 3858 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3859 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3860 return ImplicitConversionSequence::Better; 3861 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3862 return ImplicitConversionSequence::Worse; 3863 } 3864 3865 // -- conversion of B* to A* is better than conversion of C* to A*, 3866 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3867 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3868 return ImplicitConversionSequence::Better; 3869 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3870 return ImplicitConversionSequence::Worse; 3871 } 3872 } else if (SCS1.Second == ICK_Pointer_Conversion && 3873 SCS2.Second == ICK_Pointer_Conversion) { 3874 const ObjCObjectPointerType *FromPtr1 3875 = FromType1->getAs<ObjCObjectPointerType>(); 3876 const ObjCObjectPointerType *FromPtr2 3877 = FromType2->getAs<ObjCObjectPointerType>(); 3878 const ObjCObjectPointerType *ToPtr1 3879 = ToType1->getAs<ObjCObjectPointerType>(); 3880 const ObjCObjectPointerType *ToPtr2 3881 = ToType2->getAs<ObjCObjectPointerType>(); 3882 3883 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3884 // Apply the same conversion ranking rules for Objective-C pointer types 3885 // that we do for C++ pointers to class types. However, we employ the 3886 // Objective-C pseudo-subtyping relationship used for assignment of 3887 // Objective-C pointer types. 3888 bool FromAssignLeft 3889 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3890 bool FromAssignRight 3891 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3892 bool ToAssignLeft 3893 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3894 bool ToAssignRight 3895 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3896 3897 // A conversion to an a non-id object pointer type or qualified 'id' 3898 // type is better than a conversion to 'id'. 3899 if (ToPtr1->isObjCIdType() && 3900 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3901 return ImplicitConversionSequence::Worse; 3902 if (ToPtr2->isObjCIdType() && 3903 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3904 return ImplicitConversionSequence::Better; 3905 3906 // A conversion to a non-id object pointer type is better than a 3907 // conversion to a qualified 'id' type 3908 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3909 return ImplicitConversionSequence::Worse; 3910 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3911 return ImplicitConversionSequence::Better; 3912 3913 // A conversion to an a non-Class object pointer type or qualified 'Class' 3914 // type is better than a conversion to 'Class'. 3915 if (ToPtr1->isObjCClassType() && 3916 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3917 return ImplicitConversionSequence::Worse; 3918 if (ToPtr2->isObjCClassType() && 3919 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3920 return ImplicitConversionSequence::Better; 3921 3922 // A conversion to a non-Class object pointer type is better than a 3923 // conversion to a qualified 'Class' type. 3924 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3925 return ImplicitConversionSequence::Worse; 3926 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3927 return ImplicitConversionSequence::Better; 3928 3929 // -- "conversion of C* to B* is better than conversion of C* to A*," 3930 if (S.Context.hasSameType(FromType1, FromType2) && 3931 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3932 (ToAssignLeft != ToAssignRight)) 3933 return ToAssignLeft? ImplicitConversionSequence::Worse 3934 : ImplicitConversionSequence::Better; 3935 3936 // -- "conversion of B* to A* is better than conversion of C* to A*," 3937 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3938 (FromAssignLeft != FromAssignRight)) 3939 return FromAssignLeft? ImplicitConversionSequence::Better 3940 : ImplicitConversionSequence::Worse; 3941 } 3942 } 3943 3944 // Ranking of member-pointer types. 3945 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3946 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3947 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3948 const MemberPointerType * FromMemPointer1 = 3949 FromType1->getAs<MemberPointerType>(); 3950 const MemberPointerType * ToMemPointer1 = 3951 ToType1->getAs<MemberPointerType>(); 3952 const MemberPointerType * FromMemPointer2 = 3953 FromType2->getAs<MemberPointerType>(); 3954 const MemberPointerType * ToMemPointer2 = 3955 ToType2->getAs<MemberPointerType>(); 3956 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3957 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3958 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3959 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3960 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3961 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3962 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3963 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3964 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3965 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3966 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3967 return ImplicitConversionSequence::Worse; 3968 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3969 return ImplicitConversionSequence::Better; 3970 } 3971 // conversion of B::* to C::* is better than conversion of A::* to C::* 3972 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3973 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3974 return ImplicitConversionSequence::Better; 3975 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3976 return ImplicitConversionSequence::Worse; 3977 } 3978 } 3979 3980 if (SCS1.Second == ICK_Derived_To_Base) { 3981 // -- conversion of C to B is better than conversion of C to A, 3982 // -- binding of an expression of type C to a reference of type 3983 // B& is better than binding an expression of type C to a 3984 // reference of type A&, 3985 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3986 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3987 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 3988 return ImplicitConversionSequence::Better; 3989 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 3990 return ImplicitConversionSequence::Worse; 3991 } 3992 3993 // -- conversion of B to A is better than conversion of C to A. 3994 // -- binding of an expression of type B to a reference of type 3995 // A& is better than binding an expression of type C to a 3996 // reference of type A&, 3997 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3998 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3999 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4000 return ImplicitConversionSequence::Better; 4001 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4002 return ImplicitConversionSequence::Worse; 4003 } 4004 } 4005 4006 return ImplicitConversionSequence::Indistinguishable; 4007 } 4008 4009 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4010 /// C++ class. 4011 static bool isTypeValid(QualType T) { 4012 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4013 return !Record->isInvalidDecl(); 4014 4015 return true; 4016 } 4017 4018 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4019 /// determine whether they are reference-related, 4020 /// reference-compatible, reference-compatible with added 4021 /// qualification, or incompatible, for use in C++ initialization by 4022 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4023 /// type, and the first type (T1) is the pointee type of the reference 4024 /// type being initialized. 4025 Sema::ReferenceCompareResult 4026 Sema::CompareReferenceRelationship(SourceLocation Loc, 4027 QualType OrigT1, QualType OrigT2, 4028 bool &DerivedToBase, 4029 bool &ObjCConversion, 4030 bool &ObjCLifetimeConversion) { 4031 assert(!OrigT1->isReferenceType() && 4032 "T1 must be the pointee type of the reference type"); 4033 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4034 4035 QualType T1 = Context.getCanonicalType(OrigT1); 4036 QualType T2 = Context.getCanonicalType(OrigT2); 4037 Qualifiers T1Quals, T2Quals; 4038 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4039 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4040 4041 // C++ [dcl.init.ref]p4: 4042 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4043 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4044 // T1 is a base class of T2. 4045 DerivedToBase = false; 4046 ObjCConversion = false; 4047 ObjCLifetimeConversion = false; 4048 if (UnqualT1 == UnqualT2) { 4049 // Nothing to do. 4050 } else if (isCompleteType(Loc, OrigT2) && 4051 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4052 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4053 DerivedToBase = true; 4054 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4055 UnqualT2->isObjCObjectOrInterfaceType() && 4056 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4057 ObjCConversion = true; 4058 else 4059 return Ref_Incompatible; 4060 4061 // At this point, we know that T1 and T2 are reference-related (at 4062 // least). 4063 4064 // If the type is an array type, promote the element qualifiers to the type 4065 // for comparison. 4066 if (isa<ArrayType>(T1) && T1Quals) 4067 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4068 if (isa<ArrayType>(T2) && T2Quals) 4069 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4070 4071 // C++ [dcl.init.ref]p4: 4072 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4073 // reference-related to T2 and cv1 is the same cv-qualification 4074 // as, or greater cv-qualification than, cv2. For purposes of 4075 // overload resolution, cases for which cv1 is greater 4076 // cv-qualification than cv2 are identified as 4077 // reference-compatible with added qualification (see 13.3.3.2). 4078 // 4079 // Note that we also require equivalence of Objective-C GC and address-space 4080 // qualifiers when performing these computations, so that e.g., an int in 4081 // address space 1 is not reference-compatible with an int in address 4082 // space 2. 4083 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4084 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4085 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4086 ObjCLifetimeConversion = true; 4087 4088 T1Quals.removeObjCLifetime(); 4089 T2Quals.removeObjCLifetime(); 4090 } 4091 4092 if (T1Quals == T2Quals) 4093 return Ref_Compatible; 4094 else if (T1Quals.compatiblyIncludes(T2Quals)) 4095 return Ref_Compatible_With_Added_Qualification; 4096 else 4097 return Ref_Related; 4098 } 4099 4100 /// \brief Look for a user-defined conversion to an value reference-compatible 4101 /// with DeclType. Return true if something definite is found. 4102 static bool 4103 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4104 QualType DeclType, SourceLocation DeclLoc, 4105 Expr *Init, QualType T2, bool AllowRvalues, 4106 bool AllowExplicit) { 4107 assert(T2->isRecordType() && "Can only find conversions of record types."); 4108 CXXRecordDecl *T2RecordDecl 4109 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4110 4111 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4112 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4113 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4114 NamedDecl *D = *I; 4115 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4116 if (isa<UsingShadowDecl>(D)) 4117 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4118 4119 FunctionTemplateDecl *ConvTemplate 4120 = dyn_cast<FunctionTemplateDecl>(D); 4121 CXXConversionDecl *Conv; 4122 if (ConvTemplate) 4123 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4124 else 4125 Conv = cast<CXXConversionDecl>(D); 4126 4127 // If this is an explicit conversion, and we're not allowed to consider 4128 // explicit conversions, skip it. 4129 if (!AllowExplicit && Conv->isExplicit()) 4130 continue; 4131 4132 if (AllowRvalues) { 4133 bool DerivedToBase = false; 4134 bool ObjCConversion = false; 4135 bool ObjCLifetimeConversion = false; 4136 4137 // If we are initializing an rvalue reference, don't permit conversion 4138 // functions that return lvalues. 4139 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4140 const ReferenceType *RefType 4141 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4142 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4143 continue; 4144 } 4145 4146 if (!ConvTemplate && 4147 S.CompareReferenceRelationship( 4148 DeclLoc, 4149 Conv->getConversionType().getNonReferenceType() 4150 .getUnqualifiedType(), 4151 DeclType.getNonReferenceType().getUnqualifiedType(), 4152 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4153 Sema::Ref_Incompatible) 4154 continue; 4155 } else { 4156 // If the conversion function doesn't return a reference type, 4157 // it can't be considered for this conversion. An rvalue reference 4158 // is only acceptable if its referencee is a function type. 4159 4160 const ReferenceType *RefType = 4161 Conv->getConversionType()->getAs<ReferenceType>(); 4162 if (!RefType || 4163 (!RefType->isLValueReferenceType() && 4164 !RefType->getPointeeType()->isFunctionType())) 4165 continue; 4166 } 4167 4168 if (ConvTemplate) 4169 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4170 Init, DeclType, CandidateSet, 4171 /*AllowObjCConversionOnExplicit=*/false); 4172 else 4173 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4174 DeclType, CandidateSet, 4175 /*AllowObjCConversionOnExplicit=*/false); 4176 } 4177 4178 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4179 4180 OverloadCandidateSet::iterator Best; 4181 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4182 case OR_Success: 4183 // C++ [over.ics.ref]p1: 4184 // 4185 // [...] If the parameter binds directly to the result of 4186 // applying a conversion function to the argument 4187 // expression, the implicit conversion sequence is a 4188 // user-defined conversion sequence (13.3.3.1.2), with the 4189 // second standard conversion sequence either an identity 4190 // conversion or, if the conversion function returns an 4191 // entity of a type that is a derived class of the parameter 4192 // type, a derived-to-base Conversion. 4193 if (!Best->FinalConversion.DirectBinding) 4194 return false; 4195 4196 ICS.setUserDefined(); 4197 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4198 ICS.UserDefined.After = Best->FinalConversion; 4199 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4200 ICS.UserDefined.ConversionFunction = Best->Function; 4201 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4202 ICS.UserDefined.EllipsisConversion = false; 4203 assert(ICS.UserDefined.After.ReferenceBinding && 4204 ICS.UserDefined.After.DirectBinding && 4205 "Expected a direct reference binding!"); 4206 return true; 4207 4208 case OR_Ambiguous: 4209 ICS.setAmbiguous(); 4210 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4211 Cand != CandidateSet.end(); ++Cand) 4212 if (Cand->Viable) 4213 ICS.Ambiguous.addConversion(Cand->Function); 4214 return true; 4215 4216 case OR_No_Viable_Function: 4217 case OR_Deleted: 4218 // There was no suitable conversion, or we found a deleted 4219 // conversion; continue with other checks. 4220 return false; 4221 } 4222 4223 llvm_unreachable("Invalid OverloadResult!"); 4224 } 4225 4226 /// \brief Compute an implicit conversion sequence for reference 4227 /// initialization. 4228 static ImplicitConversionSequence 4229 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4230 SourceLocation DeclLoc, 4231 bool SuppressUserConversions, 4232 bool AllowExplicit) { 4233 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4234 4235 // Most paths end in a failed conversion. 4236 ImplicitConversionSequence ICS; 4237 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4238 4239 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4240 QualType T2 = Init->getType(); 4241 4242 // If the initializer is the address of an overloaded function, try 4243 // to resolve the overloaded function. If all goes well, T2 is the 4244 // type of the resulting function. 4245 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4246 DeclAccessPair Found; 4247 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4248 false, Found)) 4249 T2 = Fn->getType(); 4250 } 4251 4252 // Compute some basic properties of the types and the initializer. 4253 bool isRValRef = DeclType->isRValueReferenceType(); 4254 bool DerivedToBase = false; 4255 bool ObjCConversion = false; 4256 bool ObjCLifetimeConversion = false; 4257 Expr::Classification InitCategory = Init->Classify(S.Context); 4258 Sema::ReferenceCompareResult RefRelationship 4259 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4260 ObjCConversion, ObjCLifetimeConversion); 4261 4262 4263 // C++0x [dcl.init.ref]p5: 4264 // A reference to type "cv1 T1" is initialized by an expression 4265 // of type "cv2 T2" as follows: 4266 4267 // -- If reference is an lvalue reference and the initializer expression 4268 if (!isRValRef) { 4269 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4270 // reference-compatible with "cv2 T2," or 4271 // 4272 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4273 if (InitCategory.isLValue() && 4274 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4275 // C++ [over.ics.ref]p1: 4276 // When a parameter of reference type binds directly (8.5.3) 4277 // to an argument expression, the implicit conversion sequence 4278 // is the identity conversion, unless the argument expression 4279 // has a type that is a derived class of the parameter type, 4280 // in which case the implicit conversion sequence is a 4281 // derived-to-base Conversion (13.3.3.1). 4282 ICS.setStandard(); 4283 ICS.Standard.First = ICK_Identity; 4284 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4285 : ObjCConversion? ICK_Compatible_Conversion 4286 : ICK_Identity; 4287 ICS.Standard.Third = ICK_Identity; 4288 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4289 ICS.Standard.setToType(0, T2); 4290 ICS.Standard.setToType(1, T1); 4291 ICS.Standard.setToType(2, T1); 4292 ICS.Standard.ReferenceBinding = true; 4293 ICS.Standard.DirectBinding = true; 4294 ICS.Standard.IsLvalueReference = !isRValRef; 4295 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4296 ICS.Standard.BindsToRvalue = false; 4297 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4298 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4299 ICS.Standard.CopyConstructor = nullptr; 4300 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4301 4302 // Nothing more to do: the inaccessibility/ambiguity check for 4303 // derived-to-base conversions is suppressed when we're 4304 // computing the implicit conversion sequence (C++ 4305 // [over.best.ics]p2). 4306 return ICS; 4307 } 4308 4309 // -- has a class type (i.e., T2 is a class type), where T1 is 4310 // not reference-related to T2, and can be implicitly 4311 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4312 // is reference-compatible with "cv3 T3" 92) (this 4313 // conversion is selected by enumerating the applicable 4314 // conversion functions (13.3.1.6) and choosing the best 4315 // one through overload resolution (13.3)), 4316 if (!SuppressUserConversions && T2->isRecordType() && 4317 S.isCompleteType(DeclLoc, T2) && 4318 RefRelationship == Sema::Ref_Incompatible) { 4319 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4320 Init, T2, /*AllowRvalues=*/false, 4321 AllowExplicit)) 4322 return ICS; 4323 } 4324 } 4325 4326 // -- Otherwise, the reference shall be an lvalue reference to a 4327 // non-volatile const type (i.e., cv1 shall be const), or the reference 4328 // shall be an rvalue reference. 4329 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4330 return ICS; 4331 4332 // -- If the initializer expression 4333 // 4334 // -- is an xvalue, class prvalue, array prvalue or function 4335 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4336 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4337 (InitCategory.isXValue() || 4338 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4339 (InitCategory.isLValue() && T2->isFunctionType()))) { 4340 ICS.setStandard(); 4341 ICS.Standard.First = ICK_Identity; 4342 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4343 : ObjCConversion? ICK_Compatible_Conversion 4344 : ICK_Identity; 4345 ICS.Standard.Third = ICK_Identity; 4346 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4347 ICS.Standard.setToType(0, T2); 4348 ICS.Standard.setToType(1, T1); 4349 ICS.Standard.setToType(2, T1); 4350 ICS.Standard.ReferenceBinding = true; 4351 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4352 // binding unless we're binding to a class prvalue. 4353 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4354 // allow the use of rvalue references in C++98/03 for the benefit of 4355 // standard library implementors; therefore, we need the xvalue check here. 4356 ICS.Standard.DirectBinding = 4357 S.getLangOpts().CPlusPlus11 || 4358 !(InitCategory.isPRValue() || T2->isRecordType()); 4359 ICS.Standard.IsLvalueReference = !isRValRef; 4360 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4361 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4362 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4363 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4364 ICS.Standard.CopyConstructor = nullptr; 4365 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4366 return ICS; 4367 } 4368 4369 // -- has a class type (i.e., T2 is a class type), where T1 is not 4370 // reference-related to T2, and can be implicitly converted to 4371 // an xvalue, class prvalue, or function lvalue of type 4372 // "cv3 T3", where "cv1 T1" is reference-compatible with 4373 // "cv3 T3", 4374 // 4375 // then the reference is bound to the value of the initializer 4376 // expression in the first case and to the result of the conversion 4377 // in the second case (or, in either case, to an appropriate base 4378 // class subobject). 4379 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4380 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4381 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4382 Init, T2, /*AllowRvalues=*/true, 4383 AllowExplicit)) { 4384 // In the second case, if the reference is an rvalue reference 4385 // and the second standard conversion sequence of the 4386 // user-defined conversion sequence includes an lvalue-to-rvalue 4387 // conversion, the program is ill-formed. 4388 if (ICS.isUserDefined() && isRValRef && 4389 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4390 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4391 4392 return ICS; 4393 } 4394 4395 // A temporary of function type cannot be created; don't even try. 4396 if (T1->isFunctionType()) 4397 return ICS; 4398 4399 // -- Otherwise, a temporary of type "cv1 T1" is created and 4400 // initialized from the initializer expression using the 4401 // rules for a non-reference copy initialization (8.5). The 4402 // reference is then bound to the temporary. If T1 is 4403 // reference-related to T2, cv1 must be the same 4404 // cv-qualification as, or greater cv-qualification than, 4405 // cv2; otherwise, the program is ill-formed. 4406 if (RefRelationship == Sema::Ref_Related) { 4407 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4408 // we would be reference-compatible or reference-compatible with 4409 // added qualification. But that wasn't the case, so the reference 4410 // initialization fails. 4411 // 4412 // Note that we only want to check address spaces and cvr-qualifiers here. 4413 // ObjC GC and lifetime qualifiers aren't important. 4414 Qualifiers T1Quals = T1.getQualifiers(); 4415 Qualifiers T2Quals = T2.getQualifiers(); 4416 T1Quals.removeObjCGCAttr(); 4417 T1Quals.removeObjCLifetime(); 4418 T2Quals.removeObjCGCAttr(); 4419 T2Quals.removeObjCLifetime(); 4420 if (!T1Quals.compatiblyIncludes(T2Quals)) 4421 return ICS; 4422 } 4423 4424 // If at least one of the types is a class type, the types are not 4425 // related, and we aren't allowed any user conversions, the 4426 // reference binding fails. This case is important for breaking 4427 // recursion, since TryImplicitConversion below will attempt to 4428 // create a temporary through the use of a copy constructor. 4429 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4430 (T1->isRecordType() || T2->isRecordType())) 4431 return ICS; 4432 4433 // If T1 is reference-related to T2 and the reference is an rvalue 4434 // reference, the initializer expression shall not be an lvalue. 4435 if (RefRelationship >= Sema::Ref_Related && 4436 isRValRef && Init->Classify(S.Context).isLValue()) 4437 return ICS; 4438 4439 // C++ [over.ics.ref]p2: 4440 // When a parameter of reference type is not bound directly to 4441 // an argument expression, the conversion sequence is the one 4442 // required to convert the argument expression to the 4443 // underlying type of the reference according to 4444 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4445 // to copy-initializing a temporary of the underlying type with 4446 // the argument expression. Any difference in top-level 4447 // cv-qualification is subsumed by the initialization itself 4448 // and does not constitute a conversion. 4449 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4450 /*AllowExplicit=*/false, 4451 /*InOverloadResolution=*/false, 4452 /*CStyle=*/false, 4453 /*AllowObjCWritebackConversion=*/false, 4454 /*AllowObjCConversionOnExplicit=*/false); 4455 4456 // Of course, that's still a reference binding. 4457 if (ICS.isStandard()) { 4458 ICS.Standard.ReferenceBinding = true; 4459 ICS.Standard.IsLvalueReference = !isRValRef; 4460 ICS.Standard.BindsToFunctionLvalue = false; 4461 ICS.Standard.BindsToRvalue = true; 4462 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4463 ICS.Standard.ObjCLifetimeConversionBinding = false; 4464 } else if (ICS.isUserDefined()) { 4465 const ReferenceType *LValRefType = 4466 ICS.UserDefined.ConversionFunction->getReturnType() 4467 ->getAs<LValueReferenceType>(); 4468 4469 // C++ [over.ics.ref]p3: 4470 // Except for an implicit object parameter, for which see 13.3.1, a 4471 // standard conversion sequence cannot be formed if it requires [...] 4472 // binding an rvalue reference to an lvalue other than a function 4473 // lvalue. 4474 // Note that the function case is not possible here. 4475 if (DeclType->isRValueReferenceType() && LValRefType) { 4476 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4477 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4478 // reference to an rvalue! 4479 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4480 return ICS; 4481 } 4482 4483 ICS.UserDefined.Before.setAsIdentityConversion(); 4484 ICS.UserDefined.After.ReferenceBinding = true; 4485 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4486 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4487 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4488 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4489 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4490 } 4491 4492 return ICS; 4493 } 4494 4495 static ImplicitConversionSequence 4496 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4497 bool SuppressUserConversions, 4498 bool InOverloadResolution, 4499 bool AllowObjCWritebackConversion, 4500 bool AllowExplicit = false); 4501 4502 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4503 /// initializer list From. 4504 static ImplicitConversionSequence 4505 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4506 bool SuppressUserConversions, 4507 bool InOverloadResolution, 4508 bool AllowObjCWritebackConversion) { 4509 // C++11 [over.ics.list]p1: 4510 // When an argument is an initializer list, it is not an expression and 4511 // special rules apply for converting it to a parameter type. 4512 4513 ImplicitConversionSequence Result; 4514 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4515 4516 // We need a complete type for what follows. Incomplete types can never be 4517 // initialized from init lists. 4518 if (!S.isCompleteType(From->getLocStart(), ToType)) 4519 return Result; 4520 4521 // Per DR1467: 4522 // If the parameter type is a class X and the initializer list has a single 4523 // element of type cv U, where U is X or a class derived from X, the 4524 // implicit conversion sequence is the one required to convert the element 4525 // to the parameter type. 4526 // 4527 // Otherwise, if the parameter type is a character array [... ] 4528 // and the initializer list has a single element that is an 4529 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4530 // implicit conversion sequence is the identity conversion. 4531 if (From->getNumInits() == 1) { 4532 if (ToType->isRecordType()) { 4533 QualType InitType = From->getInit(0)->getType(); 4534 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4535 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4536 return TryCopyInitialization(S, From->getInit(0), ToType, 4537 SuppressUserConversions, 4538 InOverloadResolution, 4539 AllowObjCWritebackConversion); 4540 } 4541 // FIXME: Check the other conditions here: array of character type, 4542 // initializer is a string literal. 4543 if (ToType->isArrayType()) { 4544 InitializedEntity Entity = 4545 InitializedEntity::InitializeParameter(S.Context, ToType, 4546 /*Consumed=*/false); 4547 if (S.CanPerformCopyInitialization(Entity, From)) { 4548 Result.setStandard(); 4549 Result.Standard.setAsIdentityConversion(); 4550 Result.Standard.setFromType(ToType); 4551 Result.Standard.setAllToTypes(ToType); 4552 return Result; 4553 } 4554 } 4555 } 4556 4557 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4558 // C++11 [over.ics.list]p2: 4559 // If the parameter type is std::initializer_list<X> or "array of X" and 4560 // all the elements can be implicitly converted to X, the implicit 4561 // conversion sequence is the worst conversion necessary to convert an 4562 // element of the list to X. 4563 // 4564 // C++14 [over.ics.list]p3: 4565 // Otherwise, if the parameter type is "array of N X", if the initializer 4566 // list has exactly N elements or if it has fewer than N elements and X is 4567 // default-constructible, and if all the elements of the initializer list 4568 // can be implicitly converted to X, the implicit conversion sequence is 4569 // the worst conversion necessary to convert an element of the list to X. 4570 // 4571 // FIXME: We're missing a lot of these checks. 4572 bool toStdInitializerList = false; 4573 QualType X; 4574 if (ToType->isArrayType()) 4575 X = S.Context.getAsArrayType(ToType)->getElementType(); 4576 else 4577 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4578 if (!X.isNull()) { 4579 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4580 Expr *Init = From->getInit(i); 4581 ImplicitConversionSequence ICS = 4582 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4583 InOverloadResolution, 4584 AllowObjCWritebackConversion); 4585 // If a single element isn't convertible, fail. 4586 if (ICS.isBad()) { 4587 Result = ICS; 4588 break; 4589 } 4590 // Otherwise, look for the worst conversion. 4591 if (Result.isBad() || 4592 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4593 Result) == 4594 ImplicitConversionSequence::Worse) 4595 Result = ICS; 4596 } 4597 4598 // For an empty list, we won't have computed any conversion sequence. 4599 // Introduce the identity conversion sequence. 4600 if (From->getNumInits() == 0) { 4601 Result.setStandard(); 4602 Result.Standard.setAsIdentityConversion(); 4603 Result.Standard.setFromType(ToType); 4604 Result.Standard.setAllToTypes(ToType); 4605 } 4606 4607 Result.setStdInitializerListElement(toStdInitializerList); 4608 return Result; 4609 } 4610 4611 // C++14 [over.ics.list]p4: 4612 // C++11 [over.ics.list]p3: 4613 // Otherwise, if the parameter is a non-aggregate class X and overload 4614 // resolution chooses a single best constructor [...] the implicit 4615 // conversion sequence is a user-defined conversion sequence. If multiple 4616 // constructors are viable but none is better than the others, the 4617 // implicit conversion sequence is a user-defined conversion sequence. 4618 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4619 // This function can deal with initializer lists. 4620 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4621 /*AllowExplicit=*/false, 4622 InOverloadResolution, /*CStyle=*/false, 4623 AllowObjCWritebackConversion, 4624 /*AllowObjCConversionOnExplicit=*/false); 4625 } 4626 4627 // C++14 [over.ics.list]p5: 4628 // C++11 [over.ics.list]p4: 4629 // Otherwise, if the parameter has an aggregate type which can be 4630 // initialized from the initializer list [...] the implicit conversion 4631 // sequence is a user-defined conversion sequence. 4632 if (ToType->isAggregateType()) { 4633 // Type is an aggregate, argument is an init list. At this point it comes 4634 // down to checking whether the initialization works. 4635 // FIXME: Find out whether this parameter is consumed or not. 4636 InitializedEntity Entity = 4637 InitializedEntity::InitializeParameter(S.Context, ToType, 4638 /*Consumed=*/false); 4639 if (S.CanPerformCopyInitialization(Entity, From)) { 4640 Result.setUserDefined(); 4641 Result.UserDefined.Before.setAsIdentityConversion(); 4642 // Initializer lists don't have a type. 4643 Result.UserDefined.Before.setFromType(QualType()); 4644 Result.UserDefined.Before.setAllToTypes(QualType()); 4645 4646 Result.UserDefined.After.setAsIdentityConversion(); 4647 Result.UserDefined.After.setFromType(ToType); 4648 Result.UserDefined.After.setAllToTypes(ToType); 4649 Result.UserDefined.ConversionFunction = nullptr; 4650 } 4651 return Result; 4652 } 4653 4654 // C++14 [over.ics.list]p6: 4655 // C++11 [over.ics.list]p5: 4656 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4657 if (ToType->isReferenceType()) { 4658 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4659 // mention initializer lists in any way. So we go by what list- 4660 // initialization would do and try to extrapolate from that. 4661 4662 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4663 4664 // If the initializer list has a single element that is reference-related 4665 // to the parameter type, we initialize the reference from that. 4666 if (From->getNumInits() == 1) { 4667 Expr *Init = From->getInit(0); 4668 4669 QualType T2 = Init->getType(); 4670 4671 // If the initializer is the address of an overloaded function, try 4672 // to resolve the overloaded function. If all goes well, T2 is the 4673 // type of the resulting function. 4674 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4675 DeclAccessPair Found; 4676 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4677 Init, ToType, false, Found)) 4678 T2 = Fn->getType(); 4679 } 4680 4681 // Compute some basic properties of the types and the initializer. 4682 bool dummy1 = false; 4683 bool dummy2 = false; 4684 bool dummy3 = false; 4685 Sema::ReferenceCompareResult RefRelationship 4686 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4687 dummy2, dummy3); 4688 4689 if (RefRelationship >= Sema::Ref_Related) { 4690 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4691 SuppressUserConversions, 4692 /*AllowExplicit=*/false); 4693 } 4694 } 4695 4696 // Otherwise, we bind the reference to a temporary created from the 4697 // initializer list. 4698 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4699 InOverloadResolution, 4700 AllowObjCWritebackConversion); 4701 if (Result.isFailure()) 4702 return Result; 4703 assert(!Result.isEllipsis() && 4704 "Sub-initialization cannot result in ellipsis conversion."); 4705 4706 // Can we even bind to a temporary? 4707 if (ToType->isRValueReferenceType() || 4708 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4709 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4710 Result.UserDefined.After; 4711 SCS.ReferenceBinding = true; 4712 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4713 SCS.BindsToRvalue = true; 4714 SCS.BindsToFunctionLvalue = false; 4715 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4716 SCS.ObjCLifetimeConversionBinding = false; 4717 } else 4718 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4719 From, ToType); 4720 return Result; 4721 } 4722 4723 // C++14 [over.ics.list]p7: 4724 // C++11 [over.ics.list]p6: 4725 // Otherwise, if the parameter type is not a class: 4726 if (!ToType->isRecordType()) { 4727 // - if the initializer list has one element that is not itself an 4728 // initializer list, the implicit conversion sequence is the one 4729 // required to convert the element to the parameter type. 4730 unsigned NumInits = From->getNumInits(); 4731 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4732 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4733 SuppressUserConversions, 4734 InOverloadResolution, 4735 AllowObjCWritebackConversion); 4736 // - if the initializer list has no elements, the implicit conversion 4737 // sequence is the identity conversion. 4738 else if (NumInits == 0) { 4739 Result.setStandard(); 4740 Result.Standard.setAsIdentityConversion(); 4741 Result.Standard.setFromType(ToType); 4742 Result.Standard.setAllToTypes(ToType); 4743 } 4744 return Result; 4745 } 4746 4747 // C++14 [over.ics.list]p8: 4748 // C++11 [over.ics.list]p7: 4749 // In all cases other than those enumerated above, no conversion is possible 4750 return Result; 4751 } 4752 4753 /// TryCopyInitialization - Try to copy-initialize a value of type 4754 /// ToType from the expression From. Return the implicit conversion 4755 /// sequence required to pass this argument, which may be a bad 4756 /// conversion sequence (meaning that the argument cannot be passed to 4757 /// a parameter of this type). If @p SuppressUserConversions, then we 4758 /// do not permit any user-defined conversion sequences. 4759 static ImplicitConversionSequence 4760 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4761 bool SuppressUserConversions, 4762 bool InOverloadResolution, 4763 bool AllowObjCWritebackConversion, 4764 bool AllowExplicit) { 4765 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4766 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4767 InOverloadResolution,AllowObjCWritebackConversion); 4768 4769 if (ToType->isReferenceType()) 4770 return TryReferenceInit(S, From, ToType, 4771 /*FIXME:*/From->getLocStart(), 4772 SuppressUserConversions, 4773 AllowExplicit); 4774 4775 return TryImplicitConversion(S, From, ToType, 4776 SuppressUserConversions, 4777 /*AllowExplicit=*/false, 4778 InOverloadResolution, 4779 /*CStyle=*/false, 4780 AllowObjCWritebackConversion, 4781 /*AllowObjCConversionOnExplicit=*/false); 4782 } 4783 4784 static bool TryCopyInitialization(const CanQualType FromQTy, 4785 const CanQualType ToQTy, 4786 Sema &S, 4787 SourceLocation Loc, 4788 ExprValueKind FromVK) { 4789 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4790 ImplicitConversionSequence ICS = 4791 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4792 4793 return !ICS.isBad(); 4794 } 4795 4796 /// TryObjectArgumentInitialization - Try to initialize the object 4797 /// parameter of the given member function (@c Method) from the 4798 /// expression @p From. 4799 static ImplicitConversionSequence 4800 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4801 Expr::Classification FromClassification, 4802 CXXMethodDecl *Method, 4803 CXXRecordDecl *ActingContext) { 4804 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4805 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4806 // const volatile object. 4807 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4808 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4809 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4810 4811 // Set up the conversion sequence as a "bad" conversion, to allow us 4812 // to exit early. 4813 ImplicitConversionSequence ICS; 4814 4815 // We need to have an object of class type. 4816 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4817 FromType = PT->getPointeeType(); 4818 4819 // When we had a pointer, it's implicitly dereferenced, so we 4820 // better have an lvalue. 4821 assert(FromClassification.isLValue()); 4822 } 4823 4824 assert(FromType->isRecordType()); 4825 4826 // C++0x [over.match.funcs]p4: 4827 // For non-static member functions, the type of the implicit object 4828 // parameter is 4829 // 4830 // - "lvalue reference to cv X" for functions declared without a 4831 // ref-qualifier or with the & ref-qualifier 4832 // - "rvalue reference to cv X" for functions declared with the && 4833 // ref-qualifier 4834 // 4835 // where X is the class of which the function is a member and cv is the 4836 // cv-qualification on the member function declaration. 4837 // 4838 // However, when finding an implicit conversion sequence for the argument, we 4839 // are not allowed to create temporaries or perform user-defined conversions 4840 // (C++ [over.match.funcs]p5). We perform a simplified version of 4841 // reference binding here, that allows class rvalues to bind to 4842 // non-constant references. 4843 4844 // First check the qualifiers. 4845 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4846 if (ImplicitParamType.getCVRQualifiers() 4847 != FromTypeCanon.getLocalCVRQualifiers() && 4848 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4849 ICS.setBad(BadConversionSequence::bad_qualifiers, 4850 FromType, ImplicitParamType); 4851 return ICS; 4852 } 4853 4854 // Check that we have either the same type or a derived type. It 4855 // affects the conversion rank. 4856 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4857 ImplicitConversionKind SecondKind; 4858 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4859 SecondKind = ICK_Identity; 4860 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4861 SecondKind = ICK_Derived_To_Base; 4862 else { 4863 ICS.setBad(BadConversionSequence::unrelated_class, 4864 FromType, ImplicitParamType); 4865 return ICS; 4866 } 4867 4868 // Check the ref-qualifier. 4869 switch (Method->getRefQualifier()) { 4870 case RQ_None: 4871 // Do nothing; we don't care about lvalueness or rvalueness. 4872 break; 4873 4874 case RQ_LValue: 4875 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4876 // non-const lvalue reference cannot bind to an rvalue 4877 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4878 ImplicitParamType); 4879 return ICS; 4880 } 4881 break; 4882 4883 case RQ_RValue: 4884 if (!FromClassification.isRValue()) { 4885 // rvalue reference cannot bind to an lvalue 4886 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4887 ImplicitParamType); 4888 return ICS; 4889 } 4890 break; 4891 } 4892 4893 // Success. Mark this as a reference binding. 4894 ICS.setStandard(); 4895 ICS.Standard.setAsIdentityConversion(); 4896 ICS.Standard.Second = SecondKind; 4897 ICS.Standard.setFromType(FromType); 4898 ICS.Standard.setAllToTypes(ImplicitParamType); 4899 ICS.Standard.ReferenceBinding = true; 4900 ICS.Standard.DirectBinding = true; 4901 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4902 ICS.Standard.BindsToFunctionLvalue = false; 4903 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4904 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4905 = (Method->getRefQualifier() == RQ_None); 4906 return ICS; 4907 } 4908 4909 /// PerformObjectArgumentInitialization - Perform initialization of 4910 /// the implicit object parameter for the given Method with the given 4911 /// expression. 4912 ExprResult 4913 Sema::PerformObjectArgumentInitialization(Expr *From, 4914 NestedNameSpecifier *Qualifier, 4915 NamedDecl *FoundDecl, 4916 CXXMethodDecl *Method) { 4917 QualType FromRecordType, DestType; 4918 QualType ImplicitParamRecordType = 4919 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4920 4921 Expr::Classification FromClassification; 4922 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4923 FromRecordType = PT->getPointeeType(); 4924 DestType = Method->getThisType(Context); 4925 FromClassification = Expr::Classification::makeSimpleLValue(); 4926 } else { 4927 FromRecordType = From->getType(); 4928 DestType = ImplicitParamRecordType; 4929 FromClassification = From->Classify(Context); 4930 } 4931 4932 // Note that we always use the true parent context when performing 4933 // the actual argument initialization. 4934 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4935 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4936 Method->getParent()); 4937 if (ICS.isBad()) { 4938 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4939 Qualifiers FromQs = FromRecordType.getQualifiers(); 4940 Qualifiers ToQs = DestType.getQualifiers(); 4941 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4942 if (CVR) { 4943 Diag(From->getLocStart(), 4944 diag::err_member_function_call_bad_cvr) 4945 << Method->getDeclName() << FromRecordType << (CVR - 1) 4946 << From->getSourceRange(); 4947 Diag(Method->getLocation(), diag::note_previous_decl) 4948 << Method->getDeclName(); 4949 return ExprError(); 4950 } 4951 } 4952 4953 return Diag(From->getLocStart(), 4954 diag::err_implicit_object_parameter_init) 4955 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4956 } 4957 4958 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4959 ExprResult FromRes = 4960 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4961 if (FromRes.isInvalid()) 4962 return ExprError(); 4963 From = FromRes.get(); 4964 } 4965 4966 if (!Context.hasSameType(From->getType(), DestType)) 4967 From = ImpCastExprToType(From, DestType, CK_NoOp, 4968 From->getValueKind()).get(); 4969 return From; 4970 } 4971 4972 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4973 /// expression From to bool (C++0x [conv]p3). 4974 static ImplicitConversionSequence 4975 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4976 return TryImplicitConversion(S, From, S.Context.BoolTy, 4977 /*SuppressUserConversions=*/false, 4978 /*AllowExplicit=*/true, 4979 /*InOverloadResolution=*/false, 4980 /*CStyle=*/false, 4981 /*AllowObjCWritebackConversion=*/false, 4982 /*AllowObjCConversionOnExplicit=*/false); 4983 } 4984 4985 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4986 /// of the expression From to bool (C++0x [conv]p3). 4987 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4988 if (checkPlaceholderForOverload(*this, From)) 4989 return ExprError(); 4990 4991 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4992 if (!ICS.isBad()) 4993 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4994 4995 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4996 return Diag(From->getLocStart(), 4997 diag::err_typecheck_bool_condition) 4998 << From->getType() << From->getSourceRange(); 4999 return ExprError(); 5000 } 5001 5002 /// Check that the specified conversion is permitted in a converted constant 5003 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5004 /// is acceptable. 5005 static bool CheckConvertedConstantConversions(Sema &S, 5006 StandardConversionSequence &SCS) { 5007 // Since we know that the target type is an integral or unscoped enumeration 5008 // type, most conversion kinds are impossible. All possible First and Third 5009 // conversions are fine. 5010 switch (SCS.Second) { 5011 case ICK_Identity: 5012 case ICK_NoReturn_Adjustment: 5013 case ICK_Integral_Promotion: 5014 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5015 return true; 5016 5017 case ICK_Boolean_Conversion: 5018 // Conversion from an integral or unscoped enumeration type to bool is 5019 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5020 // conversion, so we allow it in a converted constant expression. 5021 // 5022 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5023 // a lot of popular code. We should at least add a warning for this 5024 // (non-conforming) extension. 5025 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5026 SCS.getToType(2)->isBooleanType(); 5027 5028 case ICK_Pointer_Conversion: 5029 case ICK_Pointer_Member: 5030 // C++1z: null pointer conversions and null member pointer conversions are 5031 // only permitted if the source type is std::nullptr_t. 5032 return SCS.getFromType()->isNullPtrType(); 5033 5034 case ICK_Floating_Promotion: 5035 case ICK_Complex_Promotion: 5036 case ICK_Floating_Conversion: 5037 case ICK_Complex_Conversion: 5038 case ICK_Floating_Integral: 5039 case ICK_Compatible_Conversion: 5040 case ICK_Derived_To_Base: 5041 case ICK_Vector_Conversion: 5042 case ICK_Vector_Splat: 5043 case ICK_Complex_Real: 5044 case ICK_Block_Pointer_Conversion: 5045 case ICK_TransparentUnionConversion: 5046 case ICK_Writeback_Conversion: 5047 case ICK_Zero_Event_Conversion: 5048 case ICK_C_Only_Conversion: 5049 return false; 5050 5051 case ICK_Lvalue_To_Rvalue: 5052 case ICK_Array_To_Pointer: 5053 case ICK_Function_To_Pointer: 5054 llvm_unreachable("found a first conversion kind in Second"); 5055 5056 case ICK_Qualification: 5057 llvm_unreachable("found a third conversion kind in Second"); 5058 5059 case ICK_Num_Conversion_Kinds: 5060 break; 5061 } 5062 5063 llvm_unreachable("unknown conversion kind"); 5064 } 5065 5066 /// CheckConvertedConstantExpression - Check that the expression From is a 5067 /// converted constant expression of type T, perform the conversion and produce 5068 /// the converted expression, per C++11 [expr.const]p3. 5069 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5070 QualType T, APValue &Value, 5071 Sema::CCEKind CCE, 5072 bool RequireInt) { 5073 assert(S.getLangOpts().CPlusPlus11 && 5074 "converted constant expression outside C++11"); 5075 5076 if (checkPlaceholderForOverload(S, From)) 5077 return ExprError(); 5078 5079 // C++1z [expr.const]p3: 5080 // A converted constant expression of type T is an expression, 5081 // implicitly converted to type T, where the converted 5082 // expression is a constant expression and the implicit conversion 5083 // sequence contains only [... list of conversions ...]. 5084 ImplicitConversionSequence ICS = 5085 TryCopyInitialization(S, From, T, 5086 /*SuppressUserConversions=*/false, 5087 /*InOverloadResolution=*/false, 5088 /*AllowObjcWritebackConversion=*/false, 5089 /*AllowExplicit=*/false); 5090 StandardConversionSequence *SCS = nullptr; 5091 switch (ICS.getKind()) { 5092 case ImplicitConversionSequence::StandardConversion: 5093 SCS = &ICS.Standard; 5094 break; 5095 case ImplicitConversionSequence::UserDefinedConversion: 5096 // We are converting to a non-class type, so the Before sequence 5097 // must be trivial. 5098 SCS = &ICS.UserDefined.After; 5099 break; 5100 case ImplicitConversionSequence::AmbiguousConversion: 5101 case ImplicitConversionSequence::BadConversion: 5102 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5103 return S.Diag(From->getLocStart(), 5104 diag::err_typecheck_converted_constant_expression) 5105 << From->getType() << From->getSourceRange() << T; 5106 return ExprError(); 5107 5108 case ImplicitConversionSequence::EllipsisConversion: 5109 llvm_unreachable("ellipsis conversion in converted constant expression"); 5110 } 5111 5112 // Check that we would only use permitted conversions. 5113 if (!CheckConvertedConstantConversions(S, *SCS)) { 5114 return S.Diag(From->getLocStart(), 5115 diag::err_typecheck_converted_constant_expression_disallowed) 5116 << From->getType() << From->getSourceRange() << T; 5117 } 5118 // [...] and where the reference binding (if any) binds directly. 5119 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5120 return S.Diag(From->getLocStart(), 5121 diag::err_typecheck_converted_constant_expression_indirect) 5122 << From->getType() << From->getSourceRange() << T; 5123 } 5124 5125 ExprResult Result = 5126 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5127 if (Result.isInvalid()) 5128 return Result; 5129 5130 // Check for a narrowing implicit conversion. 5131 APValue PreNarrowingValue; 5132 QualType PreNarrowingType; 5133 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5134 PreNarrowingType)) { 5135 case NK_Variable_Narrowing: 5136 // Implicit conversion to a narrower type, and the value is not a constant 5137 // expression. We'll diagnose this in a moment. 5138 case NK_Not_Narrowing: 5139 break; 5140 5141 case NK_Constant_Narrowing: 5142 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5143 << CCE << /*Constant*/1 5144 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5145 break; 5146 5147 case NK_Type_Narrowing: 5148 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5149 << CCE << /*Constant*/0 << From->getType() << T; 5150 break; 5151 } 5152 5153 // Check the expression is a constant expression. 5154 SmallVector<PartialDiagnosticAt, 8> Notes; 5155 Expr::EvalResult Eval; 5156 Eval.Diag = &Notes; 5157 5158 if ((T->isReferenceType() 5159 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5160 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5161 (RequireInt && !Eval.Val.isInt())) { 5162 // The expression can't be folded, so we can't keep it at this position in 5163 // the AST. 5164 Result = ExprError(); 5165 } else { 5166 Value = Eval.Val; 5167 5168 if (Notes.empty()) { 5169 // It's a constant expression. 5170 return Result; 5171 } 5172 } 5173 5174 // It's not a constant expression. Produce an appropriate diagnostic. 5175 if (Notes.size() == 1 && 5176 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5177 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5178 else { 5179 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5180 << CCE << From->getSourceRange(); 5181 for (unsigned I = 0; I < Notes.size(); ++I) 5182 S.Diag(Notes[I].first, Notes[I].second); 5183 } 5184 return ExprError(); 5185 } 5186 5187 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5188 APValue &Value, CCEKind CCE) { 5189 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5190 } 5191 5192 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5193 llvm::APSInt &Value, 5194 CCEKind CCE) { 5195 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5196 5197 APValue V; 5198 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5199 if (!R.isInvalid()) 5200 Value = V.getInt(); 5201 return R; 5202 } 5203 5204 5205 /// dropPointerConversions - If the given standard conversion sequence 5206 /// involves any pointer conversions, remove them. This may change 5207 /// the result type of the conversion sequence. 5208 static void dropPointerConversion(StandardConversionSequence &SCS) { 5209 if (SCS.Second == ICK_Pointer_Conversion) { 5210 SCS.Second = ICK_Identity; 5211 SCS.Third = ICK_Identity; 5212 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5213 } 5214 } 5215 5216 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5217 /// convert the expression From to an Objective-C pointer type. 5218 static ImplicitConversionSequence 5219 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5220 // Do an implicit conversion to 'id'. 5221 QualType Ty = S.Context.getObjCIdType(); 5222 ImplicitConversionSequence ICS 5223 = TryImplicitConversion(S, From, Ty, 5224 // FIXME: Are these flags correct? 5225 /*SuppressUserConversions=*/false, 5226 /*AllowExplicit=*/true, 5227 /*InOverloadResolution=*/false, 5228 /*CStyle=*/false, 5229 /*AllowObjCWritebackConversion=*/false, 5230 /*AllowObjCConversionOnExplicit=*/true); 5231 5232 // Strip off any final conversions to 'id'. 5233 switch (ICS.getKind()) { 5234 case ImplicitConversionSequence::BadConversion: 5235 case ImplicitConversionSequence::AmbiguousConversion: 5236 case ImplicitConversionSequence::EllipsisConversion: 5237 break; 5238 5239 case ImplicitConversionSequence::UserDefinedConversion: 5240 dropPointerConversion(ICS.UserDefined.After); 5241 break; 5242 5243 case ImplicitConversionSequence::StandardConversion: 5244 dropPointerConversion(ICS.Standard); 5245 break; 5246 } 5247 5248 return ICS; 5249 } 5250 5251 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5252 /// conversion of the expression From to an Objective-C pointer type. 5253 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5254 if (checkPlaceholderForOverload(*this, From)) 5255 return ExprError(); 5256 5257 QualType Ty = Context.getObjCIdType(); 5258 ImplicitConversionSequence ICS = 5259 TryContextuallyConvertToObjCPointer(*this, From); 5260 if (!ICS.isBad()) 5261 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5262 return ExprError(); 5263 } 5264 5265 /// Determine whether the provided type is an integral type, or an enumeration 5266 /// type of a permitted flavor. 5267 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5268 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5269 : T->isIntegralOrUnscopedEnumerationType(); 5270 } 5271 5272 static ExprResult 5273 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5274 Sema::ContextualImplicitConverter &Converter, 5275 QualType T, UnresolvedSetImpl &ViableConversions) { 5276 5277 if (Converter.Suppress) 5278 return ExprError(); 5279 5280 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5281 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5282 CXXConversionDecl *Conv = 5283 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5284 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5285 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5286 } 5287 return From; 5288 } 5289 5290 static bool 5291 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5292 Sema::ContextualImplicitConverter &Converter, 5293 QualType T, bool HadMultipleCandidates, 5294 UnresolvedSetImpl &ExplicitConversions) { 5295 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5296 DeclAccessPair Found = ExplicitConversions[0]; 5297 CXXConversionDecl *Conversion = 5298 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5299 5300 // The user probably meant to invoke the given explicit 5301 // conversion; use it. 5302 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5303 std::string TypeStr; 5304 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5305 5306 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5307 << FixItHint::CreateInsertion(From->getLocStart(), 5308 "static_cast<" + TypeStr + ">(") 5309 << FixItHint::CreateInsertion( 5310 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5311 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5312 5313 // If we aren't in a SFINAE context, build a call to the 5314 // explicit conversion function. 5315 if (SemaRef.isSFINAEContext()) 5316 return true; 5317 5318 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5319 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5320 HadMultipleCandidates); 5321 if (Result.isInvalid()) 5322 return true; 5323 // Record usage of conversion in an implicit cast. 5324 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5325 CK_UserDefinedConversion, Result.get(), 5326 nullptr, Result.get()->getValueKind()); 5327 } 5328 return false; 5329 } 5330 5331 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5332 Sema::ContextualImplicitConverter &Converter, 5333 QualType T, bool HadMultipleCandidates, 5334 DeclAccessPair &Found) { 5335 CXXConversionDecl *Conversion = 5336 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5337 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5338 5339 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5340 if (!Converter.SuppressConversion) { 5341 if (SemaRef.isSFINAEContext()) 5342 return true; 5343 5344 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5345 << From->getSourceRange(); 5346 } 5347 5348 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5349 HadMultipleCandidates); 5350 if (Result.isInvalid()) 5351 return true; 5352 // Record usage of conversion in an implicit cast. 5353 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5354 CK_UserDefinedConversion, Result.get(), 5355 nullptr, Result.get()->getValueKind()); 5356 return false; 5357 } 5358 5359 static ExprResult finishContextualImplicitConversion( 5360 Sema &SemaRef, SourceLocation Loc, Expr *From, 5361 Sema::ContextualImplicitConverter &Converter) { 5362 if (!Converter.match(From->getType()) && !Converter.Suppress) 5363 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5364 << From->getSourceRange(); 5365 5366 return SemaRef.DefaultLvalueConversion(From); 5367 } 5368 5369 static void 5370 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5371 UnresolvedSetImpl &ViableConversions, 5372 OverloadCandidateSet &CandidateSet) { 5373 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5374 DeclAccessPair FoundDecl = ViableConversions[I]; 5375 NamedDecl *D = FoundDecl.getDecl(); 5376 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5377 if (isa<UsingShadowDecl>(D)) 5378 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5379 5380 CXXConversionDecl *Conv; 5381 FunctionTemplateDecl *ConvTemplate; 5382 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5383 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5384 else 5385 Conv = cast<CXXConversionDecl>(D); 5386 5387 if (ConvTemplate) 5388 SemaRef.AddTemplateConversionCandidate( 5389 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5390 /*AllowObjCConversionOnExplicit=*/false); 5391 else 5392 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5393 ToType, CandidateSet, 5394 /*AllowObjCConversionOnExplicit=*/false); 5395 } 5396 } 5397 5398 /// \brief Attempt to convert the given expression to a type which is accepted 5399 /// by the given converter. 5400 /// 5401 /// This routine will attempt to convert an expression of class type to a 5402 /// type accepted by the specified converter. In C++11 and before, the class 5403 /// must have a single non-explicit conversion function converting to a matching 5404 /// type. In C++1y, there can be multiple such conversion functions, but only 5405 /// one target type. 5406 /// 5407 /// \param Loc The source location of the construct that requires the 5408 /// conversion. 5409 /// 5410 /// \param From The expression we're converting from. 5411 /// 5412 /// \param Converter Used to control and diagnose the conversion process. 5413 /// 5414 /// \returns The expression, converted to an integral or enumeration type if 5415 /// successful. 5416 ExprResult Sema::PerformContextualImplicitConversion( 5417 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5418 // We can't perform any more checking for type-dependent expressions. 5419 if (From->isTypeDependent()) 5420 return From; 5421 5422 // Process placeholders immediately. 5423 if (From->hasPlaceholderType()) { 5424 ExprResult result = CheckPlaceholderExpr(From); 5425 if (result.isInvalid()) 5426 return result; 5427 From = result.get(); 5428 } 5429 5430 // If the expression already has a matching type, we're golden. 5431 QualType T = From->getType(); 5432 if (Converter.match(T)) 5433 return DefaultLvalueConversion(From); 5434 5435 // FIXME: Check for missing '()' if T is a function type? 5436 5437 // We can only perform contextual implicit conversions on objects of class 5438 // type. 5439 const RecordType *RecordTy = T->getAs<RecordType>(); 5440 if (!RecordTy || !getLangOpts().CPlusPlus) { 5441 if (!Converter.Suppress) 5442 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5443 return From; 5444 } 5445 5446 // We must have a complete class type. 5447 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5448 ContextualImplicitConverter &Converter; 5449 Expr *From; 5450 5451 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5452 : Converter(Converter), From(From) {} 5453 5454 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5455 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5456 } 5457 } IncompleteDiagnoser(Converter, From); 5458 5459 if (Converter.Suppress ? !isCompleteType(Loc, T) 5460 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5461 return From; 5462 5463 // Look for a conversion to an integral or enumeration type. 5464 UnresolvedSet<4> 5465 ViableConversions; // These are *potentially* viable in C++1y. 5466 UnresolvedSet<4> ExplicitConversions; 5467 const auto &Conversions = 5468 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5469 5470 bool HadMultipleCandidates = 5471 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5472 5473 // To check that there is only one target type, in C++1y: 5474 QualType ToType; 5475 bool HasUniqueTargetType = true; 5476 5477 // Collect explicit or viable (potentially in C++1y) conversions. 5478 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5479 NamedDecl *D = (*I)->getUnderlyingDecl(); 5480 CXXConversionDecl *Conversion; 5481 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5482 if (ConvTemplate) { 5483 if (getLangOpts().CPlusPlus14) 5484 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5485 else 5486 continue; // C++11 does not consider conversion operator templates(?). 5487 } else 5488 Conversion = cast<CXXConversionDecl>(D); 5489 5490 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5491 "Conversion operator templates are considered potentially " 5492 "viable in C++1y"); 5493 5494 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5495 if (Converter.match(CurToType) || ConvTemplate) { 5496 5497 if (Conversion->isExplicit()) { 5498 // FIXME: For C++1y, do we need this restriction? 5499 // cf. diagnoseNoViableConversion() 5500 if (!ConvTemplate) 5501 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5502 } else { 5503 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5504 if (ToType.isNull()) 5505 ToType = CurToType.getUnqualifiedType(); 5506 else if (HasUniqueTargetType && 5507 (CurToType.getUnqualifiedType() != ToType)) 5508 HasUniqueTargetType = false; 5509 } 5510 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5511 } 5512 } 5513 } 5514 5515 if (getLangOpts().CPlusPlus14) { 5516 // C++1y [conv]p6: 5517 // ... An expression e of class type E appearing in such a context 5518 // is said to be contextually implicitly converted to a specified 5519 // type T and is well-formed if and only if e can be implicitly 5520 // converted to a type T that is determined as follows: E is searched 5521 // for conversion functions whose return type is cv T or reference to 5522 // cv T such that T is allowed by the context. There shall be 5523 // exactly one such T. 5524 5525 // If no unique T is found: 5526 if (ToType.isNull()) { 5527 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5528 HadMultipleCandidates, 5529 ExplicitConversions)) 5530 return ExprError(); 5531 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5532 } 5533 5534 // If more than one unique Ts are found: 5535 if (!HasUniqueTargetType) 5536 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5537 ViableConversions); 5538 5539 // If one unique T is found: 5540 // First, build a candidate set from the previously recorded 5541 // potentially viable conversions. 5542 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5543 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5544 CandidateSet); 5545 5546 // Then, perform overload resolution over the candidate set. 5547 OverloadCandidateSet::iterator Best; 5548 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5549 case OR_Success: { 5550 // Apply this conversion. 5551 DeclAccessPair Found = 5552 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5553 if (recordConversion(*this, Loc, From, Converter, T, 5554 HadMultipleCandidates, Found)) 5555 return ExprError(); 5556 break; 5557 } 5558 case OR_Ambiguous: 5559 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5560 ViableConversions); 5561 case OR_No_Viable_Function: 5562 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5563 HadMultipleCandidates, 5564 ExplicitConversions)) 5565 return ExprError(); 5566 // fall through 'OR_Deleted' case. 5567 case OR_Deleted: 5568 // We'll complain below about a non-integral condition type. 5569 break; 5570 } 5571 } else { 5572 switch (ViableConversions.size()) { 5573 case 0: { 5574 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5575 HadMultipleCandidates, 5576 ExplicitConversions)) 5577 return ExprError(); 5578 5579 // We'll complain below about a non-integral condition type. 5580 break; 5581 } 5582 case 1: { 5583 // Apply this conversion. 5584 DeclAccessPair Found = ViableConversions[0]; 5585 if (recordConversion(*this, Loc, From, Converter, T, 5586 HadMultipleCandidates, Found)) 5587 return ExprError(); 5588 break; 5589 } 5590 default: 5591 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5592 ViableConversions); 5593 } 5594 } 5595 5596 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5597 } 5598 5599 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5600 /// an acceptable non-member overloaded operator for a call whose 5601 /// arguments have types T1 (and, if non-empty, T2). This routine 5602 /// implements the check in C++ [over.match.oper]p3b2 concerning 5603 /// enumeration types. 5604 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5605 FunctionDecl *Fn, 5606 ArrayRef<Expr *> Args) { 5607 QualType T1 = Args[0]->getType(); 5608 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5609 5610 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5611 return true; 5612 5613 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5614 return true; 5615 5616 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5617 if (Proto->getNumParams() < 1) 5618 return false; 5619 5620 if (T1->isEnumeralType()) { 5621 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5622 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5623 return true; 5624 } 5625 5626 if (Proto->getNumParams() < 2) 5627 return false; 5628 5629 if (!T2.isNull() && T2->isEnumeralType()) { 5630 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5631 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5632 return true; 5633 } 5634 5635 return false; 5636 } 5637 5638 /// AddOverloadCandidate - Adds the given function to the set of 5639 /// candidate functions, using the given function call arguments. If 5640 /// @p SuppressUserConversions, then don't allow user-defined 5641 /// conversions via constructors or conversion operators. 5642 /// 5643 /// \param PartialOverloading true if we are performing "partial" overloading 5644 /// based on an incomplete set of function arguments. This feature is used by 5645 /// code completion. 5646 void 5647 Sema::AddOverloadCandidate(FunctionDecl *Function, 5648 DeclAccessPair FoundDecl, 5649 ArrayRef<Expr *> Args, 5650 OverloadCandidateSet &CandidateSet, 5651 bool SuppressUserConversions, 5652 bool PartialOverloading, 5653 bool AllowExplicit) { 5654 const FunctionProtoType *Proto 5655 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5656 assert(Proto && "Functions without a prototype cannot be overloaded"); 5657 assert(!Function->getDescribedFunctionTemplate() && 5658 "Use AddTemplateOverloadCandidate for function templates"); 5659 5660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5661 if (!isa<CXXConstructorDecl>(Method)) { 5662 // If we get here, it's because we're calling a member function 5663 // that is named without a member access expression (e.g., 5664 // "this->f") that was either written explicitly or created 5665 // implicitly. This can happen with a qualified call to a member 5666 // function, e.g., X::f(). We use an empty type for the implied 5667 // object argument (C++ [over.call.func]p3), and the acting context 5668 // is irrelevant. 5669 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5670 QualType(), Expr::Classification::makeSimpleLValue(), 5671 Args, CandidateSet, SuppressUserConversions, 5672 PartialOverloading); 5673 return; 5674 } 5675 // We treat a constructor like a non-member function, since its object 5676 // argument doesn't participate in overload resolution. 5677 } 5678 5679 if (!CandidateSet.isNewCandidate(Function)) 5680 return; 5681 5682 // C++ [over.match.oper]p3: 5683 // if no operand has a class type, only those non-member functions in the 5684 // lookup set that have a first parameter of type T1 or "reference to 5685 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5686 // is a right operand) a second parameter of type T2 or "reference to 5687 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5688 // candidate functions. 5689 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5690 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5691 return; 5692 5693 // C++11 [class.copy]p11: [DR1402] 5694 // A defaulted move constructor that is defined as deleted is ignored by 5695 // overload resolution. 5696 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5697 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5698 Constructor->isMoveConstructor()) 5699 return; 5700 5701 // Overload resolution is always an unevaluated context. 5702 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5703 5704 // Add this candidate 5705 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5706 Candidate.FoundDecl = FoundDecl; 5707 Candidate.Function = Function; 5708 Candidate.Viable = true; 5709 Candidate.IsSurrogate = false; 5710 Candidate.IgnoreObjectArgument = false; 5711 Candidate.ExplicitCallArguments = Args.size(); 5712 5713 if (Constructor) { 5714 // C++ [class.copy]p3: 5715 // A member function template is never instantiated to perform the copy 5716 // of a class object to an object of its class type. 5717 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5718 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5719 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5720 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5721 ClassType))) { 5722 Candidate.Viable = false; 5723 Candidate.FailureKind = ovl_fail_illegal_constructor; 5724 return; 5725 } 5726 } 5727 5728 unsigned NumParams = Proto->getNumParams(); 5729 5730 // (C++ 13.3.2p2): A candidate function having fewer than m 5731 // parameters is viable only if it has an ellipsis in its parameter 5732 // list (8.3.5). 5733 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5734 !Proto->isVariadic()) { 5735 Candidate.Viable = false; 5736 Candidate.FailureKind = ovl_fail_too_many_arguments; 5737 return; 5738 } 5739 5740 // (C++ 13.3.2p2): A candidate function having more than m parameters 5741 // is viable only if the (m+1)st parameter has a default argument 5742 // (8.3.6). For the purposes of overload resolution, the 5743 // parameter list is truncated on the right, so that there are 5744 // exactly m parameters. 5745 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5746 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5747 // Not enough arguments. 5748 Candidate.Viable = false; 5749 Candidate.FailureKind = ovl_fail_too_few_arguments; 5750 return; 5751 } 5752 5753 // (CUDA B.1): Check for invalid calls between targets. 5754 if (getLangOpts().CUDA) 5755 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5756 // Skip the check for callers that are implicit members, because in this 5757 // case we may not yet know what the member's target is; the target is 5758 // inferred for the member automatically, based on the bases and fields of 5759 // the class. 5760 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5761 Candidate.Viable = false; 5762 Candidate.FailureKind = ovl_fail_bad_target; 5763 return; 5764 } 5765 5766 // Determine the implicit conversion sequences for each of the 5767 // arguments. 5768 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5769 if (ArgIdx < NumParams) { 5770 // (C++ 13.3.2p3): for F to be a viable function, there shall 5771 // exist for each argument an implicit conversion sequence 5772 // (13.3.3.1) that converts that argument to the corresponding 5773 // parameter of F. 5774 QualType ParamType = Proto->getParamType(ArgIdx); 5775 Candidate.Conversions[ArgIdx] 5776 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5777 SuppressUserConversions, 5778 /*InOverloadResolution=*/true, 5779 /*AllowObjCWritebackConversion=*/ 5780 getLangOpts().ObjCAutoRefCount, 5781 AllowExplicit); 5782 if (Candidate.Conversions[ArgIdx].isBad()) { 5783 Candidate.Viable = false; 5784 Candidate.FailureKind = ovl_fail_bad_conversion; 5785 return; 5786 } 5787 } else { 5788 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5789 // argument for which there is no corresponding parameter is 5790 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5791 Candidate.Conversions[ArgIdx].setEllipsis(); 5792 } 5793 } 5794 5795 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5796 Candidate.Viable = false; 5797 Candidate.FailureKind = ovl_fail_enable_if; 5798 Candidate.DeductionFailure.Data = FailedAttr; 5799 return; 5800 } 5801 } 5802 5803 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5804 bool IsInstance) { 5805 SmallVector<ObjCMethodDecl*, 4> Methods; 5806 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5807 return nullptr; 5808 5809 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5810 bool Match = true; 5811 ObjCMethodDecl *Method = Methods[b]; 5812 unsigned NumNamedArgs = Sel.getNumArgs(); 5813 // Method might have more arguments than selector indicates. This is due 5814 // to addition of c-style arguments in method. 5815 if (Method->param_size() > NumNamedArgs) 5816 NumNamedArgs = Method->param_size(); 5817 if (Args.size() < NumNamedArgs) 5818 continue; 5819 5820 for (unsigned i = 0; i < NumNamedArgs; i++) { 5821 // We can't do any type-checking on a type-dependent argument. 5822 if (Args[i]->isTypeDependent()) { 5823 Match = false; 5824 break; 5825 } 5826 5827 ParmVarDecl *param = Method->parameters()[i]; 5828 Expr *argExpr = Args[i]; 5829 assert(argExpr && "SelectBestMethod(): missing expression"); 5830 5831 // Strip the unbridged-cast placeholder expression off unless it's 5832 // a consumed argument. 5833 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5834 !param->hasAttr<CFConsumedAttr>()) 5835 argExpr = stripARCUnbridgedCast(argExpr); 5836 5837 // If the parameter is __unknown_anytype, move on to the next method. 5838 if (param->getType() == Context.UnknownAnyTy) { 5839 Match = false; 5840 break; 5841 } 5842 5843 ImplicitConversionSequence ConversionState 5844 = TryCopyInitialization(*this, argExpr, param->getType(), 5845 /*SuppressUserConversions*/false, 5846 /*InOverloadResolution=*/true, 5847 /*AllowObjCWritebackConversion=*/ 5848 getLangOpts().ObjCAutoRefCount, 5849 /*AllowExplicit*/false); 5850 if (ConversionState.isBad()) { 5851 Match = false; 5852 break; 5853 } 5854 } 5855 // Promote additional arguments to variadic methods. 5856 if (Match && Method->isVariadic()) { 5857 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5858 if (Args[i]->isTypeDependent()) { 5859 Match = false; 5860 break; 5861 } 5862 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5863 nullptr); 5864 if (Arg.isInvalid()) { 5865 Match = false; 5866 break; 5867 } 5868 } 5869 } else { 5870 // Check for extra arguments to non-variadic methods. 5871 if (Args.size() != NumNamedArgs) 5872 Match = false; 5873 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5874 // Special case when selectors have no argument. In this case, select 5875 // one with the most general result type of 'id'. 5876 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5877 QualType ReturnT = Methods[b]->getReturnType(); 5878 if (ReturnT->isObjCIdType()) 5879 return Methods[b]; 5880 } 5881 } 5882 } 5883 5884 if (Match) 5885 return Method; 5886 } 5887 return nullptr; 5888 } 5889 5890 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5891 // enable_if is order-sensitive. As a result, we need to reverse things 5892 // sometimes. Size of 4 elements is arbitrary. 5893 static SmallVector<EnableIfAttr *, 4> 5894 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5895 SmallVector<EnableIfAttr *, 4> Result; 5896 if (!Function->hasAttrs()) 5897 return Result; 5898 5899 const auto &FuncAttrs = Function->getAttrs(); 5900 for (Attr *Attr : FuncAttrs) 5901 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5902 Result.push_back(EnableIf); 5903 5904 std::reverse(Result.begin(), Result.end()); 5905 return Result; 5906 } 5907 5908 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5909 bool MissingImplicitThis) { 5910 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5911 if (EnableIfAttrs.empty()) 5912 return nullptr; 5913 5914 SFINAETrap Trap(*this); 5915 SmallVector<Expr *, 16> ConvertedArgs; 5916 bool InitializationFailed = false; 5917 bool ContainsValueDependentExpr = false; 5918 5919 // Convert the arguments. 5920 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5921 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5922 !cast<CXXMethodDecl>(Function)->isStatic() && 5923 !isa<CXXConstructorDecl>(Function)) { 5924 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5925 ExprResult R = 5926 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5927 Method, Method); 5928 if (R.isInvalid()) { 5929 InitializationFailed = true; 5930 break; 5931 } 5932 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5933 ConvertedArgs.push_back(R.get()); 5934 } else { 5935 ExprResult R = 5936 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5937 Context, 5938 Function->getParamDecl(i)), 5939 SourceLocation(), 5940 Args[i]); 5941 if (R.isInvalid()) { 5942 InitializationFailed = true; 5943 break; 5944 } 5945 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5946 ConvertedArgs.push_back(R.get()); 5947 } 5948 } 5949 5950 if (InitializationFailed || Trap.hasErrorOccurred()) 5951 return EnableIfAttrs[0]; 5952 5953 // Push default arguments if needed. 5954 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5955 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5956 ParmVarDecl *P = Function->getParamDecl(i); 5957 ExprResult R = PerformCopyInitialization( 5958 InitializedEntity::InitializeParameter(Context, 5959 Function->getParamDecl(i)), 5960 SourceLocation(), 5961 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5962 : P->getDefaultArg()); 5963 if (R.isInvalid()) { 5964 InitializationFailed = true; 5965 break; 5966 } 5967 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5968 ConvertedArgs.push_back(R.get()); 5969 } 5970 5971 if (InitializationFailed || Trap.hasErrorOccurred()) 5972 return EnableIfAttrs[0]; 5973 } 5974 5975 for (auto *EIA : EnableIfAttrs) { 5976 APValue Result; 5977 if (EIA->getCond()->isValueDependent()) { 5978 // Don't even try now, we'll examine it after instantiation. 5979 continue; 5980 } 5981 5982 if (!EIA->getCond()->EvaluateWithSubstitution( 5983 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5984 if (!ContainsValueDependentExpr) 5985 return EIA; 5986 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5987 return EIA; 5988 } 5989 } 5990 return nullptr; 5991 } 5992 5993 /// \brief Add all of the function declarations in the given function set to 5994 /// the overload candidate set. 5995 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5996 ArrayRef<Expr *> Args, 5997 OverloadCandidateSet& CandidateSet, 5998 TemplateArgumentListInfo *ExplicitTemplateArgs, 5999 bool SuppressUserConversions, 6000 bool PartialOverloading) { 6001 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6002 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6003 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6004 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6005 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6006 cast<CXXMethodDecl>(FD)->getParent(), 6007 Args[0]->getType(), Args[0]->Classify(Context), 6008 Args.slice(1), CandidateSet, 6009 SuppressUserConversions, PartialOverloading); 6010 else 6011 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6012 SuppressUserConversions, PartialOverloading); 6013 } else { 6014 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6015 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6016 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6017 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6018 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6019 ExplicitTemplateArgs, 6020 Args[0]->getType(), 6021 Args[0]->Classify(Context), Args.slice(1), 6022 CandidateSet, SuppressUserConversions, 6023 PartialOverloading); 6024 else 6025 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6026 ExplicitTemplateArgs, Args, 6027 CandidateSet, SuppressUserConversions, 6028 PartialOverloading); 6029 } 6030 } 6031 } 6032 6033 /// AddMethodCandidate - Adds a named decl (which is some kind of 6034 /// method) as a method candidate to the given overload set. 6035 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6036 QualType ObjectType, 6037 Expr::Classification ObjectClassification, 6038 ArrayRef<Expr *> Args, 6039 OverloadCandidateSet& CandidateSet, 6040 bool SuppressUserConversions) { 6041 NamedDecl *Decl = FoundDecl.getDecl(); 6042 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6043 6044 if (isa<UsingShadowDecl>(Decl)) 6045 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6046 6047 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6048 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6049 "Expected a member function template"); 6050 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6051 /*ExplicitArgs*/ nullptr, 6052 ObjectType, ObjectClassification, 6053 Args, CandidateSet, 6054 SuppressUserConversions); 6055 } else { 6056 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6057 ObjectType, ObjectClassification, 6058 Args, 6059 CandidateSet, SuppressUserConversions); 6060 } 6061 } 6062 6063 /// AddMethodCandidate - Adds the given C++ member function to the set 6064 /// of candidate functions, using the given function call arguments 6065 /// and the object argument (@c Object). For example, in a call 6066 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6067 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6068 /// allow user-defined conversions via constructors or conversion 6069 /// operators. 6070 void 6071 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6072 CXXRecordDecl *ActingContext, QualType ObjectType, 6073 Expr::Classification ObjectClassification, 6074 ArrayRef<Expr *> Args, 6075 OverloadCandidateSet &CandidateSet, 6076 bool SuppressUserConversions, 6077 bool PartialOverloading) { 6078 const FunctionProtoType *Proto 6079 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6080 assert(Proto && "Methods without a prototype cannot be overloaded"); 6081 assert(!isa<CXXConstructorDecl>(Method) && 6082 "Use AddOverloadCandidate for constructors"); 6083 6084 if (!CandidateSet.isNewCandidate(Method)) 6085 return; 6086 6087 // C++11 [class.copy]p23: [DR1402] 6088 // A defaulted move assignment operator that is defined as deleted is 6089 // ignored by overload resolution. 6090 if (Method->isDefaulted() && Method->isDeleted() && 6091 Method->isMoveAssignmentOperator()) 6092 return; 6093 6094 // Overload resolution is always an unevaluated context. 6095 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6096 6097 // Add this candidate 6098 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6099 Candidate.FoundDecl = FoundDecl; 6100 Candidate.Function = Method; 6101 Candidate.IsSurrogate = false; 6102 Candidate.IgnoreObjectArgument = false; 6103 Candidate.ExplicitCallArguments = Args.size(); 6104 6105 unsigned NumParams = Proto->getNumParams(); 6106 6107 // (C++ 13.3.2p2): A candidate function having fewer than m 6108 // parameters is viable only if it has an ellipsis in its parameter 6109 // list (8.3.5). 6110 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6111 !Proto->isVariadic()) { 6112 Candidate.Viable = false; 6113 Candidate.FailureKind = ovl_fail_too_many_arguments; 6114 return; 6115 } 6116 6117 // (C++ 13.3.2p2): A candidate function having more than m parameters 6118 // is viable only if the (m+1)st parameter has a default argument 6119 // (8.3.6). For the purposes of overload resolution, the 6120 // parameter list is truncated on the right, so that there are 6121 // exactly m parameters. 6122 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6123 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6124 // Not enough arguments. 6125 Candidate.Viable = false; 6126 Candidate.FailureKind = ovl_fail_too_few_arguments; 6127 return; 6128 } 6129 6130 Candidate.Viable = true; 6131 6132 if (Method->isStatic() || ObjectType.isNull()) 6133 // The implicit object argument is ignored. 6134 Candidate.IgnoreObjectArgument = true; 6135 else { 6136 // Determine the implicit conversion sequence for the object 6137 // parameter. 6138 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6139 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6140 Method, ActingContext); 6141 if (Candidate.Conversions[0].isBad()) { 6142 Candidate.Viable = false; 6143 Candidate.FailureKind = ovl_fail_bad_conversion; 6144 return; 6145 } 6146 } 6147 6148 // (CUDA B.1): Check for invalid calls between targets. 6149 if (getLangOpts().CUDA) 6150 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6151 if (CheckCUDATarget(Caller, Method)) { 6152 Candidate.Viable = false; 6153 Candidate.FailureKind = ovl_fail_bad_target; 6154 return; 6155 } 6156 6157 // Determine the implicit conversion sequences for each of the 6158 // arguments. 6159 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6160 if (ArgIdx < NumParams) { 6161 // (C++ 13.3.2p3): for F to be a viable function, there shall 6162 // exist for each argument an implicit conversion sequence 6163 // (13.3.3.1) that converts that argument to the corresponding 6164 // parameter of F. 6165 QualType ParamType = Proto->getParamType(ArgIdx); 6166 Candidate.Conversions[ArgIdx + 1] 6167 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6168 SuppressUserConversions, 6169 /*InOverloadResolution=*/true, 6170 /*AllowObjCWritebackConversion=*/ 6171 getLangOpts().ObjCAutoRefCount); 6172 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6173 Candidate.Viable = false; 6174 Candidate.FailureKind = ovl_fail_bad_conversion; 6175 return; 6176 } 6177 } else { 6178 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6179 // argument for which there is no corresponding parameter is 6180 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6181 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6182 } 6183 } 6184 6185 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6186 Candidate.Viable = false; 6187 Candidate.FailureKind = ovl_fail_enable_if; 6188 Candidate.DeductionFailure.Data = FailedAttr; 6189 return; 6190 } 6191 } 6192 6193 /// \brief Add a C++ member function template as a candidate to the candidate 6194 /// set, using template argument deduction to produce an appropriate member 6195 /// function template specialization. 6196 void 6197 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6198 DeclAccessPair FoundDecl, 6199 CXXRecordDecl *ActingContext, 6200 TemplateArgumentListInfo *ExplicitTemplateArgs, 6201 QualType ObjectType, 6202 Expr::Classification ObjectClassification, 6203 ArrayRef<Expr *> Args, 6204 OverloadCandidateSet& CandidateSet, 6205 bool SuppressUserConversions, 6206 bool PartialOverloading) { 6207 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6208 return; 6209 6210 // C++ [over.match.funcs]p7: 6211 // In each case where a candidate is a function template, candidate 6212 // function template specializations are generated using template argument 6213 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6214 // candidate functions in the usual way.113) A given name can refer to one 6215 // or more function templates and also to a set of overloaded non-template 6216 // functions. In such a case, the candidate functions generated from each 6217 // function template are combined with the set of non-template candidate 6218 // functions. 6219 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6220 FunctionDecl *Specialization = nullptr; 6221 if (TemplateDeductionResult Result 6222 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6223 Specialization, Info, PartialOverloading)) { 6224 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6225 Candidate.FoundDecl = FoundDecl; 6226 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6227 Candidate.Viable = false; 6228 Candidate.FailureKind = ovl_fail_bad_deduction; 6229 Candidate.IsSurrogate = false; 6230 Candidate.IgnoreObjectArgument = false; 6231 Candidate.ExplicitCallArguments = Args.size(); 6232 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6233 Info); 6234 return; 6235 } 6236 6237 // Add the function template specialization produced by template argument 6238 // deduction as a candidate. 6239 assert(Specialization && "Missing member function template specialization?"); 6240 assert(isa<CXXMethodDecl>(Specialization) && 6241 "Specialization is not a member function?"); 6242 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6243 ActingContext, ObjectType, ObjectClassification, Args, 6244 CandidateSet, SuppressUserConversions, PartialOverloading); 6245 } 6246 6247 /// \brief Add a C++ function template specialization as a candidate 6248 /// in the candidate set, using template argument deduction to produce 6249 /// an appropriate function template specialization. 6250 void 6251 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6252 DeclAccessPair FoundDecl, 6253 TemplateArgumentListInfo *ExplicitTemplateArgs, 6254 ArrayRef<Expr *> Args, 6255 OverloadCandidateSet& CandidateSet, 6256 bool SuppressUserConversions, 6257 bool PartialOverloading) { 6258 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6259 return; 6260 6261 // C++ [over.match.funcs]p7: 6262 // In each case where a candidate is a function template, candidate 6263 // function template specializations are generated using template argument 6264 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6265 // candidate functions in the usual way.113) A given name can refer to one 6266 // or more function templates and also to a set of overloaded non-template 6267 // functions. In such a case, the candidate functions generated from each 6268 // function template are combined with the set of non-template candidate 6269 // functions. 6270 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6271 FunctionDecl *Specialization = nullptr; 6272 if (TemplateDeductionResult Result 6273 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6274 Specialization, Info, PartialOverloading)) { 6275 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6276 Candidate.FoundDecl = FoundDecl; 6277 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6278 Candidate.Viable = false; 6279 Candidate.FailureKind = ovl_fail_bad_deduction; 6280 Candidate.IsSurrogate = false; 6281 Candidate.IgnoreObjectArgument = false; 6282 Candidate.ExplicitCallArguments = Args.size(); 6283 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6284 Info); 6285 return; 6286 } 6287 6288 // Add the function template specialization produced by template argument 6289 // deduction as a candidate. 6290 assert(Specialization && "Missing function template specialization?"); 6291 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6292 SuppressUserConversions, PartialOverloading); 6293 } 6294 6295 /// Determine whether this is an allowable conversion from the result 6296 /// of an explicit conversion operator to the expected type, per C++ 6297 /// [over.match.conv]p1 and [over.match.ref]p1. 6298 /// 6299 /// \param ConvType The return type of the conversion function. 6300 /// 6301 /// \param ToType The type we are converting to. 6302 /// 6303 /// \param AllowObjCPointerConversion Allow a conversion from one 6304 /// Objective-C pointer to another. 6305 /// 6306 /// \returns true if the conversion is allowable, false otherwise. 6307 static bool isAllowableExplicitConversion(Sema &S, 6308 QualType ConvType, QualType ToType, 6309 bool AllowObjCPointerConversion) { 6310 QualType ToNonRefType = ToType.getNonReferenceType(); 6311 6312 // Easy case: the types are the same. 6313 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6314 return true; 6315 6316 // Allow qualification conversions. 6317 bool ObjCLifetimeConversion; 6318 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6319 ObjCLifetimeConversion)) 6320 return true; 6321 6322 // If we're not allowed to consider Objective-C pointer conversions, 6323 // we're done. 6324 if (!AllowObjCPointerConversion) 6325 return false; 6326 6327 // Is this an Objective-C pointer conversion? 6328 bool IncompatibleObjC = false; 6329 QualType ConvertedType; 6330 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6331 IncompatibleObjC); 6332 } 6333 6334 /// AddConversionCandidate - Add a C++ conversion function as a 6335 /// candidate in the candidate set (C++ [over.match.conv], 6336 /// C++ [over.match.copy]). From is the expression we're converting from, 6337 /// and ToType is the type that we're eventually trying to convert to 6338 /// (which may or may not be the same type as the type that the 6339 /// conversion function produces). 6340 void 6341 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6342 DeclAccessPair FoundDecl, 6343 CXXRecordDecl *ActingContext, 6344 Expr *From, QualType ToType, 6345 OverloadCandidateSet& CandidateSet, 6346 bool AllowObjCConversionOnExplicit) { 6347 assert(!Conversion->getDescribedFunctionTemplate() && 6348 "Conversion function templates use AddTemplateConversionCandidate"); 6349 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6350 if (!CandidateSet.isNewCandidate(Conversion)) 6351 return; 6352 6353 // If the conversion function has an undeduced return type, trigger its 6354 // deduction now. 6355 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6356 if (DeduceReturnType(Conversion, From->getExprLoc())) 6357 return; 6358 ConvType = Conversion->getConversionType().getNonReferenceType(); 6359 } 6360 6361 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6362 // operator is only a candidate if its return type is the target type or 6363 // can be converted to the target type with a qualification conversion. 6364 if (Conversion->isExplicit() && 6365 !isAllowableExplicitConversion(*this, ConvType, ToType, 6366 AllowObjCConversionOnExplicit)) 6367 return; 6368 6369 // Overload resolution is always an unevaluated context. 6370 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6371 6372 // Add this candidate 6373 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6374 Candidate.FoundDecl = FoundDecl; 6375 Candidate.Function = Conversion; 6376 Candidate.IsSurrogate = false; 6377 Candidate.IgnoreObjectArgument = false; 6378 Candidate.FinalConversion.setAsIdentityConversion(); 6379 Candidate.FinalConversion.setFromType(ConvType); 6380 Candidate.FinalConversion.setAllToTypes(ToType); 6381 Candidate.Viable = true; 6382 Candidate.ExplicitCallArguments = 1; 6383 6384 // C++ [over.match.funcs]p4: 6385 // For conversion functions, the function is considered to be a member of 6386 // the class of the implicit implied object argument for the purpose of 6387 // defining the type of the implicit object parameter. 6388 // 6389 // Determine the implicit conversion sequence for the implicit 6390 // object parameter. 6391 QualType ImplicitParamType = From->getType(); 6392 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6393 ImplicitParamType = FromPtrType->getPointeeType(); 6394 CXXRecordDecl *ConversionContext 6395 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6396 6397 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6398 *this, CandidateSet.getLocation(), From->getType(), 6399 From->Classify(Context), Conversion, ConversionContext); 6400 6401 if (Candidate.Conversions[0].isBad()) { 6402 Candidate.Viable = false; 6403 Candidate.FailureKind = ovl_fail_bad_conversion; 6404 return; 6405 } 6406 6407 // We won't go through a user-defined type conversion function to convert a 6408 // derived to base as such conversions are given Conversion Rank. They only 6409 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6410 QualType FromCanon 6411 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6412 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6413 if (FromCanon == ToCanon || 6414 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6415 Candidate.Viable = false; 6416 Candidate.FailureKind = ovl_fail_trivial_conversion; 6417 return; 6418 } 6419 6420 // To determine what the conversion from the result of calling the 6421 // conversion function to the type we're eventually trying to 6422 // convert to (ToType), we need to synthesize a call to the 6423 // conversion function and attempt copy initialization from it. This 6424 // makes sure that we get the right semantics with respect to 6425 // lvalues/rvalues and the type. Fortunately, we can allocate this 6426 // call on the stack and we don't need its arguments to be 6427 // well-formed. 6428 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6429 VK_LValue, From->getLocStart()); 6430 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6431 Context.getPointerType(Conversion->getType()), 6432 CK_FunctionToPointerDecay, 6433 &ConversionRef, VK_RValue); 6434 6435 QualType ConversionType = Conversion->getConversionType(); 6436 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6437 Candidate.Viable = false; 6438 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6439 return; 6440 } 6441 6442 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6443 6444 // Note that it is safe to allocate CallExpr on the stack here because 6445 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6446 // allocator). 6447 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6448 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6449 From->getLocStart()); 6450 ImplicitConversionSequence ICS = 6451 TryCopyInitialization(*this, &Call, ToType, 6452 /*SuppressUserConversions=*/true, 6453 /*InOverloadResolution=*/false, 6454 /*AllowObjCWritebackConversion=*/false); 6455 6456 switch (ICS.getKind()) { 6457 case ImplicitConversionSequence::StandardConversion: 6458 Candidate.FinalConversion = ICS.Standard; 6459 6460 // C++ [over.ics.user]p3: 6461 // If the user-defined conversion is specified by a specialization of a 6462 // conversion function template, the second standard conversion sequence 6463 // shall have exact match rank. 6464 if (Conversion->getPrimaryTemplate() && 6465 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6466 Candidate.Viable = false; 6467 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6468 return; 6469 } 6470 6471 // C++0x [dcl.init.ref]p5: 6472 // In the second case, if the reference is an rvalue reference and 6473 // the second standard conversion sequence of the user-defined 6474 // conversion sequence includes an lvalue-to-rvalue conversion, the 6475 // program is ill-formed. 6476 if (ToType->isRValueReferenceType() && 6477 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6478 Candidate.Viable = false; 6479 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6480 return; 6481 } 6482 break; 6483 6484 case ImplicitConversionSequence::BadConversion: 6485 Candidate.Viable = false; 6486 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6487 return; 6488 6489 default: 6490 llvm_unreachable( 6491 "Can only end up with a standard conversion sequence or failure"); 6492 } 6493 6494 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6495 Candidate.Viable = false; 6496 Candidate.FailureKind = ovl_fail_enable_if; 6497 Candidate.DeductionFailure.Data = FailedAttr; 6498 return; 6499 } 6500 } 6501 6502 /// \brief Adds a conversion function template specialization 6503 /// candidate to the overload set, using template argument deduction 6504 /// to deduce the template arguments of the conversion function 6505 /// template from the type that we are converting to (C++ 6506 /// [temp.deduct.conv]). 6507 void 6508 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6509 DeclAccessPair FoundDecl, 6510 CXXRecordDecl *ActingDC, 6511 Expr *From, QualType ToType, 6512 OverloadCandidateSet &CandidateSet, 6513 bool AllowObjCConversionOnExplicit) { 6514 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6515 "Only conversion function templates permitted here"); 6516 6517 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6518 return; 6519 6520 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6521 CXXConversionDecl *Specialization = nullptr; 6522 if (TemplateDeductionResult Result 6523 = DeduceTemplateArguments(FunctionTemplate, ToType, 6524 Specialization, Info)) { 6525 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6526 Candidate.FoundDecl = FoundDecl; 6527 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6528 Candidate.Viable = false; 6529 Candidate.FailureKind = ovl_fail_bad_deduction; 6530 Candidate.IsSurrogate = false; 6531 Candidate.IgnoreObjectArgument = false; 6532 Candidate.ExplicitCallArguments = 1; 6533 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6534 Info); 6535 return; 6536 } 6537 6538 // Add the conversion function template specialization produced by 6539 // template argument deduction as a candidate. 6540 assert(Specialization && "Missing function template specialization?"); 6541 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6542 CandidateSet, AllowObjCConversionOnExplicit); 6543 } 6544 6545 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6546 /// converts the given @c Object to a function pointer via the 6547 /// conversion function @c Conversion, and then attempts to call it 6548 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6549 /// the type of function that we'll eventually be calling. 6550 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6551 DeclAccessPair FoundDecl, 6552 CXXRecordDecl *ActingContext, 6553 const FunctionProtoType *Proto, 6554 Expr *Object, 6555 ArrayRef<Expr *> Args, 6556 OverloadCandidateSet& CandidateSet) { 6557 if (!CandidateSet.isNewCandidate(Conversion)) 6558 return; 6559 6560 // Overload resolution is always an unevaluated context. 6561 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6562 6563 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6564 Candidate.FoundDecl = FoundDecl; 6565 Candidate.Function = nullptr; 6566 Candidate.Surrogate = Conversion; 6567 Candidate.Viable = true; 6568 Candidate.IsSurrogate = true; 6569 Candidate.IgnoreObjectArgument = false; 6570 Candidate.ExplicitCallArguments = Args.size(); 6571 6572 // Determine the implicit conversion sequence for the implicit 6573 // object parameter. 6574 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6575 *this, CandidateSet.getLocation(), Object->getType(), 6576 Object->Classify(Context), Conversion, ActingContext); 6577 if (ObjectInit.isBad()) { 6578 Candidate.Viable = false; 6579 Candidate.FailureKind = ovl_fail_bad_conversion; 6580 Candidate.Conversions[0] = ObjectInit; 6581 return; 6582 } 6583 6584 // The first conversion is actually a user-defined conversion whose 6585 // first conversion is ObjectInit's standard conversion (which is 6586 // effectively a reference binding). Record it as such. 6587 Candidate.Conversions[0].setUserDefined(); 6588 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6589 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6590 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6591 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6592 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6593 Candidate.Conversions[0].UserDefined.After 6594 = Candidate.Conversions[0].UserDefined.Before; 6595 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6596 6597 // Find the 6598 unsigned NumParams = Proto->getNumParams(); 6599 6600 // (C++ 13.3.2p2): A candidate function having fewer than m 6601 // parameters is viable only if it has an ellipsis in its parameter 6602 // list (8.3.5). 6603 if (Args.size() > NumParams && !Proto->isVariadic()) { 6604 Candidate.Viable = false; 6605 Candidate.FailureKind = ovl_fail_too_many_arguments; 6606 return; 6607 } 6608 6609 // Function types don't have any default arguments, so just check if 6610 // we have enough arguments. 6611 if (Args.size() < NumParams) { 6612 // Not enough arguments. 6613 Candidate.Viable = false; 6614 Candidate.FailureKind = ovl_fail_too_few_arguments; 6615 return; 6616 } 6617 6618 // Determine the implicit conversion sequences for each of the 6619 // arguments. 6620 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6621 if (ArgIdx < NumParams) { 6622 // (C++ 13.3.2p3): for F to be a viable function, there shall 6623 // exist for each argument an implicit conversion sequence 6624 // (13.3.3.1) that converts that argument to the corresponding 6625 // parameter of F. 6626 QualType ParamType = Proto->getParamType(ArgIdx); 6627 Candidate.Conversions[ArgIdx + 1] 6628 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6629 /*SuppressUserConversions=*/false, 6630 /*InOverloadResolution=*/false, 6631 /*AllowObjCWritebackConversion=*/ 6632 getLangOpts().ObjCAutoRefCount); 6633 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6634 Candidate.Viable = false; 6635 Candidate.FailureKind = ovl_fail_bad_conversion; 6636 return; 6637 } 6638 } else { 6639 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6640 // argument for which there is no corresponding parameter is 6641 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6642 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6643 } 6644 } 6645 6646 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6647 Candidate.Viable = false; 6648 Candidate.FailureKind = ovl_fail_enable_if; 6649 Candidate.DeductionFailure.Data = FailedAttr; 6650 return; 6651 } 6652 } 6653 6654 /// \brief Add overload candidates for overloaded operators that are 6655 /// member functions. 6656 /// 6657 /// Add the overloaded operator candidates that are member functions 6658 /// for the operator Op that was used in an operator expression such 6659 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6660 /// CandidateSet will store the added overload candidates. (C++ 6661 /// [over.match.oper]). 6662 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6663 SourceLocation OpLoc, 6664 ArrayRef<Expr *> Args, 6665 OverloadCandidateSet& CandidateSet, 6666 SourceRange OpRange) { 6667 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6668 6669 // C++ [over.match.oper]p3: 6670 // For a unary operator @ with an operand of a type whose 6671 // cv-unqualified version is T1, and for a binary operator @ with 6672 // a left operand of a type whose cv-unqualified version is T1 and 6673 // a right operand of a type whose cv-unqualified version is T2, 6674 // three sets of candidate functions, designated member 6675 // candidates, non-member candidates and built-in candidates, are 6676 // constructed as follows: 6677 QualType T1 = Args[0]->getType(); 6678 6679 // -- If T1 is a complete class type or a class currently being 6680 // defined, the set of member candidates is the result of the 6681 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6682 // the set of member candidates is empty. 6683 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6684 // Complete the type if it can be completed. 6685 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6686 return; 6687 // If the type is neither complete nor being defined, bail out now. 6688 if (!T1Rec->getDecl()->getDefinition()) 6689 return; 6690 6691 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6692 LookupQualifiedName(Operators, T1Rec->getDecl()); 6693 Operators.suppressDiagnostics(); 6694 6695 for (LookupResult::iterator Oper = Operators.begin(), 6696 OperEnd = Operators.end(); 6697 Oper != OperEnd; 6698 ++Oper) 6699 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6700 Args[0]->Classify(Context), 6701 Args.slice(1), 6702 CandidateSet, 6703 /* SuppressUserConversions = */ false); 6704 } 6705 } 6706 6707 /// AddBuiltinCandidate - Add a candidate for a built-in 6708 /// operator. ResultTy and ParamTys are the result and parameter types 6709 /// of the built-in candidate, respectively. Args and NumArgs are the 6710 /// arguments being passed to the candidate. IsAssignmentOperator 6711 /// should be true when this built-in candidate is an assignment 6712 /// operator. NumContextualBoolArguments is the number of arguments 6713 /// (at the beginning of the argument list) that will be contextually 6714 /// converted to bool. 6715 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6716 ArrayRef<Expr *> Args, 6717 OverloadCandidateSet& CandidateSet, 6718 bool IsAssignmentOperator, 6719 unsigned NumContextualBoolArguments) { 6720 // Overload resolution is always an unevaluated context. 6721 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6722 6723 // Add this candidate 6724 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6725 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6726 Candidate.Function = nullptr; 6727 Candidate.IsSurrogate = false; 6728 Candidate.IgnoreObjectArgument = false; 6729 Candidate.BuiltinTypes.ResultTy = ResultTy; 6730 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6731 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6732 6733 // Determine the implicit conversion sequences for each of the 6734 // arguments. 6735 Candidate.Viable = true; 6736 Candidate.ExplicitCallArguments = Args.size(); 6737 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6738 // C++ [over.match.oper]p4: 6739 // For the built-in assignment operators, conversions of the 6740 // left operand are restricted as follows: 6741 // -- no temporaries are introduced to hold the left operand, and 6742 // -- no user-defined conversions are applied to the left 6743 // operand to achieve a type match with the left-most 6744 // parameter of a built-in candidate. 6745 // 6746 // We block these conversions by turning off user-defined 6747 // conversions, since that is the only way that initialization of 6748 // a reference to a non-class type can occur from something that 6749 // is not of the same type. 6750 if (ArgIdx < NumContextualBoolArguments) { 6751 assert(ParamTys[ArgIdx] == Context.BoolTy && 6752 "Contextual conversion to bool requires bool type"); 6753 Candidate.Conversions[ArgIdx] 6754 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6755 } else { 6756 Candidate.Conversions[ArgIdx] 6757 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6758 ArgIdx == 0 && IsAssignmentOperator, 6759 /*InOverloadResolution=*/false, 6760 /*AllowObjCWritebackConversion=*/ 6761 getLangOpts().ObjCAutoRefCount); 6762 } 6763 if (Candidate.Conversions[ArgIdx].isBad()) { 6764 Candidate.Viable = false; 6765 Candidate.FailureKind = ovl_fail_bad_conversion; 6766 break; 6767 } 6768 } 6769 } 6770 6771 namespace { 6772 6773 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6774 /// candidate operator functions for built-in operators (C++ 6775 /// [over.built]). The types are separated into pointer types and 6776 /// enumeration types. 6777 class BuiltinCandidateTypeSet { 6778 /// TypeSet - A set of types. 6779 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6780 6781 /// PointerTypes - The set of pointer types that will be used in the 6782 /// built-in candidates. 6783 TypeSet PointerTypes; 6784 6785 /// MemberPointerTypes - The set of member pointer types that will be 6786 /// used in the built-in candidates. 6787 TypeSet MemberPointerTypes; 6788 6789 /// EnumerationTypes - The set of enumeration types that will be 6790 /// used in the built-in candidates. 6791 TypeSet EnumerationTypes; 6792 6793 /// \brief The set of vector types that will be used in the built-in 6794 /// candidates. 6795 TypeSet VectorTypes; 6796 6797 /// \brief A flag indicating non-record types are viable candidates 6798 bool HasNonRecordTypes; 6799 6800 /// \brief A flag indicating whether either arithmetic or enumeration types 6801 /// were present in the candidate set. 6802 bool HasArithmeticOrEnumeralTypes; 6803 6804 /// \brief A flag indicating whether the nullptr type was present in the 6805 /// candidate set. 6806 bool HasNullPtrType; 6807 6808 /// Sema - The semantic analysis instance where we are building the 6809 /// candidate type set. 6810 Sema &SemaRef; 6811 6812 /// Context - The AST context in which we will build the type sets. 6813 ASTContext &Context; 6814 6815 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6816 const Qualifiers &VisibleQuals); 6817 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6818 6819 public: 6820 /// iterator - Iterates through the types that are part of the set. 6821 typedef TypeSet::iterator iterator; 6822 6823 BuiltinCandidateTypeSet(Sema &SemaRef) 6824 : HasNonRecordTypes(false), 6825 HasArithmeticOrEnumeralTypes(false), 6826 HasNullPtrType(false), 6827 SemaRef(SemaRef), 6828 Context(SemaRef.Context) { } 6829 6830 void AddTypesConvertedFrom(QualType Ty, 6831 SourceLocation Loc, 6832 bool AllowUserConversions, 6833 bool AllowExplicitConversions, 6834 const Qualifiers &VisibleTypeConversionsQuals); 6835 6836 /// pointer_begin - First pointer type found; 6837 iterator pointer_begin() { return PointerTypes.begin(); } 6838 6839 /// pointer_end - Past the last pointer type found; 6840 iterator pointer_end() { return PointerTypes.end(); } 6841 6842 /// member_pointer_begin - First member pointer type found; 6843 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6844 6845 /// member_pointer_end - Past the last member pointer type found; 6846 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6847 6848 /// enumeration_begin - First enumeration type found; 6849 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6850 6851 /// enumeration_end - Past the last enumeration type found; 6852 iterator enumeration_end() { return EnumerationTypes.end(); } 6853 6854 iterator vector_begin() { return VectorTypes.begin(); } 6855 iterator vector_end() { return VectorTypes.end(); } 6856 6857 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6858 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6859 bool hasNullPtrType() const { return HasNullPtrType; } 6860 }; 6861 6862 } // end anonymous namespace 6863 6864 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6865 /// the set of pointer types along with any more-qualified variants of 6866 /// that type. For example, if @p Ty is "int const *", this routine 6867 /// will add "int const *", "int const volatile *", "int const 6868 /// restrict *", and "int const volatile restrict *" to the set of 6869 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6870 /// false otherwise. 6871 /// 6872 /// FIXME: what to do about extended qualifiers? 6873 bool 6874 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6875 const Qualifiers &VisibleQuals) { 6876 6877 // Insert this type. 6878 if (!PointerTypes.insert(Ty).second) 6879 return false; 6880 6881 QualType PointeeTy; 6882 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6883 bool buildObjCPtr = false; 6884 if (!PointerTy) { 6885 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6886 PointeeTy = PTy->getPointeeType(); 6887 buildObjCPtr = true; 6888 } else { 6889 PointeeTy = PointerTy->getPointeeType(); 6890 } 6891 6892 // Don't add qualified variants of arrays. For one, they're not allowed 6893 // (the qualifier would sink to the element type), and for another, the 6894 // only overload situation where it matters is subscript or pointer +- int, 6895 // and those shouldn't have qualifier variants anyway. 6896 if (PointeeTy->isArrayType()) 6897 return true; 6898 6899 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6900 bool hasVolatile = VisibleQuals.hasVolatile(); 6901 bool hasRestrict = VisibleQuals.hasRestrict(); 6902 6903 // Iterate through all strict supersets of BaseCVR. 6904 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6905 if ((CVR | BaseCVR) != CVR) continue; 6906 // Skip over volatile if no volatile found anywhere in the types. 6907 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6908 6909 // Skip over restrict if no restrict found anywhere in the types, or if 6910 // the type cannot be restrict-qualified. 6911 if ((CVR & Qualifiers::Restrict) && 6912 (!hasRestrict || 6913 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6914 continue; 6915 6916 // Build qualified pointee type. 6917 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6918 6919 // Build qualified pointer type. 6920 QualType QPointerTy; 6921 if (!buildObjCPtr) 6922 QPointerTy = Context.getPointerType(QPointeeTy); 6923 else 6924 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6925 6926 // Insert qualified pointer type. 6927 PointerTypes.insert(QPointerTy); 6928 } 6929 6930 return true; 6931 } 6932 6933 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6934 /// to the set of pointer types along with any more-qualified variants of 6935 /// that type. For example, if @p Ty is "int const *", this routine 6936 /// will add "int const *", "int const volatile *", "int const 6937 /// restrict *", and "int const volatile restrict *" to the set of 6938 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6939 /// false otherwise. 6940 /// 6941 /// FIXME: what to do about extended qualifiers? 6942 bool 6943 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6944 QualType Ty) { 6945 // Insert this type. 6946 if (!MemberPointerTypes.insert(Ty).second) 6947 return false; 6948 6949 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6950 assert(PointerTy && "type was not a member pointer type!"); 6951 6952 QualType PointeeTy = PointerTy->getPointeeType(); 6953 // Don't add qualified variants of arrays. For one, they're not allowed 6954 // (the qualifier would sink to the element type), and for another, the 6955 // only overload situation where it matters is subscript or pointer +- int, 6956 // and those shouldn't have qualifier variants anyway. 6957 if (PointeeTy->isArrayType()) 6958 return true; 6959 const Type *ClassTy = PointerTy->getClass(); 6960 6961 // Iterate through all strict supersets of the pointee type's CVR 6962 // qualifiers. 6963 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6964 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6965 if ((CVR | BaseCVR) != CVR) continue; 6966 6967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6968 MemberPointerTypes.insert( 6969 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6970 } 6971 6972 return true; 6973 } 6974 6975 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6976 /// Ty can be implicit converted to the given set of @p Types. We're 6977 /// primarily interested in pointer types and enumeration types. We also 6978 /// take member pointer types, for the conditional operator. 6979 /// AllowUserConversions is true if we should look at the conversion 6980 /// functions of a class type, and AllowExplicitConversions if we 6981 /// should also include the explicit conversion functions of a class 6982 /// type. 6983 void 6984 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6985 SourceLocation Loc, 6986 bool AllowUserConversions, 6987 bool AllowExplicitConversions, 6988 const Qualifiers &VisibleQuals) { 6989 // Only deal with canonical types. 6990 Ty = Context.getCanonicalType(Ty); 6991 6992 // Look through reference types; they aren't part of the type of an 6993 // expression for the purposes of conversions. 6994 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6995 Ty = RefTy->getPointeeType(); 6996 6997 // If we're dealing with an array type, decay to the pointer. 6998 if (Ty->isArrayType()) 6999 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7000 7001 // Otherwise, we don't care about qualifiers on the type. 7002 Ty = Ty.getLocalUnqualifiedType(); 7003 7004 // Flag if we ever add a non-record type. 7005 const RecordType *TyRec = Ty->getAs<RecordType>(); 7006 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7007 7008 // Flag if we encounter an arithmetic type. 7009 HasArithmeticOrEnumeralTypes = 7010 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7011 7012 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7013 PointerTypes.insert(Ty); 7014 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7015 // Insert our type, and its more-qualified variants, into the set 7016 // of types. 7017 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7018 return; 7019 } else if (Ty->isMemberPointerType()) { 7020 // Member pointers are far easier, since the pointee can't be converted. 7021 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7022 return; 7023 } else if (Ty->isEnumeralType()) { 7024 HasArithmeticOrEnumeralTypes = true; 7025 EnumerationTypes.insert(Ty); 7026 } else if (Ty->isVectorType()) { 7027 // We treat vector types as arithmetic types in many contexts as an 7028 // extension. 7029 HasArithmeticOrEnumeralTypes = true; 7030 VectorTypes.insert(Ty); 7031 } else if (Ty->isNullPtrType()) { 7032 HasNullPtrType = true; 7033 } else if (AllowUserConversions && TyRec) { 7034 // No conversion functions in incomplete types. 7035 if (!SemaRef.isCompleteType(Loc, Ty)) 7036 return; 7037 7038 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7039 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7040 if (isa<UsingShadowDecl>(D)) 7041 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7042 7043 // Skip conversion function templates; they don't tell us anything 7044 // about which builtin types we can convert to. 7045 if (isa<FunctionTemplateDecl>(D)) 7046 continue; 7047 7048 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7049 if (AllowExplicitConversions || !Conv->isExplicit()) { 7050 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7051 VisibleQuals); 7052 } 7053 } 7054 } 7055 } 7056 7057 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7058 /// the volatile- and non-volatile-qualified assignment operators for the 7059 /// given type to the candidate set. 7060 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7061 QualType T, 7062 ArrayRef<Expr *> Args, 7063 OverloadCandidateSet &CandidateSet) { 7064 QualType ParamTypes[2]; 7065 7066 // T& operator=(T&, T) 7067 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7068 ParamTypes[1] = T; 7069 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7070 /*IsAssignmentOperator=*/true); 7071 7072 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7073 // volatile T& operator=(volatile T&, T) 7074 ParamTypes[0] 7075 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7076 ParamTypes[1] = T; 7077 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7078 /*IsAssignmentOperator=*/true); 7079 } 7080 } 7081 7082 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7083 /// if any, found in visible type conversion functions found in ArgExpr's type. 7084 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7085 Qualifiers VRQuals; 7086 const RecordType *TyRec; 7087 if (const MemberPointerType *RHSMPType = 7088 ArgExpr->getType()->getAs<MemberPointerType>()) 7089 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7090 else 7091 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7092 if (!TyRec) { 7093 // Just to be safe, assume the worst case. 7094 VRQuals.addVolatile(); 7095 VRQuals.addRestrict(); 7096 return VRQuals; 7097 } 7098 7099 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7100 if (!ClassDecl->hasDefinition()) 7101 return VRQuals; 7102 7103 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7104 if (isa<UsingShadowDecl>(D)) 7105 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7106 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7107 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7108 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7109 CanTy = ResTypeRef->getPointeeType(); 7110 // Need to go down the pointer/mempointer chain and add qualifiers 7111 // as see them. 7112 bool done = false; 7113 while (!done) { 7114 if (CanTy.isRestrictQualified()) 7115 VRQuals.addRestrict(); 7116 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7117 CanTy = ResTypePtr->getPointeeType(); 7118 else if (const MemberPointerType *ResTypeMPtr = 7119 CanTy->getAs<MemberPointerType>()) 7120 CanTy = ResTypeMPtr->getPointeeType(); 7121 else 7122 done = true; 7123 if (CanTy.isVolatileQualified()) 7124 VRQuals.addVolatile(); 7125 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7126 return VRQuals; 7127 } 7128 } 7129 } 7130 return VRQuals; 7131 } 7132 7133 namespace { 7134 7135 /// \brief Helper class to manage the addition of builtin operator overload 7136 /// candidates. It provides shared state and utility methods used throughout 7137 /// the process, as well as a helper method to add each group of builtin 7138 /// operator overloads from the standard to a candidate set. 7139 class BuiltinOperatorOverloadBuilder { 7140 // Common instance state available to all overload candidate addition methods. 7141 Sema &S; 7142 ArrayRef<Expr *> Args; 7143 Qualifiers VisibleTypeConversionsQuals; 7144 bool HasArithmeticOrEnumeralCandidateType; 7145 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7146 OverloadCandidateSet &CandidateSet; 7147 7148 // Define some constants used to index and iterate over the arithemetic types 7149 // provided via the getArithmeticType() method below. 7150 // The "promoted arithmetic types" are the arithmetic 7151 // types are that preserved by promotion (C++ [over.built]p2). 7152 static const unsigned FirstIntegralType = 3; 7153 static const unsigned LastIntegralType = 20; 7154 static const unsigned FirstPromotedIntegralType = 3, 7155 LastPromotedIntegralType = 11; 7156 static const unsigned FirstPromotedArithmeticType = 0, 7157 LastPromotedArithmeticType = 11; 7158 static const unsigned NumArithmeticTypes = 20; 7159 7160 /// \brief Get the canonical type for a given arithmetic type index. 7161 CanQualType getArithmeticType(unsigned index) { 7162 assert(index < NumArithmeticTypes); 7163 static CanQualType ASTContext::* const 7164 ArithmeticTypes[NumArithmeticTypes] = { 7165 // Start of promoted types. 7166 &ASTContext::FloatTy, 7167 &ASTContext::DoubleTy, 7168 &ASTContext::LongDoubleTy, 7169 7170 // Start of integral types. 7171 &ASTContext::IntTy, 7172 &ASTContext::LongTy, 7173 &ASTContext::LongLongTy, 7174 &ASTContext::Int128Ty, 7175 &ASTContext::UnsignedIntTy, 7176 &ASTContext::UnsignedLongTy, 7177 &ASTContext::UnsignedLongLongTy, 7178 &ASTContext::UnsignedInt128Ty, 7179 // End of promoted types. 7180 7181 &ASTContext::BoolTy, 7182 &ASTContext::CharTy, 7183 &ASTContext::WCharTy, 7184 &ASTContext::Char16Ty, 7185 &ASTContext::Char32Ty, 7186 &ASTContext::SignedCharTy, 7187 &ASTContext::ShortTy, 7188 &ASTContext::UnsignedCharTy, 7189 &ASTContext::UnsignedShortTy, 7190 // End of integral types. 7191 // FIXME: What about complex? What about half? 7192 }; 7193 return S.Context.*ArithmeticTypes[index]; 7194 } 7195 7196 /// \brief Gets the canonical type resulting from the usual arithemetic 7197 /// converions for the given arithmetic types. 7198 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7199 // Accelerator table for performing the usual arithmetic conversions. 7200 // The rules are basically: 7201 // - if either is floating-point, use the wider floating-point 7202 // - if same signedness, use the higher rank 7203 // - if same size, use unsigned of the higher rank 7204 // - use the larger type 7205 // These rules, together with the axiom that higher ranks are 7206 // never smaller, are sufficient to precompute all of these results 7207 // *except* when dealing with signed types of higher rank. 7208 // (we could precompute SLL x UI for all known platforms, but it's 7209 // better not to make any assumptions). 7210 // We assume that int128 has a higher rank than long long on all platforms. 7211 enum PromotedType { 7212 Dep=-1, 7213 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7214 }; 7215 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7216 [LastPromotedArithmeticType] = { 7217 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7218 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7219 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7220 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7221 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7222 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7223 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7224 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7225 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7226 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7227 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7228 }; 7229 7230 assert(L < LastPromotedArithmeticType); 7231 assert(R < LastPromotedArithmeticType); 7232 int Idx = ConversionsTable[L][R]; 7233 7234 // Fast path: the table gives us a concrete answer. 7235 if (Idx != Dep) return getArithmeticType(Idx); 7236 7237 // Slow path: we need to compare widths. 7238 // An invariant is that the signed type has higher rank. 7239 CanQualType LT = getArithmeticType(L), 7240 RT = getArithmeticType(R); 7241 unsigned LW = S.Context.getIntWidth(LT), 7242 RW = S.Context.getIntWidth(RT); 7243 7244 // If they're different widths, use the signed type. 7245 if (LW > RW) return LT; 7246 else if (LW < RW) return RT; 7247 7248 // Otherwise, use the unsigned type of the signed type's rank. 7249 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7250 assert(L == SLL || R == SLL); 7251 return S.Context.UnsignedLongLongTy; 7252 } 7253 7254 /// \brief Helper method to factor out the common pattern of adding overloads 7255 /// for '++' and '--' builtin operators. 7256 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7257 bool HasVolatile, 7258 bool HasRestrict) { 7259 QualType ParamTypes[2] = { 7260 S.Context.getLValueReferenceType(CandidateTy), 7261 S.Context.IntTy 7262 }; 7263 7264 // Non-volatile version. 7265 if (Args.size() == 1) 7266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7267 else 7268 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7269 7270 // Use a heuristic to reduce number of builtin candidates in the set: 7271 // add volatile version only if there are conversions to a volatile type. 7272 if (HasVolatile) { 7273 ParamTypes[0] = 7274 S.Context.getLValueReferenceType( 7275 S.Context.getVolatileType(CandidateTy)); 7276 if (Args.size() == 1) 7277 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7278 else 7279 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7280 } 7281 7282 // Add restrict version only if there are conversions to a restrict type 7283 // and our candidate type is a non-restrict-qualified pointer. 7284 if (HasRestrict && CandidateTy->isAnyPointerType() && 7285 !CandidateTy.isRestrictQualified()) { 7286 ParamTypes[0] 7287 = S.Context.getLValueReferenceType( 7288 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7289 if (Args.size() == 1) 7290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7291 else 7292 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7293 7294 if (HasVolatile) { 7295 ParamTypes[0] 7296 = S.Context.getLValueReferenceType( 7297 S.Context.getCVRQualifiedType(CandidateTy, 7298 (Qualifiers::Volatile | 7299 Qualifiers::Restrict))); 7300 if (Args.size() == 1) 7301 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7302 else 7303 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7304 } 7305 } 7306 7307 } 7308 7309 public: 7310 BuiltinOperatorOverloadBuilder( 7311 Sema &S, ArrayRef<Expr *> Args, 7312 Qualifiers VisibleTypeConversionsQuals, 7313 bool HasArithmeticOrEnumeralCandidateType, 7314 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7315 OverloadCandidateSet &CandidateSet) 7316 : S(S), Args(Args), 7317 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7318 HasArithmeticOrEnumeralCandidateType( 7319 HasArithmeticOrEnumeralCandidateType), 7320 CandidateTypes(CandidateTypes), 7321 CandidateSet(CandidateSet) { 7322 // Validate some of our static helper constants in debug builds. 7323 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7324 "Invalid first promoted integral type"); 7325 assert(getArithmeticType(LastPromotedIntegralType - 1) 7326 == S.Context.UnsignedInt128Ty && 7327 "Invalid last promoted integral type"); 7328 assert(getArithmeticType(FirstPromotedArithmeticType) 7329 == S.Context.FloatTy && 7330 "Invalid first promoted arithmetic type"); 7331 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7332 == S.Context.UnsignedInt128Ty && 7333 "Invalid last promoted arithmetic type"); 7334 } 7335 7336 // C++ [over.built]p3: 7337 // 7338 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7339 // is either volatile or empty, there exist candidate operator 7340 // functions of the form 7341 // 7342 // VQ T& operator++(VQ T&); 7343 // T operator++(VQ T&, int); 7344 // 7345 // C++ [over.built]p4: 7346 // 7347 // For every pair (T, VQ), where T is an arithmetic type other 7348 // than bool, and VQ is either volatile or empty, there exist 7349 // candidate operator functions of the form 7350 // 7351 // VQ T& operator--(VQ T&); 7352 // T operator--(VQ T&, int); 7353 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7354 if (!HasArithmeticOrEnumeralCandidateType) 7355 return; 7356 7357 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7358 Arith < NumArithmeticTypes; ++Arith) { 7359 addPlusPlusMinusMinusStyleOverloads( 7360 getArithmeticType(Arith), 7361 VisibleTypeConversionsQuals.hasVolatile(), 7362 VisibleTypeConversionsQuals.hasRestrict()); 7363 } 7364 } 7365 7366 // C++ [over.built]p5: 7367 // 7368 // For every pair (T, VQ), where T is a cv-qualified or 7369 // cv-unqualified object type, and VQ is either volatile or 7370 // empty, there exist candidate operator functions of the form 7371 // 7372 // T*VQ& operator++(T*VQ&); 7373 // T*VQ& operator--(T*VQ&); 7374 // T* operator++(T*VQ&, int); 7375 // T* operator--(T*VQ&, int); 7376 void addPlusPlusMinusMinusPointerOverloads() { 7377 for (BuiltinCandidateTypeSet::iterator 7378 Ptr = CandidateTypes[0].pointer_begin(), 7379 PtrEnd = CandidateTypes[0].pointer_end(); 7380 Ptr != PtrEnd; ++Ptr) { 7381 // Skip pointer types that aren't pointers to object types. 7382 if (!(*Ptr)->getPointeeType()->isObjectType()) 7383 continue; 7384 7385 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7386 (!(*Ptr).isVolatileQualified() && 7387 VisibleTypeConversionsQuals.hasVolatile()), 7388 (!(*Ptr).isRestrictQualified() && 7389 VisibleTypeConversionsQuals.hasRestrict())); 7390 } 7391 } 7392 7393 // C++ [over.built]p6: 7394 // For every cv-qualified or cv-unqualified object type T, there 7395 // exist candidate operator functions of the form 7396 // 7397 // T& operator*(T*); 7398 // 7399 // C++ [over.built]p7: 7400 // For every function type T that does not have cv-qualifiers or a 7401 // ref-qualifier, there exist candidate operator functions of the form 7402 // T& operator*(T*); 7403 void addUnaryStarPointerOverloads() { 7404 for (BuiltinCandidateTypeSet::iterator 7405 Ptr = CandidateTypes[0].pointer_begin(), 7406 PtrEnd = CandidateTypes[0].pointer_end(); 7407 Ptr != PtrEnd; ++Ptr) { 7408 QualType ParamTy = *Ptr; 7409 QualType PointeeTy = ParamTy->getPointeeType(); 7410 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7411 continue; 7412 7413 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7414 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7415 continue; 7416 7417 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7418 &ParamTy, Args, CandidateSet); 7419 } 7420 } 7421 7422 // C++ [over.built]p9: 7423 // For every promoted arithmetic type T, there exist candidate 7424 // operator functions of the form 7425 // 7426 // T operator+(T); 7427 // T operator-(T); 7428 void addUnaryPlusOrMinusArithmeticOverloads() { 7429 if (!HasArithmeticOrEnumeralCandidateType) 7430 return; 7431 7432 for (unsigned Arith = FirstPromotedArithmeticType; 7433 Arith < LastPromotedArithmeticType; ++Arith) { 7434 QualType ArithTy = getArithmeticType(Arith); 7435 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7436 } 7437 7438 // Extension: We also add these operators for vector types. 7439 for (BuiltinCandidateTypeSet::iterator 7440 Vec = CandidateTypes[0].vector_begin(), 7441 VecEnd = CandidateTypes[0].vector_end(); 7442 Vec != VecEnd; ++Vec) { 7443 QualType VecTy = *Vec; 7444 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7445 } 7446 } 7447 7448 // C++ [over.built]p8: 7449 // For every type T, there exist candidate operator functions of 7450 // the form 7451 // 7452 // T* operator+(T*); 7453 void addUnaryPlusPointerOverloads() { 7454 for (BuiltinCandidateTypeSet::iterator 7455 Ptr = CandidateTypes[0].pointer_begin(), 7456 PtrEnd = CandidateTypes[0].pointer_end(); 7457 Ptr != PtrEnd; ++Ptr) { 7458 QualType ParamTy = *Ptr; 7459 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7460 } 7461 } 7462 7463 // C++ [over.built]p10: 7464 // For every promoted integral type T, there exist candidate 7465 // operator functions of the form 7466 // 7467 // T operator~(T); 7468 void addUnaryTildePromotedIntegralOverloads() { 7469 if (!HasArithmeticOrEnumeralCandidateType) 7470 return; 7471 7472 for (unsigned Int = FirstPromotedIntegralType; 7473 Int < LastPromotedIntegralType; ++Int) { 7474 QualType IntTy = getArithmeticType(Int); 7475 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7476 } 7477 7478 // Extension: We also add this operator for vector types. 7479 for (BuiltinCandidateTypeSet::iterator 7480 Vec = CandidateTypes[0].vector_begin(), 7481 VecEnd = CandidateTypes[0].vector_end(); 7482 Vec != VecEnd; ++Vec) { 7483 QualType VecTy = *Vec; 7484 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7485 } 7486 } 7487 7488 // C++ [over.match.oper]p16: 7489 // For every pointer to member type T, there exist candidate operator 7490 // functions of the form 7491 // 7492 // bool operator==(T,T); 7493 // bool operator!=(T,T); 7494 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7495 /// Set of (canonical) types that we've already handled. 7496 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7497 7498 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7499 for (BuiltinCandidateTypeSet::iterator 7500 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7501 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7502 MemPtr != MemPtrEnd; 7503 ++MemPtr) { 7504 // Don't add the same builtin candidate twice. 7505 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7506 continue; 7507 7508 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7509 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7510 } 7511 } 7512 } 7513 7514 // C++ [over.built]p15: 7515 // 7516 // For every T, where T is an enumeration type, a pointer type, or 7517 // std::nullptr_t, there exist candidate operator functions of the form 7518 // 7519 // bool operator<(T, T); 7520 // bool operator>(T, T); 7521 // bool operator<=(T, T); 7522 // bool operator>=(T, T); 7523 // bool operator==(T, T); 7524 // bool operator!=(T, T); 7525 void addRelationalPointerOrEnumeralOverloads() { 7526 // C++ [over.match.oper]p3: 7527 // [...]the built-in candidates include all of the candidate operator 7528 // functions defined in 13.6 that, compared to the given operator, [...] 7529 // do not have the same parameter-type-list as any non-template non-member 7530 // candidate. 7531 // 7532 // Note that in practice, this only affects enumeration types because there 7533 // aren't any built-in candidates of record type, and a user-defined operator 7534 // must have an operand of record or enumeration type. Also, the only other 7535 // overloaded operator with enumeration arguments, operator=, 7536 // cannot be overloaded for enumeration types, so this is the only place 7537 // where we must suppress candidates like this. 7538 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7539 UserDefinedBinaryOperators; 7540 7541 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7542 if (CandidateTypes[ArgIdx].enumeration_begin() != 7543 CandidateTypes[ArgIdx].enumeration_end()) { 7544 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7545 CEnd = CandidateSet.end(); 7546 C != CEnd; ++C) { 7547 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7548 continue; 7549 7550 if (C->Function->isFunctionTemplateSpecialization()) 7551 continue; 7552 7553 QualType FirstParamType = 7554 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7555 QualType SecondParamType = 7556 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7557 7558 // Skip if either parameter isn't of enumeral type. 7559 if (!FirstParamType->isEnumeralType() || 7560 !SecondParamType->isEnumeralType()) 7561 continue; 7562 7563 // Add this operator to the set of known user-defined operators. 7564 UserDefinedBinaryOperators.insert( 7565 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7566 S.Context.getCanonicalType(SecondParamType))); 7567 } 7568 } 7569 } 7570 7571 /// Set of (canonical) types that we've already handled. 7572 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7573 7574 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7575 for (BuiltinCandidateTypeSet::iterator 7576 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7577 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7578 Ptr != PtrEnd; ++Ptr) { 7579 // Don't add the same builtin candidate twice. 7580 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7581 continue; 7582 7583 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7584 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7585 } 7586 for (BuiltinCandidateTypeSet::iterator 7587 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7588 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7589 Enum != EnumEnd; ++Enum) { 7590 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7591 7592 // Don't add the same builtin candidate twice, or if a user defined 7593 // candidate exists. 7594 if (!AddedTypes.insert(CanonType).second || 7595 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7596 CanonType))) 7597 continue; 7598 7599 QualType ParamTypes[2] = { *Enum, *Enum }; 7600 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7601 } 7602 7603 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7604 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7605 if (AddedTypes.insert(NullPtrTy).second && 7606 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7607 NullPtrTy))) { 7608 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7609 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7610 CandidateSet); 7611 } 7612 } 7613 } 7614 } 7615 7616 // C++ [over.built]p13: 7617 // 7618 // For every cv-qualified or cv-unqualified object type T 7619 // there exist candidate operator functions of the form 7620 // 7621 // T* operator+(T*, ptrdiff_t); 7622 // T& operator[](T*, ptrdiff_t); [BELOW] 7623 // T* operator-(T*, ptrdiff_t); 7624 // T* operator+(ptrdiff_t, T*); 7625 // T& operator[](ptrdiff_t, T*); [BELOW] 7626 // 7627 // C++ [over.built]p14: 7628 // 7629 // For every T, where T is a pointer to object type, there 7630 // exist candidate operator functions of the form 7631 // 7632 // ptrdiff_t operator-(T, T); 7633 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7634 /// Set of (canonical) types that we've already handled. 7635 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7636 7637 for (int Arg = 0; Arg < 2; ++Arg) { 7638 QualType AsymmetricParamTypes[2] = { 7639 S.Context.getPointerDiffType(), 7640 S.Context.getPointerDiffType(), 7641 }; 7642 for (BuiltinCandidateTypeSet::iterator 7643 Ptr = CandidateTypes[Arg].pointer_begin(), 7644 PtrEnd = CandidateTypes[Arg].pointer_end(); 7645 Ptr != PtrEnd; ++Ptr) { 7646 QualType PointeeTy = (*Ptr)->getPointeeType(); 7647 if (!PointeeTy->isObjectType()) 7648 continue; 7649 7650 AsymmetricParamTypes[Arg] = *Ptr; 7651 if (Arg == 0 || Op == OO_Plus) { 7652 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7653 // T* operator+(ptrdiff_t, T*); 7654 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7655 } 7656 if (Op == OO_Minus) { 7657 // ptrdiff_t operator-(T, T); 7658 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7659 continue; 7660 7661 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7662 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7663 Args, CandidateSet); 7664 } 7665 } 7666 } 7667 } 7668 7669 // C++ [over.built]p12: 7670 // 7671 // For every pair of promoted arithmetic types L and R, there 7672 // exist candidate operator functions of the form 7673 // 7674 // LR operator*(L, R); 7675 // LR operator/(L, R); 7676 // LR operator+(L, R); 7677 // LR operator-(L, R); 7678 // bool operator<(L, R); 7679 // bool operator>(L, R); 7680 // bool operator<=(L, R); 7681 // bool operator>=(L, R); 7682 // bool operator==(L, R); 7683 // bool operator!=(L, R); 7684 // 7685 // where LR is the result of the usual arithmetic conversions 7686 // between types L and R. 7687 // 7688 // C++ [over.built]p24: 7689 // 7690 // For every pair of promoted arithmetic types L and R, there exist 7691 // candidate operator functions of the form 7692 // 7693 // LR operator?(bool, L, R); 7694 // 7695 // where LR is the result of the usual arithmetic conversions 7696 // between types L and R. 7697 // Our candidates ignore the first parameter. 7698 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7699 if (!HasArithmeticOrEnumeralCandidateType) 7700 return; 7701 7702 for (unsigned Left = FirstPromotedArithmeticType; 7703 Left < LastPromotedArithmeticType; ++Left) { 7704 for (unsigned Right = FirstPromotedArithmeticType; 7705 Right < LastPromotedArithmeticType; ++Right) { 7706 QualType LandR[2] = { getArithmeticType(Left), 7707 getArithmeticType(Right) }; 7708 QualType Result = 7709 isComparison ? S.Context.BoolTy 7710 : getUsualArithmeticConversions(Left, Right); 7711 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7712 } 7713 } 7714 7715 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7716 // conditional operator for vector types. 7717 for (BuiltinCandidateTypeSet::iterator 7718 Vec1 = CandidateTypes[0].vector_begin(), 7719 Vec1End = CandidateTypes[0].vector_end(); 7720 Vec1 != Vec1End; ++Vec1) { 7721 for (BuiltinCandidateTypeSet::iterator 7722 Vec2 = CandidateTypes[1].vector_begin(), 7723 Vec2End = CandidateTypes[1].vector_end(); 7724 Vec2 != Vec2End; ++Vec2) { 7725 QualType LandR[2] = { *Vec1, *Vec2 }; 7726 QualType Result = S.Context.BoolTy; 7727 if (!isComparison) { 7728 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7729 Result = *Vec1; 7730 else 7731 Result = *Vec2; 7732 } 7733 7734 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7735 } 7736 } 7737 } 7738 7739 // C++ [over.built]p17: 7740 // 7741 // For every pair of promoted integral types L and R, there 7742 // exist candidate operator functions of the form 7743 // 7744 // LR operator%(L, R); 7745 // LR operator&(L, R); 7746 // LR operator^(L, R); 7747 // LR operator|(L, R); 7748 // L operator<<(L, R); 7749 // L operator>>(L, R); 7750 // 7751 // where LR is the result of the usual arithmetic conversions 7752 // between types L and R. 7753 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7754 if (!HasArithmeticOrEnumeralCandidateType) 7755 return; 7756 7757 for (unsigned Left = FirstPromotedIntegralType; 7758 Left < LastPromotedIntegralType; ++Left) { 7759 for (unsigned Right = FirstPromotedIntegralType; 7760 Right < LastPromotedIntegralType; ++Right) { 7761 QualType LandR[2] = { getArithmeticType(Left), 7762 getArithmeticType(Right) }; 7763 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7764 ? LandR[0] 7765 : getUsualArithmeticConversions(Left, Right); 7766 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7767 } 7768 } 7769 } 7770 7771 // C++ [over.built]p20: 7772 // 7773 // For every pair (T, VQ), where T is an enumeration or 7774 // pointer to member type and VQ is either volatile or 7775 // empty, there exist candidate operator functions of the form 7776 // 7777 // VQ T& operator=(VQ T&, T); 7778 void addAssignmentMemberPointerOrEnumeralOverloads() { 7779 /// Set of (canonical) types that we've already handled. 7780 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7781 7782 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7783 for (BuiltinCandidateTypeSet::iterator 7784 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7785 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7786 Enum != EnumEnd; ++Enum) { 7787 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7788 continue; 7789 7790 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7791 } 7792 7793 for (BuiltinCandidateTypeSet::iterator 7794 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7795 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7796 MemPtr != MemPtrEnd; ++MemPtr) { 7797 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7798 continue; 7799 7800 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7801 } 7802 } 7803 } 7804 7805 // C++ [over.built]p19: 7806 // 7807 // For every pair (T, VQ), where T is any type and VQ is either 7808 // volatile or empty, there exist candidate operator functions 7809 // of the form 7810 // 7811 // T*VQ& operator=(T*VQ&, T*); 7812 // 7813 // C++ [over.built]p21: 7814 // 7815 // For every pair (T, VQ), where T is a cv-qualified or 7816 // cv-unqualified object type and VQ is either volatile or 7817 // empty, there exist candidate operator functions of the form 7818 // 7819 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7820 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7821 void addAssignmentPointerOverloads(bool isEqualOp) { 7822 /// Set of (canonical) types that we've already handled. 7823 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7824 7825 for (BuiltinCandidateTypeSet::iterator 7826 Ptr = CandidateTypes[0].pointer_begin(), 7827 PtrEnd = CandidateTypes[0].pointer_end(); 7828 Ptr != PtrEnd; ++Ptr) { 7829 // If this is operator=, keep track of the builtin candidates we added. 7830 if (isEqualOp) 7831 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7832 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7833 continue; 7834 7835 // non-volatile version 7836 QualType ParamTypes[2] = { 7837 S.Context.getLValueReferenceType(*Ptr), 7838 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7839 }; 7840 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7841 /*IsAssigmentOperator=*/ isEqualOp); 7842 7843 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7844 VisibleTypeConversionsQuals.hasVolatile(); 7845 if (NeedVolatile) { 7846 // volatile version 7847 ParamTypes[0] = 7848 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7849 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7850 /*IsAssigmentOperator=*/isEqualOp); 7851 } 7852 7853 if (!(*Ptr).isRestrictQualified() && 7854 VisibleTypeConversionsQuals.hasRestrict()) { 7855 // restrict version 7856 ParamTypes[0] 7857 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7858 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7859 /*IsAssigmentOperator=*/isEqualOp); 7860 7861 if (NeedVolatile) { 7862 // volatile restrict version 7863 ParamTypes[0] 7864 = S.Context.getLValueReferenceType( 7865 S.Context.getCVRQualifiedType(*Ptr, 7866 (Qualifiers::Volatile | 7867 Qualifiers::Restrict))); 7868 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7869 /*IsAssigmentOperator=*/isEqualOp); 7870 } 7871 } 7872 } 7873 7874 if (isEqualOp) { 7875 for (BuiltinCandidateTypeSet::iterator 7876 Ptr = CandidateTypes[1].pointer_begin(), 7877 PtrEnd = CandidateTypes[1].pointer_end(); 7878 Ptr != PtrEnd; ++Ptr) { 7879 // Make sure we don't add the same candidate twice. 7880 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7881 continue; 7882 7883 QualType ParamTypes[2] = { 7884 S.Context.getLValueReferenceType(*Ptr), 7885 *Ptr, 7886 }; 7887 7888 // non-volatile version 7889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7890 /*IsAssigmentOperator=*/true); 7891 7892 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7893 VisibleTypeConversionsQuals.hasVolatile(); 7894 if (NeedVolatile) { 7895 // volatile version 7896 ParamTypes[0] = 7897 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7898 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7899 /*IsAssigmentOperator=*/true); 7900 } 7901 7902 if (!(*Ptr).isRestrictQualified() && 7903 VisibleTypeConversionsQuals.hasRestrict()) { 7904 // restrict version 7905 ParamTypes[0] 7906 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7907 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7908 /*IsAssigmentOperator=*/true); 7909 7910 if (NeedVolatile) { 7911 // volatile restrict version 7912 ParamTypes[0] 7913 = S.Context.getLValueReferenceType( 7914 S.Context.getCVRQualifiedType(*Ptr, 7915 (Qualifiers::Volatile | 7916 Qualifiers::Restrict))); 7917 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7918 /*IsAssigmentOperator=*/true); 7919 } 7920 } 7921 } 7922 } 7923 } 7924 7925 // C++ [over.built]p18: 7926 // 7927 // For every triple (L, VQ, R), where L is an arithmetic type, 7928 // VQ is either volatile or empty, and R is a promoted 7929 // arithmetic type, there exist candidate operator functions of 7930 // the form 7931 // 7932 // VQ L& operator=(VQ L&, R); 7933 // VQ L& operator*=(VQ L&, R); 7934 // VQ L& operator/=(VQ L&, R); 7935 // VQ L& operator+=(VQ L&, R); 7936 // VQ L& operator-=(VQ L&, R); 7937 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7938 if (!HasArithmeticOrEnumeralCandidateType) 7939 return; 7940 7941 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7942 for (unsigned Right = FirstPromotedArithmeticType; 7943 Right < LastPromotedArithmeticType; ++Right) { 7944 QualType ParamTypes[2]; 7945 ParamTypes[1] = getArithmeticType(Right); 7946 7947 // Add this built-in operator as a candidate (VQ is empty). 7948 ParamTypes[0] = 7949 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7950 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7951 /*IsAssigmentOperator=*/isEqualOp); 7952 7953 // Add this built-in operator as a candidate (VQ is 'volatile'). 7954 if (VisibleTypeConversionsQuals.hasVolatile()) { 7955 ParamTypes[0] = 7956 S.Context.getVolatileType(getArithmeticType(Left)); 7957 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7959 /*IsAssigmentOperator=*/isEqualOp); 7960 } 7961 } 7962 } 7963 7964 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7965 for (BuiltinCandidateTypeSet::iterator 7966 Vec1 = CandidateTypes[0].vector_begin(), 7967 Vec1End = CandidateTypes[0].vector_end(); 7968 Vec1 != Vec1End; ++Vec1) { 7969 for (BuiltinCandidateTypeSet::iterator 7970 Vec2 = CandidateTypes[1].vector_begin(), 7971 Vec2End = CandidateTypes[1].vector_end(); 7972 Vec2 != Vec2End; ++Vec2) { 7973 QualType ParamTypes[2]; 7974 ParamTypes[1] = *Vec2; 7975 // Add this built-in operator as a candidate (VQ is empty). 7976 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7977 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7978 /*IsAssigmentOperator=*/isEqualOp); 7979 7980 // Add this built-in operator as a candidate (VQ is 'volatile'). 7981 if (VisibleTypeConversionsQuals.hasVolatile()) { 7982 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7983 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7985 /*IsAssigmentOperator=*/isEqualOp); 7986 } 7987 } 7988 } 7989 } 7990 7991 // C++ [over.built]p22: 7992 // 7993 // For every triple (L, VQ, R), where L is an integral type, VQ 7994 // is either volatile or empty, and R is a promoted integral 7995 // type, there exist candidate operator functions of the form 7996 // 7997 // VQ L& operator%=(VQ L&, R); 7998 // VQ L& operator<<=(VQ L&, R); 7999 // VQ L& operator>>=(VQ L&, R); 8000 // VQ L& operator&=(VQ L&, R); 8001 // VQ L& operator^=(VQ L&, R); 8002 // VQ L& operator|=(VQ L&, R); 8003 void addAssignmentIntegralOverloads() { 8004 if (!HasArithmeticOrEnumeralCandidateType) 8005 return; 8006 8007 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8008 for (unsigned Right = FirstPromotedIntegralType; 8009 Right < LastPromotedIntegralType; ++Right) { 8010 QualType ParamTypes[2]; 8011 ParamTypes[1] = getArithmeticType(Right); 8012 8013 // Add this built-in operator as a candidate (VQ is empty). 8014 ParamTypes[0] = 8015 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8016 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8017 if (VisibleTypeConversionsQuals.hasVolatile()) { 8018 // Add this built-in operator as a candidate (VQ is 'volatile'). 8019 ParamTypes[0] = getArithmeticType(Left); 8020 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8021 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8023 } 8024 } 8025 } 8026 } 8027 8028 // C++ [over.operator]p23: 8029 // 8030 // There also exist candidate operator functions of the form 8031 // 8032 // bool operator!(bool); 8033 // bool operator&&(bool, bool); 8034 // bool operator||(bool, bool); 8035 void addExclaimOverload() { 8036 QualType ParamTy = S.Context.BoolTy; 8037 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8038 /*IsAssignmentOperator=*/false, 8039 /*NumContextualBoolArguments=*/1); 8040 } 8041 void addAmpAmpOrPipePipeOverload() { 8042 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8043 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8044 /*IsAssignmentOperator=*/false, 8045 /*NumContextualBoolArguments=*/2); 8046 } 8047 8048 // C++ [over.built]p13: 8049 // 8050 // For every cv-qualified or cv-unqualified object type T there 8051 // exist candidate operator functions of the form 8052 // 8053 // T* operator+(T*, ptrdiff_t); [ABOVE] 8054 // T& operator[](T*, ptrdiff_t); 8055 // T* operator-(T*, ptrdiff_t); [ABOVE] 8056 // T* operator+(ptrdiff_t, T*); [ABOVE] 8057 // T& operator[](ptrdiff_t, T*); 8058 void addSubscriptOverloads() { 8059 for (BuiltinCandidateTypeSet::iterator 8060 Ptr = CandidateTypes[0].pointer_begin(), 8061 PtrEnd = CandidateTypes[0].pointer_end(); 8062 Ptr != PtrEnd; ++Ptr) { 8063 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8064 QualType PointeeType = (*Ptr)->getPointeeType(); 8065 if (!PointeeType->isObjectType()) 8066 continue; 8067 8068 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8069 8070 // T& operator[](T*, ptrdiff_t) 8071 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8072 } 8073 8074 for (BuiltinCandidateTypeSet::iterator 8075 Ptr = CandidateTypes[1].pointer_begin(), 8076 PtrEnd = CandidateTypes[1].pointer_end(); 8077 Ptr != PtrEnd; ++Ptr) { 8078 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8079 QualType PointeeType = (*Ptr)->getPointeeType(); 8080 if (!PointeeType->isObjectType()) 8081 continue; 8082 8083 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8084 8085 // T& operator[](ptrdiff_t, T*) 8086 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8087 } 8088 } 8089 8090 // C++ [over.built]p11: 8091 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8092 // C1 is the same type as C2 or is a derived class of C2, T is an object 8093 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8094 // there exist candidate operator functions of the form 8095 // 8096 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8097 // 8098 // where CV12 is the union of CV1 and CV2. 8099 void addArrowStarOverloads() { 8100 for (BuiltinCandidateTypeSet::iterator 8101 Ptr = CandidateTypes[0].pointer_begin(), 8102 PtrEnd = CandidateTypes[0].pointer_end(); 8103 Ptr != PtrEnd; ++Ptr) { 8104 QualType C1Ty = (*Ptr); 8105 QualType C1; 8106 QualifierCollector Q1; 8107 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8108 if (!isa<RecordType>(C1)) 8109 continue; 8110 // heuristic to reduce number of builtin candidates in the set. 8111 // Add volatile/restrict version only if there are conversions to a 8112 // volatile/restrict type. 8113 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8114 continue; 8115 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8116 continue; 8117 for (BuiltinCandidateTypeSet::iterator 8118 MemPtr = CandidateTypes[1].member_pointer_begin(), 8119 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8120 MemPtr != MemPtrEnd; ++MemPtr) { 8121 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8122 QualType C2 = QualType(mptr->getClass(), 0); 8123 C2 = C2.getUnqualifiedType(); 8124 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8125 break; 8126 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8127 // build CV12 T& 8128 QualType T = mptr->getPointeeType(); 8129 if (!VisibleTypeConversionsQuals.hasVolatile() && 8130 T.isVolatileQualified()) 8131 continue; 8132 if (!VisibleTypeConversionsQuals.hasRestrict() && 8133 T.isRestrictQualified()) 8134 continue; 8135 T = Q1.apply(S.Context, T); 8136 QualType ResultTy = S.Context.getLValueReferenceType(T); 8137 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8138 } 8139 } 8140 } 8141 8142 // Note that we don't consider the first argument, since it has been 8143 // contextually converted to bool long ago. The candidates below are 8144 // therefore added as binary. 8145 // 8146 // C++ [over.built]p25: 8147 // For every type T, where T is a pointer, pointer-to-member, or scoped 8148 // enumeration type, there exist candidate operator functions of the form 8149 // 8150 // T operator?(bool, T, T); 8151 // 8152 void addConditionalOperatorOverloads() { 8153 /// Set of (canonical) types that we've already handled. 8154 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8155 8156 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8157 for (BuiltinCandidateTypeSet::iterator 8158 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8159 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8160 Ptr != PtrEnd; ++Ptr) { 8161 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8162 continue; 8163 8164 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8165 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8166 } 8167 8168 for (BuiltinCandidateTypeSet::iterator 8169 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8170 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8171 MemPtr != MemPtrEnd; ++MemPtr) { 8172 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8173 continue; 8174 8175 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8176 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8177 } 8178 8179 if (S.getLangOpts().CPlusPlus11) { 8180 for (BuiltinCandidateTypeSet::iterator 8181 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8182 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8183 Enum != EnumEnd; ++Enum) { 8184 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8185 continue; 8186 8187 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8188 continue; 8189 8190 QualType ParamTypes[2] = { *Enum, *Enum }; 8191 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8192 } 8193 } 8194 } 8195 } 8196 }; 8197 8198 } // end anonymous namespace 8199 8200 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8201 /// operator overloads to the candidate set (C++ [over.built]), based 8202 /// on the operator @p Op and the arguments given. For example, if the 8203 /// operator is a binary '+', this routine might add "int 8204 /// operator+(int, int)" to cover integer addition. 8205 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8206 SourceLocation OpLoc, 8207 ArrayRef<Expr *> Args, 8208 OverloadCandidateSet &CandidateSet) { 8209 // Find all of the types that the arguments can convert to, but only 8210 // if the operator we're looking at has built-in operator candidates 8211 // that make use of these types. Also record whether we encounter non-record 8212 // candidate types or either arithmetic or enumeral candidate types. 8213 Qualifiers VisibleTypeConversionsQuals; 8214 VisibleTypeConversionsQuals.addConst(); 8215 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8216 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8217 8218 bool HasNonRecordCandidateType = false; 8219 bool HasArithmeticOrEnumeralCandidateType = false; 8220 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8221 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8222 CandidateTypes.emplace_back(*this); 8223 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8224 OpLoc, 8225 true, 8226 (Op == OO_Exclaim || 8227 Op == OO_AmpAmp || 8228 Op == OO_PipePipe), 8229 VisibleTypeConversionsQuals); 8230 HasNonRecordCandidateType = HasNonRecordCandidateType || 8231 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8232 HasArithmeticOrEnumeralCandidateType = 8233 HasArithmeticOrEnumeralCandidateType || 8234 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8235 } 8236 8237 // Exit early when no non-record types have been added to the candidate set 8238 // for any of the arguments to the operator. 8239 // 8240 // We can't exit early for !, ||, or &&, since there we have always have 8241 // 'bool' overloads. 8242 if (!HasNonRecordCandidateType && 8243 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8244 return; 8245 8246 // Setup an object to manage the common state for building overloads. 8247 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8248 VisibleTypeConversionsQuals, 8249 HasArithmeticOrEnumeralCandidateType, 8250 CandidateTypes, CandidateSet); 8251 8252 // Dispatch over the operation to add in only those overloads which apply. 8253 switch (Op) { 8254 case OO_None: 8255 case NUM_OVERLOADED_OPERATORS: 8256 llvm_unreachable("Expected an overloaded operator"); 8257 8258 case OO_New: 8259 case OO_Delete: 8260 case OO_Array_New: 8261 case OO_Array_Delete: 8262 case OO_Call: 8263 llvm_unreachable( 8264 "Special operators don't use AddBuiltinOperatorCandidates"); 8265 8266 case OO_Comma: 8267 case OO_Arrow: 8268 case OO_Coawait: 8269 // C++ [over.match.oper]p3: 8270 // -- For the operator ',', the unary operator '&', the 8271 // operator '->', or the operator 'co_await', the 8272 // built-in candidates set is empty. 8273 break; 8274 8275 case OO_Plus: // '+' is either unary or binary 8276 if (Args.size() == 1) 8277 OpBuilder.addUnaryPlusPointerOverloads(); 8278 // Fall through. 8279 8280 case OO_Minus: // '-' is either unary or binary 8281 if (Args.size() == 1) { 8282 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8283 } else { 8284 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8285 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8286 } 8287 break; 8288 8289 case OO_Star: // '*' is either unary or binary 8290 if (Args.size() == 1) 8291 OpBuilder.addUnaryStarPointerOverloads(); 8292 else 8293 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8294 break; 8295 8296 case OO_Slash: 8297 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8298 break; 8299 8300 case OO_PlusPlus: 8301 case OO_MinusMinus: 8302 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8303 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8304 break; 8305 8306 case OO_EqualEqual: 8307 case OO_ExclaimEqual: 8308 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8309 // Fall through. 8310 8311 case OO_Less: 8312 case OO_Greater: 8313 case OO_LessEqual: 8314 case OO_GreaterEqual: 8315 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8316 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8317 break; 8318 8319 case OO_Percent: 8320 case OO_Caret: 8321 case OO_Pipe: 8322 case OO_LessLess: 8323 case OO_GreaterGreater: 8324 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8325 break; 8326 8327 case OO_Amp: // '&' is either unary or binary 8328 if (Args.size() == 1) 8329 // C++ [over.match.oper]p3: 8330 // -- For the operator ',', the unary operator '&', or the 8331 // operator '->', the built-in candidates set is empty. 8332 break; 8333 8334 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8335 break; 8336 8337 case OO_Tilde: 8338 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8339 break; 8340 8341 case OO_Equal: 8342 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8343 // Fall through. 8344 8345 case OO_PlusEqual: 8346 case OO_MinusEqual: 8347 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8348 // Fall through. 8349 8350 case OO_StarEqual: 8351 case OO_SlashEqual: 8352 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8353 break; 8354 8355 case OO_PercentEqual: 8356 case OO_LessLessEqual: 8357 case OO_GreaterGreaterEqual: 8358 case OO_AmpEqual: 8359 case OO_CaretEqual: 8360 case OO_PipeEqual: 8361 OpBuilder.addAssignmentIntegralOverloads(); 8362 break; 8363 8364 case OO_Exclaim: 8365 OpBuilder.addExclaimOverload(); 8366 break; 8367 8368 case OO_AmpAmp: 8369 case OO_PipePipe: 8370 OpBuilder.addAmpAmpOrPipePipeOverload(); 8371 break; 8372 8373 case OO_Subscript: 8374 OpBuilder.addSubscriptOverloads(); 8375 break; 8376 8377 case OO_ArrowStar: 8378 OpBuilder.addArrowStarOverloads(); 8379 break; 8380 8381 case OO_Conditional: 8382 OpBuilder.addConditionalOperatorOverloads(); 8383 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8384 break; 8385 } 8386 } 8387 8388 /// \brief Add function candidates found via argument-dependent lookup 8389 /// to the set of overloading candidates. 8390 /// 8391 /// This routine performs argument-dependent name lookup based on the 8392 /// given function name (which may also be an operator name) and adds 8393 /// all of the overload candidates found by ADL to the overload 8394 /// candidate set (C++ [basic.lookup.argdep]). 8395 void 8396 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8397 SourceLocation Loc, 8398 ArrayRef<Expr *> Args, 8399 TemplateArgumentListInfo *ExplicitTemplateArgs, 8400 OverloadCandidateSet& CandidateSet, 8401 bool PartialOverloading) { 8402 ADLResult Fns; 8403 8404 // FIXME: This approach for uniquing ADL results (and removing 8405 // redundant candidates from the set) relies on pointer-equality, 8406 // which means we need to key off the canonical decl. However, 8407 // always going back to the canonical decl might not get us the 8408 // right set of default arguments. What default arguments are 8409 // we supposed to consider on ADL candidates, anyway? 8410 8411 // FIXME: Pass in the explicit template arguments? 8412 ArgumentDependentLookup(Name, Loc, Args, Fns); 8413 8414 // Erase all of the candidates we already knew about. 8415 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8416 CandEnd = CandidateSet.end(); 8417 Cand != CandEnd; ++Cand) 8418 if (Cand->Function) { 8419 Fns.erase(Cand->Function); 8420 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8421 Fns.erase(FunTmpl); 8422 } 8423 8424 // For each of the ADL candidates we found, add it to the overload 8425 // set. 8426 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8427 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8428 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8429 if (ExplicitTemplateArgs) 8430 continue; 8431 8432 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8433 PartialOverloading); 8434 } else 8435 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8436 FoundDecl, ExplicitTemplateArgs, 8437 Args, CandidateSet, PartialOverloading); 8438 } 8439 } 8440 8441 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8442 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8443 // on Cand1 and Cand2 have conditions that evaluate to true. 8444 // 8445 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8446 // Cand1's first N enable_if attributes have precisely the same conditions as 8447 // Cand2's first N enable_if attributes (where N = the number of enable_if 8448 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8449 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8450 const FunctionDecl *Cand2) { 8451 8452 // FIXME: The next several lines are just 8453 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8454 // instead of reverse order which is how they're stored in the AST. 8455 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8456 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8457 8458 // Candidate 1 is better if it has strictly more attributes and 8459 // the common sequence is identical. 8460 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8461 return false; 8462 8463 auto Cand1I = Cand1Attrs.begin(); 8464 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8465 for (auto &Cand2A : Cand2Attrs) { 8466 Cand1ID.clear(); 8467 Cand2ID.clear(); 8468 8469 auto &Cand1A = *Cand1I++; 8470 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8471 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8472 if (Cand1ID != Cand2ID) 8473 return false; 8474 } 8475 8476 return true; 8477 } 8478 8479 /// isBetterOverloadCandidate - Determines whether the first overload 8480 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8481 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8482 const OverloadCandidate &Cand2, 8483 SourceLocation Loc, 8484 bool UserDefinedConversion) { 8485 // Define viable functions to be better candidates than non-viable 8486 // functions. 8487 if (!Cand2.Viable) 8488 return Cand1.Viable; 8489 else if (!Cand1.Viable) 8490 return false; 8491 8492 // C++ [over.match.best]p1: 8493 // 8494 // -- if F is a static member function, ICS1(F) is defined such 8495 // that ICS1(F) is neither better nor worse than ICS1(G) for 8496 // any function G, and, symmetrically, ICS1(G) is neither 8497 // better nor worse than ICS1(F). 8498 unsigned StartArg = 0; 8499 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8500 StartArg = 1; 8501 8502 // C++ [over.match.best]p1: 8503 // A viable function F1 is defined to be a better function than another 8504 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8505 // conversion sequence than ICSi(F2), and then... 8506 unsigned NumArgs = Cand1.NumConversions; 8507 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8508 bool HasBetterConversion = false; 8509 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8510 switch (CompareImplicitConversionSequences(S, Loc, 8511 Cand1.Conversions[ArgIdx], 8512 Cand2.Conversions[ArgIdx])) { 8513 case ImplicitConversionSequence::Better: 8514 // Cand1 has a better conversion sequence. 8515 HasBetterConversion = true; 8516 break; 8517 8518 case ImplicitConversionSequence::Worse: 8519 // Cand1 can't be better than Cand2. 8520 return false; 8521 8522 case ImplicitConversionSequence::Indistinguishable: 8523 // Do nothing. 8524 break; 8525 } 8526 } 8527 8528 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8529 // ICSj(F2), or, if not that, 8530 if (HasBetterConversion) 8531 return true; 8532 8533 // -- the context is an initialization by user-defined conversion 8534 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8535 // from the return type of F1 to the destination type (i.e., 8536 // the type of the entity being initialized) is a better 8537 // conversion sequence than the standard conversion sequence 8538 // from the return type of F2 to the destination type. 8539 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8540 isa<CXXConversionDecl>(Cand1.Function) && 8541 isa<CXXConversionDecl>(Cand2.Function)) { 8542 // First check whether we prefer one of the conversion functions over the 8543 // other. This only distinguishes the results in non-standard, extension 8544 // cases such as the conversion from a lambda closure type to a function 8545 // pointer or block. 8546 ImplicitConversionSequence::CompareKind Result = 8547 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8548 if (Result == ImplicitConversionSequence::Indistinguishable) 8549 Result = CompareStandardConversionSequences(S, Loc, 8550 Cand1.FinalConversion, 8551 Cand2.FinalConversion); 8552 8553 if (Result != ImplicitConversionSequence::Indistinguishable) 8554 return Result == ImplicitConversionSequence::Better; 8555 8556 // FIXME: Compare kind of reference binding if conversion functions 8557 // convert to a reference type used in direct reference binding, per 8558 // C++14 [over.match.best]p1 section 2 bullet 3. 8559 } 8560 8561 // -- F1 is a non-template function and F2 is a function template 8562 // specialization, or, if not that, 8563 bool Cand1IsSpecialization = Cand1.Function && 8564 Cand1.Function->getPrimaryTemplate(); 8565 bool Cand2IsSpecialization = Cand2.Function && 8566 Cand2.Function->getPrimaryTemplate(); 8567 if (Cand1IsSpecialization != Cand2IsSpecialization) 8568 return Cand2IsSpecialization; 8569 8570 // -- F1 and F2 are function template specializations, and the function 8571 // template for F1 is more specialized than the template for F2 8572 // according to the partial ordering rules described in 14.5.5.2, or, 8573 // if not that, 8574 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8575 if (FunctionTemplateDecl *BetterTemplate 8576 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8577 Cand2.Function->getPrimaryTemplate(), 8578 Loc, 8579 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8580 : TPOC_Call, 8581 Cand1.ExplicitCallArguments, 8582 Cand2.ExplicitCallArguments)) 8583 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8584 } 8585 8586 // Check for enable_if value-based overload resolution. 8587 if (Cand1.Function && Cand2.Function && 8588 (Cand1.Function->hasAttr<EnableIfAttr>() || 8589 Cand2.Function->hasAttr<EnableIfAttr>())) 8590 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8591 8592 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8593 Cand1.Function && Cand2.Function) { 8594 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8595 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8596 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8597 } 8598 8599 bool HasPS1 = Cand1.Function != nullptr && 8600 functionHasPassObjectSizeParams(Cand1.Function); 8601 bool HasPS2 = Cand2.Function != nullptr && 8602 functionHasPassObjectSizeParams(Cand2.Function); 8603 return HasPS1 != HasPS2 && HasPS1; 8604 } 8605 8606 /// Determine whether two declarations are "equivalent" for the purposes of 8607 /// name lookup and overload resolution. This applies when the same internal/no 8608 /// linkage entity is defined by two modules (probably by textually including 8609 /// the same header). In such a case, we don't consider the declarations to 8610 /// declare the same entity, but we also don't want lookups with both 8611 /// declarations visible to be ambiguous in some cases (this happens when using 8612 /// a modularized libstdc++). 8613 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8614 const NamedDecl *B) { 8615 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8616 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8617 if (!VA || !VB) 8618 return false; 8619 8620 // The declarations must be declaring the same name as an internal linkage 8621 // entity in different modules. 8622 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8623 VB->getDeclContext()->getRedeclContext()) || 8624 getOwningModule(const_cast<ValueDecl *>(VA)) == 8625 getOwningModule(const_cast<ValueDecl *>(VB)) || 8626 VA->isExternallyVisible() || VB->isExternallyVisible()) 8627 return false; 8628 8629 // Check that the declarations appear to be equivalent. 8630 // 8631 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8632 // For constants and functions, we should check the initializer or body is 8633 // the same. For non-constant variables, we shouldn't allow it at all. 8634 if (Context.hasSameType(VA->getType(), VB->getType())) 8635 return true; 8636 8637 // Enum constants within unnamed enumerations will have different types, but 8638 // may still be similar enough to be interchangeable for our purposes. 8639 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8640 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8641 // Only handle anonymous enums. If the enumerations were named and 8642 // equivalent, they would have been merged to the same type. 8643 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8644 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8645 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8646 !Context.hasSameType(EnumA->getIntegerType(), 8647 EnumB->getIntegerType())) 8648 return false; 8649 // Allow this only if the value is the same for both enumerators. 8650 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8651 } 8652 } 8653 8654 // Nothing else is sufficiently similar. 8655 return false; 8656 } 8657 8658 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8659 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8660 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8661 8662 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8663 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8664 << !M << (M ? M->getFullModuleName() : ""); 8665 8666 for (auto *E : Equiv) { 8667 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8668 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8669 << !M << (M ? M->getFullModuleName() : ""); 8670 } 8671 } 8672 8673 /// \brief Computes the best viable function (C++ 13.3.3) 8674 /// within an overload candidate set. 8675 /// 8676 /// \param Loc The location of the function name (or operator symbol) for 8677 /// which overload resolution occurs. 8678 /// 8679 /// \param Best If overload resolution was successful or found a deleted 8680 /// function, \p Best points to the candidate function found. 8681 /// 8682 /// \returns The result of overload resolution. 8683 OverloadingResult 8684 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8685 iterator &Best, 8686 bool UserDefinedConversion) { 8687 // Find the best viable function. 8688 Best = end(); 8689 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8690 if (Cand->Viable) 8691 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8692 UserDefinedConversion)) 8693 Best = Cand; 8694 } 8695 8696 // If we didn't find any viable functions, abort. 8697 if (Best == end()) 8698 return OR_No_Viable_Function; 8699 8700 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8701 8702 // Make sure that this function is better than every other viable 8703 // function. If not, we have an ambiguity. 8704 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8705 if (Cand->Viable && 8706 Cand != Best && 8707 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8708 UserDefinedConversion)) { 8709 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8710 Cand->Function)) { 8711 EquivalentCands.push_back(Cand->Function); 8712 continue; 8713 } 8714 8715 Best = end(); 8716 return OR_Ambiguous; 8717 } 8718 } 8719 8720 // Best is the best viable function. 8721 if (Best->Function && 8722 (Best->Function->isDeleted() || 8723 S.isFunctionConsideredUnavailable(Best->Function))) 8724 return OR_Deleted; 8725 8726 if (!EquivalentCands.empty()) 8727 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8728 EquivalentCands); 8729 8730 return OR_Success; 8731 } 8732 8733 namespace { 8734 8735 enum OverloadCandidateKind { 8736 oc_function, 8737 oc_method, 8738 oc_constructor, 8739 oc_function_template, 8740 oc_method_template, 8741 oc_constructor_template, 8742 oc_implicit_default_constructor, 8743 oc_implicit_copy_constructor, 8744 oc_implicit_move_constructor, 8745 oc_implicit_copy_assignment, 8746 oc_implicit_move_assignment, 8747 oc_implicit_inherited_constructor 8748 }; 8749 8750 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8751 FunctionDecl *Fn, 8752 std::string &Description) { 8753 bool isTemplate = false; 8754 8755 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8756 isTemplate = true; 8757 Description = S.getTemplateArgumentBindingsText( 8758 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8759 } 8760 8761 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8762 if (!Ctor->isImplicit()) 8763 return isTemplate ? oc_constructor_template : oc_constructor; 8764 8765 if (Ctor->getInheritedConstructor()) 8766 return oc_implicit_inherited_constructor; 8767 8768 if (Ctor->isDefaultConstructor()) 8769 return oc_implicit_default_constructor; 8770 8771 if (Ctor->isMoveConstructor()) 8772 return oc_implicit_move_constructor; 8773 8774 assert(Ctor->isCopyConstructor() && 8775 "unexpected sort of implicit constructor"); 8776 return oc_implicit_copy_constructor; 8777 } 8778 8779 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8780 // This actually gets spelled 'candidate function' for now, but 8781 // it doesn't hurt to split it out. 8782 if (!Meth->isImplicit()) 8783 return isTemplate ? oc_method_template : oc_method; 8784 8785 if (Meth->isMoveAssignmentOperator()) 8786 return oc_implicit_move_assignment; 8787 8788 if (Meth->isCopyAssignmentOperator()) 8789 return oc_implicit_copy_assignment; 8790 8791 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8792 return oc_method; 8793 } 8794 8795 return isTemplate ? oc_function_template : oc_function; 8796 } 8797 8798 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8799 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8800 if (!Ctor) return; 8801 8802 Ctor = Ctor->getInheritedConstructor(); 8803 if (!Ctor) return; 8804 8805 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8806 } 8807 8808 } // end anonymous namespace 8809 8810 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8811 const FunctionDecl *FD) { 8812 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8813 bool AlwaysTrue; 8814 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8815 return false; 8816 if (!AlwaysTrue) 8817 return false; 8818 } 8819 return true; 8820 } 8821 8822 /// \brief Returns true if we can take the address of the function. 8823 /// 8824 /// \param Complain - If true, we'll emit a diagnostic 8825 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8826 /// we in overload resolution? 8827 /// \param Loc - The location of the statement we're complaining about. Ignored 8828 /// if we're not complaining, or if we're in overload resolution. 8829 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8830 bool Complain, 8831 bool InOverloadResolution, 8832 SourceLocation Loc) { 8833 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8834 if (Complain) { 8835 if (InOverloadResolution) 8836 S.Diag(FD->getLocStart(), 8837 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8838 else 8839 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8840 } 8841 return false; 8842 } 8843 8844 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8845 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8846 if (I == FD->param_end()) 8847 return true; 8848 8849 if (Complain) { 8850 // Add one to ParamNo because it's user-facing 8851 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8852 if (InOverloadResolution) 8853 S.Diag(FD->getLocation(), 8854 diag::note_ovl_candidate_has_pass_object_size_params) 8855 << ParamNo; 8856 else 8857 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8858 << FD << ParamNo; 8859 } 8860 return false; 8861 } 8862 8863 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8864 const FunctionDecl *FD) { 8865 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8866 /*InOverloadResolution=*/true, 8867 /*Loc=*/SourceLocation()); 8868 } 8869 8870 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8871 bool Complain, 8872 SourceLocation Loc) { 8873 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8874 /*InOverloadResolution=*/false, 8875 Loc); 8876 } 8877 8878 // Notes the location of an overload candidate. 8879 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8880 bool TakingAddress) { 8881 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8882 return; 8883 8884 std::string FnDesc; 8885 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8886 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8887 << (unsigned) K << FnDesc; 8888 8889 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8890 Diag(Fn->getLocation(), PD); 8891 MaybeEmitInheritedConstructorNote(*this, Fn); 8892 } 8893 8894 // Notes the location of all overload candidates designated through 8895 // OverloadedExpr 8896 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8897 bool TakingAddress) { 8898 assert(OverloadedExpr->getType() == Context.OverloadTy); 8899 8900 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8901 OverloadExpr *OvlExpr = Ovl.Expression; 8902 8903 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8904 IEnd = OvlExpr->decls_end(); 8905 I != IEnd; ++I) { 8906 if (FunctionTemplateDecl *FunTmpl = 8907 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8908 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8909 TakingAddress); 8910 } else if (FunctionDecl *Fun 8911 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8912 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8913 } 8914 } 8915 } 8916 8917 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8918 /// "lead" diagnostic; it will be given two arguments, the source and 8919 /// target types of the conversion. 8920 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8921 Sema &S, 8922 SourceLocation CaretLoc, 8923 const PartialDiagnostic &PDiag) const { 8924 S.Diag(CaretLoc, PDiag) 8925 << Ambiguous.getFromType() << Ambiguous.getToType(); 8926 // FIXME: The note limiting machinery is borrowed from 8927 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8928 // refactoring here. 8929 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8930 unsigned CandsShown = 0; 8931 AmbiguousConversionSequence::const_iterator I, E; 8932 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8933 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8934 break; 8935 ++CandsShown; 8936 S.NoteOverloadCandidate(*I); 8937 } 8938 if (I != E) 8939 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8940 } 8941 8942 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8943 unsigned I, bool TakingCandidateAddress) { 8944 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8945 assert(Conv.isBad()); 8946 assert(Cand->Function && "for now, candidate must be a function"); 8947 FunctionDecl *Fn = Cand->Function; 8948 8949 // There's a conversion slot for the object argument if this is a 8950 // non-constructor method. Note that 'I' corresponds the 8951 // conversion-slot index. 8952 bool isObjectArgument = false; 8953 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8954 if (I == 0) 8955 isObjectArgument = true; 8956 else 8957 I--; 8958 } 8959 8960 std::string FnDesc; 8961 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8962 8963 Expr *FromExpr = Conv.Bad.FromExpr; 8964 QualType FromTy = Conv.Bad.getFromType(); 8965 QualType ToTy = Conv.Bad.getToType(); 8966 8967 if (FromTy == S.Context.OverloadTy) { 8968 assert(FromExpr && "overload set argument came from implicit argument?"); 8969 Expr *E = FromExpr->IgnoreParens(); 8970 if (isa<UnaryOperator>(E)) 8971 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8972 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8973 8974 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8975 << (unsigned) FnKind << FnDesc 8976 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8977 << ToTy << Name << I+1; 8978 MaybeEmitInheritedConstructorNote(S, Fn); 8979 return; 8980 } 8981 8982 // Do some hand-waving analysis to see if the non-viability is due 8983 // to a qualifier mismatch. 8984 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8985 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8986 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8987 CToTy = RT->getPointeeType(); 8988 else { 8989 // TODO: detect and diagnose the full richness of const mismatches. 8990 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8991 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8992 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8993 } 8994 8995 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8996 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8997 Qualifiers FromQs = CFromTy.getQualifiers(); 8998 Qualifiers ToQs = CToTy.getQualifiers(); 8999 9000 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9002 << (unsigned) FnKind << FnDesc 9003 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9004 << FromTy 9005 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9006 << (unsigned) isObjectArgument << I+1; 9007 MaybeEmitInheritedConstructorNote(S, Fn); 9008 return; 9009 } 9010 9011 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9012 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9013 << (unsigned) FnKind << FnDesc 9014 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9015 << FromTy 9016 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9017 << (unsigned) isObjectArgument << I+1; 9018 MaybeEmitInheritedConstructorNote(S, Fn); 9019 return; 9020 } 9021 9022 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9023 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9024 << (unsigned) FnKind << FnDesc 9025 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9026 << FromTy 9027 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9028 << (unsigned) isObjectArgument << I+1; 9029 MaybeEmitInheritedConstructorNote(S, Fn); 9030 return; 9031 } 9032 9033 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9034 assert(CVR && "unexpected qualifiers mismatch"); 9035 9036 if (isObjectArgument) { 9037 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9038 << (unsigned) FnKind << FnDesc 9039 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9040 << FromTy << (CVR - 1); 9041 } else { 9042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9043 << (unsigned) FnKind << FnDesc 9044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9045 << FromTy << (CVR - 1) << I+1; 9046 } 9047 MaybeEmitInheritedConstructorNote(S, Fn); 9048 return; 9049 } 9050 9051 // Special diagnostic for failure to convert an initializer list, since 9052 // telling the user that it has type void is not useful. 9053 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9055 << (unsigned) FnKind << FnDesc 9056 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9057 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9058 MaybeEmitInheritedConstructorNote(S, Fn); 9059 return; 9060 } 9061 9062 // Diagnose references or pointers to incomplete types differently, 9063 // since it's far from impossible that the incompleteness triggered 9064 // the failure. 9065 QualType TempFromTy = FromTy.getNonReferenceType(); 9066 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9067 TempFromTy = PTy->getPointeeType(); 9068 if (TempFromTy->isIncompleteType()) { 9069 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9070 << (unsigned) FnKind << FnDesc 9071 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9072 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9073 MaybeEmitInheritedConstructorNote(S, Fn); 9074 return; 9075 } 9076 9077 // Diagnose base -> derived pointer conversions. 9078 unsigned BaseToDerivedConversion = 0; 9079 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9080 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9081 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9082 FromPtrTy->getPointeeType()) && 9083 !FromPtrTy->getPointeeType()->isIncompleteType() && 9084 !ToPtrTy->getPointeeType()->isIncompleteType() && 9085 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9086 FromPtrTy->getPointeeType())) 9087 BaseToDerivedConversion = 1; 9088 } 9089 } else if (const ObjCObjectPointerType *FromPtrTy 9090 = FromTy->getAs<ObjCObjectPointerType>()) { 9091 if (const ObjCObjectPointerType *ToPtrTy 9092 = ToTy->getAs<ObjCObjectPointerType>()) 9093 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9094 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9095 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9096 FromPtrTy->getPointeeType()) && 9097 FromIface->isSuperClassOf(ToIface)) 9098 BaseToDerivedConversion = 2; 9099 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9100 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9101 !FromTy->isIncompleteType() && 9102 !ToRefTy->getPointeeType()->isIncompleteType() && 9103 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9104 BaseToDerivedConversion = 3; 9105 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9106 ToTy.getNonReferenceType().getCanonicalType() == 9107 FromTy.getNonReferenceType().getCanonicalType()) { 9108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9109 << (unsigned) FnKind << FnDesc 9110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9111 << (unsigned) isObjectArgument << I + 1; 9112 MaybeEmitInheritedConstructorNote(S, Fn); 9113 return; 9114 } 9115 } 9116 9117 if (BaseToDerivedConversion) { 9118 S.Diag(Fn->getLocation(), 9119 diag::note_ovl_candidate_bad_base_to_derived_conv) 9120 << (unsigned) FnKind << FnDesc 9121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9122 << (BaseToDerivedConversion - 1) 9123 << FromTy << ToTy << I+1; 9124 MaybeEmitInheritedConstructorNote(S, Fn); 9125 return; 9126 } 9127 9128 if (isa<ObjCObjectPointerType>(CFromTy) && 9129 isa<PointerType>(CToTy)) { 9130 Qualifiers FromQs = CFromTy.getQualifiers(); 9131 Qualifiers ToQs = CToTy.getQualifiers(); 9132 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9134 << (unsigned) FnKind << FnDesc 9135 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9136 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9137 MaybeEmitInheritedConstructorNote(S, Fn); 9138 return; 9139 } 9140 } 9141 9142 if (TakingCandidateAddress && 9143 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9144 return; 9145 9146 // Emit the generic diagnostic and, optionally, add the hints to it. 9147 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9148 FDiag << (unsigned) FnKind << FnDesc 9149 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9150 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9151 << (unsigned) (Cand->Fix.Kind); 9152 9153 // If we can fix the conversion, suggest the FixIts. 9154 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9155 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9156 FDiag << *HI; 9157 S.Diag(Fn->getLocation(), FDiag); 9158 9159 MaybeEmitInheritedConstructorNote(S, Fn); 9160 } 9161 9162 /// Additional arity mismatch diagnosis specific to a function overload 9163 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9164 /// over a candidate in any candidate set. 9165 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9166 unsigned NumArgs) { 9167 FunctionDecl *Fn = Cand->Function; 9168 unsigned MinParams = Fn->getMinRequiredArguments(); 9169 9170 // With invalid overloaded operators, it's possible that we think we 9171 // have an arity mismatch when in fact it looks like we have the 9172 // right number of arguments, because only overloaded operators have 9173 // the weird behavior of overloading member and non-member functions. 9174 // Just don't report anything. 9175 if (Fn->isInvalidDecl() && 9176 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9177 return true; 9178 9179 if (NumArgs < MinParams) { 9180 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9181 (Cand->FailureKind == ovl_fail_bad_deduction && 9182 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9183 } else { 9184 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9185 (Cand->FailureKind == ovl_fail_bad_deduction && 9186 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9187 } 9188 9189 return false; 9190 } 9191 9192 /// General arity mismatch diagnosis over a candidate in a candidate set. 9193 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9194 assert(isa<FunctionDecl>(D) && 9195 "The templated declaration should at least be a function" 9196 " when diagnosing bad template argument deduction due to too many" 9197 " or too few arguments"); 9198 9199 FunctionDecl *Fn = cast<FunctionDecl>(D); 9200 9201 // TODO: treat calls to a missing default constructor as a special case 9202 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9203 unsigned MinParams = Fn->getMinRequiredArguments(); 9204 9205 // at least / at most / exactly 9206 unsigned mode, modeCount; 9207 if (NumFormalArgs < MinParams) { 9208 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9209 FnTy->isTemplateVariadic()) 9210 mode = 0; // "at least" 9211 else 9212 mode = 2; // "exactly" 9213 modeCount = MinParams; 9214 } else { 9215 if (MinParams != FnTy->getNumParams()) 9216 mode = 1; // "at most" 9217 else 9218 mode = 2; // "exactly" 9219 modeCount = FnTy->getNumParams(); 9220 } 9221 9222 std::string Description; 9223 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9224 9225 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9226 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9227 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9228 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9229 else 9230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9231 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9232 << mode << modeCount << NumFormalArgs; 9233 MaybeEmitInheritedConstructorNote(S, Fn); 9234 } 9235 9236 /// Arity mismatch diagnosis specific to a function overload candidate. 9237 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9238 unsigned NumFormalArgs) { 9239 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9240 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9241 } 9242 9243 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9245 return FD->getDescribedFunctionTemplate(); 9246 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9247 return RD->getDescribedClassTemplate(); 9248 9249 llvm_unreachable("Unsupported: Getting the described template declaration" 9250 " for bad deduction diagnosis"); 9251 } 9252 9253 /// Diagnose a failed template-argument deduction. 9254 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9255 DeductionFailureInfo &DeductionFailure, 9256 unsigned NumArgs, 9257 bool TakingCandidateAddress) { 9258 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9259 NamedDecl *ParamD; 9260 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9261 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9262 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9263 switch (DeductionFailure.Result) { 9264 case Sema::TDK_Success: 9265 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9266 9267 case Sema::TDK_Incomplete: { 9268 assert(ParamD && "no parameter found for incomplete deduction result"); 9269 S.Diag(Templated->getLocation(), 9270 diag::note_ovl_candidate_incomplete_deduction) 9271 << ParamD->getDeclName(); 9272 MaybeEmitInheritedConstructorNote(S, Templated); 9273 return; 9274 } 9275 9276 case Sema::TDK_Underqualified: { 9277 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9278 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9279 9280 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9281 9282 // Param will have been canonicalized, but it should just be a 9283 // qualified version of ParamD, so move the qualifiers to that. 9284 QualifierCollector Qs; 9285 Qs.strip(Param); 9286 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9287 assert(S.Context.hasSameType(Param, NonCanonParam)); 9288 9289 // Arg has also been canonicalized, but there's nothing we can do 9290 // about that. It also doesn't matter as much, because it won't 9291 // have any template parameters in it (because deduction isn't 9292 // done on dependent types). 9293 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9294 9295 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9296 << ParamD->getDeclName() << Arg << NonCanonParam; 9297 MaybeEmitInheritedConstructorNote(S, Templated); 9298 return; 9299 } 9300 9301 case Sema::TDK_Inconsistent: { 9302 assert(ParamD && "no parameter found for inconsistent deduction result"); 9303 int which = 0; 9304 if (isa<TemplateTypeParmDecl>(ParamD)) 9305 which = 0; 9306 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9307 which = 1; 9308 else { 9309 which = 2; 9310 } 9311 9312 S.Diag(Templated->getLocation(), 9313 diag::note_ovl_candidate_inconsistent_deduction) 9314 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9315 << *DeductionFailure.getSecondArg(); 9316 MaybeEmitInheritedConstructorNote(S, Templated); 9317 return; 9318 } 9319 9320 case Sema::TDK_InvalidExplicitArguments: 9321 assert(ParamD && "no parameter found for invalid explicit arguments"); 9322 if (ParamD->getDeclName()) 9323 S.Diag(Templated->getLocation(), 9324 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9325 << ParamD->getDeclName(); 9326 else { 9327 int index = 0; 9328 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9329 index = TTP->getIndex(); 9330 else if (NonTypeTemplateParmDecl *NTTP 9331 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9332 index = NTTP->getIndex(); 9333 else 9334 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9335 S.Diag(Templated->getLocation(), 9336 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9337 << (index + 1); 9338 } 9339 MaybeEmitInheritedConstructorNote(S, Templated); 9340 return; 9341 9342 case Sema::TDK_TooManyArguments: 9343 case Sema::TDK_TooFewArguments: 9344 DiagnoseArityMismatch(S, Templated, NumArgs); 9345 return; 9346 9347 case Sema::TDK_InstantiationDepth: 9348 S.Diag(Templated->getLocation(), 9349 diag::note_ovl_candidate_instantiation_depth); 9350 MaybeEmitInheritedConstructorNote(S, Templated); 9351 return; 9352 9353 case Sema::TDK_SubstitutionFailure: { 9354 // Format the template argument list into the argument string. 9355 SmallString<128> TemplateArgString; 9356 if (TemplateArgumentList *Args = 9357 DeductionFailure.getTemplateArgumentList()) { 9358 TemplateArgString = " "; 9359 TemplateArgString += S.getTemplateArgumentBindingsText( 9360 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9361 } 9362 9363 // If this candidate was disabled by enable_if, say so. 9364 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9365 if (PDiag && PDiag->second.getDiagID() == 9366 diag::err_typename_nested_not_found_enable_if) { 9367 // FIXME: Use the source range of the condition, and the fully-qualified 9368 // name of the enable_if template. These are both present in PDiag. 9369 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9370 << "'enable_if'" << TemplateArgString; 9371 return; 9372 } 9373 9374 // Format the SFINAE diagnostic into the argument string. 9375 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9376 // formatted message in another diagnostic. 9377 SmallString<128> SFINAEArgString; 9378 SourceRange R; 9379 if (PDiag) { 9380 SFINAEArgString = ": "; 9381 R = SourceRange(PDiag->first, PDiag->first); 9382 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9383 } 9384 9385 S.Diag(Templated->getLocation(), 9386 diag::note_ovl_candidate_substitution_failure) 9387 << TemplateArgString << SFINAEArgString << R; 9388 MaybeEmitInheritedConstructorNote(S, Templated); 9389 return; 9390 } 9391 9392 case Sema::TDK_FailedOverloadResolution: { 9393 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9394 S.Diag(Templated->getLocation(), 9395 diag::note_ovl_candidate_failed_overload_resolution) 9396 << R.Expression->getName(); 9397 return; 9398 } 9399 9400 case Sema::TDK_NonDeducedMismatch: { 9401 // FIXME: Provide a source location to indicate what we couldn't match. 9402 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9403 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9404 if (FirstTA.getKind() == TemplateArgument::Template && 9405 SecondTA.getKind() == TemplateArgument::Template) { 9406 TemplateName FirstTN = FirstTA.getAsTemplate(); 9407 TemplateName SecondTN = SecondTA.getAsTemplate(); 9408 if (FirstTN.getKind() == TemplateName::Template && 9409 SecondTN.getKind() == TemplateName::Template) { 9410 if (FirstTN.getAsTemplateDecl()->getName() == 9411 SecondTN.getAsTemplateDecl()->getName()) { 9412 // FIXME: This fixes a bad diagnostic where both templates are named 9413 // the same. This particular case is a bit difficult since: 9414 // 1) It is passed as a string to the diagnostic printer. 9415 // 2) The diagnostic printer only attempts to find a better 9416 // name for types, not decls. 9417 // Ideally, this should folded into the diagnostic printer. 9418 S.Diag(Templated->getLocation(), 9419 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9420 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9421 return; 9422 } 9423 } 9424 } 9425 9426 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9427 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9428 return; 9429 9430 // FIXME: For generic lambda parameters, check if the function is a lambda 9431 // call operator, and if so, emit a prettier and more informative 9432 // diagnostic that mentions 'auto' and lambda in addition to 9433 // (or instead of?) the canonical template type parameters. 9434 S.Diag(Templated->getLocation(), 9435 diag::note_ovl_candidate_non_deduced_mismatch) 9436 << FirstTA << SecondTA; 9437 return; 9438 } 9439 // TODO: diagnose these individually, then kill off 9440 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9441 case Sema::TDK_MiscellaneousDeductionFailure: 9442 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9443 MaybeEmitInheritedConstructorNote(S, Templated); 9444 return; 9445 } 9446 } 9447 9448 /// Diagnose a failed template-argument deduction, for function calls. 9449 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9450 unsigned NumArgs, 9451 bool TakingCandidateAddress) { 9452 unsigned TDK = Cand->DeductionFailure.Result; 9453 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9454 if (CheckArityMismatch(S, Cand, NumArgs)) 9455 return; 9456 } 9457 DiagnoseBadDeduction(S, Cand->Function, // pattern 9458 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9459 } 9460 9461 /// CUDA: diagnose an invalid call across targets. 9462 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9463 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9464 FunctionDecl *Callee = Cand->Function; 9465 9466 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9467 CalleeTarget = S.IdentifyCUDATarget(Callee); 9468 9469 std::string FnDesc; 9470 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9471 9472 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9473 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9474 9475 // This could be an implicit constructor for which we could not infer the 9476 // target due to a collsion. Diagnose that case. 9477 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9478 if (Meth != nullptr && Meth->isImplicit()) { 9479 CXXRecordDecl *ParentClass = Meth->getParent(); 9480 Sema::CXXSpecialMember CSM; 9481 9482 switch (FnKind) { 9483 default: 9484 return; 9485 case oc_implicit_default_constructor: 9486 CSM = Sema::CXXDefaultConstructor; 9487 break; 9488 case oc_implicit_copy_constructor: 9489 CSM = Sema::CXXCopyConstructor; 9490 break; 9491 case oc_implicit_move_constructor: 9492 CSM = Sema::CXXMoveConstructor; 9493 break; 9494 case oc_implicit_copy_assignment: 9495 CSM = Sema::CXXCopyAssignment; 9496 break; 9497 case oc_implicit_move_assignment: 9498 CSM = Sema::CXXMoveAssignment; 9499 break; 9500 }; 9501 9502 bool ConstRHS = false; 9503 if (Meth->getNumParams()) { 9504 if (const ReferenceType *RT = 9505 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9506 ConstRHS = RT->getPointeeType().isConstQualified(); 9507 } 9508 } 9509 9510 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9511 /* ConstRHS */ ConstRHS, 9512 /* Diagnose */ true); 9513 } 9514 } 9515 9516 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9517 FunctionDecl *Callee = Cand->Function; 9518 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9519 9520 S.Diag(Callee->getLocation(), 9521 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9522 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9523 } 9524 9525 /// Generates a 'note' diagnostic for an overload candidate. We've 9526 /// already generated a primary error at the call site. 9527 /// 9528 /// It really does need to be a single diagnostic with its caret 9529 /// pointed at the candidate declaration. Yes, this creates some 9530 /// major challenges of technical writing. Yes, this makes pointing 9531 /// out problems with specific arguments quite awkward. It's still 9532 /// better than generating twenty screens of text for every failed 9533 /// overload. 9534 /// 9535 /// It would be great to be able to express per-candidate problems 9536 /// more richly for those diagnostic clients that cared, but we'd 9537 /// still have to be just as careful with the default diagnostics. 9538 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9539 unsigned NumArgs, 9540 bool TakingCandidateAddress) { 9541 FunctionDecl *Fn = Cand->Function; 9542 9543 // Note deleted candidates, but only if they're viable. 9544 if (Cand->Viable && (Fn->isDeleted() || 9545 S.isFunctionConsideredUnavailable(Fn))) { 9546 std::string FnDesc; 9547 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9548 9549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9550 << FnKind << FnDesc 9551 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9552 MaybeEmitInheritedConstructorNote(S, Fn); 9553 return; 9554 } 9555 9556 // We don't really have anything else to say about viable candidates. 9557 if (Cand->Viable) { 9558 S.NoteOverloadCandidate(Fn); 9559 return; 9560 } 9561 9562 switch (Cand->FailureKind) { 9563 case ovl_fail_too_many_arguments: 9564 case ovl_fail_too_few_arguments: 9565 return DiagnoseArityMismatch(S, Cand, NumArgs); 9566 9567 case ovl_fail_bad_deduction: 9568 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9569 9570 case ovl_fail_illegal_constructor: { 9571 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9572 << (Fn->getPrimaryTemplate() ? 1 : 0); 9573 MaybeEmitInheritedConstructorNote(S, Fn); 9574 return; 9575 } 9576 9577 case ovl_fail_trivial_conversion: 9578 case ovl_fail_bad_final_conversion: 9579 case ovl_fail_final_conversion_not_exact: 9580 return S.NoteOverloadCandidate(Fn); 9581 9582 case ovl_fail_bad_conversion: { 9583 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9584 for (unsigned N = Cand->NumConversions; I != N; ++I) 9585 if (Cand->Conversions[I].isBad()) 9586 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9587 9588 // FIXME: this currently happens when we're called from SemaInit 9589 // when user-conversion overload fails. Figure out how to handle 9590 // those conditions and diagnose them well. 9591 return S.NoteOverloadCandidate(Fn); 9592 } 9593 9594 case ovl_fail_bad_target: 9595 return DiagnoseBadTarget(S, Cand); 9596 9597 case ovl_fail_enable_if: 9598 return DiagnoseFailedEnableIfAttr(S, Cand); 9599 } 9600 } 9601 9602 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9603 // Desugar the type of the surrogate down to a function type, 9604 // retaining as many typedefs as possible while still showing 9605 // the function type (and, therefore, its parameter types). 9606 QualType FnType = Cand->Surrogate->getConversionType(); 9607 bool isLValueReference = false; 9608 bool isRValueReference = false; 9609 bool isPointer = false; 9610 if (const LValueReferenceType *FnTypeRef = 9611 FnType->getAs<LValueReferenceType>()) { 9612 FnType = FnTypeRef->getPointeeType(); 9613 isLValueReference = true; 9614 } else if (const RValueReferenceType *FnTypeRef = 9615 FnType->getAs<RValueReferenceType>()) { 9616 FnType = FnTypeRef->getPointeeType(); 9617 isRValueReference = true; 9618 } 9619 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9620 FnType = FnTypePtr->getPointeeType(); 9621 isPointer = true; 9622 } 9623 // Desugar down to a function type. 9624 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9625 // Reconstruct the pointer/reference as appropriate. 9626 if (isPointer) FnType = S.Context.getPointerType(FnType); 9627 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9628 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9629 9630 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9631 << FnType; 9632 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9633 } 9634 9635 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9636 SourceLocation OpLoc, 9637 OverloadCandidate *Cand) { 9638 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9639 std::string TypeStr("operator"); 9640 TypeStr += Opc; 9641 TypeStr += "("; 9642 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9643 if (Cand->NumConversions == 1) { 9644 TypeStr += ")"; 9645 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9646 } else { 9647 TypeStr += ", "; 9648 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9649 TypeStr += ")"; 9650 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9651 } 9652 } 9653 9654 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9655 OverloadCandidate *Cand) { 9656 unsigned NoOperands = Cand->NumConversions; 9657 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9658 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9659 if (ICS.isBad()) break; // all meaningless after first invalid 9660 if (!ICS.isAmbiguous()) continue; 9661 9662 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9663 S.PDiag(diag::note_ambiguous_type_conversion)); 9664 } 9665 } 9666 9667 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9668 if (Cand->Function) 9669 return Cand->Function->getLocation(); 9670 if (Cand->IsSurrogate) 9671 return Cand->Surrogate->getLocation(); 9672 return SourceLocation(); 9673 } 9674 9675 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9676 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9677 case Sema::TDK_Success: 9678 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9679 9680 case Sema::TDK_Invalid: 9681 case Sema::TDK_Incomplete: 9682 return 1; 9683 9684 case Sema::TDK_Underqualified: 9685 case Sema::TDK_Inconsistent: 9686 return 2; 9687 9688 case Sema::TDK_SubstitutionFailure: 9689 case Sema::TDK_NonDeducedMismatch: 9690 case Sema::TDK_MiscellaneousDeductionFailure: 9691 return 3; 9692 9693 case Sema::TDK_InstantiationDepth: 9694 case Sema::TDK_FailedOverloadResolution: 9695 return 4; 9696 9697 case Sema::TDK_InvalidExplicitArguments: 9698 return 5; 9699 9700 case Sema::TDK_TooManyArguments: 9701 case Sema::TDK_TooFewArguments: 9702 return 6; 9703 } 9704 llvm_unreachable("Unhandled deduction result"); 9705 } 9706 9707 namespace { 9708 struct CompareOverloadCandidatesForDisplay { 9709 Sema &S; 9710 SourceLocation Loc; 9711 size_t NumArgs; 9712 9713 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9714 : S(S), NumArgs(nArgs) {} 9715 9716 bool operator()(const OverloadCandidate *L, 9717 const OverloadCandidate *R) { 9718 // Fast-path this check. 9719 if (L == R) return false; 9720 9721 // Order first by viability. 9722 if (L->Viable) { 9723 if (!R->Viable) return true; 9724 9725 // TODO: introduce a tri-valued comparison for overload 9726 // candidates. Would be more worthwhile if we had a sort 9727 // that could exploit it. 9728 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9729 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9730 } else if (R->Viable) 9731 return false; 9732 9733 assert(L->Viable == R->Viable); 9734 9735 // Criteria by which we can sort non-viable candidates: 9736 if (!L->Viable) { 9737 // 1. Arity mismatches come after other candidates. 9738 if (L->FailureKind == ovl_fail_too_many_arguments || 9739 L->FailureKind == ovl_fail_too_few_arguments) { 9740 if (R->FailureKind == ovl_fail_too_many_arguments || 9741 R->FailureKind == ovl_fail_too_few_arguments) { 9742 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9743 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9744 if (LDist == RDist) { 9745 if (L->FailureKind == R->FailureKind) 9746 // Sort non-surrogates before surrogates. 9747 return !L->IsSurrogate && R->IsSurrogate; 9748 // Sort candidates requiring fewer parameters than there were 9749 // arguments given after candidates requiring more parameters 9750 // than there were arguments given. 9751 return L->FailureKind == ovl_fail_too_many_arguments; 9752 } 9753 return LDist < RDist; 9754 } 9755 return false; 9756 } 9757 if (R->FailureKind == ovl_fail_too_many_arguments || 9758 R->FailureKind == ovl_fail_too_few_arguments) 9759 return true; 9760 9761 // 2. Bad conversions come first and are ordered by the number 9762 // of bad conversions and quality of good conversions. 9763 if (L->FailureKind == ovl_fail_bad_conversion) { 9764 if (R->FailureKind != ovl_fail_bad_conversion) 9765 return true; 9766 9767 // The conversion that can be fixed with a smaller number of changes, 9768 // comes first. 9769 unsigned numLFixes = L->Fix.NumConversionsFixed; 9770 unsigned numRFixes = R->Fix.NumConversionsFixed; 9771 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9772 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9773 if (numLFixes != numRFixes) { 9774 return numLFixes < numRFixes; 9775 } 9776 9777 // If there's any ordering between the defined conversions... 9778 // FIXME: this might not be transitive. 9779 assert(L->NumConversions == R->NumConversions); 9780 9781 int leftBetter = 0; 9782 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9783 for (unsigned E = L->NumConversions; I != E; ++I) { 9784 switch (CompareImplicitConversionSequences(S, Loc, 9785 L->Conversions[I], 9786 R->Conversions[I])) { 9787 case ImplicitConversionSequence::Better: 9788 leftBetter++; 9789 break; 9790 9791 case ImplicitConversionSequence::Worse: 9792 leftBetter--; 9793 break; 9794 9795 case ImplicitConversionSequence::Indistinguishable: 9796 break; 9797 } 9798 } 9799 if (leftBetter > 0) return true; 9800 if (leftBetter < 0) return false; 9801 9802 } else if (R->FailureKind == ovl_fail_bad_conversion) 9803 return false; 9804 9805 if (L->FailureKind == ovl_fail_bad_deduction) { 9806 if (R->FailureKind != ovl_fail_bad_deduction) 9807 return true; 9808 9809 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9810 return RankDeductionFailure(L->DeductionFailure) 9811 < RankDeductionFailure(R->DeductionFailure); 9812 } else if (R->FailureKind == ovl_fail_bad_deduction) 9813 return false; 9814 9815 // TODO: others? 9816 } 9817 9818 // Sort everything else by location. 9819 SourceLocation LLoc = GetLocationForCandidate(L); 9820 SourceLocation RLoc = GetLocationForCandidate(R); 9821 9822 // Put candidates without locations (e.g. builtins) at the end. 9823 if (LLoc.isInvalid()) return false; 9824 if (RLoc.isInvalid()) return true; 9825 9826 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9827 } 9828 }; 9829 } 9830 9831 /// CompleteNonViableCandidate - Normally, overload resolution only 9832 /// computes up to the first. Produces the FixIt set if possible. 9833 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9834 ArrayRef<Expr *> Args) { 9835 assert(!Cand->Viable); 9836 9837 // Don't do anything on failures other than bad conversion. 9838 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9839 9840 // We only want the FixIts if all the arguments can be corrected. 9841 bool Unfixable = false; 9842 // Use a implicit copy initialization to check conversion fixes. 9843 Cand->Fix.setConversionChecker(TryCopyInitialization); 9844 9845 // Skip forward to the first bad conversion. 9846 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9847 unsigned ConvCount = Cand->NumConversions; 9848 while (true) { 9849 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9850 ConvIdx++; 9851 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9852 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9853 break; 9854 } 9855 } 9856 9857 if (ConvIdx == ConvCount) 9858 return; 9859 9860 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9861 "remaining conversion is initialized?"); 9862 9863 // FIXME: this should probably be preserved from the overload 9864 // operation somehow. 9865 bool SuppressUserConversions = false; 9866 9867 const FunctionProtoType* Proto; 9868 unsigned ArgIdx = ConvIdx; 9869 9870 if (Cand->IsSurrogate) { 9871 QualType ConvType 9872 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9873 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9874 ConvType = ConvPtrType->getPointeeType(); 9875 Proto = ConvType->getAs<FunctionProtoType>(); 9876 ArgIdx--; 9877 } else if (Cand->Function) { 9878 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9879 if (isa<CXXMethodDecl>(Cand->Function) && 9880 !isa<CXXConstructorDecl>(Cand->Function)) 9881 ArgIdx--; 9882 } else { 9883 // Builtin binary operator with a bad first conversion. 9884 assert(ConvCount <= 3); 9885 for (; ConvIdx != ConvCount; ++ConvIdx) 9886 Cand->Conversions[ConvIdx] 9887 = TryCopyInitialization(S, Args[ConvIdx], 9888 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9889 SuppressUserConversions, 9890 /*InOverloadResolution*/ true, 9891 /*AllowObjCWritebackConversion=*/ 9892 S.getLangOpts().ObjCAutoRefCount); 9893 return; 9894 } 9895 9896 // Fill in the rest of the conversions. 9897 unsigned NumParams = Proto->getNumParams(); 9898 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9899 if (ArgIdx < NumParams) { 9900 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9901 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9902 /*InOverloadResolution=*/true, 9903 /*AllowObjCWritebackConversion=*/ 9904 S.getLangOpts().ObjCAutoRefCount); 9905 // Store the FixIt in the candidate if it exists. 9906 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9907 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9908 } 9909 else 9910 Cand->Conversions[ConvIdx].setEllipsis(); 9911 } 9912 } 9913 9914 /// PrintOverloadCandidates - When overload resolution fails, prints 9915 /// diagnostic messages containing the candidates in the candidate 9916 /// set. 9917 void OverloadCandidateSet::NoteCandidates(Sema &S, 9918 OverloadCandidateDisplayKind OCD, 9919 ArrayRef<Expr *> Args, 9920 StringRef Opc, 9921 SourceLocation OpLoc) { 9922 // Sort the candidates by viability and position. Sorting directly would 9923 // be prohibitive, so we make a set of pointers and sort those. 9924 SmallVector<OverloadCandidate*, 32> Cands; 9925 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9926 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9927 if (Cand->Viable) 9928 Cands.push_back(Cand); 9929 else if (OCD == OCD_AllCandidates) { 9930 CompleteNonViableCandidate(S, Cand, Args); 9931 if (Cand->Function || Cand->IsSurrogate) 9932 Cands.push_back(Cand); 9933 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9934 // want to list every possible builtin candidate. 9935 } 9936 } 9937 9938 std::sort(Cands.begin(), Cands.end(), 9939 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 9940 9941 bool ReportedAmbiguousConversions = false; 9942 9943 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9944 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9945 unsigned CandsShown = 0; 9946 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9947 OverloadCandidate *Cand = *I; 9948 9949 // Set an arbitrary limit on the number of candidate functions we'll spam 9950 // the user with. FIXME: This limit should depend on details of the 9951 // candidate list. 9952 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9953 break; 9954 } 9955 ++CandsShown; 9956 9957 if (Cand->Function) 9958 NoteFunctionCandidate(S, Cand, Args.size(), 9959 /*TakingCandidateAddress=*/false); 9960 else if (Cand->IsSurrogate) 9961 NoteSurrogateCandidate(S, Cand); 9962 else { 9963 assert(Cand->Viable && 9964 "Non-viable built-in candidates are not added to Cands."); 9965 // Generally we only see ambiguities including viable builtin 9966 // operators if overload resolution got screwed up by an 9967 // ambiguous user-defined conversion. 9968 // 9969 // FIXME: It's quite possible for different conversions to see 9970 // different ambiguities, though. 9971 if (!ReportedAmbiguousConversions) { 9972 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9973 ReportedAmbiguousConversions = true; 9974 } 9975 9976 // If this is a viable builtin, print it. 9977 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9978 } 9979 } 9980 9981 if (I != E) 9982 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9983 } 9984 9985 static SourceLocation 9986 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9987 return Cand->Specialization ? Cand->Specialization->getLocation() 9988 : SourceLocation(); 9989 } 9990 9991 namespace { 9992 struct CompareTemplateSpecCandidatesForDisplay { 9993 Sema &S; 9994 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9995 9996 bool operator()(const TemplateSpecCandidate *L, 9997 const TemplateSpecCandidate *R) { 9998 // Fast-path this check. 9999 if (L == R) 10000 return false; 10001 10002 // Assuming that both candidates are not matches... 10003 10004 // Sort by the ranking of deduction failures. 10005 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10006 return RankDeductionFailure(L->DeductionFailure) < 10007 RankDeductionFailure(R->DeductionFailure); 10008 10009 // Sort everything else by location. 10010 SourceLocation LLoc = GetLocationForCandidate(L); 10011 SourceLocation RLoc = GetLocationForCandidate(R); 10012 10013 // Put candidates without locations (e.g. builtins) at the end. 10014 if (LLoc.isInvalid()) 10015 return false; 10016 if (RLoc.isInvalid()) 10017 return true; 10018 10019 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10020 } 10021 }; 10022 } 10023 10024 /// Diagnose a template argument deduction failure. 10025 /// We are treating these failures as overload failures due to bad 10026 /// deductions. 10027 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10028 bool ForTakingAddress) { 10029 DiagnoseBadDeduction(S, Specialization, // pattern 10030 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10031 } 10032 10033 void TemplateSpecCandidateSet::destroyCandidates() { 10034 for (iterator i = begin(), e = end(); i != e; ++i) { 10035 i->DeductionFailure.Destroy(); 10036 } 10037 } 10038 10039 void TemplateSpecCandidateSet::clear() { 10040 destroyCandidates(); 10041 Candidates.clear(); 10042 } 10043 10044 /// NoteCandidates - When no template specialization match is found, prints 10045 /// diagnostic messages containing the non-matching specializations that form 10046 /// the candidate set. 10047 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10048 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10049 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10050 // Sort the candidates by position (assuming no candidate is a match). 10051 // Sorting directly would be prohibitive, so we make a set of pointers 10052 // and sort those. 10053 SmallVector<TemplateSpecCandidate *, 32> Cands; 10054 Cands.reserve(size()); 10055 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10056 if (Cand->Specialization) 10057 Cands.push_back(Cand); 10058 // Otherwise, this is a non-matching builtin candidate. We do not, 10059 // in general, want to list every possible builtin candidate. 10060 } 10061 10062 std::sort(Cands.begin(), Cands.end(), 10063 CompareTemplateSpecCandidatesForDisplay(S)); 10064 10065 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10066 // for generalization purposes (?). 10067 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10068 10069 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10070 unsigned CandsShown = 0; 10071 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10072 TemplateSpecCandidate *Cand = *I; 10073 10074 // Set an arbitrary limit on the number of candidates we'll spam 10075 // the user with. FIXME: This limit should depend on details of the 10076 // candidate list. 10077 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10078 break; 10079 ++CandsShown; 10080 10081 assert(Cand->Specialization && 10082 "Non-matching built-in candidates are not added to Cands."); 10083 Cand->NoteDeductionFailure(S, ForTakingAddress); 10084 } 10085 10086 if (I != E) 10087 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10088 } 10089 10090 // [PossiblyAFunctionType] --> [Return] 10091 // NonFunctionType --> NonFunctionType 10092 // R (A) --> R(A) 10093 // R (*)(A) --> R (A) 10094 // R (&)(A) --> R (A) 10095 // R (S::*)(A) --> R (A) 10096 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10097 QualType Ret = PossiblyAFunctionType; 10098 if (const PointerType *ToTypePtr = 10099 PossiblyAFunctionType->getAs<PointerType>()) 10100 Ret = ToTypePtr->getPointeeType(); 10101 else if (const ReferenceType *ToTypeRef = 10102 PossiblyAFunctionType->getAs<ReferenceType>()) 10103 Ret = ToTypeRef->getPointeeType(); 10104 else if (const MemberPointerType *MemTypePtr = 10105 PossiblyAFunctionType->getAs<MemberPointerType>()) 10106 Ret = MemTypePtr->getPointeeType(); 10107 Ret = 10108 Context.getCanonicalType(Ret).getUnqualifiedType(); 10109 return Ret; 10110 } 10111 10112 namespace { 10113 // A helper class to help with address of function resolution 10114 // - allows us to avoid passing around all those ugly parameters 10115 class AddressOfFunctionResolver { 10116 Sema& S; 10117 Expr* SourceExpr; 10118 const QualType& TargetType; 10119 QualType TargetFunctionType; // Extracted function type from target type 10120 10121 bool Complain; 10122 //DeclAccessPair& ResultFunctionAccessPair; 10123 ASTContext& Context; 10124 10125 bool TargetTypeIsNonStaticMemberFunction; 10126 bool FoundNonTemplateFunction; 10127 bool StaticMemberFunctionFromBoundPointer; 10128 bool HasComplained; 10129 10130 OverloadExpr::FindResult OvlExprInfo; 10131 OverloadExpr *OvlExpr; 10132 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10133 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10134 TemplateSpecCandidateSet FailedCandidates; 10135 10136 public: 10137 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10138 const QualType &TargetType, bool Complain) 10139 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10140 Complain(Complain), Context(S.getASTContext()), 10141 TargetTypeIsNonStaticMemberFunction( 10142 !!TargetType->getAs<MemberPointerType>()), 10143 FoundNonTemplateFunction(false), 10144 StaticMemberFunctionFromBoundPointer(false), 10145 HasComplained(false), 10146 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10147 OvlExpr(OvlExprInfo.Expression), 10148 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10149 ExtractUnqualifiedFunctionTypeFromTargetType(); 10150 10151 if (TargetFunctionType->isFunctionType()) { 10152 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10153 if (!UME->isImplicitAccess() && 10154 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10155 StaticMemberFunctionFromBoundPointer = true; 10156 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10157 DeclAccessPair dap; 10158 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10159 OvlExpr, false, &dap)) { 10160 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10161 if (!Method->isStatic()) { 10162 // If the target type is a non-function type and the function found 10163 // is a non-static member function, pretend as if that was the 10164 // target, it's the only possible type to end up with. 10165 TargetTypeIsNonStaticMemberFunction = true; 10166 10167 // And skip adding the function if its not in the proper form. 10168 // We'll diagnose this due to an empty set of functions. 10169 if (!OvlExprInfo.HasFormOfMemberPointer) 10170 return; 10171 } 10172 10173 Matches.push_back(std::make_pair(dap, Fn)); 10174 } 10175 return; 10176 } 10177 10178 if (OvlExpr->hasExplicitTemplateArgs()) 10179 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 10180 10181 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10182 // C++ [over.over]p4: 10183 // If more than one function is selected, [...] 10184 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10185 if (FoundNonTemplateFunction) 10186 EliminateAllTemplateMatches(); 10187 else 10188 EliminateAllExceptMostSpecializedTemplate(); 10189 } 10190 } 10191 10192 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10193 Matches.size() > 1) 10194 EliminateSuboptimalCudaMatches(); 10195 } 10196 10197 bool hasComplained() const { return HasComplained; } 10198 10199 private: 10200 // Is A considered a better overload candidate for the desired type than B? 10201 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10202 return hasBetterEnableIfAttrs(S, A, B); 10203 } 10204 10205 // Returns true if we've eliminated any (read: all but one) candidates, false 10206 // otherwise. 10207 bool eliminiateSuboptimalOverloadCandidates() { 10208 // Same algorithm as overload resolution -- one pass to pick the "best", 10209 // another pass to be sure that nothing is better than the best. 10210 auto Best = Matches.begin(); 10211 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10212 if (isBetterCandidate(I->second, Best->second)) 10213 Best = I; 10214 10215 const FunctionDecl *BestFn = Best->second; 10216 auto IsBestOrInferiorToBest = [this, BestFn]( 10217 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10218 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10219 }; 10220 10221 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10222 // option, so we can potentially give the user a better error 10223 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10224 return false; 10225 Matches[0] = *Best; 10226 Matches.resize(1); 10227 return true; 10228 } 10229 10230 bool isTargetTypeAFunction() const { 10231 return TargetFunctionType->isFunctionType(); 10232 } 10233 10234 // [ToType] [Return] 10235 10236 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10237 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10238 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10239 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10240 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10241 } 10242 10243 // return true if any matching specializations were found 10244 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10245 const DeclAccessPair& CurAccessFunPair) { 10246 if (CXXMethodDecl *Method 10247 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10248 // Skip non-static function templates when converting to pointer, and 10249 // static when converting to member pointer. 10250 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10251 return false; 10252 } 10253 else if (TargetTypeIsNonStaticMemberFunction) 10254 return false; 10255 10256 // C++ [over.over]p2: 10257 // If the name is a function template, template argument deduction is 10258 // done (14.8.2.2), and if the argument deduction succeeds, the 10259 // resulting template argument list is used to generate a single 10260 // function template specialization, which is added to the set of 10261 // overloaded functions considered. 10262 FunctionDecl *Specialization = nullptr; 10263 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10264 if (Sema::TemplateDeductionResult Result 10265 = S.DeduceTemplateArguments(FunctionTemplate, 10266 &OvlExplicitTemplateArgs, 10267 TargetFunctionType, Specialization, 10268 Info, /*InOverloadResolution=*/true)) { 10269 // Make a note of the failed deduction for diagnostics. 10270 FailedCandidates.addCandidate() 10271 .set(FunctionTemplate->getTemplatedDecl(), 10272 MakeDeductionFailureInfo(Context, Result, Info)); 10273 return false; 10274 } 10275 10276 // Template argument deduction ensures that we have an exact match or 10277 // compatible pointer-to-function arguments that would be adjusted by ICS. 10278 // This function template specicalization works. 10279 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 10280 assert(S.isSameOrCompatibleFunctionType( 10281 Context.getCanonicalType(Specialization->getType()), 10282 Context.getCanonicalType(TargetFunctionType))); 10283 10284 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10285 return false; 10286 10287 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10288 return true; 10289 } 10290 10291 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10292 const DeclAccessPair& CurAccessFunPair) { 10293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10294 // Skip non-static functions when converting to pointer, and static 10295 // when converting to member pointer. 10296 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10297 return false; 10298 } 10299 else if (TargetTypeIsNonStaticMemberFunction) 10300 return false; 10301 10302 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10303 if (S.getLangOpts().CUDA) 10304 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10305 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10306 return false; 10307 10308 // If any candidate has a placeholder return type, trigger its deduction 10309 // now. 10310 if (S.getLangOpts().CPlusPlus14 && 10311 FunDecl->getReturnType()->isUndeducedType() && 10312 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10313 HasComplained |= Complain; 10314 return false; 10315 } 10316 10317 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10318 return false; 10319 10320 QualType ResultTy; 10321 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10322 FunDecl->getType()) || 10323 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10324 ResultTy) || 10325 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10326 Matches.push_back(std::make_pair( 10327 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10328 FoundNonTemplateFunction = true; 10329 return true; 10330 } 10331 } 10332 10333 return false; 10334 } 10335 10336 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10337 bool Ret = false; 10338 10339 // If the overload expression doesn't have the form of a pointer to 10340 // member, don't try to convert it to a pointer-to-member type. 10341 if (IsInvalidFormOfPointerToMemberFunction()) 10342 return false; 10343 10344 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10345 E = OvlExpr->decls_end(); 10346 I != E; ++I) { 10347 // Look through any using declarations to find the underlying function. 10348 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10349 10350 // C++ [over.over]p3: 10351 // Non-member functions and static member functions match 10352 // targets of type "pointer-to-function" or "reference-to-function." 10353 // Nonstatic member functions match targets of 10354 // type "pointer-to-member-function." 10355 // Note that according to DR 247, the containing class does not matter. 10356 if (FunctionTemplateDecl *FunctionTemplate 10357 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10358 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10359 Ret = true; 10360 } 10361 // If we have explicit template arguments supplied, skip non-templates. 10362 else if (!OvlExpr->hasExplicitTemplateArgs() && 10363 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10364 Ret = true; 10365 } 10366 assert(Ret || Matches.empty()); 10367 return Ret; 10368 } 10369 10370 void EliminateAllExceptMostSpecializedTemplate() { 10371 // [...] and any given function template specialization F1 is 10372 // eliminated if the set contains a second function template 10373 // specialization whose function template is more specialized 10374 // than the function template of F1 according to the partial 10375 // ordering rules of 14.5.5.2. 10376 10377 // The algorithm specified above is quadratic. We instead use a 10378 // two-pass algorithm (similar to the one used to identify the 10379 // best viable function in an overload set) that identifies the 10380 // best function template (if it exists). 10381 10382 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10383 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10384 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10385 10386 // TODO: It looks like FailedCandidates does not serve much purpose 10387 // here, since the no_viable diagnostic has index 0. 10388 UnresolvedSetIterator Result = S.getMostSpecialized( 10389 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10390 SourceExpr->getLocStart(), S.PDiag(), 10391 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10392 .second->getDeclName(), 10393 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10394 Complain, TargetFunctionType); 10395 10396 if (Result != MatchesCopy.end()) { 10397 // Make it the first and only element 10398 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10399 Matches[0].second = cast<FunctionDecl>(*Result); 10400 Matches.resize(1); 10401 } else 10402 HasComplained |= Complain; 10403 } 10404 10405 void EliminateAllTemplateMatches() { 10406 // [...] any function template specializations in the set are 10407 // eliminated if the set also contains a non-template function, [...] 10408 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10409 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10410 ++I; 10411 else { 10412 Matches[I] = Matches[--N]; 10413 Matches.resize(N); 10414 } 10415 } 10416 } 10417 10418 void EliminateSuboptimalCudaMatches() { 10419 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10420 } 10421 10422 public: 10423 void ComplainNoMatchesFound() const { 10424 assert(Matches.empty()); 10425 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10426 << OvlExpr->getName() << TargetFunctionType 10427 << OvlExpr->getSourceRange(); 10428 if (FailedCandidates.empty()) 10429 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10430 /*TakingAddress=*/true); 10431 else { 10432 // We have some deduction failure messages. Use them to diagnose 10433 // the function templates, and diagnose the non-template candidates 10434 // normally. 10435 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10436 IEnd = OvlExpr->decls_end(); 10437 I != IEnd; ++I) 10438 if (FunctionDecl *Fun = 10439 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10440 if (!functionHasPassObjectSizeParams(Fun)) 10441 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10442 /*TakingAddress=*/true); 10443 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10444 } 10445 } 10446 10447 bool IsInvalidFormOfPointerToMemberFunction() const { 10448 return TargetTypeIsNonStaticMemberFunction && 10449 !OvlExprInfo.HasFormOfMemberPointer; 10450 } 10451 10452 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10453 // TODO: Should we condition this on whether any functions might 10454 // have matched, or is it more appropriate to do that in callers? 10455 // TODO: a fixit wouldn't hurt. 10456 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10457 << TargetType << OvlExpr->getSourceRange(); 10458 } 10459 10460 bool IsStaticMemberFunctionFromBoundPointer() const { 10461 return StaticMemberFunctionFromBoundPointer; 10462 } 10463 10464 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10465 S.Diag(OvlExpr->getLocStart(), 10466 diag::err_invalid_form_pointer_member_function) 10467 << OvlExpr->getSourceRange(); 10468 } 10469 10470 void ComplainOfInvalidConversion() const { 10471 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10472 << OvlExpr->getName() << TargetType; 10473 } 10474 10475 void ComplainMultipleMatchesFound() const { 10476 assert(Matches.size() > 1); 10477 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10478 << OvlExpr->getName() 10479 << OvlExpr->getSourceRange(); 10480 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10481 /*TakingAddress=*/true); 10482 } 10483 10484 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10485 10486 int getNumMatches() const { return Matches.size(); } 10487 10488 FunctionDecl* getMatchingFunctionDecl() const { 10489 if (Matches.size() != 1) return nullptr; 10490 return Matches[0].second; 10491 } 10492 10493 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10494 if (Matches.size() != 1) return nullptr; 10495 return &Matches[0].first; 10496 } 10497 }; 10498 } 10499 10500 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10501 /// an overloaded function (C++ [over.over]), where @p From is an 10502 /// expression with overloaded function type and @p ToType is the type 10503 /// we're trying to resolve to. For example: 10504 /// 10505 /// @code 10506 /// int f(double); 10507 /// int f(int); 10508 /// 10509 /// int (*pfd)(double) = f; // selects f(double) 10510 /// @endcode 10511 /// 10512 /// This routine returns the resulting FunctionDecl if it could be 10513 /// resolved, and NULL otherwise. When @p Complain is true, this 10514 /// routine will emit diagnostics if there is an error. 10515 FunctionDecl * 10516 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10517 QualType TargetType, 10518 bool Complain, 10519 DeclAccessPair &FoundResult, 10520 bool *pHadMultipleCandidates) { 10521 assert(AddressOfExpr->getType() == Context.OverloadTy); 10522 10523 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10524 Complain); 10525 int NumMatches = Resolver.getNumMatches(); 10526 FunctionDecl *Fn = nullptr; 10527 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10528 if (NumMatches == 0 && ShouldComplain) { 10529 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10530 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10531 else 10532 Resolver.ComplainNoMatchesFound(); 10533 } 10534 else if (NumMatches > 1 && ShouldComplain) 10535 Resolver.ComplainMultipleMatchesFound(); 10536 else if (NumMatches == 1) { 10537 Fn = Resolver.getMatchingFunctionDecl(); 10538 assert(Fn); 10539 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10540 if (Complain) { 10541 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10542 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10543 else 10544 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10545 } 10546 } 10547 10548 if (pHadMultipleCandidates) 10549 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10550 return Fn; 10551 } 10552 10553 /// \brief Given an expression that refers to an overloaded function, try to 10554 /// resolve that overloaded function expression down to a single function. 10555 /// 10556 /// This routine can only resolve template-ids that refer to a single function 10557 /// template, where that template-id refers to a single template whose template 10558 /// arguments are either provided by the template-id or have defaults, 10559 /// as described in C++0x [temp.arg.explicit]p3. 10560 /// 10561 /// If no template-ids are found, no diagnostics are emitted and NULL is 10562 /// returned. 10563 FunctionDecl * 10564 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10565 bool Complain, 10566 DeclAccessPair *FoundResult) { 10567 // C++ [over.over]p1: 10568 // [...] [Note: any redundant set of parentheses surrounding the 10569 // overloaded function name is ignored (5.1). ] 10570 // C++ [over.over]p1: 10571 // [...] The overloaded function name can be preceded by the & 10572 // operator. 10573 10574 // If we didn't actually find any template-ids, we're done. 10575 if (!ovl->hasExplicitTemplateArgs()) 10576 return nullptr; 10577 10578 TemplateArgumentListInfo ExplicitTemplateArgs; 10579 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10580 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10581 10582 // Look through all of the overloaded functions, searching for one 10583 // whose type matches exactly. 10584 FunctionDecl *Matched = nullptr; 10585 for (UnresolvedSetIterator I = ovl->decls_begin(), 10586 E = ovl->decls_end(); I != E; ++I) { 10587 // C++0x [temp.arg.explicit]p3: 10588 // [...] In contexts where deduction is done and fails, or in contexts 10589 // where deduction is not done, if a template argument list is 10590 // specified and it, along with any default template arguments, 10591 // identifies a single function template specialization, then the 10592 // template-id is an lvalue for the function template specialization. 10593 FunctionTemplateDecl *FunctionTemplate 10594 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10595 10596 // C++ [over.over]p2: 10597 // If the name is a function template, template argument deduction is 10598 // done (14.8.2.2), and if the argument deduction succeeds, the 10599 // resulting template argument list is used to generate a single 10600 // function template specialization, which is added to the set of 10601 // overloaded functions considered. 10602 FunctionDecl *Specialization = nullptr; 10603 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10604 if (TemplateDeductionResult Result 10605 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10606 Specialization, Info, 10607 /*InOverloadResolution=*/true)) { 10608 // Make a note of the failed deduction for diagnostics. 10609 // TODO: Actually use the failed-deduction info? 10610 FailedCandidates.addCandidate() 10611 .set(FunctionTemplate->getTemplatedDecl(), 10612 MakeDeductionFailureInfo(Context, Result, Info)); 10613 continue; 10614 } 10615 10616 assert(Specialization && "no specialization and no error?"); 10617 10618 // Multiple matches; we can't resolve to a single declaration. 10619 if (Matched) { 10620 if (Complain) { 10621 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10622 << ovl->getName(); 10623 NoteAllOverloadCandidates(ovl); 10624 } 10625 return nullptr; 10626 } 10627 10628 Matched = Specialization; 10629 if (FoundResult) *FoundResult = I.getPair(); 10630 } 10631 10632 if (Matched && getLangOpts().CPlusPlus14 && 10633 Matched->getReturnType()->isUndeducedType() && 10634 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10635 return nullptr; 10636 10637 return Matched; 10638 } 10639 10640 10641 10642 10643 // Resolve and fix an overloaded expression that can be resolved 10644 // because it identifies a single function template specialization. 10645 // 10646 // Last three arguments should only be supplied if Complain = true 10647 // 10648 // Return true if it was logically possible to so resolve the 10649 // expression, regardless of whether or not it succeeded. Always 10650 // returns true if 'complain' is set. 10651 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10652 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10653 bool complain, SourceRange OpRangeForComplaining, 10654 QualType DestTypeForComplaining, 10655 unsigned DiagIDForComplaining) { 10656 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10657 10658 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10659 10660 DeclAccessPair found; 10661 ExprResult SingleFunctionExpression; 10662 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10663 ovl.Expression, /*complain*/ false, &found)) { 10664 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10665 SrcExpr = ExprError(); 10666 return true; 10667 } 10668 10669 // It is only correct to resolve to an instance method if we're 10670 // resolving a form that's permitted to be a pointer to member. 10671 // Otherwise we'll end up making a bound member expression, which 10672 // is illegal in all the contexts we resolve like this. 10673 if (!ovl.HasFormOfMemberPointer && 10674 isa<CXXMethodDecl>(fn) && 10675 cast<CXXMethodDecl>(fn)->isInstance()) { 10676 if (!complain) return false; 10677 10678 Diag(ovl.Expression->getExprLoc(), 10679 diag::err_bound_member_function) 10680 << 0 << ovl.Expression->getSourceRange(); 10681 10682 // TODO: I believe we only end up here if there's a mix of 10683 // static and non-static candidates (otherwise the expression 10684 // would have 'bound member' type, not 'overload' type). 10685 // Ideally we would note which candidate was chosen and why 10686 // the static candidates were rejected. 10687 SrcExpr = ExprError(); 10688 return true; 10689 } 10690 10691 // Fix the expression to refer to 'fn'. 10692 SingleFunctionExpression = 10693 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10694 10695 // If desired, do function-to-pointer decay. 10696 if (doFunctionPointerConverion) { 10697 SingleFunctionExpression = 10698 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10699 if (SingleFunctionExpression.isInvalid()) { 10700 SrcExpr = ExprError(); 10701 return true; 10702 } 10703 } 10704 } 10705 10706 if (!SingleFunctionExpression.isUsable()) { 10707 if (complain) { 10708 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10709 << ovl.Expression->getName() 10710 << DestTypeForComplaining 10711 << OpRangeForComplaining 10712 << ovl.Expression->getQualifierLoc().getSourceRange(); 10713 NoteAllOverloadCandidates(SrcExpr.get()); 10714 10715 SrcExpr = ExprError(); 10716 return true; 10717 } 10718 10719 return false; 10720 } 10721 10722 SrcExpr = SingleFunctionExpression; 10723 return true; 10724 } 10725 10726 /// \brief Add a single candidate to the overload set. 10727 static void AddOverloadedCallCandidate(Sema &S, 10728 DeclAccessPair FoundDecl, 10729 TemplateArgumentListInfo *ExplicitTemplateArgs, 10730 ArrayRef<Expr *> Args, 10731 OverloadCandidateSet &CandidateSet, 10732 bool PartialOverloading, 10733 bool KnownValid) { 10734 NamedDecl *Callee = FoundDecl.getDecl(); 10735 if (isa<UsingShadowDecl>(Callee)) 10736 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10737 10738 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10739 if (ExplicitTemplateArgs) { 10740 assert(!KnownValid && "Explicit template arguments?"); 10741 return; 10742 } 10743 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10744 /*SuppressUsedConversions=*/false, 10745 PartialOverloading); 10746 return; 10747 } 10748 10749 if (FunctionTemplateDecl *FuncTemplate 10750 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10751 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10752 ExplicitTemplateArgs, Args, CandidateSet, 10753 /*SuppressUsedConversions=*/false, 10754 PartialOverloading); 10755 return; 10756 } 10757 10758 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10759 } 10760 10761 /// \brief Add the overload candidates named by callee and/or found by argument 10762 /// dependent lookup to the given overload set. 10763 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10764 ArrayRef<Expr *> Args, 10765 OverloadCandidateSet &CandidateSet, 10766 bool PartialOverloading) { 10767 10768 #ifndef NDEBUG 10769 // Verify that ArgumentDependentLookup is consistent with the rules 10770 // in C++0x [basic.lookup.argdep]p3: 10771 // 10772 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10773 // and let Y be the lookup set produced by argument dependent 10774 // lookup (defined as follows). If X contains 10775 // 10776 // -- a declaration of a class member, or 10777 // 10778 // -- a block-scope function declaration that is not a 10779 // using-declaration, or 10780 // 10781 // -- a declaration that is neither a function or a function 10782 // template 10783 // 10784 // then Y is empty. 10785 10786 if (ULE->requiresADL()) { 10787 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10788 E = ULE->decls_end(); I != E; ++I) { 10789 assert(!(*I)->getDeclContext()->isRecord()); 10790 assert(isa<UsingShadowDecl>(*I) || 10791 !(*I)->getDeclContext()->isFunctionOrMethod()); 10792 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10793 } 10794 } 10795 #endif 10796 10797 // It would be nice to avoid this copy. 10798 TemplateArgumentListInfo TABuffer; 10799 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10800 if (ULE->hasExplicitTemplateArgs()) { 10801 ULE->copyTemplateArgumentsInto(TABuffer); 10802 ExplicitTemplateArgs = &TABuffer; 10803 } 10804 10805 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10806 E = ULE->decls_end(); I != E; ++I) 10807 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10808 CandidateSet, PartialOverloading, 10809 /*KnownValid*/ true); 10810 10811 if (ULE->requiresADL()) 10812 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10813 Args, ExplicitTemplateArgs, 10814 CandidateSet, PartialOverloading); 10815 } 10816 10817 /// Determine whether a declaration with the specified name could be moved into 10818 /// a different namespace. 10819 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10820 switch (Name.getCXXOverloadedOperator()) { 10821 case OO_New: case OO_Array_New: 10822 case OO_Delete: case OO_Array_Delete: 10823 return false; 10824 10825 default: 10826 return true; 10827 } 10828 } 10829 10830 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10831 /// template, where the non-dependent name was declared after the template 10832 /// was defined. This is common in code written for a compilers which do not 10833 /// correctly implement two-stage name lookup. 10834 /// 10835 /// Returns true if a viable candidate was found and a diagnostic was issued. 10836 static bool 10837 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10838 const CXXScopeSpec &SS, LookupResult &R, 10839 OverloadCandidateSet::CandidateSetKind CSK, 10840 TemplateArgumentListInfo *ExplicitTemplateArgs, 10841 ArrayRef<Expr *> Args, 10842 bool *DoDiagnoseEmptyLookup = nullptr) { 10843 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10844 return false; 10845 10846 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10847 if (DC->isTransparentContext()) 10848 continue; 10849 10850 SemaRef.LookupQualifiedName(R, DC); 10851 10852 if (!R.empty()) { 10853 R.suppressDiagnostics(); 10854 10855 if (isa<CXXRecordDecl>(DC)) { 10856 // Don't diagnose names we find in classes; we get much better 10857 // diagnostics for these from DiagnoseEmptyLookup. 10858 R.clear(); 10859 if (DoDiagnoseEmptyLookup) 10860 *DoDiagnoseEmptyLookup = true; 10861 return false; 10862 } 10863 10864 OverloadCandidateSet Candidates(FnLoc, CSK); 10865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10866 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10867 ExplicitTemplateArgs, Args, 10868 Candidates, false, /*KnownValid*/ false); 10869 10870 OverloadCandidateSet::iterator Best; 10871 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10872 // No viable functions. Don't bother the user with notes for functions 10873 // which don't work and shouldn't be found anyway. 10874 R.clear(); 10875 return false; 10876 } 10877 10878 // Find the namespaces where ADL would have looked, and suggest 10879 // declaring the function there instead. 10880 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10881 Sema::AssociatedClassSet AssociatedClasses; 10882 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10883 AssociatedNamespaces, 10884 AssociatedClasses); 10885 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10886 if (canBeDeclaredInNamespace(R.getLookupName())) { 10887 DeclContext *Std = SemaRef.getStdNamespace(); 10888 for (Sema::AssociatedNamespaceSet::iterator 10889 it = AssociatedNamespaces.begin(), 10890 end = AssociatedNamespaces.end(); it != end; ++it) { 10891 // Never suggest declaring a function within namespace 'std'. 10892 if (Std && Std->Encloses(*it)) 10893 continue; 10894 10895 // Never suggest declaring a function within a namespace with a 10896 // reserved name, like __gnu_cxx. 10897 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10898 if (NS && 10899 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10900 continue; 10901 10902 SuggestedNamespaces.insert(*it); 10903 } 10904 } 10905 10906 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10907 << R.getLookupName(); 10908 if (SuggestedNamespaces.empty()) { 10909 SemaRef.Diag(Best->Function->getLocation(), 10910 diag::note_not_found_by_two_phase_lookup) 10911 << R.getLookupName() << 0; 10912 } else if (SuggestedNamespaces.size() == 1) { 10913 SemaRef.Diag(Best->Function->getLocation(), 10914 diag::note_not_found_by_two_phase_lookup) 10915 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10916 } else { 10917 // FIXME: It would be useful to list the associated namespaces here, 10918 // but the diagnostics infrastructure doesn't provide a way to produce 10919 // a localized representation of a list of items. 10920 SemaRef.Diag(Best->Function->getLocation(), 10921 diag::note_not_found_by_two_phase_lookup) 10922 << R.getLookupName() << 2; 10923 } 10924 10925 // Try to recover by calling this function. 10926 return true; 10927 } 10928 10929 R.clear(); 10930 } 10931 10932 return false; 10933 } 10934 10935 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10936 /// template, where the non-dependent operator was declared after the template 10937 /// was defined. 10938 /// 10939 /// Returns true if a viable candidate was found and a diagnostic was issued. 10940 static bool 10941 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10942 SourceLocation OpLoc, 10943 ArrayRef<Expr *> Args) { 10944 DeclarationName OpName = 10945 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10946 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10947 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10948 OverloadCandidateSet::CSK_Operator, 10949 /*ExplicitTemplateArgs=*/nullptr, Args); 10950 } 10951 10952 namespace { 10953 class BuildRecoveryCallExprRAII { 10954 Sema &SemaRef; 10955 public: 10956 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10957 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10958 SemaRef.IsBuildingRecoveryCallExpr = true; 10959 } 10960 10961 ~BuildRecoveryCallExprRAII() { 10962 SemaRef.IsBuildingRecoveryCallExpr = false; 10963 } 10964 }; 10965 10966 } 10967 10968 static std::unique_ptr<CorrectionCandidateCallback> 10969 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10970 bool HasTemplateArgs, bool AllowTypoCorrection) { 10971 if (!AllowTypoCorrection) 10972 return llvm::make_unique<NoTypoCorrectionCCC>(); 10973 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10974 HasTemplateArgs, ME); 10975 } 10976 10977 /// Attempts to recover from a call where no functions were found. 10978 /// 10979 /// Returns true if new candidates were found. 10980 static ExprResult 10981 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10982 UnresolvedLookupExpr *ULE, 10983 SourceLocation LParenLoc, 10984 MutableArrayRef<Expr *> Args, 10985 SourceLocation RParenLoc, 10986 bool EmptyLookup, bool AllowTypoCorrection) { 10987 // Do not try to recover if it is already building a recovery call. 10988 // This stops infinite loops for template instantiations like 10989 // 10990 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10991 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10992 // 10993 if (SemaRef.IsBuildingRecoveryCallExpr) 10994 return ExprError(); 10995 BuildRecoveryCallExprRAII RCE(SemaRef); 10996 10997 CXXScopeSpec SS; 10998 SS.Adopt(ULE->getQualifierLoc()); 10999 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11000 11001 TemplateArgumentListInfo TABuffer; 11002 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11003 if (ULE->hasExplicitTemplateArgs()) { 11004 ULE->copyTemplateArgumentsInto(TABuffer); 11005 ExplicitTemplateArgs = &TABuffer; 11006 } 11007 11008 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11009 Sema::LookupOrdinaryName); 11010 bool DoDiagnoseEmptyLookup = EmptyLookup; 11011 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11012 OverloadCandidateSet::CSK_Normal, 11013 ExplicitTemplateArgs, Args, 11014 &DoDiagnoseEmptyLookup) && 11015 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11016 S, SS, R, 11017 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11018 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11019 ExplicitTemplateArgs, Args))) 11020 return ExprError(); 11021 11022 assert(!R.empty() && "lookup results empty despite recovery"); 11023 11024 // Build an implicit member call if appropriate. Just drop the 11025 // casts and such from the call, we don't really care. 11026 ExprResult NewFn = ExprError(); 11027 if ((*R.begin())->isCXXClassMember()) 11028 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11029 ExplicitTemplateArgs, S); 11030 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11031 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11032 ExplicitTemplateArgs); 11033 else 11034 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11035 11036 if (NewFn.isInvalid()) 11037 return ExprError(); 11038 11039 // This shouldn't cause an infinite loop because we're giving it 11040 // an expression with viable lookup results, which should never 11041 // end up here. 11042 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11043 MultiExprArg(Args.data(), Args.size()), 11044 RParenLoc); 11045 } 11046 11047 /// \brief Constructs and populates an OverloadedCandidateSet from 11048 /// the given function. 11049 /// \returns true when an the ExprResult output parameter has been set. 11050 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11051 UnresolvedLookupExpr *ULE, 11052 MultiExprArg Args, 11053 SourceLocation RParenLoc, 11054 OverloadCandidateSet *CandidateSet, 11055 ExprResult *Result) { 11056 #ifndef NDEBUG 11057 if (ULE->requiresADL()) { 11058 // To do ADL, we must have found an unqualified name. 11059 assert(!ULE->getQualifier() && "qualified name with ADL"); 11060 11061 // We don't perform ADL for implicit declarations of builtins. 11062 // Verify that this was correctly set up. 11063 FunctionDecl *F; 11064 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11065 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11066 F->getBuiltinID() && F->isImplicit()) 11067 llvm_unreachable("performing ADL for builtin"); 11068 11069 // We don't perform ADL in C. 11070 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11071 } 11072 #endif 11073 11074 UnbridgedCastsSet UnbridgedCasts; 11075 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11076 *Result = ExprError(); 11077 return true; 11078 } 11079 11080 // Add the functions denoted by the callee to the set of candidate 11081 // functions, including those from argument-dependent lookup. 11082 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11083 11084 if (getLangOpts().MSVCCompat && 11085 CurContext->isDependentContext() && !isSFINAEContext() && 11086 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11087 11088 OverloadCandidateSet::iterator Best; 11089 if (CandidateSet->empty() || 11090 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11091 OR_No_Viable_Function) { 11092 // In Microsoft mode, if we are inside a template class member function then 11093 // create a type dependent CallExpr. The goal is to postpone name lookup 11094 // to instantiation time to be able to search into type dependent base 11095 // classes. 11096 CallExpr *CE = new (Context) CallExpr( 11097 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11098 CE->setTypeDependent(true); 11099 CE->setValueDependent(true); 11100 CE->setInstantiationDependent(true); 11101 *Result = CE; 11102 return true; 11103 } 11104 } 11105 11106 if (CandidateSet->empty()) 11107 return false; 11108 11109 UnbridgedCasts.restore(); 11110 return false; 11111 } 11112 11113 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11114 /// the completed call expression. If overload resolution fails, emits 11115 /// diagnostics and returns ExprError() 11116 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11117 UnresolvedLookupExpr *ULE, 11118 SourceLocation LParenLoc, 11119 MultiExprArg Args, 11120 SourceLocation RParenLoc, 11121 Expr *ExecConfig, 11122 OverloadCandidateSet *CandidateSet, 11123 OverloadCandidateSet::iterator *Best, 11124 OverloadingResult OverloadResult, 11125 bool AllowTypoCorrection) { 11126 if (CandidateSet->empty()) 11127 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11128 RParenLoc, /*EmptyLookup=*/true, 11129 AllowTypoCorrection); 11130 11131 switch (OverloadResult) { 11132 case OR_Success: { 11133 FunctionDecl *FDecl = (*Best)->Function; 11134 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11135 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11136 return ExprError(); 11137 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11138 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11139 ExecConfig); 11140 } 11141 11142 case OR_No_Viable_Function: { 11143 // Try to recover by looking for viable functions which the user might 11144 // have meant to call. 11145 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11146 Args, RParenLoc, 11147 /*EmptyLookup=*/false, 11148 AllowTypoCorrection); 11149 if (!Recovery.isInvalid()) 11150 return Recovery; 11151 11152 // If the user passes in a function that we can't take the address of, we 11153 // generally end up emitting really bad error messages. Here, we attempt to 11154 // emit better ones. 11155 for (const Expr *Arg : Args) { 11156 if (!Arg->getType()->isFunctionType()) 11157 continue; 11158 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11159 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11160 if (FD && 11161 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11162 Arg->getExprLoc())) 11163 return ExprError(); 11164 } 11165 } 11166 11167 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11168 << ULE->getName() << Fn->getSourceRange(); 11169 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11170 break; 11171 } 11172 11173 case OR_Ambiguous: 11174 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11175 << ULE->getName() << Fn->getSourceRange(); 11176 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11177 break; 11178 11179 case OR_Deleted: { 11180 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11181 << (*Best)->Function->isDeleted() 11182 << ULE->getName() 11183 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11184 << Fn->getSourceRange(); 11185 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11186 11187 // We emitted an error for the unvailable/deleted function call but keep 11188 // the call in the AST. 11189 FunctionDecl *FDecl = (*Best)->Function; 11190 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11191 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11192 ExecConfig); 11193 } 11194 } 11195 11196 // Overload resolution failed. 11197 return ExprError(); 11198 } 11199 11200 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11201 /// (which eventually refers to the declaration Func) and the call 11202 /// arguments Args/NumArgs, attempt to resolve the function call down 11203 /// to a specific function. If overload resolution succeeds, returns 11204 /// the call expression produced by overload resolution. 11205 /// Otherwise, emits diagnostics and returns ExprError. 11206 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11207 UnresolvedLookupExpr *ULE, 11208 SourceLocation LParenLoc, 11209 MultiExprArg Args, 11210 SourceLocation RParenLoc, 11211 Expr *ExecConfig, 11212 bool AllowTypoCorrection) { 11213 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11214 OverloadCandidateSet::CSK_Normal); 11215 ExprResult result; 11216 11217 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11218 &result)) 11219 return result; 11220 11221 OverloadCandidateSet::iterator Best; 11222 OverloadingResult OverloadResult = 11223 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11224 11225 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11226 RParenLoc, ExecConfig, &CandidateSet, 11227 &Best, OverloadResult, 11228 AllowTypoCorrection); 11229 } 11230 11231 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11232 return Functions.size() > 1 || 11233 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11234 } 11235 11236 /// \brief Create a unary operation that may resolve to an overloaded 11237 /// operator. 11238 /// 11239 /// \param OpLoc The location of the operator itself (e.g., '*'). 11240 /// 11241 /// \param Opc The UnaryOperatorKind that describes this operator. 11242 /// 11243 /// \param Fns The set of non-member functions that will be 11244 /// considered by overload resolution. The caller needs to build this 11245 /// set based on the context using, e.g., 11246 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11247 /// set should not contain any member functions; those will be added 11248 /// by CreateOverloadedUnaryOp(). 11249 /// 11250 /// \param Input The input argument. 11251 ExprResult 11252 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11253 const UnresolvedSetImpl &Fns, 11254 Expr *Input) { 11255 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11256 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11257 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11258 // TODO: provide better source location info. 11259 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11260 11261 if (checkPlaceholderForOverload(*this, Input)) 11262 return ExprError(); 11263 11264 Expr *Args[2] = { Input, nullptr }; 11265 unsigned NumArgs = 1; 11266 11267 // For post-increment and post-decrement, add the implicit '0' as 11268 // the second argument, so that we know this is a post-increment or 11269 // post-decrement. 11270 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11271 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11272 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11273 SourceLocation()); 11274 NumArgs = 2; 11275 } 11276 11277 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11278 11279 if (Input->isTypeDependent()) { 11280 if (Fns.empty()) 11281 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11282 VK_RValue, OK_Ordinary, OpLoc); 11283 11284 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11285 UnresolvedLookupExpr *Fn 11286 = UnresolvedLookupExpr::Create(Context, NamingClass, 11287 NestedNameSpecifierLoc(), OpNameInfo, 11288 /*ADL*/ true, IsOverloaded(Fns), 11289 Fns.begin(), Fns.end()); 11290 return new (Context) 11291 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11292 VK_RValue, OpLoc, false); 11293 } 11294 11295 // Build an empty overload set. 11296 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11297 11298 // Add the candidates from the given function set. 11299 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11300 11301 // Add operator candidates that are member functions. 11302 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11303 11304 // Add candidates from ADL. 11305 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11306 /*ExplicitTemplateArgs*/nullptr, 11307 CandidateSet); 11308 11309 // Add builtin operator candidates. 11310 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11311 11312 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11313 11314 // Perform overload resolution. 11315 OverloadCandidateSet::iterator Best; 11316 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11317 case OR_Success: { 11318 // We found a built-in operator or an overloaded operator. 11319 FunctionDecl *FnDecl = Best->Function; 11320 11321 if (FnDecl) { 11322 // We matched an overloaded operator. Build a call to that 11323 // operator. 11324 11325 // Convert the arguments. 11326 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11327 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11328 11329 ExprResult InputRes = 11330 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11331 Best->FoundDecl, Method); 11332 if (InputRes.isInvalid()) 11333 return ExprError(); 11334 Input = InputRes.get(); 11335 } else { 11336 // Convert the arguments. 11337 ExprResult InputInit 11338 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11339 Context, 11340 FnDecl->getParamDecl(0)), 11341 SourceLocation(), 11342 Input); 11343 if (InputInit.isInvalid()) 11344 return ExprError(); 11345 Input = InputInit.get(); 11346 } 11347 11348 // Build the actual expression node. 11349 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11350 HadMultipleCandidates, OpLoc); 11351 if (FnExpr.isInvalid()) 11352 return ExprError(); 11353 11354 // Determine the result type. 11355 QualType ResultTy = FnDecl->getReturnType(); 11356 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11357 ResultTy = ResultTy.getNonLValueExprType(Context); 11358 11359 Args[0] = Input; 11360 CallExpr *TheCall = 11361 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11362 ResultTy, VK, OpLoc, false); 11363 11364 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11365 return ExprError(); 11366 11367 return MaybeBindToTemporary(TheCall); 11368 } else { 11369 // We matched a built-in operator. Convert the arguments, then 11370 // break out so that we will build the appropriate built-in 11371 // operator node. 11372 ExprResult InputRes = 11373 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11374 Best->Conversions[0], AA_Passing); 11375 if (InputRes.isInvalid()) 11376 return ExprError(); 11377 Input = InputRes.get(); 11378 break; 11379 } 11380 } 11381 11382 case OR_No_Viable_Function: 11383 // This is an erroneous use of an operator which can be overloaded by 11384 // a non-member function. Check for non-member operators which were 11385 // defined too late to be candidates. 11386 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11387 // FIXME: Recover by calling the found function. 11388 return ExprError(); 11389 11390 // No viable function; fall through to handling this as a 11391 // built-in operator, which will produce an error message for us. 11392 break; 11393 11394 case OR_Ambiguous: 11395 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11396 << UnaryOperator::getOpcodeStr(Opc) 11397 << Input->getType() 11398 << Input->getSourceRange(); 11399 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11400 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11401 return ExprError(); 11402 11403 case OR_Deleted: 11404 Diag(OpLoc, diag::err_ovl_deleted_oper) 11405 << Best->Function->isDeleted() 11406 << UnaryOperator::getOpcodeStr(Opc) 11407 << getDeletedOrUnavailableSuffix(Best->Function) 11408 << Input->getSourceRange(); 11409 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11410 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11411 return ExprError(); 11412 } 11413 11414 // Either we found no viable overloaded operator or we matched a 11415 // built-in operator. In either case, fall through to trying to 11416 // build a built-in operation. 11417 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11418 } 11419 11420 /// \brief Create a binary operation that may resolve to an overloaded 11421 /// operator. 11422 /// 11423 /// \param OpLoc The location of the operator itself (e.g., '+'). 11424 /// 11425 /// \param Opc The BinaryOperatorKind that describes this operator. 11426 /// 11427 /// \param Fns The set of non-member functions that will be 11428 /// considered by overload resolution. The caller needs to build this 11429 /// set based on the context using, e.g., 11430 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11431 /// set should not contain any member functions; those will be added 11432 /// by CreateOverloadedBinOp(). 11433 /// 11434 /// \param LHS Left-hand argument. 11435 /// \param RHS Right-hand argument. 11436 ExprResult 11437 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11438 BinaryOperatorKind Opc, 11439 const UnresolvedSetImpl &Fns, 11440 Expr *LHS, Expr *RHS) { 11441 Expr *Args[2] = { LHS, RHS }; 11442 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11443 11444 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11445 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11446 11447 // If either side is type-dependent, create an appropriate dependent 11448 // expression. 11449 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11450 if (Fns.empty()) { 11451 // If there are no functions to store, just build a dependent 11452 // BinaryOperator or CompoundAssignment. 11453 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11454 return new (Context) BinaryOperator( 11455 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11456 OpLoc, FPFeatures.fp_contract); 11457 11458 return new (Context) CompoundAssignOperator( 11459 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11460 Context.DependentTy, Context.DependentTy, OpLoc, 11461 FPFeatures.fp_contract); 11462 } 11463 11464 // FIXME: save results of ADL from here? 11465 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11466 // TODO: provide better source location info in DNLoc component. 11467 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11468 UnresolvedLookupExpr *Fn 11469 = UnresolvedLookupExpr::Create(Context, NamingClass, 11470 NestedNameSpecifierLoc(), OpNameInfo, 11471 /*ADL*/ true, IsOverloaded(Fns), 11472 Fns.begin(), Fns.end()); 11473 return new (Context) 11474 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11475 VK_RValue, OpLoc, FPFeatures.fp_contract); 11476 } 11477 11478 // Always do placeholder-like conversions on the RHS. 11479 if (checkPlaceholderForOverload(*this, Args[1])) 11480 return ExprError(); 11481 11482 // Do placeholder-like conversion on the LHS; note that we should 11483 // not get here with a PseudoObject LHS. 11484 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11485 if (checkPlaceholderForOverload(*this, Args[0])) 11486 return ExprError(); 11487 11488 // If this is the assignment operator, we only perform overload resolution 11489 // if the left-hand side is a class or enumeration type. This is actually 11490 // a hack. The standard requires that we do overload resolution between the 11491 // various built-in candidates, but as DR507 points out, this can lead to 11492 // problems. So we do it this way, which pretty much follows what GCC does. 11493 // Note that we go the traditional code path for compound assignment forms. 11494 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11495 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11496 11497 // If this is the .* operator, which is not overloadable, just 11498 // create a built-in binary operator. 11499 if (Opc == BO_PtrMemD) 11500 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11501 11502 // Build an empty overload set. 11503 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11504 11505 // Add the candidates from the given function set. 11506 AddFunctionCandidates(Fns, Args, CandidateSet); 11507 11508 // Add operator candidates that are member functions. 11509 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11510 11511 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11512 // performed for an assignment operator (nor for operator[] nor operator->, 11513 // which don't get here). 11514 if (Opc != BO_Assign) 11515 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11516 /*ExplicitTemplateArgs*/ nullptr, 11517 CandidateSet); 11518 11519 // Add builtin operator candidates. 11520 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11521 11522 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11523 11524 // Perform overload resolution. 11525 OverloadCandidateSet::iterator Best; 11526 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11527 case OR_Success: { 11528 // We found a built-in operator or an overloaded operator. 11529 FunctionDecl *FnDecl = Best->Function; 11530 11531 if (FnDecl) { 11532 // We matched an overloaded operator. Build a call to that 11533 // operator. 11534 11535 // Convert the arguments. 11536 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11537 // Best->Access is only meaningful for class members. 11538 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11539 11540 ExprResult Arg1 = 11541 PerformCopyInitialization( 11542 InitializedEntity::InitializeParameter(Context, 11543 FnDecl->getParamDecl(0)), 11544 SourceLocation(), Args[1]); 11545 if (Arg1.isInvalid()) 11546 return ExprError(); 11547 11548 ExprResult Arg0 = 11549 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11550 Best->FoundDecl, Method); 11551 if (Arg0.isInvalid()) 11552 return ExprError(); 11553 Args[0] = Arg0.getAs<Expr>(); 11554 Args[1] = RHS = Arg1.getAs<Expr>(); 11555 } else { 11556 // Convert the arguments. 11557 ExprResult Arg0 = PerformCopyInitialization( 11558 InitializedEntity::InitializeParameter(Context, 11559 FnDecl->getParamDecl(0)), 11560 SourceLocation(), Args[0]); 11561 if (Arg0.isInvalid()) 11562 return ExprError(); 11563 11564 ExprResult Arg1 = 11565 PerformCopyInitialization( 11566 InitializedEntity::InitializeParameter(Context, 11567 FnDecl->getParamDecl(1)), 11568 SourceLocation(), Args[1]); 11569 if (Arg1.isInvalid()) 11570 return ExprError(); 11571 Args[0] = LHS = Arg0.getAs<Expr>(); 11572 Args[1] = RHS = Arg1.getAs<Expr>(); 11573 } 11574 11575 // Build the actual expression node. 11576 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11577 Best->FoundDecl, 11578 HadMultipleCandidates, OpLoc); 11579 if (FnExpr.isInvalid()) 11580 return ExprError(); 11581 11582 // Determine the result type. 11583 QualType ResultTy = FnDecl->getReturnType(); 11584 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11585 ResultTy = ResultTy.getNonLValueExprType(Context); 11586 11587 CXXOperatorCallExpr *TheCall = 11588 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11589 Args, ResultTy, VK, OpLoc, 11590 FPFeatures.fp_contract); 11591 11592 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11593 FnDecl)) 11594 return ExprError(); 11595 11596 ArrayRef<const Expr *> ArgsArray(Args, 2); 11597 // Cut off the implicit 'this'. 11598 if (isa<CXXMethodDecl>(FnDecl)) 11599 ArgsArray = ArgsArray.slice(1); 11600 11601 // Check for a self move. 11602 if (Op == OO_Equal) 11603 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11604 11605 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11606 TheCall->getSourceRange(), VariadicDoesNotApply); 11607 11608 return MaybeBindToTemporary(TheCall); 11609 } else { 11610 // We matched a built-in operator. Convert the arguments, then 11611 // break out so that we will build the appropriate built-in 11612 // operator node. 11613 ExprResult ArgsRes0 = 11614 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11615 Best->Conversions[0], AA_Passing); 11616 if (ArgsRes0.isInvalid()) 11617 return ExprError(); 11618 Args[0] = ArgsRes0.get(); 11619 11620 ExprResult ArgsRes1 = 11621 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11622 Best->Conversions[1], AA_Passing); 11623 if (ArgsRes1.isInvalid()) 11624 return ExprError(); 11625 Args[1] = ArgsRes1.get(); 11626 break; 11627 } 11628 } 11629 11630 case OR_No_Viable_Function: { 11631 // C++ [over.match.oper]p9: 11632 // If the operator is the operator , [...] and there are no 11633 // viable functions, then the operator is assumed to be the 11634 // built-in operator and interpreted according to clause 5. 11635 if (Opc == BO_Comma) 11636 break; 11637 11638 // For class as left operand for assignment or compound assigment 11639 // operator do not fall through to handling in built-in, but report that 11640 // no overloaded assignment operator found 11641 ExprResult Result = ExprError(); 11642 if (Args[0]->getType()->isRecordType() && 11643 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11644 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11645 << BinaryOperator::getOpcodeStr(Opc) 11646 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11647 if (Args[0]->getType()->isIncompleteType()) { 11648 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11649 << Args[0]->getType() 11650 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11651 } 11652 } else { 11653 // This is an erroneous use of an operator which can be overloaded by 11654 // a non-member function. Check for non-member operators which were 11655 // defined too late to be candidates. 11656 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11657 // FIXME: Recover by calling the found function. 11658 return ExprError(); 11659 11660 // No viable function; try to create a built-in operation, which will 11661 // produce an error. Then, show the non-viable candidates. 11662 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11663 } 11664 assert(Result.isInvalid() && 11665 "C++ binary operator overloading is missing candidates!"); 11666 if (Result.isInvalid()) 11667 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11668 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11669 return Result; 11670 } 11671 11672 case OR_Ambiguous: 11673 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11674 << BinaryOperator::getOpcodeStr(Opc) 11675 << Args[0]->getType() << Args[1]->getType() 11676 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11677 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11678 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11679 return ExprError(); 11680 11681 case OR_Deleted: 11682 if (isImplicitlyDeleted(Best->Function)) { 11683 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11684 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11685 << Context.getRecordType(Method->getParent()) 11686 << getSpecialMember(Method); 11687 11688 // The user probably meant to call this special member. Just 11689 // explain why it's deleted. 11690 NoteDeletedFunction(Method); 11691 return ExprError(); 11692 } else { 11693 Diag(OpLoc, diag::err_ovl_deleted_oper) 11694 << Best->Function->isDeleted() 11695 << BinaryOperator::getOpcodeStr(Opc) 11696 << getDeletedOrUnavailableSuffix(Best->Function) 11697 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11698 } 11699 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11700 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11701 return ExprError(); 11702 } 11703 11704 // We matched a built-in operator; build it. 11705 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11706 } 11707 11708 ExprResult 11709 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11710 SourceLocation RLoc, 11711 Expr *Base, Expr *Idx) { 11712 Expr *Args[2] = { Base, Idx }; 11713 DeclarationName OpName = 11714 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11715 11716 // If either side is type-dependent, create an appropriate dependent 11717 // expression. 11718 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11719 11720 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11721 // CHECKME: no 'operator' keyword? 11722 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11723 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11724 UnresolvedLookupExpr *Fn 11725 = UnresolvedLookupExpr::Create(Context, NamingClass, 11726 NestedNameSpecifierLoc(), OpNameInfo, 11727 /*ADL*/ true, /*Overloaded*/ false, 11728 UnresolvedSetIterator(), 11729 UnresolvedSetIterator()); 11730 // Can't add any actual overloads yet 11731 11732 return new (Context) 11733 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11734 Context.DependentTy, VK_RValue, RLoc, false); 11735 } 11736 11737 // Handle placeholders on both operands. 11738 if (checkPlaceholderForOverload(*this, Args[0])) 11739 return ExprError(); 11740 if (checkPlaceholderForOverload(*this, Args[1])) 11741 return ExprError(); 11742 11743 // Build an empty overload set. 11744 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11745 11746 // Subscript can only be overloaded as a member function. 11747 11748 // Add operator candidates that are member functions. 11749 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11750 11751 // Add builtin operator candidates. 11752 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11753 11754 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11755 11756 // Perform overload resolution. 11757 OverloadCandidateSet::iterator Best; 11758 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11759 case OR_Success: { 11760 // We found a built-in operator or an overloaded operator. 11761 FunctionDecl *FnDecl = Best->Function; 11762 11763 if (FnDecl) { 11764 // We matched an overloaded operator. Build a call to that 11765 // operator. 11766 11767 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11768 11769 // Convert the arguments. 11770 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11771 ExprResult Arg0 = 11772 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11773 Best->FoundDecl, Method); 11774 if (Arg0.isInvalid()) 11775 return ExprError(); 11776 Args[0] = Arg0.get(); 11777 11778 // Convert the arguments. 11779 ExprResult InputInit 11780 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11781 Context, 11782 FnDecl->getParamDecl(0)), 11783 SourceLocation(), 11784 Args[1]); 11785 if (InputInit.isInvalid()) 11786 return ExprError(); 11787 11788 Args[1] = InputInit.getAs<Expr>(); 11789 11790 // Build the actual expression node. 11791 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11792 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11793 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11794 Best->FoundDecl, 11795 HadMultipleCandidates, 11796 OpLocInfo.getLoc(), 11797 OpLocInfo.getInfo()); 11798 if (FnExpr.isInvalid()) 11799 return ExprError(); 11800 11801 // Determine the result type 11802 QualType ResultTy = FnDecl->getReturnType(); 11803 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11804 ResultTy = ResultTy.getNonLValueExprType(Context); 11805 11806 CXXOperatorCallExpr *TheCall = 11807 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11808 FnExpr.get(), Args, 11809 ResultTy, VK, RLoc, 11810 false); 11811 11812 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11813 return ExprError(); 11814 11815 return MaybeBindToTemporary(TheCall); 11816 } else { 11817 // We matched a built-in operator. Convert the arguments, then 11818 // break out so that we will build the appropriate built-in 11819 // operator node. 11820 ExprResult ArgsRes0 = 11821 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11822 Best->Conversions[0], AA_Passing); 11823 if (ArgsRes0.isInvalid()) 11824 return ExprError(); 11825 Args[0] = ArgsRes0.get(); 11826 11827 ExprResult ArgsRes1 = 11828 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11829 Best->Conversions[1], AA_Passing); 11830 if (ArgsRes1.isInvalid()) 11831 return ExprError(); 11832 Args[1] = ArgsRes1.get(); 11833 11834 break; 11835 } 11836 } 11837 11838 case OR_No_Viable_Function: { 11839 if (CandidateSet.empty()) 11840 Diag(LLoc, diag::err_ovl_no_oper) 11841 << Args[0]->getType() << /*subscript*/ 0 11842 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11843 else 11844 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11845 << Args[0]->getType() 11846 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11847 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11848 "[]", LLoc); 11849 return ExprError(); 11850 } 11851 11852 case OR_Ambiguous: 11853 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11854 << "[]" 11855 << Args[0]->getType() << Args[1]->getType() 11856 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11857 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11858 "[]", LLoc); 11859 return ExprError(); 11860 11861 case OR_Deleted: 11862 Diag(LLoc, diag::err_ovl_deleted_oper) 11863 << Best->Function->isDeleted() << "[]" 11864 << getDeletedOrUnavailableSuffix(Best->Function) 11865 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11866 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11867 "[]", LLoc); 11868 return ExprError(); 11869 } 11870 11871 // We matched a built-in operator; build it. 11872 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11873 } 11874 11875 /// BuildCallToMemberFunction - Build a call to a member 11876 /// function. MemExpr is the expression that refers to the member 11877 /// function (and includes the object parameter), Args/NumArgs are the 11878 /// arguments to the function call (not including the object 11879 /// parameter). The caller needs to validate that the member 11880 /// expression refers to a non-static member function or an overloaded 11881 /// member function. 11882 ExprResult 11883 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11884 SourceLocation LParenLoc, 11885 MultiExprArg Args, 11886 SourceLocation RParenLoc) { 11887 assert(MemExprE->getType() == Context.BoundMemberTy || 11888 MemExprE->getType() == Context.OverloadTy); 11889 11890 // Dig out the member expression. This holds both the object 11891 // argument and the member function we're referring to. 11892 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11893 11894 // Determine whether this is a call to a pointer-to-member function. 11895 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11896 assert(op->getType() == Context.BoundMemberTy); 11897 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11898 11899 QualType fnType = 11900 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11901 11902 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11903 QualType resultType = proto->getCallResultType(Context); 11904 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11905 11906 // Check that the object type isn't more qualified than the 11907 // member function we're calling. 11908 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11909 11910 QualType objectType = op->getLHS()->getType(); 11911 if (op->getOpcode() == BO_PtrMemI) 11912 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11913 Qualifiers objectQuals = objectType.getQualifiers(); 11914 11915 Qualifiers difference = objectQuals - funcQuals; 11916 difference.removeObjCGCAttr(); 11917 difference.removeAddressSpace(); 11918 if (difference) { 11919 std::string qualsString = difference.getAsString(); 11920 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11921 << fnType.getUnqualifiedType() 11922 << qualsString 11923 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11924 } 11925 11926 CXXMemberCallExpr *call 11927 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11928 resultType, valueKind, RParenLoc); 11929 11930 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11931 call, nullptr)) 11932 return ExprError(); 11933 11934 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11935 return ExprError(); 11936 11937 if (CheckOtherCall(call, proto)) 11938 return ExprError(); 11939 11940 return MaybeBindToTemporary(call); 11941 } 11942 11943 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11944 return new (Context) 11945 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11946 11947 UnbridgedCastsSet UnbridgedCasts; 11948 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11949 return ExprError(); 11950 11951 MemberExpr *MemExpr; 11952 CXXMethodDecl *Method = nullptr; 11953 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11954 NestedNameSpecifier *Qualifier = nullptr; 11955 if (isa<MemberExpr>(NakedMemExpr)) { 11956 MemExpr = cast<MemberExpr>(NakedMemExpr); 11957 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11958 FoundDecl = MemExpr->getFoundDecl(); 11959 Qualifier = MemExpr->getQualifier(); 11960 UnbridgedCasts.restore(); 11961 } else { 11962 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11963 Qualifier = UnresExpr->getQualifier(); 11964 11965 QualType ObjectType = UnresExpr->getBaseType(); 11966 Expr::Classification ObjectClassification 11967 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11968 : UnresExpr->getBase()->Classify(Context); 11969 11970 // Add overload candidates 11971 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11972 OverloadCandidateSet::CSK_Normal); 11973 11974 // FIXME: avoid copy. 11975 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11976 if (UnresExpr->hasExplicitTemplateArgs()) { 11977 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11978 TemplateArgs = &TemplateArgsBuffer; 11979 } 11980 11981 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11982 E = UnresExpr->decls_end(); I != E; ++I) { 11983 11984 NamedDecl *Func = *I; 11985 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11986 if (isa<UsingShadowDecl>(Func)) 11987 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11988 11989 11990 // Microsoft supports direct constructor calls. 11991 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11992 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11993 Args, CandidateSet); 11994 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11995 // If explicit template arguments were provided, we can't call a 11996 // non-template member function. 11997 if (TemplateArgs) 11998 continue; 11999 12000 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12001 ObjectClassification, Args, CandidateSet, 12002 /*SuppressUserConversions=*/false); 12003 } else { 12004 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12005 I.getPair(), ActingDC, TemplateArgs, 12006 ObjectType, ObjectClassification, 12007 Args, CandidateSet, 12008 /*SuppressUsedConversions=*/false); 12009 } 12010 } 12011 12012 DeclarationName DeclName = UnresExpr->getMemberName(); 12013 12014 UnbridgedCasts.restore(); 12015 12016 OverloadCandidateSet::iterator Best; 12017 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12018 Best)) { 12019 case OR_Success: 12020 Method = cast<CXXMethodDecl>(Best->Function); 12021 FoundDecl = Best->FoundDecl; 12022 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12023 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12024 return ExprError(); 12025 // If FoundDecl is different from Method (such as if one is a template 12026 // and the other a specialization), make sure DiagnoseUseOfDecl is 12027 // called on both. 12028 // FIXME: This would be more comprehensively addressed by modifying 12029 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12030 // being used. 12031 if (Method != FoundDecl.getDecl() && 12032 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12033 return ExprError(); 12034 break; 12035 12036 case OR_No_Viable_Function: 12037 Diag(UnresExpr->getMemberLoc(), 12038 diag::err_ovl_no_viable_member_function_in_call) 12039 << DeclName << MemExprE->getSourceRange(); 12040 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12041 // FIXME: Leaking incoming expressions! 12042 return ExprError(); 12043 12044 case OR_Ambiguous: 12045 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12046 << DeclName << MemExprE->getSourceRange(); 12047 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12048 // FIXME: Leaking incoming expressions! 12049 return ExprError(); 12050 12051 case OR_Deleted: 12052 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12053 << Best->Function->isDeleted() 12054 << DeclName 12055 << getDeletedOrUnavailableSuffix(Best->Function) 12056 << MemExprE->getSourceRange(); 12057 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12058 // FIXME: Leaking incoming expressions! 12059 return ExprError(); 12060 } 12061 12062 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12063 12064 // If overload resolution picked a static member, build a 12065 // non-member call based on that function. 12066 if (Method->isStatic()) { 12067 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12068 RParenLoc); 12069 } 12070 12071 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12072 } 12073 12074 QualType ResultType = Method->getReturnType(); 12075 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12076 ResultType = ResultType.getNonLValueExprType(Context); 12077 12078 assert(Method && "Member call to something that isn't a method?"); 12079 CXXMemberCallExpr *TheCall = 12080 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12081 ResultType, VK, RParenLoc); 12082 12083 // (CUDA B.1): Check for invalid calls between targets. 12084 if (getLangOpts().CUDA) { 12085 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12086 if (CheckCUDATarget(Caller, Method)) { 12087 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12088 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12089 << IdentifyCUDATarget(Caller); 12090 return ExprError(); 12091 } 12092 } 12093 } 12094 12095 // Check for a valid return type. 12096 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12097 TheCall, Method)) 12098 return ExprError(); 12099 12100 // Convert the object argument (for a non-static member function call). 12101 // We only need to do this if there was actually an overload; otherwise 12102 // it was done at lookup. 12103 if (!Method->isStatic()) { 12104 ExprResult ObjectArg = 12105 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12106 FoundDecl, Method); 12107 if (ObjectArg.isInvalid()) 12108 return ExprError(); 12109 MemExpr->setBase(ObjectArg.get()); 12110 } 12111 12112 // Convert the rest of the arguments 12113 const FunctionProtoType *Proto = 12114 Method->getType()->getAs<FunctionProtoType>(); 12115 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12116 RParenLoc)) 12117 return ExprError(); 12118 12119 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12120 12121 if (CheckFunctionCall(Method, TheCall, Proto)) 12122 return ExprError(); 12123 12124 // In the case the method to call was not selected by the overloading 12125 // resolution process, we still need to handle the enable_if attribute. Do 12126 // that here, so it will not hide previous -- and more relevant -- errors 12127 if (isa<MemberExpr>(NakedMemExpr)) { 12128 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12129 Diag(MemExprE->getLocStart(), 12130 diag::err_ovl_no_viable_member_function_in_call) 12131 << Method << Method->getSourceRange(); 12132 Diag(Method->getLocation(), 12133 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12134 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12135 return ExprError(); 12136 } 12137 } 12138 12139 if ((isa<CXXConstructorDecl>(CurContext) || 12140 isa<CXXDestructorDecl>(CurContext)) && 12141 TheCall->getMethodDecl()->isPure()) { 12142 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12143 12144 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12145 MemExpr->performsVirtualDispatch(getLangOpts())) { 12146 Diag(MemExpr->getLocStart(), 12147 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12148 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12149 << MD->getParent()->getDeclName(); 12150 12151 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12152 if (getLangOpts().AppleKext) 12153 Diag(MemExpr->getLocStart(), 12154 diag::note_pure_qualified_call_kext) 12155 << MD->getParent()->getDeclName() 12156 << MD->getDeclName(); 12157 } 12158 } 12159 return MaybeBindToTemporary(TheCall); 12160 } 12161 12162 /// BuildCallToObjectOfClassType - Build a call to an object of class 12163 /// type (C++ [over.call.object]), which can end up invoking an 12164 /// overloaded function call operator (@c operator()) or performing a 12165 /// user-defined conversion on the object argument. 12166 ExprResult 12167 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12168 SourceLocation LParenLoc, 12169 MultiExprArg Args, 12170 SourceLocation RParenLoc) { 12171 if (checkPlaceholderForOverload(*this, Obj)) 12172 return ExprError(); 12173 ExprResult Object = Obj; 12174 12175 UnbridgedCastsSet UnbridgedCasts; 12176 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12177 return ExprError(); 12178 12179 assert(Object.get()->getType()->isRecordType() && 12180 "Requires object type argument"); 12181 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12182 12183 // C++ [over.call.object]p1: 12184 // If the primary-expression E in the function call syntax 12185 // evaluates to a class object of type "cv T", then the set of 12186 // candidate functions includes at least the function call 12187 // operators of T. The function call operators of T are obtained by 12188 // ordinary lookup of the name operator() in the context of 12189 // (E).operator(). 12190 OverloadCandidateSet CandidateSet(LParenLoc, 12191 OverloadCandidateSet::CSK_Operator); 12192 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12193 12194 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12195 diag::err_incomplete_object_call, Object.get())) 12196 return true; 12197 12198 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12199 LookupQualifiedName(R, Record->getDecl()); 12200 R.suppressDiagnostics(); 12201 12202 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12203 Oper != OperEnd; ++Oper) { 12204 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12205 Object.get()->Classify(Context), 12206 Args, CandidateSet, 12207 /*SuppressUserConversions=*/ false); 12208 } 12209 12210 // C++ [over.call.object]p2: 12211 // In addition, for each (non-explicit in C++0x) conversion function 12212 // declared in T of the form 12213 // 12214 // operator conversion-type-id () cv-qualifier; 12215 // 12216 // where cv-qualifier is the same cv-qualification as, or a 12217 // greater cv-qualification than, cv, and where conversion-type-id 12218 // denotes the type "pointer to function of (P1,...,Pn) returning 12219 // R", or the type "reference to pointer to function of 12220 // (P1,...,Pn) returning R", or the type "reference to function 12221 // of (P1,...,Pn) returning R", a surrogate call function [...] 12222 // is also considered as a candidate function. Similarly, 12223 // surrogate call functions are added to the set of candidate 12224 // functions for each conversion function declared in an 12225 // accessible base class provided the function is not hidden 12226 // within T by another intervening declaration. 12227 const auto &Conversions = 12228 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12229 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12230 NamedDecl *D = *I; 12231 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12232 if (isa<UsingShadowDecl>(D)) 12233 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12234 12235 // Skip over templated conversion functions; they aren't 12236 // surrogates. 12237 if (isa<FunctionTemplateDecl>(D)) 12238 continue; 12239 12240 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12241 if (!Conv->isExplicit()) { 12242 // Strip the reference type (if any) and then the pointer type (if 12243 // any) to get down to what might be a function type. 12244 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12245 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12246 ConvType = ConvPtrType->getPointeeType(); 12247 12248 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12249 { 12250 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12251 Object.get(), Args, CandidateSet); 12252 } 12253 } 12254 } 12255 12256 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12257 12258 // Perform overload resolution. 12259 OverloadCandidateSet::iterator Best; 12260 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12261 Best)) { 12262 case OR_Success: 12263 // Overload resolution succeeded; we'll build the appropriate call 12264 // below. 12265 break; 12266 12267 case OR_No_Viable_Function: 12268 if (CandidateSet.empty()) 12269 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12270 << Object.get()->getType() << /*call*/ 1 12271 << Object.get()->getSourceRange(); 12272 else 12273 Diag(Object.get()->getLocStart(), 12274 diag::err_ovl_no_viable_object_call) 12275 << Object.get()->getType() << Object.get()->getSourceRange(); 12276 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12277 break; 12278 12279 case OR_Ambiguous: 12280 Diag(Object.get()->getLocStart(), 12281 diag::err_ovl_ambiguous_object_call) 12282 << Object.get()->getType() << Object.get()->getSourceRange(); 12283 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12284 break; 12285 12286 case OR_Deleted: 12287 Diag(Object.get()->getLocStart(), 12288 diag::err_ovl_deleted_object_call) 12289 << Best->Function->isDeleted() 12290 << Object.get()->getType() 12291 << getDeletedOrUnavailableSuffix(Best->Function) 12292 << Object.get()->getSourceRange(); 12293 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12294 break; 12295 } 12296 12297 if (Best == CandidateSet.end()) 12298 return true; 12299 12300 UnbridgedCasts.restore(); 12301 12302 if (Best->Function == nullptr) { 12303 // Since there is no function declaration, this is one of the 12304 // surrogate candidates. Dig out the conversion function. 12305 CXXConversionDecl *Conv 12306 = cast<CXXConversionDecl>( 12307 Best->Conversions[0].UserDefined.ConversionFunction); 12308 12309 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12310 Best->FoundDecl); 12311 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12312 return ExprError(); 12313 assert(Conv == Best->FoundDecl.getDecl() && 12314 "Found Decl & conversion-to-functionptr should be same, right?!"); 12315 // We selected one of the surrogate functions that converts the 12316 // object parameter to a function pointer. Perform the conversion 12317 // on the object argument, then let ActOnCallExpr finish the job. 12318 12319 // Create an implicit member expr to refer to the conversion operator. 12320 // and then call it. 12321 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12322 Conv, HadMultipleCandidates); 12323 if (Call.isInvalid()) 12324 return ExprError(); 12325 // Record usage of conversion in an implicit cast. 12326 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12327 CK_UserDefinedConversion, Call.get(), 12328 nullptr, VK_RValue); 12329 12330 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12331 } 12332 12333 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12334 12335 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12336 // that calls this method, using Object for the implicit object 12337 // parameter and passing along the remaining arguments. 12338 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12339 12340 // An error diagnostic has already been printed when parsing the declaration. 12341 if (Method->isInvalidDecl()) 12342 return ExprError(); 12343 12344 const FunctionProtoType *Proto = 12345 Method->getType()->getAs<FunctionProtoType>(); 12346 12347 unsigned NumParams = Proto->getNumParams(); 12348 12349 DeclarationNameInfo OpLocInfo( 12350 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12351 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12352 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12353 HadMultipleCandidates, 12354 OpLocInfo.getLoc(), 12355 OpLocInfo.getInfo()); 12356 if (NewFn.isInvalid()) 12357 return true; 12358 12359 // Build the full argument list for the method call (the implicit object 12360 // parameter is placed at the beginning of the list). 12361 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12362 MethodArgs[0] = Object.get(); 12363 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12364 12365 // Once we've built TheCall, all of the expressions are properly 12366 // owned. 12367 QualType ResultTy = Method->getReturnType(); 12368 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12369 ResultTy = ResultTy.getNonLValueExprType(Context); 12370 12371 CXXOperatorCallExpr *TheCall = new (Context) 12372 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12373 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12374 ResultTy, VK, RParenLoc, false); 12375 MethodArgs.reset(); 12376 12377 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12378 return true; 12379 12380 // We may have default arguments. If so, we need to allocate more 12381 // slots in the call for them. 12382 if (Args.size() < NumParams) 12383 TheCall->setNumArgs(Context, NumParams + 1); 12384 12385 bool IsError = false; 12386 12387 // Initialize the implicit object parameter. 12388 ExprResult ObjRes = 12389 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12390 Best->FoundDecl, Method); 12391 if (ObjRes.isInvalid()) 12392 IsError = true; 12393 else 12394 Object = ObjRes; 12395 TheCall->setArg(0, Object.get()); 12396 12397 // Check the argument types. 12398 for (unsigned i = 0; i != NumParams; i++) { 12399 Expr *Arg; 12400 if (i < Args.size()) { 12401 Arg = Args[i]; 12402 12403 // Pass the argument. 12404 12405 ExprResult InputInit 12406 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12407 Context, 12408 Method->getParamDecl(i)), 12409 SourceLocation(), Arg); 12410 12411 IsError |= InputInit.isInvalid(); 12412 Arg = InputInit.getAs<Expr>(); 12413 } else { 12414 ExprResult DefArg 12415 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12416 if (DefArg.isInvalid()) { 12417 IsError = true; 12418 break; 12419 } 12420 12421 Arg = DefArg.getAs<Expr>(); 12422 } 12423 12424 TheCall->setArg(i + 1, Arg); 12425 } 12426 12427 // If this is a variadic call, handle args passed through "...". 12428 if (Proto->isVariadic()) { 12429 // Promote the arguments (C99 6.5.2.2p7). 12430 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12431 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12432 nullptr); 12433 IsError |= Arg.isInvalid(); 12434 TheCall->setArg(i + 1, Arg.get()); 12435 } 12436 } 12437 12438 if (IsError) return true; 12439 12440 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12441 12442 if (CheckFunctionCall(Method, TheCall, Proto)) 12443 return true; 12444 12445 return MaybeBindToTemporary(TheCall); 12446 } 12447 12448 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12449 /// (if one exists), where @c Base is an expression of class type and 12450 /// @c Member is the name of the member we're trying to find. 12451 ExprResult 12452 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12453 bool *NoArrowOperatorFound) { 12454 assert(Base->getType()->isRecordType() && 12455 "left-hand side must have class type"); 12456 12457 if (checkPlaceholderForOverload(*this, Base)) 12458 return ExprError(); 12459 12460 SourceLocation Loc = Base->getExprLoc(); 12461 12462 // C++ [over.ref]p1: 12463 // 12464 // [...] An expression x->m is interpreted as (x.operator->())->m 12465 // for a class object x of type T if T::operator->() exists and if 12466 // the operator is selected as the best match function by the 12467 // overload resolution mechanism (13.3). 12468 DeclarationName OpName = 12469 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12470 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12471 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12472 12473 if (RequireCompleteType(Loc, Base->getType(), 12474 diag::err_typecheck_incomplete_tag, Base)) 12475 return ExprError(); 12476 12477 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12478 LookupQualifiedName(R, BaseRecord->getDecl()); 12479 R.suppressDiagnostics(); 12480 12481 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12482 Oper != OperEnd; ++Oper) { 12483 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12484 None, CandidateSet, /*SuppressUserConversions=*/false); 12485 } 12486 12487 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12488 12489 // Perform overload resolution. 12490 OverloadCandidateSet::iterator Best; 12491 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12492 case OR_Success: 12493 // Overload resolution succeeded; we'll build the call below. 12494 break; 12495 12496 case OR_No_Viable_Function: 12497 if (CandidateSet.empty()) { 12498 QualType BaseType = Base->getType(); 12499 if (NoArrowOperatorFound) { 12500 // Report this specific error to the caller instead of emitting a 12501 // diagnostic, as requested. 12502 *NoArrowOperatorFound = true; 12503 return ExprError(); 12504 } 12505 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12506 << BaseType << Base->getSourceRange(); 12507 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12508 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12509 << FixItHint::CreateReplacement(OpLoc, "."); 12510 } 12511 } else 12512 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12513 << "operator->" << Base->getSourceRange(); 12514 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12515 return ExprError(); 12516 12517 case OR_Ambiguous: 12518 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12519 << "->" << Base->getType() << Base->getSourceRange(); 12520 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12521 return ExprError(); 12522 12523 case OR_Deleted: 12524 Diag(OpLoc, diag::err_ovl_deleted_oper) 12525 << Best->Function->isDeleted() 12526 << "->" 12527 << getDeletedOrUnavailableSuffix(Best->Function) 12528 << Base->getSourceRange(); 12529 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12530 return ExprError(); 12531 } 12532 12533 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12534 12535 // Convert the object parameter. 12536 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12537 ExprResult BaseResult = 12538 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12539 Best->FoundDecl, Method); 12540 if (BaseResult.isInvalid()) 12541 return ExprError(); 12542 Base = BaseResult.get(); 12543 12544 // Build the operator call. 12545 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12546 HadMultipleCandidates, OpLoc); 12547 if (FnExpr.isInvalid()) 12548 return ExprError(); 12549 12550 QualType ResultTy = Method->getReturnType(); 12551 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12552 ResultTy = ResultTy.getNonLValueExprType(Context); 12553 CXXOperatorCallExpr *TheCall = 12554 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12555 Base, ResultTy, VK, OpLoc, false); 12556 12557 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12558 return ExprError(); 12559 12560 return MaybeBindToTemporary(TheCall); 12561 } 12562 12563 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12564 /// a literal operator described by the provided lookup results. 12565 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12566 DeclarationNameInfo &SuffixInfo, 12567 ArrayRef<Expr*> Args, 12568 SourceLocation LitEndLoc, 12569 TemplateArgumentListInfo *TemplateArgs) { 12570 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12571 12572 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12573 OverloadCandidateSet::CSK_Normal); 12574 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12575 /*SuppressUserConversions=*/true); 12576 12577 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12578 12579 // Perform overload resolution. This will usually be trivial, but might need 12580 // to perform substitutions for a literal operator template. 12581 OverloadCandidateSet::iterator Best; 12582 switch (CandidateSet.BestViableFunction(*this,