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 llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 64 VK_LValue, Loc, LocInfo); 65 if (HadMultipleCandidates) 66 DRE->setHadMultipleCandidates(true); 67 68 S.MarkDeclRefReferenced(DRE); 69 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 70 CK_FunctionToPointerDecay); 71 } 72 73 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 74 bool InOverloadResolution, 75 StandardConversionSequence &SCS, 76 bool CStyle, 77 bool AllowObjCWritebackConversion); 78 79 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 80 QualType &ToType, 81 bool InOverloadResolution, 82 StandardConversionSequence &SCS, 83 bool CStyle); 84 static OverloadingResult 85 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 86 UserDefinedConversionSequence& User, 87 OverloadCandidateSet& Conversions, 88 bool AllowExplicit, 89 bool AllowObjCConversionOnExplicit); 90 91 92 static ImplicitConversionSequence::CompareKind 93 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97 static ImplicitConversionSequence::CompareKind 98 CompareQualificationConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 static ImplicitConversionSequence::CompareKind 103 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 104 const StandardConversionSequence& SCS1, 105 const StandardConversionSequence& SCS2); 106 107 /// GetConversionRank - Retrieve the implicit conversion rank 108 /// corresponding to the given implicit conversion kind. 109 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 110 static const ImplicitConversionRank 111 Rank[(int)ICK_Num_Conversion_Kinds] = { 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Promotion, 119 ICR_Promotion, 120 ICR_Promotion, 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_Conversion, 132 ICR_Complex_Real_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Writeback_Conversion, 136 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 137 // it was omitted by the patch that added 138 // ICK_Zero_Event_Conversion 139 ICR_C_Conversion, 140 ICR_C_Conversion_Extension 141 }; 142 return Rank[(int)Kind]; 143 } 144 145 /// GetImplicitConversionName - Return the name of this kind of 146 /// implicit conversion. 147 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 148 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 149 "No conversion", 150 "Lvalue-to-rvalue", 151 "Array-to-pointer", 152 "Function-to-pointer", 153 "Noreturn adjustment", 154 "Qualification", 155 "Integral promotion", 156 "Floating point promotion", 157 "Complex promotion", 158 "Integral conversion", 159 "Floating conversion", 160 "Complex conversion", 161 "Floating-integral conversion", 162 "Pointer conversion", 163 "Pointer-to-member conversion", 164 "Boolean conversion", 165 "Compatible-types conversion", 166 "Derived-to-base conversion", 167 "Vector conversion", 168 "Vector splat", 169 "Complex-real conversion", 170 "Block Pointer conversion", 171 "Transparent Union Conversion", 172 "Writeback conversion", 173 "OpenCL Zero Event Conversion", 174 "C specific type conversion", 175 "Incompatible pointer conversion" 176 }; 177 return Name[Kind]; 178 } 179 180 /// StandardConversionSequence - Set the standard conversion 181 /// sequence to the identity conversion. 182 void StandardConversionSequence::setAsIdentityConversion() { 183 First = ICK_Identity; 184 Second = ICK_Identity; 185 Third = ICK_Identity; 186 DeprecatedStringLiteralToCharPtr = false; 187 QualificationIncludesObjCLifetime = false; 188 ReferenceBinding = false; 189 DirectBinding = false; 190 IsLvalueReference = true; 191 BindsToFunctionLvalue = false; 192 BindsToRvalue = false; 193 BindsImplicitObjectArgumentWithoutRefQualifier = false; 194 ObjCLifetimeConversionBinding = false; 195 CopyConstructor = nullptr; 196 } 197 198 /// getRank - Retrieve the rank of this standard conversion sequence 199 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 200 /// implicit conversions. 201 ImplicitConversionRank StandardConversionSequence::getRank() const { 202 ImplicitConversionRank Rank = ICR_Exact_Match; 203 if (GetConversionRank(First) > Rank) 204 Rank = GetConversionRank(First); 205 if (GetConversionRank(Second) > Rank) 206 Rank = GetConversionRank(Second); 207 if (GetConversionRank(Third) > Rank) 208 Rank = GetConversionRank(Third); 209 return Rank; 210 } 211 212 /// isPointerConversionToBool - Determines whether this conversion is 213 /// a conversion of a pointer or pointer-to-member to bool. This is 214 /// used as part of the ranking of standard conversion sequences 215 /// (C++ 13.3.3.2p4). 216 bool StandardConversionSequence::isPointerConversionToBool() const { 217 // Note that FromType has not necessarily been transformed by the 218 // array-to-pointer or function-to-pointer implicit conversions, so 219 // check for their presence as well as checking whether FromType is 220 // a pointer. 221 if (getToType(1)->isBooleanType() && 222 (getFromType()->isPointerType() || 223 getFromType()->isObjCObjectPointerType() || 224 getFromType()->isBlockPointerType() || 225 getFromType()->isNullPtrType() || 226 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 227 return true; 228 229 return false; 230 } 231 232 /// isPointerConversionToVoidPointer - Determines whether this 233 /// conversion is a conversion of a pointer to a void pointer. This is 234 /// used as part of the ranking of standard conversion sequences (C++ 235 /// 13.3.3.2p4). 236 bool 237 StandardConversionSequence:: 238 isPointerConversionToVoidPointer(ASTContext& Context) const { 239 QualType FromType = getFromType(); 240 QualType ToType = getToType(1); 241 242 // Note that FromType has not necessarily been transformed by the 243 // array-to-pointer implicit conversion, so check for its presence 244 // and redo the conversion to get a pointer. 245 if (First == ICK_Array_To_Pointer) 246 FromType = Context.getArrayDecayedType(FromType); 247 248 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 249 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 250 return ToPtrType->getPointeeType()->isVoidType(); 251 252 return false; 253 } 254 255 /// Skip any implicit casts which could be either part of a narrowing conversion 256 /// or after one in an implicit conversion. 257 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 258 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 259 switch (ICE->getCastKind()) { 260 case CK_NoOp: 261 case CK_IntegralCast: 262 case CK_IntegralToBoolean: 263 case CK_IntegralToFloating: 264 case CK_BooleanToSignedIntegral: 265 case CK_FloatingToIntegral: 266 case CK_FloatingToBoolean: 267 case CK_FloatingCast: 268 Converted = ICE->getSubExpr(); 269 continue; 270 271 default: 272 return Converted; 273 } 274 } 275 276 return Converted; 277 } 278 279 /// Check if this standard conversion sequence represents a narrowing 280 /// conversion, according to C++11 [dcl.init.list]p7. 281 /// 282 /// \param Ctx The AST context. 283 /// \param Converted The result of applying this standard conversion sequence. 284 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 285 /// value of the expression prior to the narrowing conversion. 286 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 287 /// type of the expression prior to the narrowing conversion. 288 NarrowingKind 289 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 290 const Expr *Converted, 291 APValue &ConstantValue, 292 QualType &ConstantType) const { 293 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 294 295 // C++11 [dcl.init.list]p7: 296 // A narrowing conversion is an implicit conversion ... 297 QualType FromType = getToType(0); 298 QualType ToType = getToType(1); 299 300 // A conversion to an enumeration type is narrowing if the conversion to 301 // the underlying type is narrowing. This only arises for expressions of 302 // the form 'Enum{init}'. 303 if (auto *ET = ToType->getAs<EnumType>()) 304 ToType = ET->getDecl()->getIntegerType(); 305 306 switch (Second) { 307 // 'bool' is an integral type; dispatch to the right place to handle it. 308 case ICK_Boolean_Conversion: 309 if (FromType->isRealFloatingType()) 310 goto FloatingIntegralConversion; 311 if (FromType->isIntegralOrUnscopedEnumerationType()) 312 goto IntegralConversion; 313 // Boolean conversions can be from pointers and pointers to members 314 // [conv.bool], and those aren't considered narrowing conversions. 315 return NK_Not_Narrowing; 316 317 // -- from a floating-point type to an integer type, or 318 // 319 // -- from an integer type or unscoped enumeration type to a floating-point 320 // type, except where the source is a constant expression and the actual 321 // value after conversion will fit into the target type and will produce 322 // the original value when converted back to the original type, or 323 case ICK_Floating_Integral: 324 FloatingIntegralConversion: 325 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 326 return NK_Type_Narrowing; 327 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 328 llvm::APSInt IntConstantValue; 329 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 330 if (Initializer && 331 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 332 // Convert the integer to the floating type. 333 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 334 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 335 llvm::APFloat::rmNearestTiesToEven); 336 // And back. 337 llvm::APSInt ConvertedValue = IntConstantValue; 338 bool ignored; 339 Result.convertToInteger(ConvertedValue, 340 llvm::APFloat::rmTowardZero, &ignored); 341 // If the resulting value is different, this was a narrowing conversion. 342 if (IntConstantValue != ConvertedValue) { 343 ConstantValue = APValue(IntConstantValue); 344 ConstantType = Initializer->getType(); 345 return NK_Constant_Narrowing; 346 } 347 } else { 348 // Variables are always narrowings. 349 return NK_Variable_Narrowing; 350 } 351 } 352 return NK_Not_Narrowing; 353 354 // -- from long double to double or float, or from double to float, except 355 // where the source is a constant expression and the actual value after 356 // conversion is within the range of values that can be represented (even 357 // if it cannot be represented exactly), or 358 case ICK_Floating_Conversion: 359 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 360 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 361 // FromType is larger than ToType. 362 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 363 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 364 // Constant! 365 assert(ConstantValue.isFloat()); 366 llvm::APFloat FloatVal = ConstantValue.getFloat(); 367 // Convert the source value into the target type. 368 bool ignored; 369 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 370 Ctx.getFloatTypeSemantics(ToType), 371 llvm::APFloat::rmNearestTiesToEven, &ignored); 372 // If there was no overflow, the source value is within the range of 373 // values that can be represented. 374 if (ConvertStatus & llvm::APFloat::opOverflow) { 375 ConstantType = Initializer->getType(); 376 return NK_Constant_Narrowing; 377 } 378 } else { 379 return NK_Variable_Narrowing; 380 } 381 } 382 return NK_Not_Narrowing; 383 384 // -- from an integer type or unscoped enumeration type to an integer type 385 // that cannot represent all the values of the original type, except where 386 // the source is a constant expression and the actual value after 387 // conversion will fit into the target type and will produce the original 388 // value when converted back to the original type. 389 case ICK_Integral_Conversion: 390 IntegralConversion: { 391 assert(FromType->isIntegralOrUnscopedEnumerationType()); 392 assert(ToType->isIntegralOrUnscopedEnumerationType()); 393 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 394 const unsigned FromWidth = Ctx.getIntWidth(FromType); 395 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 396 const unsigned ToWidth = Ctx.getIntWidth(ToType); 397 398 if (FromWidth > ToWidth || 399 (FromWidth == ToWidth && FromSigned != ToSigned) || 400 (FromSigned && !ToSigned)) { 401 // Not all values of FromType can be represented in ToType. 402 llvm::APSInt InitializerValue; 403 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 404 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 405 // Such conversions on variables are always narrowing. 406 return NK_Variable_Narrowing; 407 } 408 bool Narrowing = false; 409 if (FromWidth < ToWidth) { 410 // Negative -> unsigned is narrowing. Otherwise, more bits is never 411 // narrowing. 412 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 413 Narrowing = true; 414 } else { 415 // Add a bit to the InitializerValue so we don't have to worry about 416 // signed vs. unsigned comparisons. 417 InitializerValue = InitializerValue.extend( 418 InitializerValue.getBitWidth() + 1); 419 // Convert the initializer to and from the target width and signed-ness. 420 llvm::APSInt ConvertedValue = InitializerValue; 421 ConvertedValue = ConvertedValue.trunc(ToWidth); 422 ConvertedValue.setIsSigned(ToSigned); 423 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 424 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 425 // If the result is different, this was a narrowing conversion. 426 if (ConvertedValue != InitializerValue) 427 Narrowing = true; 428 } 429 if (Narrowing) { 430 ConstantType = Initializer->getType(); 431 ConstantValue = APValue(InitializerValue); 432 return NK_Constant_Narrowing; 433 } 434 } 435 return NK_Not_Narrowing; 436 } 437 438 default: 439 // Other kinds of conversions are not narrowings. 440 return NK_Not_Narrowing; 441 } 442 } 443 444 /// dump - Print this standard conversion sequence to standard 445 /// error. Useful for debugging overloading issues. 446 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 447 raw_ostream &OS = llvm::errs(); 448 bool PrintedSomething = false; 449 if (First != ICK_Identity) { 450 OS << GetImplicitConversionName(First); 451 PrintedSomething = true; 452 } 453 454 if (Second != ICK_Identity) { 455 if (PrintedSomething) { 456 OS << " -> "; 457 } 458 OS << GetImplicitConversionName(Second); 459 460 if (CopyConstructor) { 461 OS << " (by copy constructor)"; 462 } else if (DirectBinding) { 463 OS << " (direct reference binding)"; 464 } else if (ReferenceBinding) { 465 OS << " (reference binding)"; 466 } 467 PrintedSomething = true; 468 } 469 470 if (Third != ICK_Identity) { 471 if (PrintedSomething) { 472 OS << " -> "; 473 } 474 OS << GetImplicitConversionName(Third); 475 PrintedSomething = true; 476 } 477 478 if (!PrintedSomething) { 479 OS << "No conversions required"; 480 } 481 } 482 483 /// dump - Print this user-defined conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 void UserDefinedConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 if (Before.First || Before.Second || Before.Third) { 488 Before.dump(); 489 OS << " -> "; 490 } 491 if (ConversionFunction) 492 OS << '\'' << *ConversionFunction << '\''; 493 else 494 OS << "aggregate initialization"; 495 if (After.First || After.Second || After.Third) { 496 OS << " -> "; 497 After.dump(); 498 } 499 } 500 501 /// dump - Print this implicit conversion sequence to standard 502 /// error. Useful for debugging overloading issues. 503 void ImplicitConversionSequence::dump() const { 504 raw_ostream &OS = llvm::errs(); 505 if (isStdInitializerListElement()) 506 OS << "Worst std::initializer_list element conversion: "; 507 switch (ConversionKind) { 508 case StandardConversion: 509 OS << "Standard conversion: "; 510 Standard.dump(); 511 break; 512 case UserDefinedConversion: 513 OS << "User-defined conversion: "; 514 UserDefined.dump(); 515 break; 516 case EllipsisConversion: 517 OS << "Ellipsis conversion"; 518 break; 519 case AmbiguousConversion: 520 OS << "Ambiguous conversion"; 521 break; 522 case BadConversion: 523 OS << "Bad conversion"; 524 break; 525 } 526 527 OS << "\n"; 528 } 529 530 void AmbiguousConversionSequence::construct() { 531 new (&conversions()) ConversionSet(); 532 } 533 534 void AmbiguousConversionSequence::destruct() { 535 conversions().~ConversionSet(); 536 } 537 538 void 539 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 540 FromTypePtr = O.FromTypePtr; 541 ToTypePtr = O.ToTypePtr; 542 new (&conversions()) ConversionSet(O.conversions()); 543 } 544 545 namespace { 546 // Structure used by DeductionFailureInfo to store 547 // template argument information. 548 struct DFIArguments { 549 TemplateArgument FirstArg; 550 TemplateArgument SecondArg; 551 }; 552 // Structure used by DeductionFailureInfo to store 553 // template parameter and template argument information. 554 struct DFIParamWithArguments : DFIArguments { 555 TemplateParameter Param; 556 }; 557 // Structure used by DeductionFailureInfo to store template argument 558 // information and the index of the problematic call argument. 559 struct DFIDeducedMismatchArgs : DFIArguments { 560 TemplateArgumentList *TemplateArgs; 561 unsigned CallArgIndex; 562 }; 563 } 564 565 /// \brief Convert from Sema's representation of template deduction information 566 /// to the form used in overload-candidate information. 567 DeductionFailureInfo 568 clang::MakeDeductionFailureInfo(ASTContext &Context, 569 Sema::TemplateDeductionResult TDK, 570 TemplateDeductionInfo &Info) { 571 DeductionFailureInfo Result; 572 Result.Result = static_cast<unsigned>(TDK); 573 Result.HasDiagnostic = false; 574 switch (TDK) { 575 case Sema::TDK_Success: 576 case Sema::TDK_Invalid: 577 case Sema::TDK_InstantiationDepth: 578 case Sema::TDK_TooManyArguments: 579 case Sema::TDK_TooFewArguments: 580 case Sema::TDK_MiscellaneousDeductionFailure: 581 Result.Data = nullptr; 582 break; 583 584 case Sema::TDK_Incomplete: 585 case Sema::TDK_InvalidExplicitArguments: 586 Result.Data = Info.Param.getOpaqueValue(); 587 break; 588 589 case Sema::TDK_DeducedMismatch: { 590 // FIXME: Should allocate from normal heap so that we can free this later. 591 auto *Saved = new (Context) DFIDeducedMismatchArgs; 592 Saved->FirstArg = Info.FirstArg; 593 Saved->SecondArg = Info.SecondArg; 594 Saved->TemplateArgs = Info.take(); 595 Saved->CallArgIndex = Info.CallArgIndex; 596 Result.Data = Saved; 597 break; 598 } 599 600 case Sema::TDK_NonDeducedMismatch: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIArguments *Saved = new (Context) DFIArguments; 603 Saved->FirstArg = Info.FirstArg; 604 Saved->SecondArg = Info.SecondArg; 605 Result.Data = Saved; 606 break; 607 } 608 609 case Sema::TDK_Inconsistent: 610 case Sema::TDK_Underqualified: { 611 // FIXME: Should allocate from normal heap so that we can free this later. 612 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 613 Saved->Param = Info.Param; 614 Saved->FirstArg = Info.FirstArg; 615 Saved->SecondArg = Info.SecondArg; 616 Result.Data = Saved; 617 break; 618 } 619 620 case Sema::TDK_SubstitutionFailure: 621 Result.Data = Info.take(); 622 if (Info.hasSFINAEDiagnostic()) { 623 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 624 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 625 Info.takeSFINAEDiagnostic(*Diag); 626 Result.HasDiagnostic = true; 627 } 628 break; 629 630 case Sema::TDK_FailedOverloadResolution: 631 Result.Data = Info.Expression; 632 break; 633 } 634 635 return Result; 636 } 637 638 void DeductionFailureInfo::Destroy() { 639 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 640 case Sema::TDK_Success: 641 case Sema::TDK_Invalid: 642 case Sema::TDK_InstantiationDepth: 643 case Sema::TDK_Incomplete: 644 case Sema::TDK_TooManyArguments: 645 case Sema::TDK_TooFewArguments: 646 case Sema::TDK_InvalidExplicitArguments: 647 case Sema::TDK_FailedOverloadResolution: 648 break; 649 650 case Sema::TDK_Inconsistent: 651 case Sema::TDK_Underqualified: 652 case Sema::TDK_DeducedMismatch: 653 case Sema::TDK_NonDeducedMismatch: 654 // FIXME: Destroy the data? 655 Data = nullptr; 656 break; 657 658 case Sema::TDK_SubstitutionFailure: 659 // FIXME: Destroy the template argument list? 660 Data = nullptr; 661 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 662 Diag->~PartialDiagnosticAt(); 663 HasDiagnostic = false; 664 } 665 break; 666 667 // Unhandled 668 case Sema::TDK_MiscellaneousDeductionFailure: 669 break; 670 } 671 } 672 673 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 674 if (HasDiagnostic) 675 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 676 return nullptr; 677 } 678 679 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 681 case Sema::TDK_Success: 682 case Sema::TDK_Invalid: 683 case Sema::TDK_InstantiationDepth: 684 case Sema::TDK_TooManyArguments: 685 case Sema::TDK_TooFewArguments: 686 case Sema::TDK_SubstitutionFailure: 687 case Sema::TDK_DeducedMismatch: 688 case Sema::TDK_NonDeducedMismatch: 689 case Sema::TDK_FailedOverloadResolution: 690 return TemplateParameter(); 691 692 case Sema::TDK_Incomplete: 693 case Sema::TDK_InvalidExplicitArguments: 694 return TemplateParameter::getFromOpaqueValue(Data); 695 696 case Sema::TDK_Inconsistent: 697 case Sema::TDK_Underqualified: 698 return static_cast<DFIParamWithArguments*>(Data)->Param; 699 700 // Unhandled 701 case Sema::TDK_MiscellaneousDeductionFailure: 702 break; 703 } 704 705 return TemplateParameter(); 706 } 707 708 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 709 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 710 case Sema::TDK_Success: 711 case Sema::TDK_Invalid: 712 case Sema::TDK_InstantiationDepth: 713 case Sema::TDK_TooManyArguments: 714 case Sema::TDK_TooFewArguments: 715 case Sema::TDK_Incomplete: 716 case Sema::TDK_InvalidExplicitArguments: 717 case Sema::TDK_Inconsistent: 718 case Sema::TDK_Underqualified: 719 case Sema::TDK_NonDeducedMismatch: 720 case Sema::TDK_FailedOverloadResolution: 721 return nullptr; 722 723 case Sema::TDK_DeducedMismatch: 724 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 725 726 case Sema::TDK_SubstitutionFailure: 727 return static_cast<TemplateArgumentList*>(Data); 728 729 // Unhandled 730 case Sema::TDK_MiscellaneousDeductionFailure: 731 break; 732 } 733 734 return nullptr; 735 } 736 737 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 738 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 739 case Sema::TDK_Success: 740 case Sema::TDK_Invalid: 741 case Sema::TDK_InstantiationDepth: 742 case Sema::TDK_Incomplete: 743 case Sema::TDK_TooManyArguments: 744 case Sema::TDK_TooFewArguments: 745 case Sema::TDK_InvalidExplicitArguments: 746 case Sema::TDK_SubstitutionFailure: 747 case Sema::TDK_FailedOverloadResolution: 748 return nullptr; 749 750 case Sema::TDK_Inconsistent: 751 case Sema::TDK_Underqualified: 752 case Sema::TDK_DeducedMismatch: 753 case Sema::TDK_NonDeducedMismatch: 754 return &static_cast<DFIArguments*>(Data)->FirstArg; 755 756 // Unhandled 757 case Sema::TDK_MiscellaneousDeductionFailure: 758 break; 759 } 760 761 return nullptr; 762 } 763 764 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 765 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 766 case Sema::TDK_Success: 767 case Sema::TDK_Invalid: 768 case Sema::TDK_InstantiationDepth: 769 case Sema::TDK_Incomplete: 770 case Sema::TDK_TooManyArguments: 771 case Sema::TDK_TooFewArguments: 772 case Sema::TDK_InvalidExplicitArguments: 773 case Sema::TDK_SubstitutionFailure: 774 case Sema::TDK_FailedOverloadResolution: 775 return nullptr; 776 777 case Sema::TDK_Inconsistent: 778 case Sema::TDK_Underqualified: 779 case Sema::TDK_DeducedMismatch: 780 case Sema::TDK_NonDeducedMismatch: 781 return &static_cast<DFIArguments*>(Data)->SecondArg; 782 783 // Unhandled 784 case Sema::TDK_MiscellaneousDeductionFailure: 785 break; 786 } 787 788 return nullptr; 789 } 790 791 Expr *DeductionFailureInfo::getExpr() { 792 if (static_cast<Sema::TemplateDeductionResult>(Result) == 793 Sema::TDK_FailedOverloadResolution) 794 return static_cast<Expr*>(Data); 795 796 return nullptr; 797 } 798 799 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 800 if (static_cast<Sema::TemplateDeductionResult>(Result) == 801 Sema::TDK_DeducedMismatch) 802 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 803 804 return llvm::None; 805 } 806 807 void OverloadCandidateSet::destroyCandidates() { 808 for (iterator i = begin(), e = end(); i != e; ++i) { 809 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 810 i->Conversions[ii].~ImplicitConversionSequence(); 811 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 812 i->DeductionFailure.Destroy(); 813 } 814 } 815 816 void OverloadCandidateSet::clear() { 817 destroyCandidates(); 818 NumInlineSequences = 0; 819 Candidates.clear(); 820 Functions.clear(); 821 } 822 823 namespace { 824 class UnbridgedCastsSet { 825 struct Entry { 826 Expr **Addr; 827 Expr *Saved; 828 }; 829 SmallVector<Entry, 2> Entries; 830 831 public: 832 void save(Sema &S, Expr *&E) { 833 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 834 Entry entry = { &E, E }; 835 Entries.push_back(entry); 836 E = S.stripARCUnbridgedCast(E); 837 } 838 839 void restore() { 840 for (SmallVectorImpl<Entry>::iterator 841 i = Entries.begin(), e = Entries.end(); i != e; ++i) 842 *i->Addr = i->Saved; 843 } 844 }; 845 } 846 847 /// checkPlaceholderForOverload - Do any interesting placeholder-like 848 /// preprocessing on the given expression. 849 /// 850 /// \param unbridgedCasts a collection to which to add unbridged casts; 851 /// without this, they will be immediately diagnosed as errors 852 /// 853 /// Return true on unrecoverable error. 854 static bool 855 checkPlaceholderForOverload(Sema &S, Expr *&E, 856 UnbridgedCastsSet *unbridgedCasts = nullptr) { 857 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 858 // We can't handle overloaded expressions here because overload 859 // resolution might reasonably tweak them. 860 if (placeholder->getKind() == BuiltinType::Overload) return false; 861 862 // If the context potentially accepts unbridged ARC casts, strip 863 // the unbridged cast and add it to the collection for later restoration. 864 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 865 unbridgedCasts) { 866 unbridgedCasts->save(S, E); 867 return false; 868 } 869 870 // Go ahead and check everything else. 871 ExprResult result = S.CheckPlaceholderExpr(E); 872 if (result.isInvalid()) 873 return true; 874 875 E = result.get(); 876 return false; 877 } 878 879 // Nothing to do. 880 return false; 881 } 882 883 /// checkArgPlaceholdersForOverload - Check a set of call operands for 884 /// placeholders. 885 static bool checkArgPlaceholdersForOverload(Sema &S, 886 MultiExprArg Args, 887 UnbridgedCastsSet &unbridged) { 888 for (unsigned i = 0, e = Args.size(); i != e; ++i) 889 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 890 return true; 891 892 return false; 893 } 894 895 // IsOverload - Determine whether the given New declaration is an 896 // overload of the declarations in Old. This routine returns false if 897 // New and Old cannot be overloaded, e.g., if New has the same 898 // signature as some function in Old (C++ 1.3.10) or if the Old 899 // declarations aren't functions (or function templates) at all. When 900 // it does return false, MatchedDecl will point to the decl that New 901 // cannot be overloaded with. This decl may be a UsingShadowDecl on 902 // top of the underlying declaration. 903 // 904 // Example: Given the following input: 905 // 906 // void f(int, float); // #1 907 // void f(int, int); // #2 908 // int f(int, int); // #3 909 // 910 // When we process #1, there is no previous declaration of "f", 911 // so IsOverload will not be used. 912 // 913 // When we process #2, Old contains only the FunctionDecl for #1. By 914 // comparing the parameter types, we see that #1 and #2 are overloaded 915 // (since they have different signatures), so this routine returns 916 // false; MatchedDecl is unchanged. 917 // 918 // When we process #3, Old is an overload set containing #1 and #2. We 919 // compare the signatures of #3 to #1 (they're overloaded, so we do 920 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 921 // identical (return types of functions are not part of the 922 // signature), IsOverload returns false and MatchedDecl will be set to 923 // point to the FunctionDecl for #2. 924 // 925 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 926 // into a class by a using declaration. The rules for whether to hide 927 // shadow declarations ignore some properties which otherwise figure 928 // into a function template's signature. 929 Sema::OverloadKind 930 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 931 NamedDecl *&Match, bool NewIsUsingDecl) { 932 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 933 I != E; ++I) { 934 NamedDecl *OldD = *I; 935 936 bool OldIsUsingDecl = false; 937 if (isa<UsingShadowDecl>(OldD)) { 938 OldIsUsingDecl = true; 939 940 // We can always introduce two using declarations into the same 941 // context, even if they have identical signatures. 942 if (NewIsUsingDecl) continue; 943 944 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 945 } 946 947 // A using-declaration does not conflict with another declaration 948 // if one of them is hidden. 949 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 950 continue; 951 952 // If either declaration was introduced by a using declaration, 953 // we'll need to use slightly different rules for matching. 954 // Essentially, these rules are the normal rules, except that 955 // function templates hide function templates with different 956 // return types or template parameter lists. 957 bool UseMemberUsingDeclRules = 958 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 959 !New->getFriendObjectKind(); 960 961 if (FunctionDecl *OldF = OldD->getAsFunction()) { 962 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 963 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 964 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 965 continue; 966 } 967 968 if (!isa<FunctionTemplateDecl>(OldD) && 969 !shouldLinkPossiblyHiddenDecl(*I, New)) 970 continue; 971 972 Match = *I; 973 return Ovl_Match; 974 } 975 } else if (isa<UsingDecl>(OldD)) { 976 // We can overload with these, which can show up when doing 977 // redeclaration checks for UsingDecls. 978 assert(Old.getLookupKind() == LookupUsingDeclName); 979 } else if (isa<TagDecl>(OldD)) { 980 // We can always overload with tags by hiding them. 981 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 982 // Optimistically assume that an unresolved using decl will 983 // overload; if it doesn't, we'll have to diagnose during 984 // template instantiation. 985 } else { 986 // (C++ 13p1): 987 // Only function declarations can be overloaded; object and type 988 // declarations cannot be overloaded. 989 Match = *I; 990 return Ovl_NonFunction; 991 } 992 } 993 994 return Ovl_Overload; 995 } 996 997 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 998 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 999 // C++ [basic.start.main]p2: This function shall not be overloaded. 1000 if (New->isMain()) 1001 return false; 1002 1003 // MSVCRT user defined entry points cannot be overloaded. 1004 if (New->isMSVCRTEntryPoint()) 1005 return false; 1006 1007 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1008 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1009 1010 // C++ [temp.fct]p2: 1011 // A function template can be overloaded with other function templates 1012 // and with normal (non-template) functions. 1013 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1014 return true; 1015 1016 // Is the function New an overload of the function Old? 1017 QualType OldQType = Context.getCanonicalType(Old->getType()); 1018 QualType NewQType = Context.getCanonicalType(New->getType()); 1019 1020 // Compare the signatures (C++ 1.3.10) of the two functions to 1021 // determine whether they are overloads. If we find any mismatch 1022 // in the signature, they are overloads. 1023 1024 // If either of these functions is a K&R-style function (no 1025 // prototype), then we consider them to have matching signatures. 1026 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1027 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1028 return false; 1029 1030 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1031 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1032 1033 // The signature of a function includes the types of its 1034 // parameters (C++ 1.3.10), which includes the presence or absence 1035 // of the ellipsis; see C++ DR 357). 1036 if (OldQType != NewQType && 1037 (OldType->getNumParams() != NewType->getNumParams() || 1038 OldType->isVariadic() != NewType->isVariadic() || 1039 !FunctionParamTypesAreEqual(OldType, NewType))) 1040 return true; 1041 1042 // C++ [temp.over.link]p4: 1043 // The signature of a function template consists of its function 1044 // signature, its return type and its template parameter list. The names 1045 // of the template parameters are significant only for establishing the 1046 // relationship between the template parameters and the rest of the 1047 // signature. 1048 // 1049 // We check the return type and template parameter lists for function 1050 // templates first; the remaining checks follow. 1051 // 1052 // However, we don't consider either of these when deciding whether 1053 // a member introduced by a shadow declaration is hidden. 1054 if (!UseMemberUsingDeclRules && NewTemplate && 1055 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1056 OldTemplate->getTemplateParameters(), 1057 false, TPL_TemplateMatch) || 1058 OldType->getReturnType() != NewType->getReturnType())) 1059 return true; 1060 1061 // If the function is a class member, its signature includes the 1062 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1063 // 1064 // As part of this, also check whether one of the member functions 1065 // is static, in which case they are not overloads (C++ 1066 // 13.1p2). While not part of the definition of the signature, 1067 // this check is important to determine whether these functions 1068 // can be overloaded. 1069 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1070 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1071 if (OldMethod && NewMethod && 1072 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1073 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1074 if (!UseMemberUsingDeclRules && 1075 (OldMethod->getRefQualifier() == RQ_None || 1076 NewMethod->getRefQualifier() == RQ_None)) { 1077 // C++0x [over.load]p2: 1078 // - Member function declarations with the same name and the same 1079 // parameter-type-list as well as member function template 1080 // declarations with the same name, the same parameter-type-list, and 1081 // the same template parameter lists cannot be overloaded if any of 1082 // them, but not all, have a ref-qualifier (8.3.5). 1083 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1084 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1085 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1086 } 1087 return true; 1088 } 1089 1090 // We may not have applied the implicit const for a constexpr member 1091 // function yet (because we haven't yet resolved whether this is a static 1092 // or non-static member function). Add it now, on the assumption that this 1093 // is a redeclaration of OldMethod. 1094 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1095 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1096 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1097 !isa<CXXConstructorDecl>(NewMethod)) 1098 NewQuals |= Qualifiers::Const; 1099 1100 // We do not allow overloading based off of '__restrict'. 1101 OldQuals &= ~Qualifiers::Restrict; 1102 NewQuals &= ~Qualifiers::Restrict; 1103 if (OldQuals != NewQuals) 1104 return true; 1105 } 1106 1107 // Though pass_object_size is placed on parameters and takes an argument, we 1108 // consider it to be a function-level modifier for the sake of function 1109 // identity. Either the function has one or more parameters with 1110 // pass_object_size or it doesn't. 1111 if (functionHasPassObjectSizeParams(New) != 1112 functionHasPassObjectSizeParams(Old)) 1113 return true; 1114 1115 // enable_if attributes are an order-sensitive part of the signature. 1116 for (specific_attr_iterator<EnableIfAttr> 1117 NewI = New->specific_attr_begin<EnableIfAttr>(), 1118 NewE = New->specific_attr_end<EnableIfAttr>(), 1119 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1120 OldE = Old->specific_attr_end<EnableIfAttr>(); 1121 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1122 if (NewI == NewE || OldI == OldE) 1123 return true; 1124 llvm::FoldingSetNodeID NewID, OldID; 1125 NewI->getCond()->Profile(NewID, Context, true); 1126 OldI->getCond()->Profile(OldID, Context, true); 1127 if (NewID != OldID) 1128 return true; 1129 } 1130 1131 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1132 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1133 OldTarget = IdentifyCUDATarget(Old); 1134 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1135 return false; 1136 1137 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1138 1139 // Don't allow mixing of HD with other kinds. This guarantees that 1140 // we have only one viable function with this signature on any 1141 // side of CUDA compilation . 1142 // __global__ functions can't be overloaded based on attribute 1143 // difference because, like HD, they also exist on both sides. 1144 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1145 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1146 return false; 1147 1148 // Allow overloading of functions with same signature, but 1149 // different CUDA target attributes. 1150 return NewTarget != OldTarget; 1151 } 1152 1153 // The signatures match; this is not an overload. 1154 return false; 1155 } 1156 1157 /// \brief Checks availability of the function depending on the current 1158 /// function context. Inside an unavailable function, unavailability is ignored. 1159 /// 1160 /// \returns true if \arg FD is unavailable and current context is inside 1161 /// an available function, false otherwise. 1162 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1163 if (!FD->isUnavailable()) 1164 return false; 1165 1166 // Walk up the context of the caller. 1167 Decl *C = cast<Decl>(CurContext); 1168 do { 1169 if (C->isUnavailable()) 1170 return false; 1171 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1172 return true; 1173 } 1174 1175 /// \brief Tries a user-defined conversion from From to ToType. 1176 /// 1177 /// Produces an implicit conversion sequence for when a standard conversion 1178 /// is not an option. See TryImplicitConversion for more information. 1179 static ImplicitConversionSequence 1180 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1181 bool SuppressUserConversions, 1182 bool AllowExplicit, 1183 bool InOverloadResolution, 1184 bool CStyle, 1185 bool AllowObjCWritebackConversion, 1186 bool AllowObjCConversionOnExplicit) { 1187 ImplicitConversionSequence ICS; 1188 1189 if (SuppressUserConversions) { 1190 // We're not in the case above, so there is no conversion that 1191 // we can perform. 1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1193 return ICS; 1194 } 1195 1196 // Attempt user-defined conversion. 1197 OverloadCandidateSet Conversions(From->getExprLoc(), 1198 OverloadCandidateSet::CSK_Normal); 1199 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1200 Conversions, AllowExplicit, 1201 AllowObjCConversionOnExplicit)) { 1202 case OR_Success: 1203 case OR_Deleted: 1204 ICS.setUserDefined(); 1205 // C++ [over.ics.user]p4: 1206 // A conversion of an expression of class type to the same class 1207 // type is given Exact Match rank, and a conversion of an 1208 // expression of class type to a base class of that type is 1209 // given Conversion rank, in spite of the fact that a copy 1210 // constructor (i.e., a user-defined conversion function) is 1211 // called for those cases. 1212 if (CXXConstructorDecl *Constructor 1213 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1214 QualType FromCanon 1215 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1216 QualType ToCanon 1217 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1218 if (Constructor->isCopyConstructor() && 1219 (FromCanon == ToCanon || 1220 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1221 // Turn this into a "standard" conversion sequence, so that it 1222 // gets ranked with standard conversion sequences. 1223 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1224 ICS.setStandard(); 1225 ICS.Standard.setAsIdentityConversion(); 1226 ICS.Standard.setFromType(From->getType()); 1227 ICS.Standard.setAllToTypes(ToType); 1228 ICS.Standard.CopyConstructor = Constructor; 1229 ICS.Standard.FoundCopyConstructor = Found; 1230 if (ToCanon != FromCanon) 1231 ICS.Standard.Second = ICK_Derived_To_Base; 1232 } 1233 } 1234 break; 1235 1236 case OR_Ambiguous: 1237 ICS.setAmbiguous(); 1238 ICS.Ambiguous.setFromType(From->getType()); 1239 ICS.Ambiguous.setToType(ToType); 1240 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1241 Cand != Conversions.end(); ++Cand) 1242 if (Cand->Viable) 1243 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1244 break; 1245 1246 // Fall through. 1247 case OR_No_Viable_Function: 1248 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1249 break; 1250 } 1251 1252 return ICS; 1253 } 1254 1255 /// TryImplicitConversion - Attempt to perform an implicit conversion 1256 /// from the given expression (Expr) to the given type (ToType). This 1257 /// function returns an implicit conversion sequence that can be used 1258 /// to perform the initialization. Given 1259 /// 1260 /// void f(float f); 1261 /// void g(int i) { f(i); } 1262 /// 1263 /// this routine would produce an implicit conversion sequence to 1264 /// describe the initialization of f from i, which will be a standard 1265 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1266 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1267 // 1268 /// Note that this routine only determines how the conversion can be 1269 /// performed; it does not actually perform the conversion. As such, 1270 /// it will not produce any diagnostics if no conversion is available, 1271 /// but will instead return an implicit conversion sequence of kind 1272 /// "BadConversion". 1273 /// 1274 /// If @p SuppressUserConversions, then user-defined conversions are 1275 /// not permitted. 1276 /// If @p AllowExplicit, then explicit user-defined conversions are 1277 /// permitted. 1278 /// 1279 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1280 /// writeback conversion, which allows __autoreleasing id* parameters to 1281 /// be initialized with __strong id* or __weak id* arguments. 1282 static ImplicitConversionSequence 1283 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1284 bool SuppressUserConversions, 1285 bool AllowExplicit, 1286 bool InOverloadResolution, 1287 bool CStyle, 1288 bool AllowObjCWritebackConversion, 1289 bool AllowObjCConversionOnExplicit) { 1290 ImplicitConversionSequence ICS; 1291 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1292 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1293 ICS.setStandard(); 1294 return ICS; 1295 } 1296 1297 if (!S.getLangOpts().CPlusPlus) { 1298 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1299 return ICS; 1300 } 1301 1302 // C++ [over.ics.user]p4: 1303 // A conversion of an expression of class type to the same class 1304 // type is given Exact Match rank, and a conversion of an 1305 // expression of class type to a base class of that type is 1306 // given Conversion rank, in spite of the fact that a copy/move 1307 // constructor (i.e., a user-defined conversion function) is 1308 // called for those cases. 1309 QualType FromType = From->getType(); 1310 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1311 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1312 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1313 ICS.setStandard(); 1314 ICS.Standard.setAsIdentityConversion(); 1315 ICS.Standard.setFromType(FromType); 1316 ICS.Standard.setAllToTypes(ToType); 1317 1318 // We don't actually check at this point whether there is a valid 1319 // copy/move constructor, since overloading just assumes that it 1320 // exists. When we actually perform initialization, we'll find the 1321 // appropriate constructor to copy the returned object, if needed. 1322 ICS.Standard.CopyConstructor = nullptr; 1323 1324 // Determine whether this is considered a derived-to-base conversion. 1325 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1326 ICS.Standard.Second = ICK_Derived_To_Base; 1327 1328 return ICS; 1329 } 1330 1331 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1332 AllowExplicit, InOverloadResolution, CStyle, 1333 AllowObjCWritebackConversion, 1334 AllowObjCConversionOnExplicit); 1335 } 1336 1337 ImplicitConversionSequence 1338 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1339 bool SuppressUserConversions, 1340 bool AllowExplicit, 1341 bool InOverloadResolution, 1342 bool CStyle, 1343 bool AllowObjCWritebackConversion) { 1344 return ::TryImplicitConversion(*this, From, ToType, 1345 SuppressUserConversions, AllowExplicit, 1346 InOverloadResolution, CStyle, 1347 AllowObjCWritebackConversion, 1348 /*AllowObjCConversionOnExplicit=*/false); 1349 } 1350 1351 /// PerformImplicitConversion - Perform an implicit conversion of the 1352 /// expression From to the type ToType. Returns the 1353 /// converted expression. Flavor is the kind of conversion we're 1354 /// performing, used in the error message. If @p AllowExplicit, 1355 /// explicit user-defined conversions are permitted. 1356 ExprResult 1357 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1358 AssignmentAction Action, bool AllowExplicit) { 1359 ImplicitConversionSequence ICS; 1360 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1361 } 1362 1363 ExprResult 1364 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1365 AssignmentAction Action, bool AllowExplicit, 1366 ImplicitConversionSequence& ICS) { 1367 if (checkPlaceholderForOverload(*this, From)) 1368 return ExprError(); 1369 1370 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1371 bool AllowObjCWritebackConversion 1372 = getLangOpts().ObjCAutoRefCount && 1373 (Action == AA_Passing || Action == AA_Sending); 1374 if (getLangOpts().ObjC1) 1375 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1376 ToType, From->getType(), From); 1377 ICS = ::TryImplicitConversion(*this, From, ToType, 1378 /*SuppressUserConversions=*/false, 1379 AllowExplicit, 1380 /*InOverloadResolution=*/false, 1381 /*CStyle=*/false, 1382 AllowObjCWritebackConversion, 1383 /*AllowObjCConversionOnExplicit=*/false); 1384 return PerformImplicitConversion(From, ToType, ICS, Action); 1385 } 1386 1387 /// \brief Determine whether the conversion from FromType to ToType is a valid 1388 /// conversion that strips "noreturn" off the nested function type. 1389 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1390 QualType &ResultTy) { 1391 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1392 return false; 1393 1394 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1395 // where F adds one of the following at most once: 1396 // - a pointer 1397 // - a member pointer 1398 // - a block pointer 1399 CanQualType CanTo = Context.getCanonicalType(ToType); 1400 CanQualType CanFrom = Context.getCanonicalType(FromType); 1401 Type::TypeClass TyClass = CanTo->getTypeClass(); 1402 if (TyClass != CanFrom->getTypeClass()) return false; 1403 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1404 if (TyClass == Type::Pointer) { 1405 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1406 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1407 } else if (TyClass == Type::BlockPointer) { 1408 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1409 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1410 } else if (TyClass == Type::MemberPointer) { 1411 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1412 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1413 } else { 1414 return false; 1415 } 1416 1417 TyClass = CanTo->getTypeClass(); 1418 if (TyClass != CanFrom->getTypeClass()) return false; 1419 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1420 return false; 1421 } 1422 1423 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1424 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1425 if (!EInfo.getNoReturn()) return false; 1426 1427 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1428 assert(QualType(FromFn, 0).isCanonical()); 1429 if (QualType(FromFn, 0) != CanTo) return false; 1430 1431 ResultTy = ToType; 1432 return true; 1433 } 1434 1435 /// \brief Determine whether the conversion from FromType to ToType is a valid 1436 /// vector conversion. 1437 /// 1438 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1439 /// conversion. 1440 static bool IsVectorConversion(Sema &S, QualType FromType, 1441 QualType ToType, ImplicitConversionKind &ICK) { 1442 // We need at least one of these types to be a vector type to have a vector 1443 // conversion. 1444 if (!ToType->isVectorType() && !FromType->isVectorType()) 1445 return false; 1446 1447 // Identical types require no conversions. 1448 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1449 return false; 1450 1451 // There are no conversions between extended vector types, only identity. 1452 if (ToType->isExtVectorType()) { 1453 // There are no conversions between extended vector types other than the 1454 // identity conversion. 1455 if (FromType->isExtVectorType()) 1456 return false; 1457 1458 // Vector splat from any arithmetic type to a vector. 1459 if (FromType->isArithmeticType()) { 1460 ICK = ICK_Vector_Splat; 1461 return true; 1462 } 1463 } 1464 1465 // We can perform the conversion between vector types in the following cases: 1466 // 1)vector types are equivalent AltiVec and GCC vector types 1467 // 2)lax vector conversions are permitted and the vector types are of the 1468 // same size 1469 if (ToType->isVectorType() && FromType->isVectorType()) { 1470 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1471 S.isLaxVectorConversion(FromType, ToType)) { 1472 ICK = ICK_Vector_Conversion; 1473 return true; 1474 } 1475 } 1476 1477 return false; 1478 } 1479 1480 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1481 bool InOverloadResolution, 1482 StandardConversionSequence &SCS, 1483 bool CStyle); 1484 1485 /// IsStandardConversion - Determines whether there is a standard 1486 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1487 /// expression From to the type ToType. Standard conversion sequences 1488 /// only consider non-class types; for conversions that involve class 1489 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1490 /// contain the standard conversion sequence required to perform this 1491 /// conversion and this routine will return true. Otherwise, this 1492 /// routine will return false and the value of SCS is unspecified. 1493 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1494 bool InOverloadResolution, 1495 StandardConversionSequence &SCS, 1496 bool CStyle, 1497 bool AllowObjCWritebackConversion) { 1498 QualType FromType = From->getType(); 1499 1500 // Standard conversions (C++ [conv]) 1501 SCS.setAsIdentityConversion(); 1502 SCS.IncompatibleObjC = false; 1503 SCS.setFromType(FromType); 1504 SCS.CopyConstructor = nullptr; 1505 1506 // There are no standard conversions for class types in C++, so 1507 // abort early. When overloading in C, however, we do permit them. 1508 if (S.getLangOpts().CPlusPlus && 1509 (FromType->isRecordType() || ToType->isRecordType())) 1510 return false; 1511 1512 // The first conversion can be an lvalue-to-rvalue conversion, 1513 // array-to-pointer conversion, or function-to-pointer conversion 1514 // (C++ 4p1). 1515 1516 if (FromType == S.Context.OverloadTy) { 1517 DeclAccessPair AccessPair; 1518 if (FunctionDecl *Fn 1519 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1520 AccessPair)) { 1521 // We were able to resolve the address of the overloaded function, 1522 // so we can convert to the type of that function. 1523 FromType = Fn->getType(); 1524 SCS.setFromType(FromType); 1525 1526 // we can sometimes resolve &foo<int> regardless of ToType, so check 1527 // if the type matches (identity) or we are converting to bool 1528 if (!S.Context.hasSameUnqualifiedType( 1529 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1530 QualType resultTy; 1531 // if the function type matches except for [[noreturn]], it's ok 1532 if (!S.IsNoReturnConversion(FromType, 1533 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1534 // otherwise, only a boolean conversion is standard 1535 if (!ToType->isBooleanType()) 1536 return false; 1537 } 1538 1539 // Check if the "from" expression is taking the address of an overloaded 1540 // function and recompute the FromType accordingly. Take advantage of the 1541 // fact that non-static member functions *must* have such an address-of 1542 // expression. 1543 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1544 if (Method && !Method->isStatic()) { 1545 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1546 "Non-unary operator on non-static member address"); 1547 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1548 == UO_AddrOf && 1549 "Non-address-of operator on non-static member address"); 1550 const Type *ClassType 1551 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1552 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1553 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1554 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1555 UO_AddrOf && 1556 "Non-address-of operator for overloaded function expression"); 1557 FromType = S.Context.getPointerType(FromType); 1558 } 1559 1560 // Check that we've computed the proper type after overload resolution. 1561 assert(S.Context.hasSameType( 1562 FromType, 1563 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1564 } else { 1565 return false; 1566 } 1567 } 1568 // Lvalue-to-rvalue conversion (C++11 4.1): 1569 // A glvalue (3.10) of a non-function, non-array type T can 1570 // be converted to a prvalue. 1571 bool argIsLValue = From->isGLValue(); 1572 if (argIsLValue && 1573 !FromType->isFunctionType() && !FromType->isArrayType() && 1574 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1575 SCS.First = ICK_Lvalue_To_Rvalue; 1576 1577 // C11 6.3.2.1p2: 1578 // ... if the lvalue has atomic type, the value has the non-atomic version 1579 // of the type of the lvalue ... 1580 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1581 FromType = Atomic->getValueType(); 1582 1583 // If T is a non-class type, the type of the rvalue is the 1584 // cv-unqualified version of T. Otherwise, the type of the rvalue 1585 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1586 // just strip the qualifiers because they don't matter. 1587 FromType = FromType.getUnqualifiedType(); 1588 } else if (FromType->isArrayType()) { 1589 // Array-to-pointer conversion (C++ 4.2) 1590 SCS.First = ICK_Array_To_Pointer; 1591 1592 // An lvalue or rvalue of type "array of N T" or "array of unknown 1593 // bound of T" can be converted to an rvalue of type "pointer to 1594 // T" (C++ 4.2p1). 1595 FromType = S.Context.getArrayDecayedType(FromType); 1596 1597 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1598 // This conversion is deprecated in C++03 (D.4) 1599 SCS.DeprecatedStringLiteralToCharPtr = true; 1600 1601 // For the purpose of ranking in overload resolution 1602 // (13.3.3.1.1), this conversion is considered an 1603 // array-to-pointer conversion followed by a qualification 1604 // conversion (4.4). (C++ 4.2p2) 1605 SCS.Second = ICK_Identity; 1606 SCS.Third = ICK_Qualification; 1607 SCS.QualificationIncludesObjCLifetime = false; 1608 SCS.setAllToTypes(FromType); 1609 return true; 1610 } 1611 } else if (FromType->isFunctionType() && argIsLValue) { 1612 // Function-to-pointer conversion (C++ 4.3). 1613 SCS.First = ICK_Function_To_Pointer; 1614 1615 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1616 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1617 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1618 return false; 1619 1620 // An lvalue of function type T can be converted to an rvalue of 1621 // type "pointer to T." The result is a pointer to the 1622 // function. (C++ 4.3p1). 1623 FromType = S.Context.getPointerType(FromType); 1624 } else { 1625 // We don't require any conversions for the first step. 1626 SCS.First = ICK_Identity; 1627 } 1628 SCS.setToType(0, FromType); 1629 1630 // The second conversion can be an integral promotion, floating 1631 // point promotion, integral conversion, floating point conversion, 1632 // floating-integral conversion, pointer conversion, 1633 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1634 // For overloading in C, this can also be a "compatible-type" 1635 // conversion. 1636 bool IncompatibleObjC = false; 1637 ImplicitConversionKind SecondICK = ICK_Identity; 1638 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1639 // The unqualified versions of the types are the same: there's no 1640 // conversion to do. 1641 SCS.Second = ICK_Identity; 1642 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1643 // Integral promotion (C++ 4.5). 1644 SCS.Second = ICK_Integral_Promotion; 1645 FromType = ToType.getUnqualifiedType(); 1646 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1647 // Floating point promotion (C++ 4.6). 1648 SCS.Second = ICK_Floating_Promotion; 1649 FromType = ToType.getUnqualifiedType(); 1650 } else if (S.IsComplexPromotion(FromType, ToType)) { 1651 // Complex promotion (Clang extension) 1652 SCS.Second = ICK_Complex_Promotion; 1653 FromType = ToType.getUnqualifiedType(); 1654 } else if (ToType->isBooleanType() && 1655 (FromType->isArithmeticType() || 1656 FromType->isAnyPointerType() || 1657 FromType->isBlockPointerType() || 1658 FromType->isMemberPointerType() || 1659 FromType->isNullPtrType())) { 1660 // Boolean conversions (C++ 4.12). 1661 SCS.Second = ICK_Boolean_Conversion; 1662 FromType = S.Context.BoolTy; 1663 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1664 ToType->isIntegralType(S.Context)) { 1665 // Integral conversions (C++ 4.7). 1666 SCS.Second = ICK_Integral_Conversion; 1667 FromType = ToType.getUnqualifiedType(); 1668 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1669 // Complex conversions (C99 6.3.1.6) 1670 SCS.Second = ICK_Complex_Conversion; 1671 FromType = ToType.getUnqualifiedType(); 1672 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1673 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1674 // Complex-real conversions (C99 6.3.1.7) 1675 SCS.Second = ICK_Complex_Real; 1676 FromType = ToType.getUnqualifiedType(); 1677 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1678 // FIXME: disable conversions between long double and __float128 if 1679 // their representation is different until there is back end support 1680 // We of course allow this conversion if long double is really double. 1681 if (&S.Context.getFloatTypeSemantics(FromType) != 1682 &S.Context.getFloatTypeSemantics(ToType)) { 1683 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1684 ToType == S.Context.LongDoubleTy) || 1685 (FromType == S.Context.LongDoubleTy && 1686 ToType == S.Context.Float128Ty)); 1687 if (Float128AndLongDouble && 1688 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1689 &llvm::APFloat::IEEEdouble)) 1690 return false; 1691 } 1692 // Floating point conversions (C++ 4.8). 1693 SCS.Second = ICK_Floating_Conversion; 1694 FromType = ToType.getUnqualifiedType(); 1695 } else if ((FromType->isRealFloatingType() && 1696 ToType->isIntegralType(S.Context)) || 1697 (FromType->isIntegralOrUnscopedEnumerationType() && 1698 ToType->isRealFloatingType())) { 1699 // Floating-integral conversions (C++ 4.9). 1700 SCS.Second = ICK_Floating_Integral; 1701 FromType = ToType.getUnqualifiedType(); 1702 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1703 SCS.Second = ICK_Block_Pointer_Conversion; 1704 } else if (AllowObjCWritebackConversion && 1705 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1706 SCS.Second = ICK_Writeback_Conversion; 1707 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1708 FromType, IncompatibleObjC)) { 1709 // Pointer conversions (C++ 4.10). 1710 SCS.Second = ICK_Pointer_Conversion; 1711 SCS.IncompatibleObjC = IncompatibleObjC; 1712 FromType = FromType.getUnqualifiedType(); 1713 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1714 InOverloadResolution, FromType)) { 1715 // Pointer to member conversions (4.11). 1716 SCS.Second = ICK_Pointer_Member; 1717 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1718 SCS.Second = SecondICK; 1719 FromType = ToType.getUnqualifiedType(); 1720 } else if (!S.getLangOpts().CPlusPlus && 1721 S.Context.typesAreCompatible(ToType, FromType)) { 1722 // Compatible conversions (Clang extension for C function overloading) 1723 SCS.Second = ICK_Compatible_Conversion; 1724 FromType = ToType.getUnqualifiedType(); 1725 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1726 // Treat a conversion that strips "noreturn" as an identity conversion. 1727 SCS.Second = ICK_NoReturn_Adjustment; 1728 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1729 InOverloadResolution, 1730 SCS, CStyle)) { 1731 SCS.Second = ICK_TransparentUnionConversion; 1732 FromType = ToType; 1733 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1734 CStyle)) { 1735 // tryAtomicConversion has updated the standard conversion sequence 1736 // appropriately. 1737 return true; 1738 } else if (ToType->isEventT() && 1739 From->isIntegerConstantExpr(S.getASTContext()) && 1740 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1741 SCS.Second = ICK_Zero_Event_Conversion; 1742 FromType = ToType; 1743 } else { 1744 // No second conversion required. 1745 SCS.Second = ICK_Identity; 1746 } 1747 SCS.setToType(1, FromType); 1748 1749 QualType CanonFrom; 1750 QualType CanonTo; 1751 // The third conversion can be a qualification conversion (C++ 4p1). 1752 bool ObjCLifetimeConversion; 1753 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1754 ObjCLifetimeConversion)) { 1755 SCS.Third = ICK_Qualification; 1756 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1757 FromType = ToType; 1758 CanonFrom = S.Context.getCanonicalType(FromType); 1759 CanonTo = S.Context.getCanonicalType(ToType); 1760 } else { 1761 // No conversion required 1762 SCS.Third = ICK_Identity; 1763 1764 // C++ [over.best.ics]p6: 1765 // [...] Any difference in top-level cv-qualification is 1766 // subsumed by the initialization itself and does not constitute 1767 // a conversion. [...] 1768 CanonFrom = S.Context.getCanonicalType(FromType); 1769 CanonTo = S.Context.getCanonicalType(ToType); 1770 if (CanonFrom.getLocalUnqualifiedType() 1771 == CanonTo.getLocalUnqualifiedType() && 1772 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1773 FromType = ToType; 1774 CanonFrom = CanonTo; 1775 } 1776 } 1777 SCS.setToType(2, FromType); 1778 1779 if (CanonFrom == CanonTo) 1780 return true; 1781 1782 // If we have not converted the argument type to the parameter type, 1783 // this is a bad conversion sequence, unless we're resolving an overload in C. 1784 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1785 return false; 1786 1787 ExprResult ER = ExprResult{From}; 1788 Sema::AssignConvertType Conv = 1789 S.CheckSingleAssignmentConstraints(ToType, ER, 1790 /*Diagnose=*/false, 1791 /*DiagnoseCFAudited=*/false, 1792 /*ConvertRHS=*/false); 1793 ImplicitConversionKind SecondConv; 1794 switch (Conv) { 1795 case Sema::Compatible: 1796 SecondConv = ICK_C_Only_Conversion; 1797 break; 1798 // For our purposes, discarding qualifiers is just as bad as using an 1799 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1800 // qualifiers, as well. 1801 case Sema::CompatiblePointerDiscardsQualifiers: 1802 case Sema::IncompatiblePointer: 1803 case Sema::IncompatiblePointerSign: 1804 SecondConv = ICK_Incompatible_Pointer_Conversion; 1805 break; 1806 default: 1807 return false; 1808 } 1809 1810 // First can only be an lvalue conversion, so we pretend that this was the 1811 // second conversion. First should already be valid from earlier in the 1812 // function. 1813 SCS.Second = SecondConv; 1814 SCS.setToType(1, ToType); 1815 1816 // Third is Identity, because Second should rank us worse than any other 1817 // conversion. This could also be ICK_Qualification, but it's simpler to just 1818 // lump everything in with the second conversion, and we don't gain anything 1819 // from making this ICK_Qualification. 1820 SCS.Third = ICK_Identity; 1821 SCS.setToType(2, ToType); 1822 return true; 1823 } 1824 1825 static bool 1826 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1827 QualType &ToType, 1828 bool InOverloadResolution, 1829 StandardConversionSequence &SCS, 1830 bool CStyle) { 1831 1832 const RecordType *UT = ToType->getAsUnionType(); 1833 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1834 return false; 1835 // The field to initialize within the transparent union. 1836 RecordDecl *UD = UT->getDecl(); 1837 // It's compatible if the expression matches any of the fields. 1838 for (const auto *it : UD->fields()) { 1839 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1840 CStyle, /*ObjCWritebackConversion=*/false)) { 1841 ToType = it->getType(); 1842 return true; 1843 } 1844 } 1845 return false; 1846 } 1847 1848 /// IsIntegralPromotion - Determines whether the conversion from the 1849 /// expression From (whose potentially-adjusted type is FromType) to 1850 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1851 /// sets PromotedType to the promoted type. 1852 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1853 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1854 // All integers are built-in. 1855 if (!To) { 1856 return false; 1857 } 1858 1859 // An rvalue of type char, signed char, unsigned char, short int, or 1860 // unsigned short int can be converted to an rvalue of type int if 1861 // int can represent all the values of the source type; otherwise, 1862 // the source rvalue can be converted to an rvalue of type unsigned 1863 // int (C++ 4.5p1). 1864 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1865 !FromType->isEnumeralType()) { 1866 if (// We can promote any signed, promotable integer type to an int 1867 (FromType->isSignedIntegerType() || 1868 // We can promote any unsigned integer type whose size is 1869 // less than int to an int. 1870 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1871 return To->getKind() == BuiltinType::Int; 1872 } 1873 1874 return To->getKind() == BuiltinType::UInt; 1875 } 1876 1877 // C++11 [conv.prom]p3: 1878 // A prvalue of an unscoped enumeration type whose underlying type is not 1879 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1880 // following types that can represent all the values of the enumeration 1881 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1882 // unsigned int, long int, unsigned long int, long long int, or unsigned 1883 // long long int. If none of the types in that list can represent all the 1884 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1885 // type can be converted to an rvalue a prvalue of the extended integer type 1886 // with lowest integer conversion rank (4.13) greater than the rank of long 1887 // long in which all the values of the enumeration can be represented. If 1888 // there are two such extended types, the signed one is chosen. 1889 // C++11 [conv.prom]p4: 1890 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1891 // can be converted to a prvalue of its underlying type. Moreover, if 1892 // integral promotion can be applied to its underlying type, a prvalue of an 1893 // unscoped enumeration type whose underlying type is fixed can also be 1894 // converted to a prvalue of the promoted underlying type. 1895 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1896 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1897 // provided for a scoped enumeration. 1898 if (FromEnumType->getDecl()->isScoped()) 1899 return false; 1900 1901 // We can perform an integral promotion to the underlying type of the enum, 1902 // even if that's not the promoted type. Note that the check for promoting 1903 // the underlying type is based on the type alone, and does not consider 1904 // the bitfield-ness of the actual source expression. 1905 if (FromEnumType->getDecl()->isFixed()) { 1906 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1907 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1908 IsIntegralPromotion(nullptr, Underlying, ToType); 1909 } 1910 1911 // We have already pre-calculated the promotion type, so this is trivial. 1912 if (ToType->isIntegerType() && 1913 isCompleteType(From->getLocStart(), FromType)) 1914 return Context.hasSameUnqualifiedType( 1915 ToType, FromEnumType->getDecl()->getPromotionType()); 1916 } 1917 1918 // C++0x [conv.prom]p2: 1919 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1920 // to an rvalue a prvalue of the first of the following types that can 1921 // represent all the values of its underlying type: int, unsigned int, 1922 // long int, unsigned long int, long long int, or unsigned long long int. 1923 // If none of the types in that list can represent all the values of its 1924 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1925 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1926 // type. 1927 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1928 ToType->isIntegerType()) { 1929 // Determine whether the type we're converting from is signed or 1930 // unsigned. 1931 bool FromIsSigned = FromType->isSignedIntegerType(); 1932 uint64_t FromSize = Context.getTypeSize(FromType); 1933 1934 // The types we'll try to promote to, in the appropriate 1935 // order. Try each of these types. 1936 QualType PromoteTypes[6] = { 1937 Context.IntTy, Context.UnsignedIntTy, 1938 Context.LongTy, Context.UnsignedLongTy , 1939 Context.LongLongTy, Context.UnsignedLongLongTy 1940 }; 1941 for (int Idx = 0; Idx < 6; ++Idx) { 1942 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1943 if (FromSize < ToSize || 1944 (FromSize == ToSize && 1945 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1946 // We found the type that we can promote to. If this is the 1947 // type we wanted, we have a promotion. Otherwise, no 1948 // promotion. 1949 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1950 } 1951 } 1952 } 1953 1954 // An rvalue for an integral bit-field (9.6) can be converted to an 1955 // rvalue of type int if int can represent all the values of the 1956 // bit-field; otherwise, it can be converted to unsigned int if 1957 // unsigned int can represent all the values of the bit-field. If 1958 // the bit-field is larger yet, no integral promotion applies to 1959 // it. If the bit-field has an enumerated type, it is treated as any 1960 // other value of that type for promotion purposes (C++ 4.5p3). 1961 // FIXME: We should delay checking of bit-fields until we actually perform the 1962 // conversion. 1963 if (From) { 1964 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1965 llvm::APSInt BitWidth; 1966 if (FromType->isIntegralType(Context) && 1967 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1968 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1969 ToSize = Context.getTypeSize(ToType); 1970 1971 // Are we promoting to an int from a bitfield that fits in an int? 1972 if (BitWidth < ToSize || 1973 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1974 return To->getKind() == BuiltinType::Int; 1975 } 1976 1977 // Are we promoting to an unsigned int from an unsigned bitfield 1978 // that fits into an unsigned int? 1979 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1980 return To->getKind() == BuiltinType::UInt; 1981 } 1982 1983 return false; 1984 } 1985 } 1986 } 1987 1988 // An rvalue of type bool can be converted to an rvalue of type int, 1989 // with false becoming zero and true becoming one (C++ 4.5p4). 1990 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1991 return true; 1992 } 1993 1994 return false; 1995 } 1996 1997 /// IsFloatingPointPromotion - Determines whether the conversion from 1998 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1999 /// returns true and sets PromotedType to the promoted type. 2000 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2001 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2002 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2003 /// An rvalue of type float can be converted to an rvalue of type 2004 /// double. (C++ 4.6p1). 2005 if (FromBuiltin->getKind() == BuiltinType::Float && 2006 ToBuiltin->getKind() == BuiltinType::Double) 2007 return true; 2008 2009 // C99 6.3.1.5p1: 2010 // When a float is promoted to double or long double, or a 2011 // double is promoted to long double [...]. 2012 if (!getLangOpts().CPlusPlus && 2013 (FromBuiltin->getKind() == BuiltinType::Float || 2014 FromBuiltin->getKind() == BuiltinType::Double) && 2015 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2016 ToBuiltin->getKind() == BuiltinType::Float128)) 2017 return true; 2018 2019 // Half can be promoted to float. 2020 if (!getLangOpts().NativeHalfType && 2021 FromBuiltin->getKind() == BuiltinType::Half && 2022 ToBuiltin->getKind() == BuiltinType::Float) 2023 return true; 2024 } 2025 2026 return false; 2027 } 2028 2029 /// \brief Determine if a conversion is a complex promotion. 2030 /// 2031 /// A complex promotion is defined as a complex -> complex conversion 2032 /// where the conversion between the underlying real types is a 2033 /// floating-point or integral promotion. 2034 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2035 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2036 if (!FromComplex) 2037 return false; 2038 2039 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2040 if (!ToComplex) 2041 return false; 2042 2043 return IsFloatingPointPromotion(FromComplex->getElementType(), 2044 ToComplex->getElementType()) || 2045 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2046 ToComplex->getElementType()); 2047 } 2048 2049 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2050 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2051 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2052 /// if non-empty, will be a pointer to ToType that may or may not have 2053 /// the right set of qualifiers on its pointee. 2054 /// 2055 static QualType 2056 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2057 QualType ToPointee, QualType ToType, 2058 ASTContext &Context, 2059 bool StripObjCLifetime = false) { 2060 assert((FromPtr->getTypeClass() == Type::Pointer || 2061 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2062 "Invalid similarly-qualified pointer type"); 2063 2064 /// Conversions to 'id' subsume cv-qualifier conversions. 2065 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2066 return ToType.getUnqualifiedType(); 2067 2068 QualType CanonFromPointee 2069 = Context.getCanonicalType(FromPtr->getPointeeType()); 2070 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2071 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2072 2073 if (StripObjCLifetime) 2074 Quals.removeObjCLifetime(); 2075 2076 // Exact qualifier match -> return the pointer type we're converting to. 2077 if (CanonToPointee.getLocalQualifiers() == Quals) { 2078 // ToType is exactly what we need. Return it. 2079 if (!ToType.isNull()) 2080 return ToType.getUnqualifiedType(); 2081 2082 // Build a pointer to ToPointee. It has the right qualifiers 2083 // already. 2084 if (isa<ObjCObjectPointerType>(ToType)) 2085 return Context.getObjCObjectPointerType(ToPointee); 2086 return Context.getPointerType(ToPointee); 2087 } 2088 2089 // Just build a canonical type that has the right qualifiers. 2090 QualType QualifiedCanonToPointee 2091 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2092 2093 if (isa<ObjCObjectPointerType>(ToType)) 2094 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2095 return Context.getPointerType(QualifiedCanonToPointee); 2096 } 2097 2098 static bool isNullPointerConstantForConversion(Expr *Expr, 2099 bool InOverloadResolution, 2100 ASTContext &Context) { 2101 // Handle value-dependent integral null pointer constants correctly. 2102 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2103 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2104 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2105 return !InOverloadResolution; 2106 2107 return Expr->isNullPointerConstant(Context, 2108 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2109 : Expr::NPC_ValueDependentIsNull); 2110 } 2111 2112 /// IsPointerConversion - Determines whether the conversion of the 2113 /// expression From, which has the (possibly adjusted) type FromType, 2114 /// can be converted to the type ToType via a pointer conversion (C++ 2115 /// 4.10). If so, returns true and places the converted type (that 2116 /// might differ from ToType in its cv-qualifiers at some level) into 2117 /// ConvertedType. 2118 /// 2119 /// This routine also supports conversions to and from block pointers 2120 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2121 /// pointers to interfaces. FIXME: Once we've determined the 2122 /// appropriate overloading rules for Objective-C, we may want to 2123 /// split the Objective-C checks into a different routine; however, 2124 /// GCC seems to consider all of these conversions to be pointer 2125 /// conversions, so for now they live here. IncompatibleObjC will be 2126 /// set if the conversion is an allowed Objective-C conversion that 2127 /// should result in a warning. 2128 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2129 bool InOverloadResolution, 2130 QualType& ConvertedType, 2131 bool &IncompatibleObjC) { 2132 IncompatibleObjC = false; 2133 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2134 IncompatibleObjC)) 2135 return true; 2136 2137 // Conversion from a null pointer constant to any Objective-C pointer type. 2138 if (ToType->isObjCObjectPointerType() && 2139 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2140 ConvertedType = ToType; 2141 return true; 2142 } 2143 2144 // Blocks: Block pointers can be converted to void*. 2145 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2146 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2147 ConvertedType = ToType; 2148 return true; 2149 } 2150 // Blocks: A null pointer constant can be converted to a block 2151 // pointer type. 2152 if (ToType->isBlockPointerType() && 2153 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2154 ConvertedType = ToType; 2155 return true; 2156 } 2157 2158 // If the left-hand-side is nullptr_t, the right side can be a null 2159 // pointer constant. 2160 if (ToType->isNullPtrType() && 2161 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2162 ConvertedType = ToType; 2163 return true; 2164 } 2165 2166 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2167 if (!ToTypePtr) 2168 return false; 2169 2170 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2171 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2172 ConvertedType = ToType; 2173 return true; 2174 } 2175 2176 // Beyond this point, both types need to be pointers 2177 // , including objective-c pointers. 2178 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2179 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2180 !getLangOpts().ObjCAutoRefCount) { 2181 ConvertedType = BuildSimilarlyQualifiedPointerType( 2182 FromType->getAs<ObjCObjectPointerType>(), 2183 ToPointeeType, 2184 ToType, Context); 2185 return true; 2186 } 2187 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2188 if (!FromTypePtr) 2189 return false; 2190 2191 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2192 2193 // If the unqualified pointee types are the same, this can't be a 2194 // pointer conversion, so don't do all of the work below. 2195 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2196 return false; 2197 2198 // An rvalue of type "pointer to cv T," where T is an object type, 2199 // can be converted to an rvalue of type "pointer to cv void" (C++ 2200 // 4.10p2). 2201 if (FromPointeeType->isIncompleteOrObjectType() && 2202 ToPointeeType->isVoidType()) { 2203 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2204 ToPointeeType, 2205 ToType, Context, 2206 /*StripObjCLifetime=*/true); 2207 return true; 2208 } 2209 2210 // MSVC allows implicit function to void* type conversion. 2211 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2212 ToPointeeType->isVoidType()) { 2213 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2214 ToPointeeType, 2215 ToType, Context); 2216 return true; 2217 } 2218 2219 // When we're overloading in C, we allow a special kind of pointer 2220 // conversion for compatible-but-not-identical pointee types. 2221 if (!getLangOpts().CPlusPlus && 2222 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2223 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2224 ToPointeeType, 2225 ToType, Context); 2226 return true; 2227 } 2228 2229 // C++ [conv.ptr]p3: 2230 // 2231 // An rvalue of type "pointer to cv D," where D is a class type, 2232 // can be converted to an rvalue of type "pointer to cv B," where 2233 // B is a base class (clause 10) of D. If B is an inaccessible 2234 // (clause 11) or ambiguous (10.2) base class of D, a program that 2235 // necessitates this conversion is ill-formed. The result of the 2236 // conversion is a pointer to the base class sub-object of the 2237 // derived class object. The null pointer value is converted to 2238 // the null pointer value of the destination type. 2239 // 2240 // Note that we do not check for ambiguity or inaccessibility 2241 // here. That is handled by CheckPointerConversion. 2242 if (getLangOpts().CPlusPlus && 2243 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2244 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2245 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2246 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2247 ToPointeeType, 2248 ToType, Context); 2249 return true; 2250 } 2251 2252 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2253 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2254 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2255 ToPointeeType, 2256 ToType, Context); 2257 return true; 2258 } 2259 2260 return false; 2261 } 2262 2263 /// \brief Adopt the given qualifiers for the given type. 2264 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2265 Qualifiers TQs = T.getQualifiers(); 2266 2267 // Check whether qualifiers already match. 2268 if (TQs == Qs) 2269 return T; 2270 2271 if (Qs.compatiblyIncludes(TQs)) 2272 return Context.getQualifiedType(T, Qs); 2273 2274 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2275 } 2276 2277 /// isObjCPointerConversion - Determines whether this is an 2278 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2279 /// with the same arguments and return values. 2280 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2281 QualType& ConvertedType, 2282 bool &IncompatibleObjC) { 2283 if (!getLangOpts().ObjC1) 2284 return false; 2285 2286 // The set of qualifiers on the type we're converting from. 2287 Qualifiers FromQualifiers = FromType.getQualifiers(); 2288 2289 // First, we handle all conversions on ObjC object pointer types. 2290 const ObjCObjectPointerType* ToObjCPtr = 2291 ToType->getAs<ObjCObjectPointerType>(); 2292 const ObjCObjectPointerType *FromObjCPtr = 2293 FromType->getAs<ObjCObjectPointerType>(); 2294 2295 if (ToObjCPtr && FromObjCPtr) { 2296 // If the pointee types are the same (ignoring qualifications), 2297 // then this is not a pointer conversion. 2298 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2299 FromObjCPtr->getPointeeType())) 2300 return false; 2301 2302 // Conversion between Objective-C pointers. 2303 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2304 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2305 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2306 if (getLangOpts().CPlusPlus && LHS && RHS && 2307 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2308 FromObjCPtr->getPointeeType())) 2309 return false; 2310 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2311 ToObjCPtr->getPointeeType(), 2312 ToType, Context); 2313 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2314 return true; 2315 } 2316 2317 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2318 // Okay: this is some kind of implicit downcast of Objective-C 2319 // interfaces, which is permitted. However, we're going to 2320 // complain about it. 2321 IncompatibleObjC = true; 2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2323 ToObjCPtr->getPointeeType(), 2324 ToType, Context); 2325 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2326 return true; 2327 } 2328 } 2329 // Beyond this point, both types need to be C pointers or block pointers. 2330 QualType ToPointeeType; 2331 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2332 ToPointeeType = ToCPtr->getPointeeType(); 2333 else if (const BlockPointerType *ToBlockPtr = 2334 ToType->getAs<BlockPointerType>()) { 2335 // Objective C++: We're able to convert from a pointer to any object 2336 // to a block pointer type. 2337 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2338 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2339 return true; 2340 } 2341 ToPointeeType = ToBlockPtr->getPointeeType(); 2342 } 2343 else if (FromType->getAs<BlockPointerType>() && 2344 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2345 // Objective C++: We're able to convert from a block pointer type to a 2346 // pointer to any object. 2347 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2348 return true; 2349 } 2350 else 2351 return false; 2352 2353 QualType FromPointeeType; 2354 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2355 FromPointeeType = FromCPtr->getPointeeType(); 2356 else if (const BlockPointerType *FromBlockPtr = 2357 FromType->getAs<BlockPointerType>()) 2358 FromPointeeType = FromBlockPtr->getPointeeType(); 2359 else 2360 return false; 2361 2362 // If we have pointers to pointers, recursively check whether this 2363 // is an Objective-C conversion. 2364 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2365 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2366 IncompatibleObjC)) { 2367 // We always complain about this conversion. 2368 IncompatibleObjC = true; 2369 ConvertedType = Context.getPointerType(ConvertedType); 2370 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2371 return true; 2372 } 2373 // Allow conversion of pointee being objective-c pointer to another one; 2374 // as in I* to id. 2375 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2376 ToPointeeType->getAs<ObjCObjectPointerType>() && 2377 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2378 IncompatibleObjC)) { 2379 2380 ConvertedType = Context.getPointerType(ConvertedType); 2381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2382 return true; 2383 } 2384 2385 // If we have pointers to functions or blocks, check whether the only 2386 // differences in the argument and result types are in Objective-C 2387 // pointer conversions. If so, we permit the conversion (but 2388 // complain about it). 2389 const FunctionProtoType *FromFunctionType 2390 = FromPointeeType->getAs<FunctionProtoType>(); 2391 const FunctionProtoType *ToFunctionType 2392 = ToPointeeType->getAs<FunctionProtoType>(); 2393 if (FromFunctionType && ToFunctionType) { 2394 // If the function types are exactly the same, this isn't an 2395 // Objective-C pointer conversion. 2396 if (Context.getCanonicalType(FromPointeeType) 2397 == Context.getCanonicalType(ToPointeeType)) 2398 return false; 2399 2400 // Perform the quick checks that will tell us whether these 2401 // function types are obviously different. 2402 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2403 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2404 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2405 return false; 2406 2407 bool HasObjCConversion = false; 2408 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2409 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2410 // Okay, the types match exactly. Nothing to do. 2411 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2412 ToFunctionType->getReturnType(), 2413 ConvertedType, IncompatibleObjC)) { 2414 // Okay, we have an Objective-C pointer conversion. 2415 HasObjCConversion = true; 2416 } else { 2417 // Function types are too different. Abort. 2418 return false; 2419 } 2420 2421 // Check argument types. 2422 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2423 ArgIdx != NumArgs; ++ArgIdx) { 2424 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2425 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2426 if (Context.getCanonicalType(FromArgType) 2427 == Context.getCanonicalType(ToArgType)) { 2428 // Okay, the types match exactly. Nothing to do. 2429 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2430 ConvertedType, IncompatibleObjC)) { 2431 // Okay, we have an Objective-C pointer conversion. 2432 HasObjCConversion = true; 2433 } else { 2434 // Argument types are too different. Abort. 2435 return false; 2436 } 2437 } 2438 2439 if (HasObjCConversion) { 2440 // We had an Objective-C conversion. Allow this pointer 2441 // conversion, but complain about it. 2442 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2443 IncompatibleObjC = true; 2444 return true; 2445 } 2446 } 2447 2448 return false; 2449 } 2450 2451 /// \brief Determine whether this is an Objective-C writeback conversion, 2452 /// used for parameter passing when performing automatic reference counting. 2453 /// 2454 /// \param FromType The type we're converting form. 2455 /// 2456 /// \param ToType The type we're converting to. 2457 /// 2458 /// \param ConvertedType The type that will be produced after applying 2459 /// this conversion. 2460 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2461 QualType &ConvertedType) { 2462 if (!getLangOpts().ObjCAutoRefCount || 2463 Context.hasSameUnqualifiedType(FromType, ToType)) 2464 return false; 2465 2466 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2467 QualType ToPointee; 2468 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2469 ToPointee = ToPointer->getPointeeType(); 2470 else 2471 return false; 2472 2473 Qualifiers ToQuals = ToPointee.getQualifiers(); 2474 if (!ToPointee->isObjCLifetimeType() || 2475 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2476 !ToQuals.withoutObjCLifetime().empty()) 2477 return false; 2478 2479 // Argument must be a pointer to __strong to __weak. 2480 QualType FromPointee; 2481 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2482 FromPointee = FromPointer->getPointeeType(); 2483 else 2484 return false; 2485 2486 Qualifiers FromQuals = FromPointee.getQualifiers(); 2487 if (!FromPointee->isObjCLifetimeType() || 2488 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2489 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2490 return false; 2491 2492 // Make sure that we have compatible qualifiers. 2493 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2494 if (!ToQuals.compatiblyIncludes(FromQuals)) 2495 return false; 2496 2497 // Remove qualifiers from the pointee type we're converting from; they 2498 // aren't used in the compatibility check belong, and we'll be adding back 2499 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2500 FromPointee = FromPointee.getUnqualifiedType(); 2501 2502 // The unqualified form of the pointee types must be compatible. 2503 ToPointee = ToPointee.getUnqualifiedType(); 2504 bool IncompatibleObjC; 2505 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2506 FromPointee = ToPointee; 2507 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2508 IncompatibleObjC)) 2509 return false; 2510 2511 /// \brief Construct the type we're converting to, which is a pointer to 2512 /// __autoreleasing pointee. 2513 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2514 ConvertedType = Context.getPointerType(FromPointee); 2515 return true; 2516 } 2517 2518 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2519 QualType& ConvertedType) { 2520 QualType ToPointeeType; 2521 if (const BlockPointerType *ToBlockPtr = 2522 ToType->getAs<BlockPointerType>()) 2523 ToPointeeType = ToBlockPtr->getPointeeType(); 2524 else 2525 return false; 2526 2527 QualType FromPointeeType; 2528 if (const BlockPointerType *FromBlockPtr = 2529 FromType->getAs<BlockPointerType>()) 2530 FromPointeeType = FromBlockPtr->getPointeeType(); 2531 else 2532 return false; 2533 // We have pointer to blocks, check whether the only 2534 // differences in the argument and result types are in Objective-C 2535 // pointer conversions. If so, we permit the conversion. 2536 2537 const FunctionProtoType *FromFunctionType 2538 = FromPointeeType->getAs<FunctionProtoType>(); 2539 const FunctionProtoType *ToFunctionType 2540 = ToPointeeType->getAs<FunctionProtoType>(); 2541 2542 if (!FromFunctionType || !ToFunctionType) 2543 return false; 2544 2545 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2546 return true; 2547 2548 // Perform the quick checks that will tell us whether these 2549 // function types are obviously different. 2550 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2551 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2552 return false; 2553 2554 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2555 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2556 if (FromEInfo != ToEInfo) 2557 return false; 2558 2559 bool IncompatibleObjC = false; 2560 if (Context.hasSameType(FromFunctionType->getReturnType(), 2561 ToFunctionType->getReturnType())) { 2562 // Okay, the types match exactly. Nothing to do. 2563 } else { 2564 QualType RHS = FromFunctionType->getReturnType(); 2565 QualType LHS = ToFunctionType->getReturnType(); 2566 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2567 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2568 LHS = LHS.getUnqualifiedType(); 2569 2570 if (Context.hasSameType(RHS,LHS)) { 2571 // OK exact match. 2572 } else if (isObjCPointerConversion(RHS, LHS, 2573 ConvertedType, IncompatibleObjC)) { 2574 if (IncompatibleObjC) 2575 return false; 2576 // Okay, we have an Objective-C pointer conversion. 2577 } 2578 else 2579 return false; 2580 } 2581 2582 // Check argument types. 2583 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2584 ArgIdx != NumArgs; ++ArgIdx) { 2585 IncompatibleObjC = false; 2586 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2587 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2588 if (Context.hasSameType(FromArgType, ToArgType)) { 2589 // Okay, the types match exactly. Nothing to do. 2590 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2591 ConvertedType, IncompatibleObjC)) { 2592 if (IncompatibleObjC) 2593 return false; 2594 // Okay, we have an Objective-C pointer conversion. 2595 } else 2596 // Argument types are too different. Abort. 2597 return false; 2598 } 2599 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2600 ToFunctionType)) 2601 return false; 2602 2603 ConvertedType = ToType; 2604 return true; 2605 } 2606 2607 enum { 2608 ft_default, 2609 ft_different_class, 2610 ft_parameter_arity, 2611 ft_parameter_mismatch, 2612 ft_return_type, 2613 ft_qualifer_mismatch 2614 }; 2615 2616 /// Attempts to get the FunctionProtoType from a Type. Handles 2617 /// MemberFunctionPointers properly. 2618 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2619 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2620 return FPT; 2621 2622 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2623 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2624 2625 return nullptr; 2626 } 2627 2628 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2629 /// function types. Catches different number of parameter, mismatch in 2630 /// parameter types, and different return types. 2631 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2632 QualType FromType, QualType ToType) { 2633 // If either type is not valid, include no extra info. 2634 if (FromType.isNull() || ToType.isNull()) { 2635 PDiag << ft_default; 2636 return; 2637 } 2638 2639 // Get the function type from the pointers. 2640 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2641 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2642 *ToMember = ToType->getAs<MemberPointerType>(); 2643 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2644 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2645 << QualType(FromMember->getClass(), 0); 2646 return; 2647 } 2648 FromType = FromMember->getPointeeType(); 2649 ToType = ToMember->getPointeeType(); 2650 } 2651 2652 if (FromType->isPointerType()) 2653 FromType = FromType->getPointeeType(); 2654 if (ToType->isPointerType()) 2655 ToType = ToType->getPointeeType(); 2656 2657 // Remove references. 2658 FromType = FromType.getNonReferenceType(); 2659 ToType = ToType.getNonReferenceType(); 2660 2661 // Don't print extra info for non-specialized template functions. 2662 if (FromType->isInstantiationDependentType() && 2663 !FromType->getAs<TemplateSpecializationType>()) { 2664 PDiag << ft_default; 2665 return; 2666 } 2667 2668 // No extra info for same types. 2669 if (Context.hasSameType(FromType, ToType)) { 2670 PDiag << ft_default; 2671 return; 2672 } 2673 2674 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2675 *ToFunction = tryGetFunctionProtoType(ToType); 2676 2677 // Both types need to be function types. 2678 if (!FromFunction || !ToFunction) { 2679 PDiag << ft_default; 2680 return; 2681 } 2682 2683 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2684 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2685 << FromFunction->getNumParams(); 2686 return; 2687 } 2688 2689 // Handle different parameter types. 2690 unsigned ArgPos; 2691 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2692 PDiag << ft_parameter_mismatch << ArgPos + 1 2693 << ToFunction->getParamType(ArgPos) 2694 << FromFunction->getParamType(ArgPos); 2695 return; 2696 } 2697 2698 // Handle different return type. 2699 if (!Context.hasSameType(FromFunction->getReturnType(), 2700 ToFunction->getReturnType())) { 2701 PDiag << ft_return_type << ToFunction->getReturnType() 2702 << FromFunction->getReturnType(); 2703 return; 2704 } 2705 2706 unsigned FromQuals = FromFunction->getTypeQuals(), 2707 ToQuals = ToFunction->getTypeQuals(); 2708 if (FromQuals != ToQuals) { 2709 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2710 return; 2711 } 2712 2713 // Unable to find a difference, so add no extra info. 2714 PDiag << ft_default; 2715 } 2716 2717 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2718 /// for equality of their argument types. Caller has already checked that 2719 /// they have same number of arguments. If the parameters are different, 2720 /// ArgPos will have the parameter index of the first different parameter. 2721 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2722 const FunctionProtoType *NewType, 2723 unsigned *ArgPos) { 2724 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2725 N = NewType->param_type_begin(), 2726 E = OldType->param_type_end(); 2727 O && (O != E); ++O, ++N) { 2728 if (!Context.hasSameType(O->getUnqualifiedType(), 2729 N->getUnqualifiedType())) { 2730 if (ArgPos) 2731 *ArgPos = O - OldType->param_type_begin(); 2732 return false; 2733 } 2734 } 2735 return true; 2736 } 2737 2738 /// CheckPointerConversion - Check the pointer conversion from the 2739 /// expression From to the type ToType. This routine checks for 2740 /// ambiguous or inaccessible derived-to-base pointer 2741 /// conversions for which IsPointerConversion has already returned 2742 /// true. It returns true and produces a diagnostic if there was an 2743 /// error, or returns false otherwise. 2744 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2745 CastKind &Kind, 2746 CXXCastPath& BasePath, 2747 bool IgnoreBaseAccess, 2748 bool Diagnose) { 2749 QualType FromType = From->getType(); 2750 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2751 2752 Kind = CK_BitCast; 2753 2754 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2755 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2756 Expr::NPCK_ZeroExpression) { 2757 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2758 DiagRuntimeBehavior(From->getExprLoc(), From, 2759 PDiag(diag::warn_impcast_bool_to_null_pointer) 2760 << ToType << From->getSourceRange()); 2761 else if (!isUnevaluatedContext()) 2762 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2763 << ToType << From->getSourceRange(); 2764 } 2765 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2766 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2767 QualType FromPointeeType = FromPtrType->getPointeeType(), 2768 ToPointeeType = ToPtrType->getPointeeType(); 2769 2770 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2771 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2772 // We must have a derived-to-base conversion. Check an 2773 // ambiguous or inaccessible conversion. 2774 unsigned InaccessibleID = 0; 2775 unsigned AmbigiousID = 0; 2776 if (Diagnose) { 2777 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2778 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2779 } 2780 if (CheckDerivedToBaseConversion( 2781 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2782 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2783 &BasePath, IgnoreBaseAccess)) 2784 return true; 2785 2786 // The conversion was successful. 2787 Kind = CK_DerivedToBase; 2788 } 2789 2790 if (Diagnose && !IsCStyleOrFunctionalCast && 2791 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2792 assert(getLangOpts().MSVCCompat && 2793 "this should only be possible with MSVCCompat!"); 2794 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2795 << From->getSourceRange(); 2796 } 2797 } 2798 } else if (const ObjCObjectPointerType *ToPtrType = 2799 ToType->getAs<ObjCObjectPointerType>()) { 2800 if (const ObjCObjectPointerType *FromPtrType = 2801 FromType->getAs<ObjCObjectPointerType>()) { 2802 // Objective-C++ conversions are always okay. 2803 // FIXME: We should have a different class of conversions for the 2804 // Objective-C++ implicit conversions. 2805 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2806 return false; 2807 } else if (FromType->isBlockPointerType()) { 2808 Kind = CK_BlockPointerToObjCPointerCast; 2809 } else { 2810 Kind = CK_CPointerToObjCPointerCast; 2811 } 2812 } else if (ToType->isBlockPointerType()) { 2813 if (!FromType->isBlockPointerType()) 2814 Kind = CK_AnyPointerToBlockPointerCast; 2815 } 2816 2817 // We shouldn't fall into this case unless it's valid for other 2818 // reasons. 2819 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2820 Kind = CK_NullToPointer; 2821 2822 return false; 2823 } 2824 2825 /// IsMemberPointerConversion - Determines whether the conversion of the 2826 /// expression From, which has the (possibly adjusted) type FromType, can be 2827 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2828 /// If so, returns true and places the converted type (that might differ from 2829 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2830 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2831 QualType ToType, 2832 bool InOverloadResolution, 2833 QualType &ConvertedType) { 2834 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2835 if (!ToTypePtr) 2836 return false; 2837 2838 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2839 if (From->isNullPointerConstant(Context, 2840 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2841 : Expr::NPC_ValueDependentIsNull)) { 2842 ConvertedType = ToType; 2843 return true; 2844 } 2845 2846 // Otherwise, both types have to be member pointers. 2847 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2848 if (!FromTypePtr) 2849 return false; 2850 2851 // A pointer to member of B can be converted to a pointer to member of D, 2852 // where D is derived from B (C++ 4.11p2). 2853 QualType FromClass(FromTypePtr->getClass(), 0); 2854 QualType ToClass(ToTypePtr->getClass(), 0); 2855 2856 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2857 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2858 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2859 ToClass.getTypePtr()); 2860 return true; 2861 } 2862 2863 return false; 2864 } 2865 2866 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2867 /// expression From to the type ToType. This routine checks for ambiguous or 2868 /// virtual or inaccessible base-to-derived member pointer conversions 2869 /// for which IsMemberPointerConversion has already returned true. It returns 2870 /// true and produces a diagnostic if there was an error, or returns false 2871 /// otherwise. 2872 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2873 CastKind &Kind, 2874 CXXCastPath &BasePath, 2875 bool IgnoreBaseAccess) { 2876 QualType FromType = From->getType(); 2877 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2878 if (!FromPtrType) { 2879 // This must be a null pointer to member pointer conversion 2880 assert(From->isNullPointerConstant(Context, 2881 Expr::NPC_ValueDependentIsNull) && 2882 "Expr must be null pointer constant!"); 2883 Kind = CK_NullToMemberPointer; 2884 return false; 2885 } 2886 2887 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2888 assert(ToPtrType && "No member pointer cast has a target type " 2889 "that is not a member pointer."); 2890 2891 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2892 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2893 2894 // FIXME: What about dependent types? 2895 assert(FromClass->isRecordType() && "Pointer into non-class."); 2896 assert(ToClass->isRecordType() && "Pointer into non-class."); 2897 2898 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2899 /*DetectVirtual=*/true); 2900 bool DerivationOkay = 2901 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2902 assert(DerivationOkay && 2903 "Should not have been called if derivation isn't OK."); 2904 (void)DerivationOkay; 2905 2906 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2907 getUnqualifiedType())) { 2908 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2909 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2910 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2911 return true; 2912 } 2913 2914 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2915 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2916 << FromClass << ToClass << QualType(VBase, 0) 2917 << From->getSourceRange(); 2918 return true; 2919 } 2920 2921 if (!IgnoreBaseAccess) 2922 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2923 Paths.front(), 2924 diag::err_downcast_from_inaccessible_base); 2925 2926 // Must be a base to derived member conversion. 2927 BuildBasePathArray(Paths, BasePath); 2928 Kind = CK_BaseToDerivedMemberPointer; 2929 return false; 2930 } 2931 2932 /// Determine whether the lifetime conversion between the two given 2933 /// qualifiers sets is nontrivial. 2934 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2935 Qualifiers ToQuals) { 2936 // Converting anything to const __unsafe_unretained is trivial. 2937 if (ToQuals.hasConst() && 2938 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2939 return false; 2940 2941 return true; 2942 } 2943 2944 /// IsQualificationConversion - Determines whether the conversion from 2945 /// an rvalue of type FromType to ToType is a qualification conversion 2946 /// (C++ 4.4). 2947 /// 2948 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2949 /// when the qualification conversion involves a change in the Objective-C 2950 /// object lifetime. 2951 bool 2952 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2953 bool CStyle, bool &ObjCLifetimeConversion) { 2954 FromType = Context.getCanonicalType(FromType); 2955 ToType = Context.getCanonicalType(ToType); 2956 ObjCLifetimeConversion = false; 2957 2958 // If FromType and ToType are the same type, this is not a 2959 // qualification conversion. 2960 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2961 return false; 2962 2963 // (C++ 4.4p4): 2964 // A conversion can add cv-qualifiers at levels other than the first 2965 // in multi-level pointers, subject to the following rules: [...] 2966 bool PreviousToQualsIncludeConst = true; 2967 bool UnwrappedAnyPointer = false; 2968 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2969 // Within each iteration of the loop, we check the qualifiers to 2970 // determine if this still looks like a qualification 2971 // conversion. Then, if all is well, we unwrap one more level of 2972 // pointers or pointers-to-members and do it all again 2973 // until there are no more pointers or pointers-to-members left to 2974 // unwrap. 2975 UnwrappedAnyPointer = true; 2976 2977 Qualifiers FromQuals = FromType.getQualifiers(); 2978 Qualifiers ToQuals = ToType.getQualifiers(); 2979 2980 // Ignore __unaligned qualifier if this type is void. 2981 if (ToType.getUnqualifiedType()->isVoidType()) 2982 FromQuals.removeUnaligned(); 2983 2984 // Objective-C ARC: 2985 // Check Objective-C lifetime conversions. 2986 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2987 UnwrappedAnyPointer) { 2988 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2989 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2990 ObjCLifetimeConversion = true; 2991 FromQuals.removeObjCLifetime(); 2992 ToQuals.removeObjCLifetime(); 2993 } else { 2994 // Qualification conversions cannot cast between different 2995 // Objective-C lifetime qualifiers. 2996 return false; 2997 } 2998 } 2999 3000 // Allow addition/removal of GC attributes but not changing GC attributes. 3001 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3002 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3003 FromQuals.removeObjCGCAttr(); 3004 ToQuals.removeObjCGCAttr(); 3005 } 3006 3007 // -- for every j > 0, if const is in cv 1,j then const is in cv 3008 // 2,j, and similarly for volatile. 3009 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3010 return false; 3011 3012 // -- if the cv 1,j and cv 2,j are different, then const is in 3013 // every cv for 0 < k < j. 3014 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3015 && !PreviousToQualsIncludeConst) 3016 return false; 3017 3018 // Keep track of whether all prior cv-qualifiers in the "to" type 3019 // include const. 3020 PreviousToQualsIncludeConst 3021 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3022 } 3023 3024 // We are left with FromType and ToType being the pointee types 3025 // after unwrapping the original FromType and ToType the same number 3026 // of types. If we unwrapped any pointers, and if FromType and 3027 // ToType have the same unqualified type (since we checked 3028 // qualifiers above), then this is a qualification conversion. 3029 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3030 } 3031 3032 /// \brief - Determine whether this is a conversion from a scalar type to an 3033 /// atomic type. 3034 /// 3035 /// If successful, updates \c SCS's second and third steps in the conversion 3036 /// sequence to finish the conversion. 3037 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3038 bool InOverloadResolution, 3039 StandardConversionSequence &SCS, 3040 bool CStyle) { 3041 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3042 if (!ToAtomic) 3043 return false; 3044 3045 StandardConversionSequence InnerSCS; 3046 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3047 InOverloadResolution, InnerSCS, 3048 CStyle, /*AllowObjCWritebackConversion=*/false)) 3049 return false; 3050 3051 SCS.Second = InnerSCS.Second; 3052 SCS.setToType(1, InnerSCS.getToType(1)); 3053 SCS.Third = InnerSCS.Third; 3054 SCS.QualificationIncludesObjCLifetime 3055 = InnerSCS.QualificationIncludesObjCLifetime; 3056 SCS.setToType(2, InnerSCS.getToType(2)); 3057 return true; 3058 } 3059 3060 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3061 CXXConstructorDecl *Constructor, 3062 QualType Type) { 3063 const FunctionProtoType *CtorType = 3064 Constructor->getType()->getAs<FunctionProtoType>(); 3065 if (CtorType->getNumParams() > 0) { 3066 QualType FirstArg = CtorType->getParamType(0); 3067 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3068 return true; 3069 } 3070 return false; 3071 } 3072 3073 static OverloadingResult 3074 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3075 CXXRecordDecl *To, 3076 UserDefinedConversionSequence &User, 3077 OverloadCandidateSet &CandidateSet, 3078 bool AllowExplicit) { 3079 for (auto *D : S.LookupConstructors(To)) { 3080 auto Info = getConstructorInfo(D); 3081 if (!Info) 3082 continue; 3083 3084 bool Usable = !Info.Constructor->isInvalidDecl() && 3085 S.isInitListConstructor(Info.Constructor) && 3086 (AllowExplicit || !Info.Constructor->isExplicit()); 3087 if (Usable) { 3088 // If the first argument is (a reference to) the target type, 3089 // suppress conversions. 3090 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3091 S.Context, Info.Constructor, ToType); 3092 if (Info.ConstructorTmpl) 3093 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3094 /*ExplicitArgs*/ nullptr, From, 3095 CandidateSet, SuppressUserConversions); 3096 else 3097 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3098 CandidateSet, SuppressUserConversions); 3099 } 3100 } 3101 3102 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3103 3104 OverloadCandidateSet::iterator Best; 3105 switch (auto Result = 3106 CandidateSet.BestViableFunction(S, From->getLocStart(), 3107 Best, true)) { 3108 case OR_Deleted: 3109 case OR_Success: { 3110 // Record the standard conversion we used and the conversion function. 3111 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3112 QualType ThisType = Constructor->getThisType(S.Context); 3113 // Initializer lists don't have conversions as such. 3114 User.Before.setAsIdentityConversion(); 3115 User.HadMultipleCandidates = HadMultipleCandidates; 3116 User.ConversionFunction = Constructor; 3117 User.FoundConversionFunction = Best->FoundDecl; 3118 User.After.setAsIdentityConversion(); 3119 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3120 User.After.setAllToTypes(ToType); 3121 return Result; 3122 } 3123 3124 case OR_No_Viable_Function: 3125 return OR_No_Viable_Function; 3126 case OR_Ambiguous: 3127 return OR_Ambiguous; 3128 } 3129 3130 llvm_unreachable("Invalid OverloadResult!"); 3131 } 3132 3133 /// Determines whether there is a user-defined conversion sequence 3134 /// (C++ [over.ics.user]) that converts expression From to the type 3135 /// ToType. If such a conversion exists, User will contain the 3136 /// user-defined conversion sequence that performs such a conversion 3137 /// and this routine will return true. Otherwise, this routine returns 3138 /// false and User is unspecified. 3139 /// 3140 /// \param AllowExplicit true if the conversion should consider C++0x 3141 /// "explicit" conversion functions as well as non-explicit conversion 3142 /// functions (C++0x [class.conv.fct]p2). 3143 /// 3144 /// \param AllowObjCConversionOnExplicit true if the conversion should 3145 /// allow an extra Objective-C pointer conversion on uses of explicit 3146 /// constructors. Requires \c AllowExplicit to also be set. 3147 static OverloadingResult 3148 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3149 UserDefinedConversionSequence &User, 3150 OverloadCandidateSet &CandidateSet, 3151 bool AllowExplicit, 3152 bool AllowObjCConversionOnExplicit) { 3153 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3154 3155 // Whether we will only visit constructors. 3156 bool ConstructorsOnly = false; 3157 3158 // If the type we are conversion to is a class type, enumerate its 3159 // constructors. 3160 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3161 // C++ [over.match.ctor]p1: 3162 // When objects of class type are direct-initialized (8.5), or 3163 // copy-initialized from an expression of the same or a 3164 // derived class type (8.5), overload resolution selects the 3165 // constructor. [...] For copy-initialization, the candidate 3166 // functions are all the converting constructors (12.3.1) of 3167 // that class. The argument list is the expression-list within 3168 // the parentheses of the initializer. 3169 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3170 (From->getType()->getAs<RecordType>() && 3171 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3172 ConstructorsOnly = true; 3173 3174 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3175 // We're not going to find any constructors. 3176 } else if (CXXRecordDecl *ToRecordDecl 3177 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3178 3179 Expr **Args = &From; 3180 unsigned NumArgs = 1; 3181 bool ListInitializing = false; 3182 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3183 // But first, see if there is an init-list-constructor that will work. 3184 OverloadingResult Result = IsInitializerListConstructorConversion( 3185 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3186 if (Result != OR_No_Viable_Function) 3187 return Result; 3188 // Never mind. 3189 CandidateSet.clear(); 3190 3191 // If we're list-initializing, we pass the individual elements as 3192 // arguments, not the entire list. 3193 Args = InitList->getInits(); 3194 NumArgs = InitList->getNumInits(); 3195 ListInitializing = true; 3196 } 3197 3198 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3199 auto Info = getConstructorInfo(D); 3200 if (!Info) 3201 continue; 3202 3203 bool Usable = !Info.Constructor->isInvalidDecl(); 3204 if (ListInitializing) 3205 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3206 else 3207 Usable = Usable && 3208 Info.Constructor->isConvertingConstructor(AllowExplicit); 3209 if (Usable) { 3210 bool SuppressUserConversions = !ConstructorsOnly; 3211 if (SuppressUserConversions && ListInitializing) { 3212 SuppressUserConversions = false; 3213 if (NumArgs == 1) { 3214 // If the first argument is (a reference to) the target type, 3215 // suppress conversions. 3216 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3217 S.Context, Info.Constructor, ToType); 3218 } 3219 } 3220 if (Info.ConstructorTmpl) 3221 S.AddTemplateOverloadCandidate( 3222 Info.ConstructorTmpl, Info.FoundDecl, 3223 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3224 CandidateSet, SuppressUserConversions); 3225 else 3226 // Allow one user-defined conversion when user specifies a 3227 // From->ToType conversion via an static cast (c-style, etc). 3228 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3229 llvm::makeArrayRef(Args, NumArgs), 3230 CandidateSet, SuppressUserConversions); 3231 } 3232 } 3233 } 3234 } 3235 3236 // Enumerate conversion functions, if we're allowed to. 3237 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3238 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3239 // No conversion functions from incomplete types. 3240 } else if (const RecordType *FromRecordType 3241 = From->getType()->getAs<RecordType>()) { 3242 if (CXXRecordDecl *FromRecordDecl 3243 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3244 // Add all of the conversion functions as candidates. 3245 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3246 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3247 DeclAccessPair FoundDecl = I.getPair(); 3248 NamedDecl *D = FoundDecl.getDecl(); 3249 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3250 if (isa<UsingShadowDecl>(D)) 3251 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3252 3253 CXXConversionDecl *Conv; 3254 FunctionTemplateDecl *ConvTemplate; 3255 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3256 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3257 else 3258 Conv = cast<CXXConversionDecl>(D); 3259 3260 if (AllowExplicit || !Conv->isExplicit()) { 3261 if (ConvTemplate) 3262 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3263 ActingContext, From, ToType, 3264 CandidateSet, 3265 AllowObjCConversionOnExplicit); 3266 else 3267 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3268 From, ToType, CandidateSet, 3269 AllowObjCConversionOnExplicit); 3270 } 3271 } 3272 } 3273 } 3274 3275 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3276 3277 OverloadCandidateSet::iterator Best; 3278 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3279 Best, true)) { 3280 case OR_Success: 3281 case OR_Deleted: 3282 // Record the standard conversion we used and the conversion function. 3283 if (CXXConstructorDecl *Constructor 3284 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3285 // C++ [over.ics.user]p1: 3286 // If the user-defined conversion is specified by a 3287 // constructor (12.3.1), the initial standard conversion 3288 // sequence converts the source type to the type required by 3289 // the argument of the constructor. 3290 // 3291 QualType ThisType = Constructor->getThisType(S.Context); 3292 if (isa<InitListExpr>(From)) { 3293 // Initializer lists don't have conversions as such. 3294 User.Before.setAsIdentityConversion(); 3295 } else { 3296 if (Best->Conversions[0].isEllipsis()) 3297 User.EllipsisConversion = true; 3298 else { 3299 User.Before = Best->Conversions[0].Standard; 3300 User.EllipsisConversion = false; 3301 } 3302 } 3303 User.HadMultipleCandidates = HadMultipleCandidates; 3304 User.ConversionFunction = Constructor; 3305 User.FoundConversionFunction = Best->FoundDecl; 3306 User.After.setAsIdentityConversion(); 3307 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3308 User.After.setAllToTypes(ToType); 3309 return Result; 3310 } 3311 if (CXXConversionDecl *Conversion 3312 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3313 // C++ [over.ics.user]p1: 3314 // 3315 // [...] If the user-defined conversion is specified by a 3316 // conversion function (12.3.2), the initial standard 3317 // conversion sequence converts the source type to the 3318 // implicit object parameter of the conversion function. 3319 User.Before = Best->Conversions[0].Standard; 3320 User.HadMultipleCandidates = HadMultipleCandidates; 3321 User.ConversionFunction = Conversion; 3322 User.FoundConversionFunction = Best->FoundDecl; 3323 User.EllipsisConversion = false; 3324 3325 // C++ [over.ics.user]p2: 3326 // The second standard conversion sequence converts the 3327 // result of the user-defined conversion to the target type 3328 // for the sequence. Since an implicit conversion sequence 3329 // is an initialization, the special rules for 3330 // initialization by user-defined conversion apply when 3331 // selecting the best user-defined conversion for a 3332 // user-defined conversion sequence (see 13.3.3 and 3333 // 13.3.3.1). 3334 User.After = Best->FinalConversion; 3335 return Result; 3336 } 3337 llvm_unreachable("Not a constructor or conversion function?"); 3338 3339 case OR_No_Viable_Function: 3340 return OR_No_Viable_Function; 3341 3342 case OR_Ambiguous: 3343 return OR_Ambiguous; 3344 } 3345 3346 llvm_unreachable("Invalid OverloadResult!"); 3347 } 3348 3349 bool 3350 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3351 ImplicitConversionSequence ICS; 3352 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3353 OverloadCandidateSet::CSK_Normal); 3354 OverloadingResult OvResult = 3355 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3356 CandidateSet, false, false); 3357 if (OvResult == OR_Ambiguous) 3358 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3359 << From->getType() << ToType << From->getSourceRange(); 3360 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3361 if (!RequireCompleteType(From->getLocStart(), ToType, 3362 diag::err_typecheck_nonviable_condition_incomplete, 3363 From->getType(), From->getSourceRange())) 3364 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3365 << false << From->getType() << From->getSourceRange() << ToType; 3366 } else 3367 return false; 3368 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3369 return true; 3370 } 3371 3372 /// \brief Compare the user-defined conversion functions or constructors 3373 /// of two user-defined conversion sequences to determine whether any ordering 3374 /// is possible. 3375 static ImplicitConversionSequence::CompareKind 3376 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3377 FunctionDecl *Function2) { 3378 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3379 return ImplicitConversionSequence::Indistinguishable; 3380 3381 // Objective-C++: 3382 // If both conversion functions are implicitly-declared conversions from 3383 // a lambda closure type to a function pointer and a block pointer, 3384 // respectively, always prefer the conversion to a function pointer, 3385 // because the function pointer is more lightweight and is more likely 3386 // to keep code working. 3387 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3388 if (!Conv1) 3389 return ImplicitConversionSequence::Indistinguishable; 3390 3391 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3392 if (!Conv2) 3393 return ImplicitConversionSequence::Indistinguishable; 3394 3395 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3396 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3397 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3398 if (Block1 != Block2) 3399 return Block1 ? ImplicitConversionSequence::Worse 3400 : ImplicitConversionSequence::Better; 3401 } 3402 3403 return ImplicitConversionSequence::Indistinguishable; 3404 } 3405 3406 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3407 const ImplicitConversionSequence &ICS) { 3408 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3409 (ICS.isUserDefined() && 3410 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3411 } 3412 3413 /// CompareImplicitConversionSequences - Compare two implicit 3414 /// conversion sequences to determine whether one is better than the 3415 /// other or if they are indistinguishable (C++ 13.3.3.2). 3416 static ImplicitConversionSequence::CompareKind 3417 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3418 const ImplicitConversionSequence& ICS1, 3419 const ImplicitConversionSequence& ICS2) 3420 { 3421 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3422 // conversion sequences (as defined in 13.3.3.1) 3423 // -- a standard conversion sequence (13.3.3.1.1) is a better 3424 // conversion sequence than a user-defined conversion sequence or 3425 // an ellipsis conversion sequence, and 3426 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3427 // conversion sequence than an ellipsis conversion sequence 3428 // (13.3.3.1.3). 3429 // 3430 // C++0x [over.best.ics]p10: 3431 // For the purpose of ranking implicit conversion sequences as 3432 // described in 13.3.3.2, the ambiguous conversion sequence is 3433 // treated as a user-defined sequence that is indistinguishable 3434 // from any other user-defined conversion sequence. 3435 3436 // String literal to 'char *' conversion has been deprecated in C++03. It has 3437 // been removed from C++11. We still accept this conversion, if it happens at 3438 // the best viable function. Otherwise, this conversion is considered worse 3439 // than ellipsis conversion. Consider this as an extension; this is not in the 3440 // standard. For example: 3441 // 3442 // int &f(...); // #1 3443 // void f(char*); // #2 3444 // void g() { int &r = f("foo"); } 3445 // 3446 // In C++03, we pick #2 as the best viable function. 3447 // In C++11, we pick #1 as the best viable function, because ellipsis 3448 // conversion is better than string-literal to char* conversion (since there 3449 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3450 // convert arguments, #2 would be the best viable function in C++11. 3451 // If the best viable function has this conversion, a warning will be issued 3452 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3453 3454 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3455 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3456 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3457 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3458 ? ImplicitConversionSequence::Worse 3459 : ImplicitConversionSequence::Better; 3460 3461 if (ICS1.getKindRank() < ICS2.getKindRank()) 3462 return ImplicitConversionSequence::Better; 3463 if (ICS2.getKindRank() < ICS1.getKindRank()) 3464 return ImplicitConversionSequence::Worse; 3465 3466 // The following checks require both conversion sequences to be of 3467 // the same kind. 3468 if (ICS1.getKind() != ICS2.getKind()) 3469 return ImplicitConversionSequence::Indistinguishable; 3470 3471 ImplicitConversionSequence::CompareKind Result = 3472 ImplicitConversionSequence::Indistinguishable; 3473 3474 // Two implicit conversion sequences of the same form are 3475 // indistinguishable conversion sequences unless one of the 3476 // following rules apply: (C++ 13.3.3.2p3): 3477 3478 // List-initialization sequence L1 is a better conversion sequence than 3479 // list-initialization sequence L2 if: 3480 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3481 // if not that, 3482 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3483 // and N1 is smaller than N2., 3484 // even if one of the other rules in this paragraph would otherwise apply. 3485 if (!ICS1.isBad()) { 3486 if (ICS1.isStdInitializerListElement() && 3487 !ICS2.isStdInitializerListElement()) 3488 return ImplicitConversionSequence::Better; 3489 if (!ICS1.isStdInitializerListElement() && 3490 ICS2.isStdInitializerListElement()) 3491 return ImplicitConversionSequence::Worse; 3492 } 3493 3494 if (ICS1.isStandard()) 3495 // Standard conversion sequence S1 is a better conversion sequence than 3496 // standard conversion sequence S2 if [...] 3497 Result = CompareStandardConversionSequences(S, Loc, 3498 ICS1.Standard, ICS2.Standard); 3499 else if (ICS1.isUserDefined()) { 3500 // User-defined conversion sequence U1 is a better conversion 3501 // sequence than another user-defined conversion sequence U2 if 3502 // they contain the same user-defined conversion function or 3503 // constructor and if the second standard conversion sequence of 3504 // U1 is better than the second standard conversion sequence of 3505 // U2 (C++ 13.3.3.2p3). 3506 if (ICS1.UserDefined.ConversionFunction == 3507 ICS2.UserDefined.ConversionFunction) 3508 Result = CompareStandardConversionSequences(S, Loc, 3509 ICS1.UserDefined.After, 3510 ICS2.UserDefined.After); 3511 else 3512 Result = compareConversionFunctions(S, 3513 ICS1.UserDefined.ConversionFunction, 3514 ICS2.UserDefined.ConversionFunction); 3515 } 3516 3517 return Result; 3518 } 3519 3520 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3521 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3522 Qualifiers Quals; 3523 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3524 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3525 } 3526 3527 return Context.hasSameUnqualifiedType(T1, T2); 3528 } 3529 3530 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3531 // determine if one is a proper subset of the other. 3532 static ImplicitConversionSequence::CompareKind 3533 compareStandardConversionSubsets(ASTContext &Context, 3534 const StandardConversionSequence& SCS1, 3535 const StandardConversionSequence& SCS2) { 3536 ImplicitConversionSequence::CompareKind Result 3537 = ImplicitConversionSequence::Indistinguishable; 3538 3539 // the identity conversion sequence is considered to be a subsequence of 3540 // any non-identity conversion sequence 3541 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3542 return ImplicitConversionSequence::Better; 3543 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3544 return ImplicitConversionSequence::Worse; 3545 3546 if (SCS1.Second != SCS2.Second) { 3547 if (SCS1.Second == ICK_Identity) 3548 Result = ImplicitConversionSequence::Better; 3549 else if (SCS2.Second == ICK_Identity) 3550 Result = ImplicitConversionSequence::Worse; 3551 else 3552 return ImplicitConversionSequence::Indistinguishable; 3553 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3554 return ImplicitConversionSequence::Indistinguishable; 3555 3556 if (SCS1.Third == SCS2.Third) { 3557 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3558 : ImplicitConversionSequence::Indistinguishable; 3559 } 3560 3561 if (SCS1.Third == ICK_Identity) 3562 return Result == ImplicitConversionSequence::Worse 3563 ? ImplicitConversionSequence::Indistinguishable 3564 : ImplicitConversionSequence::Better; 3565 3566 if (SCS2.Third == ICK_Identity) 3567 return Result == ImplicitConversionSequence::Better 3568 ? ImplicitConversionSequence::Indistinguishable 3569 : ImplicitConversionSequence::Worse; 3570 3571 return ImplicitConversionSequence::Indistinguishable; 3572 } 3573 3574 /// \brief Determine whether one of the given reference bindings is better 3575 /// than the other based on what kind of bindings they are. 3576 static bool 3577 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3578 const StandardConversionSequence &SCS2) { 3579 // C++0x [over.ics.rank]p3b4: 3580 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3581 // implicit object parameter of a non-static member function declared 3582 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3583 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3584 // lvalue reference to a function lvalue and S2 binds an rvalue 3585 // reference*. 3586 // 3587 // FIXME: Rvalue references. We're going rogue with the above edits, 3588 // because the semantics in the current C++0x working paper (N3225 at the 3589 // time of this writing) break the standard definition of std::forward 3590 // and std::reference_wrapper when dealing with references to functions. 3591 // Proposed wording changes submitted to CWG for consideration. 3592 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3593 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3594 return false; 3595 3596 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3597 SCS2.IsLvalueReference) || 3598 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3599 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3600 } 3601 3602 /// CompareStandardConversionSequences - Compare two standard 3603 /// conversion sequences to determine whether one is better than the 3604 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3605 static ImplicitConversionSequence::CompareKind 3606 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3607 const StandardConversionSequence& SCS1, 3608 const StandardConversionSequence& SCS2) 3609 { 3610 // Standard conversion sequence S1 is a better conversion sequence 3611 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3612 3613 // -- S1 is a proper subsequence of S2 (comparing the conversion 3614 // sequences in the canonical form defined by 13.3.3.1.1, 3615 // excluding any Lvalue Transformation; the identity conversion 3616 // sequence is considered to be a subsequence of any 3617 // non-identity conversion sequence) or, if not that, 3618 if (ImplicitConversionSequence::CompareKind CK 3619 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3620 return CK; 3621 3622 // -- the rank of S1 is better than the rank of S2 (by the rules 3623 // defined below), or, if not that, 3624 ImplicitConversionRank Rank1 = SCS1.getRank(); 3625 ImplicitConversionRank Rank2 = SCS2.getRank(); 3626 if (Rank1 < Rank2) 3627 return ImplicitConversionSequence::Better; 3628 else if (Rank2 < Rank1) 3629 return ImplicitConversionSequence::Worse; 3630 3631 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3632 // are indistinguishable unless one of the following rules 3633 // applies: 3634 3635 // A conversion that is not a conversion of a pointer, or 3636 // pointer to member, to bool is better than another conversion 3637 // that is such a conversion. 3638 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3639 return SCS2.isPointerConversionToBool() 3640 ? ImplicitConversionSequence::Better 3641 : ImplicitConversionSequence::Worse; 3642 3643 // C++ [over.ics.rank]p4b2: 3644 // 3645 // If class B is derived directly or indirectly from class A, 3646 // conversion of B* to A* is better than conversion of B* to 3647 // void*, and conversion of A* to void* is better than conversion 3648 // of B* to void*. 3649 bool SCS1ConvertsToVoid 3650 = SCS1.isPointerConversionToVoidPointer(S.Context); 3651 bool SCS2ConvertsToVoid 3652 = SCS2.isPointerConversionToVoidPointer(S.Context); 3653 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3654 // Exactly one of the conversion sequences is a conversion to 3655 // a void pointer; it's the worse conversion. 3656 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3657 : ImplicitConversionSequence::Worse; 3658 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3659 // Neither conversion sequence converts to a void pointer; compare 3660 // their derived-to-base conversions. 3661 if (ImplicitConversionSequence::CompareKind DerivedCK 3662 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3663 return DerivedCK; 3664 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3665 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3666 // Both conversion sequences are conversions to void 3667 // pointers. Compare the source types to determine if there's an 3668 // inheritance relationship in their sources. 3669 QualType FromType1 = SCS1.getFromType(); 3670 QualType FromType2 = SCS2.getFromType(); 3671 3672 // Adjust the types we're converting from via the array-to-pointer 3673 // conversion, if we need to. 3674 if (SCS1.First == ICK_Array_To_Pointer) 3675 FromType1 = S.Context.getArrayDecayedType(FromType1); 3676 if (SCS2.First == ICK_Array_To_Pointer) 3677 FromType2 = S.Context.getArrayDecayedType(FromType2); 3678 3679 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3680 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3681 3682 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3683 return ImplicitConversionSequence::Better; 3684 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3685 return ImplicitConversionSequence::Worse; 3686 3687 // Objective-C++: If one interface is more specific than the 3688 // other, it is the better one. 3689 const ObjCObjectPointerType* FromObjCPtr1 3690 = FromType1->getAs<ObjCObjectPointerType>(); 3691 const ObjCObjectPointerType* FromObjCPtr2 3692 = FromType2->getAs<ObjCObjectPointerType>(); 3693 if (FromObjCPtr1 && FromObjCPtr2) { 3694 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3695 FromObjCPtr2); 3696 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3697 FromObjCPtr1); 3698 if (AssignLeft != AssignRight) { 3699 return AssignLeft? ImplicitConversionSequence::Better 3700 : ImplicitConversionSequence::Worse; 3701 } 3702 } 3703 } 3704 3705 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3706 // bullet 3). 3707 if (ImplicitConversionSequence::CompareKind QualCK 3708 = CompareQualificationConversions(S, SCS1, SCS2)) 3709 return QualCK; 3710 3711 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3712 // Check for a better reference binding based on the kind of bindings. 3713 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3714 return ImplicitConversionSequence::Better; 3715 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3716 return ImplicitConversionSequence::Worse; 3717 3718 // C++ [over.ics.rank]p3b4: 3719 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3720 // which the references refer are the same type except for 3721 // top-level cv-qualifiers, and the type to which the reference 3722 // initialized by S2 refers is more cv-qualified than the type 3723 // to which the reference initialized by S1 refers. 3724 QualType T1 = SCS1.getToType(2); 3725 QualType T2 = SCS2.getToType(2); 3726 T1 = S.Context.getCanonicalType(T1); 3727 T2 = S.Context.getCanonicalType(T2); 3728 Qualifiers T1Quals, T2Quals; 3729 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3730 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3731 if (UnqualT1 == UnqualT2) { 3732 // Objective-C++ ARC: If the references refer to objects with different 3733 // lifetimes, prefer bindings that don't change lifetime. 3734 if (SCS1.ObjCLifetimeConversionBinding != 3735 SCS2.ObjCLifetimeConversionBinding) { 3736 return SCS1.ObjCLifetimeConversionBinding 3737 ? ImplicitConversionSequence::Worse 3738 : ImplicitConversionSequence::Better; 3739 } 3740 3741 // If the type is an array type, promote the element qualifiers to the 3742 // type for comparison. 3743 if (isa<ArrayType>(T1) && T1Quals) 3744 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3745 if (isa<ArrayType>(T2) && T2Quals) 3746 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3747 if (T2.isMoreQualifiedThan(T1)) 3748 return ImplicitConversionSequence::Better; 3749 else if (T1.isMoreQualifiedThan(T2)) 3750 return ImplicitConversionSequence::Worse; 3751 } 3752 } 3753 3754 // In Microsoft mode, prefer an integral conversion to a 3755 // floating-to-integral conversion if the integral conversion 3756 // is between types of the same size. 3757 // For example: 3758 // void f(float); 3759 // void f(int); 3760 // int main { 3761 // long a; 3762 // f(a); 3763 // } 3764 // Here, MSVC will call f(int) instead of generating a compile error 3765 // as clang will do in standard mode. 3766 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3767 SCS2.Second == ICK_Floating_Integral && 3768 S.Context.getTypeSize(SCS1.getFromType()) == 3769 S.Context.getTypeSize(SCS1.getToType(2))) 3770 return ImplicitConversionSequence::Better; 3771 3772 return ImplicitConversionSequence::Indistinguishable; 3773 } 3774 3775 /// CompareQualificationConversions - Compares two standard conversion 3776 /// sequences to determine whether they can be ranked based on their 3777 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3778 static ImplicitConversionSequence::CompareKind 3779 CompareQualificationConversions(Sema &S, 3780 const StandardConversionSequence& SCS1, 3781 const StandardConversionSequence& SCS2) { 3782 // C++ 13.3.3.2p3: 3783 // -- S1 and S2 differ only in their qualification conversion and 3784 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3785 // cv-qualification signature of type T1 is a proper subset of 3786 // the cv-qualification signature of type T2, and S1 is not the 3787 // deprecated string literal array-to-pointer conversion (4.2). 3788 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3789 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3790 return ImplicitConversionSequence::Indistinguishable; 3791 3792 // FIXME: the example in the standard doesn't use a qualification 3793 // conversion (!) 3794 QualType T1 = SCS1.getToType(2); 3795 QualType T2 = SCS2.getToType(2); 3796 T1 = S.Context.getCanonicalType(T1); 3797 T2 = S.Context.getCanonicalType(T2); 3798 Qualifiers T1Quals, T2Quals; 3799 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3800 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3801 3802 // If the types are the same, we won't learn anything by unwrapped 3803 // them. 3804 if (UnqualT1 == UnqualT2) 3805 return ImplicitConversionSequence::Indistinguishable; 3806 3807 // If the type is an array type, promote the element qualifiers to the type 3808 // for comparison. 3809 if (isa<ArrayType>(T1) && T1Quals) 3810 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3811 if (isa<ArrayType>(T2) && T2Quals) 3812 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3813 3814 ImplicitConversionSequence::CompareKind Result 3815 = ImplicitConversionSequence::Indistinguishable; 3816 3817 // Objective-C++ ARC: 3818 // Prefer qualification conversions not involving a change in lifetime 3819 // to qualification conversions that do not change lifetime. 3820 if (SCS1.QualificationIncludesObjCLifetime != 3821 SCS2.QualificationIncludesObjCLifetime) { 3822 Result = SCS1.QualificationIncludesObjCLifetime 3823 ? ImplicitConversionSequence::Worse 3824 : ImplicitConversionSequence::Better; 3825 } 3826 3827 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3828 // Within each iteration of the loop, we check the qualifiers to 3829 // determine if this still looks like a qualification 3830 // conversion. Then, if all is well, we unwrap one more level of 3831 // pointers or pointers-to-members and do it all again 3832 // until there are no more pointers or pointers-to-members left 3833 // to unwrap. This essentially mimics what 3834 // IsQualificationConversion does, but here we're checking for a 3835 // strict subset of qualifiers. 3836 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3837 // The qualifiers are the same, so this doesn't tell us anything 3838 // about how the sequences rank. 3839 ; 3840 else if (T2.isMoreQualifiedThan(T1)) { 3841 // T1 has fewer qualifiers, so it could be the better sequence. 3842 if (Result == ImplicitConversionSequence::Worse) 3843 // Neither has qualifiers that are a subset of the other's 3844 // qualifiers. 3845 return ImplicitConversionSequence::Indistinguishable; 3846 3847 Result = ImplicitConversionSequence::Better; 3848 } else if (T1.isMoreQualifiedThan(T2)) { 3849 // T2 has fewer qualifiers, so it could be the better sequence. 3850 if (Result == ImplicitConversionSequence::Better) 3851 // Neither has qualifiers that are a subset of the other's 3852 // qualifiers. 3853 return ImplicitConversionSequence::Indistinguishable; 3854 3855 Result = ImplicitConversionSequence::Worse; 3856 } else { 3857 // Qualifiers are disjoint. 3858 return ImplicitConversionSequence::Indistinguishable; 3859 } 3860 3861 // If the types after this point are equivalent, we're done. 3862 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3863 break; 3864 } 3865 3866 // Check that the winning standard conversion sequence isn't using 3867 // the deprecated string literal array to pointer conversion. 3868 switch (Result) { 3869 case ImplicitConversionSequence::Better: 3870 if (SCS1.DeprecatedStringLiteralToCharPtr) 3871 Result = ImplicitConversionSequence::Indistinguishable; 3872 break; 3873 3874 case ImplicitConversionSequence::Indistinguishable: 3875 break; 3876 3877 case ImplicitConversionSequence::Worse: 3878 if (SCS2.DeprecatedStringLiteralToCharPtr) 3879 Result = ImplicitConversionSequence::Indistinguishable; 3880 break; 3881 } 3882 3883 return Result; 3884 } 3885 3886 /// CompareDerivedToBaseConversions - Compares two standard conversion 3887 /// sequences to determine whether they can be ranked based on their 3888 /// various kinds of derived-to-base conversions (C++ 3889 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3890 /// conversions between Objective-C interface types. 3891 static ImplicitConversionSequence::CompareKind 3892 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3893 const StandardConversionSequence& SCS1, 3894 const StandardConversionSequence& SCS2) { 3895 QualType FromType1 = SCS1.getFromType(); 3896 QualType ToType1 = SCS1.getToType(1); 3897 QualType FromType2 = SCS2.getFromType(); 3898 QualType ToType2 = SCS2.getToType(1); 3899 3900 // Adjust the types we're converting from via the array-to-pointer 3901 // conversion, if we need to. 3902 if (SCS1.First == ICK_Array_To_Pointer) 3903 FromType1 = S.Context.getArrayDecayedType(FromType1); 3904 if (SCS2.First == ICK_Array_To_Pointer) 3905 FromType2 = S.Context.getArrayDecayedType(FromType2); 3906 3907 // Canonicalize all of the types. 3908 FromType1 = S.Context.getCanonicalType(FromType1); 3909 ToType1 = S.Context.getCanonicalType(ToType1); 3910 FromType2 = S.Context.getCanonicalType(FromType2); 3911 ToType2 = S.Context.getCanonicalType(ToType2); 3912 3913 // C++ [over.ics.rank]p4b3: 3914 // 3915 // If class B is derived directly or indirectly from class A and 3916 // class C is derived directly or indirectly from B, 3917 // 3918 // Compare based on pointer conversions. 3919 if (SCS1.Second == ICK_Pointer_Conversion && 3920 SCS2.Second == ICK_Pointer_Conversion && 3921 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3922 FromType1->isPointerType() && FromType2->isPointerType() && 3923 ToType1->isPointerType() && ToType2->isPointerType()) { 3924 QualType FromPointee1 3925 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3926 QualType ToPointee1 3927 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3928 QualType FromPointee2 3929 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3930 QualType ToPointee2 3931 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3932 3933 // -- conversion of C* to B* is better than conversion of C* to A*, 3934 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3935 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3936 return ImplicitConversionSequence::Better; 3937 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3938 return ImplicitConversionSequence::Worse; 3939 } 3940 3941 // -- conversion of B* to A* is better than conversion of C* to A*, 3942 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3943 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3944 return ImplicitConversionSequence::Better; 3945 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3946 return ImplicitConversionSequence::Worse; 3947 } 3948 } else if (SCS1.Second == ICK_Pointer_Conversion && 3949 SCS2.Second == ICK_Pointer_Conversion) { 3950 const ObjCObjectPointerType *FromPtr1 3951 = FromType1->getAs<ObjCObjectPointerType>(); 3952 const ObjCObjectPointerType *FromPtr2 3953 = FromType2->getAs<ObjCObjectPointerType>(); 3954 const ObjCObjectPointerType *ToPtr1 3955 = ToType1->getAs<ObjCObjectPointerType>(); 3956 const ObjCObjectPointerType *ToPtr2 3957 = ToType2->getAs<ObjCObjectPointerType>(); 3958 3959 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3960 // Apply the same conversion ranking rules for Objective-C pointer types 3961 // that we do for C++ pointers to class types. However, we employ the 3962 // Objective-C pseudo-subtyping relationship used for assignment of 3963 // Objective-C pointer types. 3964 bool FromAssignLeft 3965 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3966 bool FromAssignRight 3967 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3968 bool ToAssignLeft 3969 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3970 bool ToAssignRight 3971 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3972 3973 // A conversion to an a non-id object pointer type or qualified 'id' 3974 // type is better than a conversion to 'id'. 3975 if (ToPtr1->isObjCIdType() && 3976 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3977 return ImplicitConversionSequence::Worse; 3978 if (ToPtr2->isObjCIdType() && 3979 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3980 return ImplicitConversionSequence::Better; 3981 3982 // A conversion to a non-id object pointer type is better than a 3983 // conversion to a qualified 'id' type 3984 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3985 return ImplicitConversionSequence::Worse; 3986 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3987 return ImplicitConversionSequence::Better; 3988 3989 // A conversion to an a non-Class object pointer type or qualified 'Class' 3990 // type is better than a conversion to 'Class'. 3991 if (ToPtr1->isObjCClassType() && 3992 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3993 return ImplicitConversionSequence::Worse; 3994 if (ToPtr2->isObjCClassType() && 3995 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3996 return ImplicitConversionSequence::Better; 3997 3998 // A conversion to a non-Class object pointer type is better than a 3999 // conversion to a qualified 'Class' type. 4000 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4001 return ImplicitConversionSequence::Worse; 4002 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4003 return ImplicitConversionSequence::Better; 4004 4005 // -- "conversion of C* to B* is better than conversion of C* to A*," 4006 if (S.Context.hasSameType(FromType1, FromType2) && 4007 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4008 (ToAssignLeft != ToAssignRight)) 4009 return ToAssignLeft? ImplicitConversionSequence::Worse 4010 : ImplicitConversionSequence::Better; 4011 4012 // -- "conversion of B* to A* is better than conversion of C* to A*," 4013 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4014 (FromAssignLeft != FromAssignRight)) 4015 return FromAssignLeft? ImplicitConversionSequence::Better 4016 : ImplicitConversionSequence::Worse; 4017 } 4018 } 4019 4020 // Ranking of member-pointer types. 4021 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4022 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4023 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4024 const MemberPointerType * FromMemPointer1 = 4025 FromType1->getAs<MemberPointerType>(); 4026 const MemberPointerType * ToMemPointer1 = 4027 ToType1->getAs<MemberPointerType>(); 4028 const MemberPointerType * FromMemPointer2 = 4029 FromType2->getAs<MemberPointerType>(); 4030 const MemberPointerType * ToMemPointer2 = 4031 ToType2->getAs<MemberPointerType>(); 4032 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4033 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4034 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4035 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4036 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4037 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4038 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4039 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4040 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4041 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4042 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4043 return ImplicitConversionSequence::Worse; 4044 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4045 return ImplicitConversionSequence::Better; 4046 } 4047 // conversion of B::* to C::* is better than conversion of A::* to C::* 4048 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4049 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4050 return ImplicitConversionSequence::Better; 4051 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4052 return ImplicitConversionSequence::Worse; 4053 } 4054 } 4055 4056 if (SCS1.Second == ICK_Derived_To_Base) { 4057 // -- conversion of C to B is better than conversion of C to A, 4058 // -- binding of an expression of type C to a reference of type 4059 // B& is better than binding an expression of type C to a 4060 // reference of type A&, 4061 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4062 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4063 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4064 return ImplicitConversionSequence::Better; 4065 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4066 return ImplicitConversionSequence::Worse; 4067 } 4068 4069 // -- conversion of B to A is better than conversion of C to A. 4070 // -- binding of an expression of type B to a reference of type 4071 // A& is better than binding an expression of type C to a 4072 // reference of type A&, 4073 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4074 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4075 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4076 return ImplicitConversionSequence::Better; 4077 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4078 return ImplicitConversionSequence::Worse; 4079 } 4080 } 4081 4082 return ImplicitConversionSequence::Indistinguishable; 4083 } 4084 4085 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4086 /// C++ class. 4087 static bool isTypeValid(QualType T) { 4088 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4089 return !Record->isInvalidDecl(); 4090 4091 return true; 4092 } 4093 4094 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4095 /// determine whether they are reference-related, 4096 /// reference-compatible, reference-compatible with added 4097 /// qualification, or incompatible, for use in C++ initialization by 4098 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4099 /// type, and the first type (T1) is the pointee type of the reference 4100 /// type being initialized. 4101 Sema::ReferenceCompareResult 4102 Sema::CompareReferenceRelationship(SourceLocation Loc, 4103 QualType OrigT1, QualType OrigT2, 4104 bool &DerivedToBase, 4105 bool &ObjCConversion, 4106 bool &ObjCLifetimeConversion) { 4107 assert(!OrigT1->isReferenceType() && 4108 "T1 must be the pointee type of the reference type"); 4109 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4110 4111 QualType T1 = Context.getCanonicalType(OrigT1); 4112 QualType T2 = Context.getCanonicalType(OrigT2); 4113 Qualifiers T1Quals, T2Quals; 4114 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4115 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4116 4117 // C++ [dcl.init.ref]p4: 4118 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4119 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4120 // T1 is a base class of T2. 4121 DerivedToBase = false; 4122 ObjCConversion = false; 4123 ObjCLifetimeConversion = false; 4124 if (UnqualT1 == UnqualT2) { 4125 // Nothing to do. 4126 } else if (isCompleteType(Loc, OrigT2) && 4127 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4128 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4129 DerivedToBase = true; 4130 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4131 UnqualT2->isObjCObjectOrInterfaceType() && 4132 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4133 ObjCConversion = true; 4134 else 4135 return Ref_Incompatible; 4136 4137 // At this point, we know that T1 and T2 are reference-related (at 4138 // least). 4139 4140 // If the type is an array type, promote the element qualifiers to the type 4141 // for comparison. 4142 if (isa<ArrayType>(T1) && T1Quals) 4143 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4144 if (isa<ArrayType>(T2) && T2Quals) 4145 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4146 4147 // C++ [dcl.init.ref]p4: 4148 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4149 // reference-related to T2 and cv1 is the same cv-qualification 4150 // as, or greater cv-qualification than, cv2. For purposes of 4151 // overload resolution, cases for which cv1 is greater 4152 // cv-qualification than cv2 are identified as 4153 // reference-compatible with added qualification (see 13.3.3.2). 4154 // 4155 // Note that we also require equivalence of Objective-C GC and address-space 4156 // qualifiers when performing these computations, so that e.g., an int in 4157 // address space 1 is not reference-compatible with an int in address 4158 // space 2. 4159 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4160 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4161 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4162 ObjCLifetimeConversion = true; 4163 4164 T1Quals.removeObjCLifetime(); 4165 T2Quals.removeObjCLifetime(); 4166 } 4167 4168 // MS compiler ignores __unaligned qualifier for references; do the same. 4169 T1Quals.removeUnaligned(); 4170 T2Quals.removeUnaligned(); 4171 4172 if (T1Quals == T2Quals) 4173 return Ref_Compatible; 4174 else if (T1Quals.compatiblyIncludes(T2Quals)) 4175 return Ref_Compatible_With_Added_Qualification; 4176 else 4177 return Ref_Related; 4178 } 4179 4180 /// \brief Look for a user-defined conversion to an value reference-compatible 4181 /// with DeclType. Return true if something definite is found. 4182 static bool 4183 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4184 QualType DeclType, SourceLocation DeclLoc, 4185 Expr *Init, QualType T2, bool AllowRvalues, 4186 bool AllowExplicit) { 4187 assert(T2->isRecordType() && "Can only find conversions of record types."); 4188 CXXRecordDecl *T2RecordDecl 4189 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4190 4191 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4192 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4193 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4194 NamedDecl *D = *I; 4195 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4196 if (isa<UsingShadowDecl>(D)) 4197 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4198 4199 FunctionTemplateDecl *ConvTemplate 4200 = dyn_cast<FunctionTemplateDecl>(D); 4201 CXXConversionDecl *Conv; 4202 if (ConvTemplate) 4203 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4204 else 4205 Conv = cast<CXXConversionDecl>(D); 4206 4207 // If this is an explicit conversion, and we're not allowed to consider 4208 // explicit conversions, skip it. 4209 if (!AllowExplicit && Conv->isExplicit()) 4210 continue; 4211 4212 if (AllowRvalues) { 4213 bool DerivedToBase = false; 4214 bool ObjCConversion = false; 4215 bool ObjCLifetimeConversion = false; 4216 4217 // If we are initializing an rvalue reference, don't permit conversion 4218 // functions that return lvalues. 4219 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4220 const ReferenceType *RefType 4221 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4222 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4223 continue; 4224 } 4225 4226 if (!ConvTemplate && 4227 S.CompareReferenceRelationship( 4228 DeclLoc, 4229 Conv->getConversionType().getNonReferenceType() 4230 .getUnqualifiedType(), 4231 DeclType.getNonReferenceType().getUnqualifiedType(), 4232 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4233 Sema::Ref_Incompatible) 4234 continue; 4235 } else { 4236 // If the conversion function doesn't return a reference type, 4237 // it can't be considered for this conversion. An rvalue reference 4238 // is only acceptable if its referencee is a function type. 4239 4240 const ReferenceType *RefType = 4241 Conv->getConversionType()->getAs<ReferenceType>(); 4242 if (!RefType || 4243 (!RefType->isLValueReferenceType() && 4244 !RefType->getPointeeType()->isFunctionType())) 4245 continue; 4246 } 4247 4248 if (ConvTemplate) 4249 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4250 Init, DeclType, CandidateSet, 4251 /*AllowObjCConversionOnExplicit=*/false); 4252 else 4253 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4254 DeclType, CandidateSet, 4255 /*AllowObjCConversionOnExplicit=*/false); 4256 } 4257 4258 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4259 4260 OverloadCandidateSet::iterator Best; 4261 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4262 case OR_Success: 4263 // C++ [over.ics.ref]p1: 4264 // 4265 // [...] If the parameter binds directly to the result of 4266 // applying a conversion function to the argument 4267 // expression, the implicit conversion sequence is a 4268 // user-defined conversion sequence (13.3.3.1.2), with the 4269 // second standard conversion sequence either an identity 4270 // conversion or, if the conversion function returns an 4271 // entity of a type that is a derived class of the parameter 4272 // type, a derived-to-base Conversion. 4273 if (!Best->FinalConversion.DirectBinding) 4274 return false; 4275 4276 ICS.setUserDefined(); 4277 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4278 ICS.UserDefined.After = Best->FinalConversion; 4279 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4280 ICS.UserDefined.ConversionFunction = Best->Function; 4281 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4282 ICS.UserDefined.EllipsisConversion = false; 4283 assert(ICS.UserDefined.After.ReferenceBinding && 4284 ICS.UserDefined.After.DirectBinding && 4285 "Expected a direct reference binding!"); 4286 return true; 4287 4288 case OR_Ambiguous: 4289 ICS.setAmbiguous(); 4290 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4291 Cand != CandidateSet.end(); ++Cand) 4292 if (Cand->Viable) 4293 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4294 return true; 4295 4296 case OR_No_Viable_Function: 4297 case OR_Deleted: 4298 // There was no suitable conversion, or we found a deleted 4299 // conversion; continue with other checks. 4300 return false; 4301 } 4302 4303 llvm_unreachable("Invalid OverloadResult!"); 4304 } 4305 4306 /// \brief Compute an implicit conversion sequence for reference 4307 /// initialization. 4308 static ImplicitConversionSequence 4309 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4310 SourceLocation DeclLoc, 4311 bool SuppressUserConversions, 4312 bool AllowExplicit) { 4313 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4314 4315 // Most paths end in a failed conversion. 4316 ImplicitConversionSequence ICS; 4317 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4318 4319 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4320 QualType T2 = Init->getType(); 4321 4322 // If the initializer is the address of an overloaded function, try 4323 // to resolve the overloaded function. If all goes well, T2 is the 4324 // type of the resulting function. 4325 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4326 DeclAccessPair Found; 4327 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4328 false, Found)) 4329 T2 = Fn->getType(); 4330 } 4331 4332 // Compute some basic properties of the types and the initializer. 4333 bool isRValRef = DeclType->isRValueReferenceType(); 4334 bool DerivedToBase = false; 4335 bool ObjCConversion = false; 4336 bool ObjCLifetimeConversion = false; 4337 Expr::Classification InitCategory = Init->Classify(S.Context); 4338 Sema::ReferenceCompareResult RefRelationship 4339 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4340 ObjCConversion, ObjCLifetimeConversion); 4341 4342 4343 // C++0x [dcl.init.ref]p5: 4344 // A reference to type "cv1 T1" is initialized by an expression 4345 // of type "cv2 T2" as follows: 4346 4347 // -- If reference is an lvalue reference and the initializer expression 4348 if (!isRValRef) { 4349 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4350 // reference-compatible with "cv2 T2," or 4351 // 4352 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4353 if (InitCategory.isLValue() && 4354 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4355 // C++ [over.ics.ref]p1: 4356 // When a parameter of reference type binds directly (8.5.3) 4357 // to an argument expression, the implicit conversion sequence 4358 // is the identity conversion, unless the argument expression 4359 // has a type that is a derived class of the parameter type, 4360 // in which case the implicit conversion sequence is a 4361 // derived-to-base Conversion (13.3.3.1). 4362 ICS.setStandard(); 4363 ICS.Standard.First = ICK_Identity; 4364 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4365 : ObjCConversion? ICK_Compatible_Conversion 4366 : ICK_Identity; 4367 ICS.Standard.Third = ICK_Identity; 4368 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4369 ICS.Standard.setToType(0, T2); 4370 ICS.Standard.setToType(1, T1); 4371 ICS.Standard.setToType(2, T1); 4372 ICS.Standard.ReferenceBinding = true; 4373 ICS.Standard.DirectBinding = true; 4374 ICS.Standard.IsLvalueReference = !isRValRef; 4375 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4376 ICS.Standard.BindsToRvalue = false; 4377 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4378 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4379 ICS.Standard.CopyConstructor = nullptr; 4380 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4381 4382 // Nothing more to do: the inaccessibility/ambiguity check for 4383 // derived-to-base conversions is suppressed when we're 4384 // computing the implicit conversion sequence (C++ 4385 // [over.best.ics]p2). 4386 return ICS; 4387 } 4388 4389 // -- has a class type (i.e., T2 is a class type), where T1 is 4390 // not reference-related to T2, and can be implicitly 4391 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4392 // is reference-compatible with "cv3 T3" 92) (this 4393 // conversion is selected by enumerating the applicable 4394 // conversion functions (13.3.1.6) and choosing the best 4395 // one through overload resolution (13.3)), 4396 if (!SuppressUserConversions && T2->isRecordType() && 4397 S.isCompleteType(DeclLoc, T2) && 4398 RefRelationship == Sema::Ref_Incompatible) { 4399 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4400 Init, T2, /*AllowRvalues=*/false, 4401 AllowExplicit)) 4402 return ICS; 4403 } 4404 } 4405 4406 // -- Otherwise, the reference shall be an lvalue reference to a 4407 // non-volatile const type (i.e., cv1 shall be const), or the reference 4408 // shall be an rvalue reference. 4409 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4410 return ICS; 4411 4412 // -- If the initializer expression 4413 // 4414 // -- is an xvalue, class prvalue, array prvalue or function 4415 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4416 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4417 (InitCategory.isXValue() || 4418 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4419 (InitCategory.isLValue() && T2->isFunctionType()))) { 4420 ICS.setStandard(); 4421 ICS.Standard.First = ICK_Identity; 4422 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4423 : ObjCConversion? ICK_Compatible_Conversion 4424 : ICK_Identity; 4425 ICS.Standard.Third = ICK_Identity; 4426 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4427 ICS.Standard.setToType(0, T2); 4428 ICS.Standard.setToType(1, T1); 4429 ICS.Standard.setToType(2, T1); 4430 ICS.Standard.ReferenceBinding = true; 4431 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4432 // binding unless we're binding to a class prvalue. 4433 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4434 // allow the use of rvalue references in C++98/03 for the benefit of 4435 // standard library implementors; therefore, we need the xvalue check here. 4436 ICS.Standard.DirectBinding = 4437 S.getLangOpts().CPlusPlus11 || 4438 !(InitCategory.isPRValue() || T2->isRecordType()); 4439 ICS.Standard.IsLvalueReference = !isRValRef; 4440 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4441 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4442 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4443 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4444 ICS.Standard.CopyConstructor = nullptr; 4445 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4446 return ICS; 4447 } 4448 4449 // -- has a class type (i.e., T2 is a class type), where T1 is not 4450 // reference-related to T2, and can be implicitly converted to 4451 // an xvalue, class prvalue, or function lvalue of type 4452 // "cv3 T3", where "cv1 T1" is reference-compatible with 4453 // "cv3 T3", 4454 // 4455 // then the reference is bound to the value of the initializer 4456 // expression in the first case and to the result of the conversion 4457 // in the second case (or, in either case, to an appropriate base 4458 // class subobject). 4459 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4460 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4461 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4462 Init, T2, /*AllowRvalues=*/true, 4463 AllowExplicit)) { 4464 // In the second case, if the reference is an rvalue reference 4465 // and the second standard conversion sequence of the 4466 // user-defined conversion sequence includes an lvalue-to-rvalue 4467 // conversion, the program is ill-formed. 4468 if (ICS.isUserDefined() && isRValRef && 4469 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4470 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4471 4472 return ICS; 4473 } 4474 4475 // A temporary of function type cannot be created; don't even try. 4476 if (T1->isFunctionType()) 4477 return ICS; 4478 4479 // -- Otherwise, a temporary of type "cv1 T1" is created and 4480 // initialized from the initializer expression using the 4481 // rules for a non-reference copy initialization (8.5). The 4482 // reference is then bound to the temporary. If T1 is 4483 // reference-related to T2, cv1 must be the same 4484 // cv-qualification as, or greater cv-qualification than, 4485 // cv2; otherwise, the program is ill-formed. 4486 if (RefRelationship == Sema::Ref_Related) { 4487 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4488 // we would be reference-compatible or reference-compatible with 4489 // added qualification. But that wasn't the case, so the reference 4490 // initialization fails. 4491 // 4492 // Note that we only want to check address spaces and cvr-qualifiers here. 4493 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4494 Qualifiers T1Quals = T1.getQualifiers(); 4495 Qualifiers T2Quals = T2.getQualifiers(); 4496 T1Quals.removeObjCGCAttr(); 4497 T1Quals.removeObjCLifetime(); 4498 T2Quals.removeObjCGCAttr(); 4499 T2Quals.removeObjCLifetime(); 4500 // MS compiler ignores __unaligned qualifier for references; do the same. 4501 T1Quals.removeUnaligned(); 4502 T2Quals.removeUnaligned(); 4503 if (!T1Quals.compatiblyIncludes(T2Quals)) 4504 return ICS; 4505 } 4506 4507 // If at least one of the types is a class type, the types are not 4508 // related, and we aren't allowed any user conversions, the 4509 // reference binding fails. This case is important for breaking 4510 // recursion, since TryImplicitConversion below will attempt to 4511 // create a temporary through the use of a copy constructor. 4512 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4513 (T1->isRecordType() || T2->isRecordType())) 4514 return ICS; 4515 4516 // If T1 is reference-related to T2 and the reference is an rvalue 4517 // reference, the initializer expression shall not be an lvalue. 4518 if (RefRelationship >= Sema::Ref_Related && 4519 isRValRef && Init->Classify(S.Context).isLValue()) 4520 return ICS; 4521 4522 // C++ [over.ics.ref]p2: 4523 // When a parameter of reference type is not bound directly to 4524 // an argument expression, the conversion sequence is the one 4525 // required to convert the argument expression to the 4526 // underlying type of the reference according to 4527 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4528 // to copy-initializing a temporary of the underlying type with 4529 // the argument expression. Any difference in top-level 4530 // cv-qualification is subsumed by the initialization itself 4531 // and does not constitute a conversion. 4532 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4533 /*AllowExplicit=*/false, 4534 /*InOverloadResolution=*/false, 4535 /*CStyle=*/false, 4536 /*AllowObjCWritebackConversion=*/false, 4537 /*AllowObjCConversionOnExplicit=*/false); 4538 4539 // Of course, that's still a reference binding. 4540 if (ICS.isStandard()) { 4541 ICS.Standard.ReferenceBinding = true; 4542 ICS.Standard.IsLvalueReference = !isRValRef; 4543 ICS.Standard.BindsToFunctionLvalue = false; 4544 ICS.Standard.BindsToRvalue = true; 4545 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4546 ICS.Standard.ObjCLifetimeConversionBinding = false; 4547 } else if (ICS.isUserDefined()) { 4548 const ReferenceType *LValRefType = 4549 ICS.UserDefined.ConversionFunction->getReturnType() 4550 ->getAs<LValueReferenceType>(); 4551 4552 // C++ [over.ics.ref]p3: 4553 // Except for an implicit object parameter, for which see 13.3.1, a 4554 // standard conversion sequence cannot be formed if it requires [...] 4555 // binding an rvalue reference to an lvalue other than a function 4556 // lvalue. 4557 // Note that the function case is not possible here. 4558 if (DeclType->isRValueReferenceType() && LValRefType) { 4559 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4560 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4561 // reference to an rvalue! 4562 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4563 return ICS; 4564 } 4565 4566 ICS.UserDefined.After.ReferenceBinding = true; 4567 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4568 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4569 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4570 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4571 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4572 } 4573 4574 return ICS; 4575 } 4576 4577 static ImplicitConversionSequence 4578 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4579 bool SuppressUserConversions, 4580 bool InOverloadResolution, 4581 bool AllowObjCWritebackConversion, 4582 bool AllowExplicit = false); 4583 4584 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4585 /// initializer list From. 4586 static ImplicitConversionSequence 4587 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4588 bool SuppressUserConversions, 4589 bool InOverloadResolution, 4590 bool AllowObjCWritebackConversion) { 4591 // C++11 [over.ics.list]p1: 4592 // When an argument is an initializer list, it is not an expression and 4593 // special rules apply for converting it to a parameter type. 4594 4595 ImplicitConversionSequence Result; 4596 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4597 4598 // We need a complete type for what follows. Incomplete types can never be 4599 // initialized from init lists. 4600 if (!S.isCompleteType(From->getLocStart(), ToType)) 4601 return Result; 4602 4603 // Per DR1467: 4604 // If the parameter type is a class X and the initializer list has a single 4605 // element of type cv U, where U is X or a class derived from X, the 4606 // implicit conversion sequence is the one required to convert the element 4607 // to the parameter type. 4608 // 4609 // Otherwise, if the parameter type is a character array [... ] 4610 // and the initializer list has a single element that is an 4611 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4612 // implicit conversion sequence is the identity conversion. 4613 if (From->getNumInits() == 1) { 4614 if (ToType->isRecordType()) { 4615 QualType InitType = From->getInit(0)->getType(); 4616 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4617 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4618 return TryCopyInitialization(S, From->getInit(0), ToType, 4619 SuppressUserConversions, 4620 InOverloadResolution, 4621 AllowObjCWritebackConversion); 4622 } 4623 // FIXME: Check the other conditions here: array of character type, 4624 // initializer is a string literal. 4625 if (ToType->isArrayType()) { 4626 InitializedEntity Entity = 4627 InitializedEntity::InitializeParameter(S.Context, ToType, 4628 /*Consumed=*/false); 4629 if (S.CanPerformCopyInitialization(Entity, From)) { 4630 Result.setStandard(); 4631 Result.Standard.setAsIdentityConversion(); 4632 Result.Standard.setFromType(ToType); 4633 Result.Standard.setAllToTypes(ToType); 4634 return Result; 4635 } 4636 } 4637 } 4638 4639 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4640 // C++11 [over.ics.list]p2: 4641 // If the parameter type is std::initializer_list<X> or "array of X" and 4642 // all the elements can be implicitly converted to X, the implicit 4643 // conversion sequence is the worst conversion necessary to convert an 4644 // element of the list to X. 4645 // 4646 // C++14 [over.ics.list]p3: 4647 // Otherwise, if the parameter type is "array of N X", if the initializer 4648 // list has exactly N elements or if it has fewer than N elements and X is 4649 // default-constructible, and if all the elements of the initializer list 4650 // can be implicitly converted to X, the implicit conversion sequence is 4651 // the worst conversion necessary to convert an element of the list to X. 4652 // 4653 // FIXME: We're missing a lot of these checks. 4654 bool toStdInitializerList = false; 4655 QualType X; 4656 if (ToType->isArrayType()) 4657 X = S.Context.getAsArrayType(ToType)->getElementType(); 4658 else 4659 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4660 if (!X.isNull()) { 4661 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4662 Expr *Init = From->getInit(i); 4663 ImplicitConversionSequence ICS = 4664 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4665 InOverloadResolution, 4666 AllowObjCWritebackConversion); 4667 // If a single element isn't convertible, fail. 4668 if (ICS.isBad()) { 4669 Result = ICS; 4670 break; 4671 } 4672 // Otherwise, look for the worst conversion. 4673 if (Result.isBad() || 4674 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4675 Result) == 4676 ImplicitConversionSequence::Worse) 4677 Result = ICS; 4678 } 4679 4680 // For an empty list, we won't have computed any conversion sequence. 4681 // Introduce the identity conversion sequence. 4682 if (From->getNumInits() == 0) { 4683 Result.setStandard(); 4684 Result.Standard.setAsIdentityConversion(); 4685 Result.Standard.setFromType(ToType); 4686 Result.Standard.setAllToTypes(ToType); 4687 } 4688 4689 Result.setStdInitializerListElement(toStdInitializerList); 4690 return Result; 4691 } 4692 4693 // C++14 [over.ics.list]p4: 4694 // C++11 [over.ics.list]p3: 4695 // Otherwise, if the parameter is a non-aggregate class X and overload 4696 // resolution chooses a single best constructor [...] the implicit 4697 // conversion sequence is a user-defined conversion sequence. If multiple 4698 // constructors are viable but none is better than the others, the 4699 // implicit conversion sequence is a user-defined conversion sequence. 4700 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4701 // This function can deal with initializer lists. 4702 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4703 /*AllowExplicit=*/false, 4704 InOverloadResolution, /*CStyle=*/false, 4705 AllowObjCWritebackConversion, 4706 /*AllowObjCConversionOnExplicit=*/false); 4707 } 4708 4709 // C++14 [over.ics.list]p5: 4710 // C++11 [over.ics.list]p4: 4711 // Otherwise, if the parameter has an aggregate type which can be 4712 // initialized from the initializer list [...] the implicit conversion 4713 // sequence is a user-defined conversion sequence. 4714 if (ToType->isAggregateType()) { 4715 // Type is an aggregate, argument is an init list. At this point it comes 4716 // down to checking whether the initialization works. 4717 // FIXME: Find out whether this parameter is consumed or not. 4718 InitializedEntity Entity = 4719 InitializedEntity::InitializeParameter(S.Context, ToType, 4720 /*Consumed=*/false); 4721 if (S.CanPerformCopyInitialization(Entity, From)) { 4722 Result.setUserDefined(); 4723 Result.UserDefined.Before.setAsIdentityConversion(); 4724 // Initializer lists don't have a type. 4725 Result.UserDefined.Before.setFromType(QualType()); 4726 Result.UserDefined.Before.setAllToTypes(QualType()); 4727 4728 Result.UserDefined.After.setAsIdentityConversion(); 4729 Result.UserDefined.After.setFromType(ToType); 4730 Result.UserDefined.After.setAllToTypes(ToType); 4731 Result.UserDefined.ConversionFunction = nullptr; 4732 } 4733 return Result; 4734 } 4735 4736 // C++14 [over.ics.list]p6: 4737 // C++11 [over.ics.list]p5: 4738 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4739 if (ToType->isReferenceType()) { 4740 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4741 // mention initializer lists in any way. So we go by what list- 4742 // initialization would do and try to extrapolate from that. 4743 4744 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4745 4746 // If the initializer list has a single element that is reference-related 4747 // to the parameter type, we initialize the reference from that. 4748 if (From->getNumInits() == 1) { 4749 Expr *Init = From->getInit(0); 4750 4751 QualType T2 = Init->getType(); 4752 4753 // If the initializer is the address of an overloaded function, try 4754 // to resolve the overloaded function. If all goes well, T2 is the 4755 // type of the resulting function. 4756 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4757 DeclAccessPair Found; 4758 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4759 Init, ToType, false, Found)) 4760 T2 = Fn->getType(); 4761 } 4762 4763 // Compute some basic properties of the types and the initializer. 4764 bool dummy1 = false; 4765 bool dummy2 = false; 4766 bool dummy3 = false; 4767 Sema::ReferenceCompareResult RefRelationship 4768 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4769 dummy2, dummy3); 4770 4771 if (RefRelationship >= Sema::Ref_Related) { 4772 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4773 SuppressUserConversions, 4774 /*AllowExplicit=*/false); 4775 } 4776 } 4777 4778 // Otherwise, we bind the reference to a temporary created from the 4779 // initializer list. 4780 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4781 InOverloadResolution, 4782 AllowObjCWritebackConversion); 4783 if (Result.isFailure()) 4784 return Result; 4785 assert(!Result.isEllipsis() && 4786 "Sub-initialization cannot result in ellipsis conversion."); 4787 4788 // Can we even bind to a temporary? 4789 if (ToType->isRValueReferenceType() || 4790 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4791 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4792 Result.UserDefined.After; 4793 SCS.ReferenceBinding = true; 4794 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4795 SCS.BindsToRvalue = true; 4796 SCS.BindsToFunctionLvalue = false; 4797 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4798 SCS.ObjCLifetimeConversionBinding = false; 4799 } else 4800 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4801 From, ToType); 4802 return Result; 4803 } 4804 4805 // C++14 [over.ics.list]p7: 4806 // C++11 [over.ics.list]p6: 4807 // Otherwise, if the parameter type is not a class: 4808 if (!ToType->isRecordType()) { 4809 // - if the initializer list has one element that is not itself an 4810 // initializer list, the implicit conversion sequence is the one 4811 // required to convert the element to the parameter type. 4812 unsigned NumInits = From->getNumInits(); 4813 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4814 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4815 SuppressUserConversions, 4816 InOverloadResolution, 4817 AllowObjCWritebackConversion); 4818 // - if the initializer list has no elements, the implicit conversion 4819 // sequence is the identity conversion. 4820 else if (NumInits == 0) { 4821 Result.setStandard(); 4822 Result.Standard.setAsIdentityConversion(); 4823 Result.Standard.setFromType(ToType); 4824 Result.Standard.setAllToTypes(ToType); 4825 } 4826 return Result; 4827 } 4828 4829 // C++14 [over.ics.list]p8: 4830 // C++11 [over.ics.list]p7: 4831 // In all cases other than those enumerated above, no conversion is possible 4832 return Result; 4833 } 4834 4835 /// TryCopyInitialization - Try to copy-initialize a value of type 4836 /// ToType from the expression From. Return the implicit conversion 4837 /// sequence required to pass this argument, which may be a bad 4838 /// conversion sequence (meaning that the argument cannot be passed to 4839 /// a parameter of this type). If @p SuppressUserConversions, then we 4840 /// do not permit any user-defined conversion sequences. 4841 static ImplicitConversionSequence 4842 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4843 bool SuppressUserConversions, 4844 bool InOverloadResolution, 4845 bool AllowObjCWritebackConversion, 4846 bool AllowExplicit) { 4847 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4848 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4849 InOverloadResolution,AllowObjCWritebackConversion); 4850 4851 if (ToType->isReferenceType()) 4852 return TryReferenceInit(S, From, ToType, 4853 /*FIXME:*/From->getLocStart(), 4854 SuppressUserConversions, 4855 AllowExplicit); 4856 4857 return TryImplicitConversion(S, From, ToType, 4858 SuppressUserConversions, 4859 /*AllowExplicit=*/false, 4860 InOverloadResolution, 4861 /*CStyle=*/false, 4862 AllowObjCWritebackConversion, 4863 /*AllowObjCConversionOnExplicit=*/false); 4864 } 4865 4866 static bool TryCopyInitialization(const CanQualType FromQTy, 4867 const CanQualType ToQTy, 4868 Sema &S, 4869 SourceLocation Loc, 4870 ExprValueKind FromVK) { 4871 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4872 ImplicitConversionSequence ICS = 4873 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4874 4875 return !ICS.isBad(); 4876 } 4877 4878 /// TryObjectArgumentInitialization - Try to initialize the object 4879 /// parameter of the given member function (@c Method) from the 4880 /// expression @p From. 4881 static ImplicitConversionSequence 4882 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4883 Expr::Classification FromClassification, 4884 CXXMethodDecl *Method, 4885 CXXRecordDecl *ActingContext) { 4886 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4887 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4888 // const volatile object. 4889 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4890 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4891 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4892 4893 // Set up the conversion sequence as a "bad" conversion, to allow us 4894 // to exit early. 4895 ImplicitConversionSequence ICS; 4896 4897 // We need to have an object of class type. 4898 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4899 FromType = PT->getPointeeType(); 4900 4901 // When we had a pointer, it's implicitly dereferenced, so we 4902 // better have an lvalue. 4903 assert(FromClassification.isLValue()); 4904 } 4905 4906 assert(FromType->isRecordType()); 4907 4908 // C++0x [over.match.funcs]p4: 4909 // For non-static member functions, the type of the implicit object 4910 // parameter is 4911 // 4912 // - "lvalue reference to cv X" for functions declared without a 4913 // ref-qualifier or with the & ref-qualifier 4914 // - "rvalue reference to cv X" for functions declared with the && 4915 // ref-qualifier 4916 // 4917 // where X is the class of which the function is a member and cv is the 4918 // cv-qualification on the member function declaration. 4919 // 4920 // However, when finding an implicit conversion sequence for the argument, we 4921 // are not allowed to create temporaries or perform user-defined conversions 4922 // (C++ [over.match.funcs]p5). We perform a simplified version of 4923 // reference binding here, that allows class rvalues to bind to 4924 // non-constant references. 4925 4926 // First check the qualifiers. 4927 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4928 if (ImplicitParamType.getCVRQualifiers() 4929 != FromTypeCanon.getLocalCVRQualifiers() && 4930 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4931 ICS.setBad(BadConversionSequence::bad_qualifiers, 4932 FromType, ImplicitParamType); 4933 return ICS; 4934 } 4935 4936 // Check that we have either the same type or a derived type. It 4937 // affects the conversion rank. 4938 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4939 ImplicitConversionKind SecondKind; 4940 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4941 SecondKind = ICK_Identity; 4942 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4943 SecondKind = ICK_Derived_To_Base; 4944 else { 4945 ICS.setBad(BadConversionSequence::unrelated_class, 4946 FromType, ImplicitParamType); 4947 return ICS; 4948 } 4949 4950 // Check the ref-qualifier. 4951 switch (Method->getRefQualifier()) { 4952 case RQ_None: 4953 // Do nothing; we don't care about lvalueness or rvalueness. 4954 break; 4955 4956 case RQ_LValue: 4957 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4958 // non-const lvalue reference cannot bind to an rvalue 4959 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4960 ImplicitParamType); 4961 return ICS; 4962 } 4963 break; 4964 4965 case RQ_RValue: 4966 if (!FromClassification.isRValue()) { 4967 // rvalue reference cannot bind to an lvalue 4968 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4969 ImplicitParamType); 4970 return ICS; 4971 } 4972 break; 4973 } 4974 4975 // Success. Mark this as a reference binding. 4976 ICS.setStandard(); 4977 ICS.Standard.setAsIdentityConversion(); 4978 ICS.Standard.Second = SecondKind; 4979 ICS.Standard.setFromType(FromType); 4980 ICS.Standard.setAllToTypes(ImplicitParamType); 4981 ICS.Standard.ReferenceBinding = true; 4982 ICS.Standard.DirectBinding = true; 4983 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4984 ICS.Standard.BindsToFunctionLvalue = false; 4985 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4986 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4987 = (Method->getRefQualifier() == RQ_None); 4988 return ICS; 4989 } 4990 4991 /// PerformObjectArgumentInitialization - Perform initialization of 4992 /// the implicit object parameter for the given Method with the given 4993 /// expression. 4994 ExprResult 4995 Sema::PerformObjectArgumentInitialization(Expr *From, 4996 NestedNameSpecifier *Qualifier, 4997 NamedDecl *FoundDecl, 4998 CXXMethodDecl *Method) { 4999 QualType FromRecordType, DestType; 5000 QualType ImplicitParamRecordType = 5001 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5002 5003 Expr::Classification FromClassification; 5004 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5005 FromRecordType = PT->getPointeeType(); 5006 DestType = Method->getThisType(Context); 5007 FromClassification = Expr::Classification::makeSimpleLValue(); 5008 } else { 5009 FromRecordType = From->getType(); 5010 DestType = ImplicitParamRecordType; 5011 FromClassification = From->Classify(Context); 5012 } 5013 5014 // Note that we always use the true parent context when performing 5015 // the actual argument initialization. 5016 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5017 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5018 Method->getParent()); 5019 if (ICS.isBad()) { 5020 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5021 Qualifiers FromQs = FromRecordType.getQualifiers(); 5022 Qualifiers ToQs = DestType.getQualifiers(); 5023 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5024 if (CVR) { 5025 Diag(From->getLocStart(), 5026 diag::err_member_function_call_bad_cvr) 5027 << Method->getDeclName() << FromRecordType << (CVR - 1) 5028 << From->getSourceRange(); 5029 Diag(Method->getLocation(), diag::note_previous_decl) 5030 << Method->getDeclName(); 5031 return ExprError(); 5032 } 5033 } 5034 5035 return Diag(From->getLocStart(), 5036 diag::err_implicit_object_parameter_init) 5037 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5038 } 5039 5040 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5041 ExprResult FromRes = 5042 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5043 if (FromRes.isInvalid()) 5044 return ExprError(); 5045 From = FromRes.get(); 5046 } 5047 5048 if (!Context.hasSameType(From->getType(), DestType)) 5049 From = ImpCastExprToType(From, DestType, CK_NoOp, 5050 From->getValueKind()).get(); 5051 return From; 5052 } 5053 5054 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5055 /// expression From to bool (C++0x [conv]p3). 5056 static ImplicitConversionSequence 5057 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5058 return TryImplicitConversion(S, From, S.Context.BoolTy, 5059 /*SuppressUserConversions=*/false, 5060 /*AllowExplicit=*/true, 5061 /*InOverloadResolution=*/false, 5062 /*CStyle=*/false, 5063 /*AllowObjCWritebackConversion=*/false, 5064 /*AllowObjCConversionOnExplicit=*/false); 5065 } 5066 5067 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5068 /// of the expression From to bool (C++0x [conv]p3). 5069 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5070 if (checkPlaceholderForOverload(*this, From)) 5071 return ExprError(); 5072 5073 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5074 if (!ICS.isBad()) 5075 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5076 5077 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5078 return Diag(From->getLocStart(), 5079 diag::err_typecheck_bool_condition) 5080 << From->getType() << From->getSourceRange(); 5081 return ExprError(); 5082 } 5083 5084 /// Check that the specified conversion is permitted in a converted constant 5085 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5086 /// is acceptable. 5087 static bool CheckConvertedConstantConversions(Sema &S, 5088 StandardConversionSequence &SCS) { 5089 // Since we know that the target type is an integral or unscoped enumeration 5090 // type, most conversion kinds are impossible. All possible First and Third 5091 // conversions are fine. 5092 switch (SCS.Second) { 5093 case ICK_Identity: 5094 case ICK_NoReturn_Adjustment: 5095 case ICK_Integral_Promotion: 5096 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5097 return true; 5098 5099 case ICK_Boolean_Conversion: 5100 // Conversion from an integral or unscoped enumeration type to bool is 5101 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5102 // conversion, so we allow it in a converted constant expression. 5103 // 5104 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5105 // a lot of popular code. We should at least add a warning for this 5106 // (non-conforming) extension. 5107 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5108 SCS.getToType(2)->isBooleanType(); 5109 5110 case ICK_Pointer_Conversion: 5111 case ICK_Pointer_Member: 5112 // C++1z: null pointer conversions and null member pointer conversions are 5113 // only permitted if the source type is std::nullptr_t. 5114 return SCS.getFromType()->isNullPtrType(); 5115 5116 case ICK_Floating_Promotion: 5117 case ICK_Complex_Promotion: 5118 case ICK_Floating_Conversion: 5119 case ICK_Complex_Conversion: 5120 case ICK_Floating_Integral: 5121 case ICK_Compatible_Conversion: 5122 case ICK_Derived_To_Base: 5123 case ICK_Vector_Conversion: 5124 case ICK_Vector_Splat: 5125 case ICK_Complex_Real: 5126 case ICK_Block_Pointer_Conversion: 5127 case ICK_TransparentUnionConversion: 5128 case ICK_Writeback_Conversion: 5129 case ICK_Zero_Event_Conversion: 5130 case ICK_C_Only_Conversion: 5131 case ICK_Incompatible_Pointer_Conversion: 5132 return false; 5133 5134 case ICK_Lvalue_To_Rvalue: 5135 case ICK_Array_To_Pointer: 5136 case ICK_Function_To_Pointer: 5137 llvm_unreachable("found a first conversion kind in Second"); 5138 5139 case ICK_Qualification: 5140 llvm_unreachable("found a third conversion kind in Second"); 5141 5142 case ICK_Num_Conversion_Kinds: 5143 break; 5144 } 5145 5146 llvm_unreachable("unknown conversion kind"); 5147 } 5148 5149 /// CheckConvertedConstantExpression - Check that the expression From is a 5150 /// converted constant expression of type T, perform the conversion and produce 5151 /// the converted expression, per C++11 [expr.const]p3. 5152 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5153 QualType T, APValue &Value, 5154 Sema::CCEKind CCE, 5155 bool RequireInt) { 5156 assert(S.getLangOpts().CPlusPlus11 && 5157 "converted constant expression outside C++11"); 5158 5159 if (checkPlaceholderForOverload(S, From)) 5160 return ExprError(); 5161 5162 // C++1z [expr.const]p3: 5163 // A converted constant expression of type T is an expression, 5164 // implicitly converted to type T, where the converted 5165 // expression is a constant expression and the implicit conversion 5166 // sequence contains only [... list of conversions ...]. 5167 ImplicitConversionSequence ICS = 5168 TryCopyInitialization(S, From, T, 5169 /*SuppressUserConversions=*/false, 5170 /*InOverloadResolution=*/false, 5171 /*AllowObjcWritebackConversion=*/false, 5172 /*AllowExplicit=*/false); 5173 StandardConversionSequence *SCS = nullptr; 5174 switch (ICS.getKind()) { 5175 case ImplicitConversionSequence::StandardConversion: 5176 SCS = &ICS.Standard; 5177 break; 5178 case ImplicitConversionSequence::UserDefinedConversion: 5179 // We are converting to a non-class type, so the Before sequence 5180 // must be trivial. 5181 SCS = &ICS.UserDefined.After; 5182 break; 5183 case ImplicitConversionSequence::AmbiguousConversion: 5184 case ImplicitConversionSequence::BadConversion: 5185 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5186 return S.Diag(From->getLocStart(), 5187 diag::err_typecheck_converted_constant_expression) 5188 << From->getType() << From->getSourceRange() << T; 5189 return ExprError(); 5190 5191 case ImplicitConversionSequence::EllipsisConversion: 5192 llvm_unreachable("ellipsis conversion in converted constant expression"); 5193 } 5194 5195 // Check that we would only use permitted conversions. 5196 if (!CheckConvertedConstantConversions(S, *SCS)) { 5197 return S.Diag(From->getLocStart(), 5198 diag::err_typecheck_converted_constant_expression_disallowed) 5199 << From->getType() << From->getSourceRange() << T; 5200 } 5201 // [...] and where the reference binding (if any) binds directly. 5202 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5203 return S.Diag(From->getLocStart(), 5204 diag::err_typecheck_converted_constant_expression_indirect) 5205 << From->getType() << From->getSourceRange() << T; 5206 } 5207 5208 ExprResult Result = 5209 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5210 if (Result.isInvalid()) 5211 return Result; 5212 5213 // Check for a narrowing implicit conversion. 5214 APValue PreNarrowingValue; 5215 QualType PreNarrowingType; 5216 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5217 PreNarrowingType)) { 5218 case NK_Variable_Narrowing: 5219 // Implicit conversion to a narrower type, and the value is not a constant 5220 // expression. We'll diagnose this in a moment. 5221 case NK_Not_Narrowing: 5222 break; 5223 5224 case NK_Constant_Narrowing: 5225 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5226 << CCE << /*Constant*/1 5227 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5228 break; 5229 5230 case NK_Type_Narrowing: 5231 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5232 << CCE << /*Constant*/0 << From->getType() << T; 5233 break; 5234 } 5235 5236 // Check the expression is a constant expression. 5237 SmallVector<PartialDiagnosticAt, 8> Notes; 5238 Expr::EvalResult Eval; 5239 Eval.Diag = &Notes; 5240 5241 if ((T->isReferenceType() 5242 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5243 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5244 (RequireInt && !Eval.Val.isInt())) { 5245 // The expression can't be folded, so we can't keep it at this position in 5246 // the AST. 5247 Result = ExprError(); 5248 } else { 5249 Value = Eval.Val; 5250 5251 if (Notes.empty()) { 5252 // It's a constant expression. 5253 return Result; 5254 } 5255 } 5256 5257 // It's not a constant expression. Produce an appropriate diagnostic. 5258 if (Notes.size() == 1 && 5259 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5260 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5261 else { 5262 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5263 << CCE << From->getSourceRange(); 5264 for (unsigned I = 0; I < Notes.size(); ++I) 5265 S.Diag(Notes[I].first, Notes[I].second); 5266 } 5267 return ExprError(); 5268 } 5269 5270 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5271 APValue &Value, CCEKind CCE) { 5272 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5273 } 5274 5275 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5276 llvm::APSInt &Value, 5277 CCEKind CCE) { 5278 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5279 5280 APValue V; 5281 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5282 if (!R.isInvalid()) 5283 Value = V.getInt(); 5284 return R; 5285 } 5286 5287 5288 /// dropPointerConversions - If the given standard conversion sequence 5289 /// involves any pointer conversions, remove them. This may change 5290 /// the result type of the conversion sequence. 5291 static void dropPointerConversion(StandardConversionSequence &SCS) { 5292 if (SCS.Second == ICK_Pointer_Conversion) { 5293 SCS.Second = ICK_Identity; 5294 SCS.Third = ICK_Identity; 5295 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5296 } 5297 } 5298 5299 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5300 /// convert the expression From to an Objective-C pointer type. 5301 static ImplicitConversionSequence 5302 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5303 // Do an implicit conversion to 'id'. 5304 QualType Ty = S.Context.getObjCIdType(); 5305 ImplicitConversionSequence ICS 5306 = TryImplicitConversion(S, From, Ty, 5307 // FIXME: Are these flags correct? 5308 /*SuppressUserConversions=*/false, 5309 /*AllowExplicit=*/true, 5310 /*InOverloadResolution=*/false, 5311 /*CStyle=*/false, 5312 /*AllowObjCWritebackConversion=*/false, 5313 /*AllowObjCConversionOnExplicit=*/true); 5314 5315 // Strip off any final conversions to 'id'. 5316 switch (ICS.getKind()) { 5317 case ImplicitConversionSequence::BadConversion: 5318 case ImplicitConversionSequence::AmbiguousConversion: 5319 case ImplicitConversionSequence::EllipsisConversion: 5320 break; 5321 5322 case ImplicitConversionSequence::UserDefinedConversion: 5323 dropPointerConversion(ICS.UserDefined.After); 5324 break; 5325 5326 case ImplicitConversionSequence::StandardConversion: 5327 dropPointerConversion(ICS.Standard); 5328 break; 5329 } 5330 5331 return ICS; 5332 } 5333 5334 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5335 /// conversion of the expression From to an Objective-C pointer type. 5336 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5337 if (checkPlaceholderForOverload(*this, From)) 5338 return ExprError(); 5339 5340 QualType Ty = Context.getObjCIdType(); 5341 ImplicitConversionSequence ICS = 5342 TryContextuallyConvertToObjCPointer(*this, From); 5343 if (!ICS.isBad()) 5344 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5345 return ExprError(); 5346 } 5347 5348 /// Determine whether the provided type is an integral type, or an enumeration 5349 /// type of a permitted flavor. 5350 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5351 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5352 : T->isIntegralOrUnscopedEnumerationType(); 5353 } 5354 5355 static ExprResult 5356 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5357 Sema::ContextualImplicitConverter &Converter, 5358 QualType T, UnresolvedSetImpl &ViableConversions) { 5359 5360 if (Converter.Suppress) 5361 return ExprError(); 5362 5363 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5364 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5365 CXXConversionDecl *Conv = 5366 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5367 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5368 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5369 } 5370 return From; 5371 } 5372 5373 static bool 5374 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5375 Sema::ContextualImplicitConverter &Converter, 5376 QualType T, bool HadMultipleCandidates, 5377 UnresolvedSetImpl &ExplicitConversions) { 5378 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5379 DeclAccessPair Found = ExplicitConversions[0]; 5380 CXXConversionDecl *Conversion = 5381 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5382 5383 // The user probably meant to invoke the given explicit 5384 // conversion; use it. 5385 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5386 std::string TypeStr; 5387 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5388 5389 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5390 << FixItHint::CreateInsertion(From->getLocStart(), 5391 "static_cast<" + TypeStr + ">(") 5392 << FixItHint::CreateInsertion( 5393 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5394 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5395 5396 // If we aren't in a SFINAE context, build a call to the 5397 // explicit conversion function. 5398 if (SemaRef.isSFINAEContext()) 5399 return true; 5400 5401 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5402 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5403 HadMultipleCandidates); 5404 if (Result.isInvalid()) 5405 return true; 5406 // Record usage of conversion in an implicit cast. 5407 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5408 CK_UserDefinedConversion, Result.get(), 5409 nullptr, Result.get()->getValueKind()); 5410 } 5411 return false; 5412 } 5413 5414 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5415 Sema::ContextualImplicitConverter &Converter, 5416 QualType T, bool HadMultipleCandidates, 5417 DeclAccessPair &Found) { 5418 CXXConversionDecl *Conversion = 5419 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5420 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5421 5422 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5423 if (!Converter.SuppressConversion) { 5424 if (SemaRef.isSFINAEContext()) 5425 return true; 5426 5427 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5428 << From->getSourceRange(); 5429 } 5430 5431 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5432 HadMultipleCandidates); 5433 if (Result.isInvalid()) 5434 return true; 5435 // Record usage of conversion in an implicit cast. 5436 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5437 CK_UserDefinedConversion, Result.get(), 5438 nullptr, Result.get()->getValueKind()); 5439 return false; 5440 } 5441 5442 static ExprResult finishContextualImplicitConversion( 5443 Sema &SemaRef, SourceLocation Loc, Expr *From, 5444 Sema::ContextualImplicitConverter &Converter) { 5445 if (!Converter.match(From->getType()) && !Converter.Suppress) 5446 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5447 << From->getSourceRange(); 5448 5449 return SemaRef.DefaultLvalueConversion(From); 5450 } 5451 5452 static void 5453 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5454 UnresolvedSetImpl &ViableConversions, 5455 OverloadCandidateSet &CandidateSet) { 5456 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5457 DeclAccessPair FoundDecl = ViableConversions[I]; 5458 NamedDecl *D = FoundDecl.getDecl(); 5459 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5460 if (isa<UsingShadowDecl>(D)) 5461 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5462 5463 CXXConversionDecl *Conv; 5464 FunctionTemplateDecl *ConvTemplate; 5465 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5466 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5467 else 5468 Conv = cast<CXXConversionDecl>(D); 5469 5470 if (ConvTemplate) 5471 SemaRef.AddTemplateConversionCandidate( 5472 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5473 /*AllowObjCConversionOnExplicit=*/false); 5474 else 5475 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5476 ToType, CandidateSet, 5477 /*AllowObjCConversionOnExplicit=*/false); 5478 } 5479 } 5480 5481 /// \brief Attempt to convert the given expression to a type which is accepted 5482 /// by the given converter. 5483 /// 5484 /// This routine will attempt to convert an expression of class type to a 5485 /// type accepted by the specified converter. In C++11 and before, the class 5486 /// must have a single non-explicit conversion function converting to a matching 5487 /// type. In C++1y, there can be multiple such conversion functions, but only 5488 /// one target type. 5489 /// 5490 /// \param Loc The source location of the construct that requires the 5491 /// conversion. 5492 /// 5493 /// \param From The expression we're converting from. 5494 /// 5495 /// \param Converter Used to control and diagnose the conversion process. 5496 /// 5497 /// \returns The expression, converted to an integral or enumeration type if 5498 /// successful. 5499 ExprResult Sema::PerformContextualImplicitConversion( 5500 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5501 // We can't perform any more checking for type-dependent expressions. 5502 if (From->isTypeDependent()) 5503 return From; 5504 5505 // Process placeholders immediately. 5506 if (From->hasPlaceholderType()) { 5507 ExprResult result = CheckPlaceholderExpr(From); 5508 if (result.isInvalid()) 5509 return result; 5510 From = result.get(); 5511 } 5512 5513 // If the expression already has a matching type, we're golden. 5514 QualType T = From->getType(); 5515 if (Converter.match(T)) 5516 return DefaultLvalueConversion(From); 5517 5518 // FIXME: Check for missing '()' if T is a function type? 5519 5520 // We can only perform contextual implicit conversions on objects of class 5521 // type. 5522 const RecordType *RecordTy = T->getAs<RecordType>(); 5523 if (!RecordTy || !getLangOpts().CPlusPlus) { 5524 if (!Converter.Suppress) 5525 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5526 return From; 5527 } 5528 5529 // We must have a complete class type. 5530 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5531 ContextualImplicitConverter &Converter; 5532 Expr *From; 5533 5534 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5535 : Converter(Converter), From(From) {} 5536 5537 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5538 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5539 } 5540 } IncompleteDiagnoser(Converter, From); 5541 5542 if (Converter.Suppress ? !isCompleteType(Loc, T) 5543 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5544 return From; 5545 5546 // Look for a conversion to an integral or enumeration type. 5547 UnresolvedSet<4> 5548 ViableConversions; // These are *potentially* viable in C++1y. 5549 UnresolvedSet<4> ExplicitConversions; 5550 const auto &Conversions = 5551 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5552 5553 bool HadMultipleCandidates = 5554 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5555 5556 // To check that there is only one target type, in C++1y: 5557 QualType ToType; 5558 bool HasUniqueTargetType = true; 5559 5560 // Collect explicit or viable (potentially in C++1y) conversions. 5561 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5562 NamedDecl *D = (*I)->getUnderlyingDecl(); 5563 CXXConversionDecl *Conversion; 5564 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5565 if (ConvTemplate) { 5566 if (getLangOpts().CPlusPlus14) 5567 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5568 else 5569 continue; // C++11 does not consider conversion operator templates(?). 5570 } else 5571 Conversion = cast<CXXConversionDecl>(D); 5572 5573 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5574 "Conversion operator templates are considered potentially " 5575 "viable in C++1y"); 5576 5577 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5578 if (Converter.match(CurToType) || ConvTemplate) { 5579 5580 if (Conversion->isExplicit()) { 5581 // FIXME: For C++1y, do we need this restriction? 5582 // cf. diagnoseNoViableConversion() 5583 if (!ConvTemplate) 5584 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5585 } else { 5586 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5587 if (ToType.isNull()) 5588 ToType = CurToType.getUnqualifiedType(); 5589 else if (HasUniqueTargetType && 5590 (CurToType.getUnqualifiedType() != ToType)) 5591 HasUniqueTargetType = false; 5592 } 5593 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5594 } 5595 } 5596 } 5597 5598 if (getLangOpts().CPlusPlus14) { 5599 // C++1y [conv]p6: 5600 // ... An expression e of class type E appearing in such a context 5601 // is said to be contextually implicitly converted to a specified 5602 // type T and is well-formed if and only if e can be implicitly 5603 // converted to a type T that is determined as follows: E is searched 5604 // for conversion functions whose return type is cv T or reference to 5605 // cv T such that T is allowed by the context. There shall be 5606 // exactly one such T. 5607 5608 // If no unique T is found: 5609 if (ToType.isNull()) { 5610 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5611 HadMultipleCandidates, 5612 ExplicitConversions)) 5613 return ExprError(); 5614 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5615 } 5616 5617 // If more than one unique Ts are found: 5618 if (!HasUniqueTargetType) 5619 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5620 ViableConversions); 5621 5622 // If one unique T is found: 5623 // First, build a candidate set from the previously recorded 5624 // potentially viable conversions. 5625 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5626 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5627 CandidateSet); 5628 5629 // Then, perform overload resolution over the candidate set. 5630 OverloadCandidateSet::iterator Best; 5631 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5632 case OR_Success: { 5633 // Apply this conversion. 5634 DeclAccessPair Found = 5635 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5636 if (recordConversion(*this, Loc, From, Converter, T, 5637 HadMultipleCandidates, Found)) 5638 return ExprError(); 5639 break; 5640 } 5641 case OR_Ambiguous: 5642 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5643 ViableConversions); 5644 case OR_No_Viable_Function: 5645 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5646 HadMultipleCandidates, 5647 ExplicitConversions)) 5648 return ExprError(); 5649 // fall through 'OR_Deleted' case. 5650 case OR_Deleted: 5651 // We'll complain below about a non-integral condition type. 5652 break; 5653 } 5654 } else { 5655 switch (ViableConversions.size()) { 5656 case 0: { 5657 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5658 HadMultipleCandidates, 5659 ExplicitConversions)) 5660 return ExprError(); 5661 5662 // We'll complain below about a non-integral condition type. 5663 break; 5664 } 5665 case 1: { 5666 // Apply this conversion. 5667 DeclAccessPair Found = ViableConversions[0]; 5668 if (recordConversion(*this, Loc, From, Converter, T, 5669 HadMultipleCandidates, Found)) 5670 return ExprError(); 5671 break; 5672 } 5673 default: 5674 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5675 ViableConversions); 5676 } 5677 } 5678 5679 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5680 } 5681 5682 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5683 /// an acceptable non-member overloaded operator for a call whose 5684 /// arguments have types T1 (and, if non-empty, T2). This routine 5685 /// implements the check in C++ [over.match.oper]p3b2 concerning 5686 /// enumeration types. 5687 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5688 FunctionDecl *Fn, 5689 ArrayRef<Expr *> Args) { 5690 QualType T1 = Args[0]->getType(); 5691 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5692 5693 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5694 return true; 5695 5696 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5697 return true; 5698 5699 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5700 if (Proto->getNumParams() < 1) 5701 return false; 5702 5703 if (T1->isEnumeralType()) { 5704 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5705 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5706 return true; 5707 } 5708 5709 if (Proto->getNumParams() < 2) 5710 return false; 5711 5712 if (!T2.isNull() && T2->isEnumeralType()) { 5713 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5714 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5715 return true; 5716 } 5717 5718 return false; 5719 } 5720 5721 /// AddOverloadCandidate - Adds the given function to the set of 5722 /// candidate functions, using the given function call arguments. If 5723 /// @p SuppressUserConversions, then don't allow user-defined 5724 /// conversions via constructors or conversion operators. 5725 /// 5726 /// \param PartialOverloading true if we are performing "partial" overloading 5727 /// based on an incomplete set of function arguments. This feature is used by 5728 /// code completion. 5729 void 5730 Sema::AddOverloadCandidate(FunctionDecl *Function, 5731 DeclAccessPair FoundDecl, 5732 ArrayRef<Expr *> Args, 5733 OverloadCandidateSet &CandidateSet, 5734 bool SuppressUserConversions, 5735 bool PartialOverloading, 5736 bool AllowExplicit) { 5737 const FunctionProtoType *Proto 5738 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5739 assert(Proto && "Functions without a prototype cannot be overloaded"); 5740 assert(!Function->getDescribedFunctionTemplate() && 5741 "Use AddTemplateOverloadCandidate for function templates"); 5742 5743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5744 if (!isa<CXXConstructorDecl>(Method)) { 5745 // If we get here, it's because we're calling a member function 5746 // that is named without a member access expression (e.g., 5747 // "this->f") that was either written explicitly or created 5748 // implicitly. This can happen with a qualified call to a member 5749 // function, e.g., X::f(). We use an empty type for the implied 5750 // object argument (C++ [over.call.func]p3), and the acting context 5751 // is irrelevant. 5752 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5753 QualType(), Expr::Classification::makeSimpleLValue(), 5754 Args, CandidateSet, SuppressUserConversions, 5755 PartialOverloading); 5756 return; 5757 } 5758 // We treat a constructor like a non-member function, since its object 5759 // argument doesn't participate in overload resolution. 5760 } 5761 5762 if (!CandidateSet.isNewCandidate(Function)) 5763 return; 5764 5765 // C++ [over.match.oper]p3: 5766 // if no operand has a class type, only those non-member functions in the 5767 // lookup set that have a first parameter of type T1 or "reference to 5768 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5769 // is a right operand) a second parameter of type T2 or "reference to 5770 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5771 // candidate functions. 5772 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5773 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5774 return; 5775 5776 // C++11 [class.copy]p11: [DR1402] 5777 // A defaulted move constructor that is defined as deleted is ignored by 5778 // overload resolution. 5779 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5780 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5781 Constructor->isMoveConstructor()) 5782 return; 5783 5784 // Overload resolution is always an unevaluated context. 5785 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5786 5787 // Add this candidate 5788 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5789 Candidate.FoundDecl = FoundDecl; 5790 Candidate.Function = Function; 5791 Candidate.Viable = true; 5792 Candidate.IsSurrogate = false; 5793 Candidate.IgnoreObjectArgument = false; 5794 Candidate.ExplicitCallArguments = Args.size(); 5795 5796 if (Constructor) { 5797 // C++ [class.copy]p3: 5798 // A member function template is never instantiated to perform the copy 5799 // of a class object to an object of its class type. 5800 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5801 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5802 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5803 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5804 ClassType))) { 5805 Candidate.Viable = false; 5806 Candidate.FailureKind = ovl_fail_illegal_constructor; 5807 return; 5808 } 5809 } 5810 5811 unsigned NumParams = Proto->getNumParams(); 5812 5813 // (C++ 13.3.2p2): A candidate function having fewer than m 5814 // parameters is viable only if it has an ellipsis in its parameter 5815 // list (8.3.5). 5816 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5817 !Proto->isVariadic()) { 5818 Candidate.Viable = false; 5819 Candidate.FailureKind = ovl_fail_too_many_arguments; 5820 return; 5821 } 5822 5823 // (C++ 13.3.2p2): A candidate function having more than m parameters 5824 // is viable only if the (m+1)st parameter has a default argument 5825 // (8.3.6). For the purposes of overload resolution, the 5826 // parameter list is truncated on the right, so that there are 5827 // exactly m parameters. 5828 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5829 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5830 // Not enough arguments. 5831 Candidate.Viable = false; 5832 Candidate.FailureKind = ovl_fail_too_few_arguments; 5833 return; 5834 } 5835 5836 // (CUDA B.1): Check for invalid calls between targets. 5837 if (getLangOpts().CUDA) 5838 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5839 // Skip the check for callers that are implicit members, because in this 5840 // case we may not yet know what the member's target is; the target is 5841 // inferred for the member automatically, based on the bases and fields of 5842 // the class. 5843 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5844 Candidate.Viable = false; 5845 Candidate.FailureKind = ovl_fail_bad_target; 5846 return; 5847 } 5848 5849 // Determine the implicit conversion sequences for each of the 5850 // arguments. 5851 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5852 if (ArgIdx < NumParams) { 5853 // (C++ 13.3.2p3): for F to be a viable function, there shall 5854 // exist for each argument an implicit conversion sequence 5855 // (13.3.3.1) that converts that argument to the corresponding 5856 // parameter of F. 5857 QualType ParamType = Proto->getParamType(ArgIdx); 5858 Candidate.Conversions[ArgIdx] 5859 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5860 SuppressUserConversions, 5861 /*InOverloadResolution=*/true, 5862 /*AllowObjCWritebackConversion=*/ 5863 getLangOpts().ObjCAutoRefCount, 5864 AllowExplicit); 5865 if (Candidate.Conversions[ArgIdx].isBad()) { 5866 Candidate.Viable = false; 5867 Candidate.FailureKind = ovl_fail_bad_conversion; 5868 return; 5869 } 5870 } else { 5871 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5872 // argument for which there is no corresponding parameter is 5873 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5874 Candidate.Conversions[ArgIdx].setEllipsis(); 5875 } 5876 } 5877 5878 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5879 Candidate.Viable = false; 5880 Candidate.FailureKind = ovl_fail_enable_if; 5881 Candidate.DeductionFailure.Data = FailedAttr; 5882 return; 5883 } 5884 } 5885 5886 ObjCMethodDecl * 5887 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5888 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5889 if (Methods.size() <= 1) 5890 return nullptr; 5891 5892 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5893 bool Match = true; 5894 ObjCMethodDecl *Method = Methods[b]; 5895 unsigned NumNamedArgs = Sel.getNumArgs(); 5896 // Method might have more arguments than selector indicates. This is due 5897 // to addition of c-style arguments in method. 5898 if (Method->param_size() > NumNamedArgs) 5899 NumNamedArgs = Method->param_size(); 5900 if (Args.size() < NumNamedArgs) 5901 continue; 5902 5903 for (unsigned i = 0; i < NumNamedArgs; i++) { 5904 // We can't do any type-checking on a type-dependent argument. 5905 if (Args[i]->isTypeDependent()) { 5906 Match = false; 5907 break; 5908 } 5909 5910 ParmVarDecl *param = Method->parameters()[i]; 5911 Expr *argExpr = Args[i]; 5912 assert(argExpr && "SelectBestMethod(): missing expression"); 5913 5914 // Strip the unbridged-cast placeholder expression off unless it's 5915 // a consumed argument. 5916 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5917 !param->hasAttr<CFConsumedAttr>()) 5918 argExpr = stripARCUnbridgedCast(argExpr); 5919 5920 // If the parameter is __unknown_anytype, move on to the next method. 5921 if (param->getType() == Context.UnknownAnyTy) { 5922 Match = false; 5923 break; 5924 } 5925 5926 ImplicitConversionSequence ConversionState 5927 = TryCopyInitialization(*this, argExpr, param->getType(), 5928 /*SuppressUserConversions*/false, 5929 /*InOverloadResolution=*/true, 5930 /*AllowObjCWritebackConversion=*/ 5931 getLangOpts().ObjCAutoRefCount, 5932 /*AllowExplicit*/false); 5933 // This function looks for a reasonably-exact match, so we consider 5934 // incompatible pointer conversions to be a failure here. 5935 if (ConversionState.isBad() || 5936 (ConversionState.isStandard() && 5937 ConversionState.Standard.Second == 5938 ICK_Incompatible_Pointer_Conversion)) { 5939 Match = false; 5940 break; 5941 } 5942 } 5943 // Promote additional arguments to variadic methods. 5944 if (Match && Method->isVariadic()) { 5945 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5946 if (Args[i]->isTypeDependent()) { 5947 Match = false; 5948 break; 5949 } 5950 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5951 nullptr); 5952 if (Arg.isInvalid()) { 5953 Match = false; 5954 break; 5955 } 5956 } 5957 } else { 5958 // Check for extra arguments to non-variadic methods. 5959 if (Args.size() != NumNamedArgs) 5960 Match = false; 5961 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5962 // Special case when selectors have no argument. In this case, select 5963 // one with the most general result type of 'id'. 5964 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5965 QualType ReturnT = Methods[b]->getReturnType(); 5966 if (ReturnT->isObjCIdType()) 5967 return Methods[b]; 5968 } 5969 } 5970 } 5971 5972 if (Match) 5973 return Method; 5974 } 5975 return nullptr; 5976 } 5977 5978 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5979 // enable_if is order-sensitive. As a result, we need to reverse things 5980 // sometimes. Size of 4 elements is arbitrary. 5981 static SmallVector<EnableIfAttr *, 4> 5982 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5983 SmallVector<EnableIfAttr *, 4> Result; 5984 if (!Function->hasAttrs()) 5985 return Result; 5986 5987 const auto &FuncAttrs = Function->getAttrs(); 5988 for (Attr *Attr : FuncAttrs) 5989 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5990 Result.push_back(EnableIf); 5991 5992 std::reverse(Result.begin(), Result.end()); 5993 return Result; 5994 } 5995 5996 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5997 bool MissingImplicitThis) { 5998 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5999 if (EnableIfAttrs.empty()) 6000 return nullptr; 6001 6002 SFINAETrap Trap(*this); 6003 SmallVector<Expr *, 16> ConvertedArgs; 6004 bool InitializationFailed = false; 6005 6006 // Ignore any variadic arguments. Converting them is pointless, since the 6007 // user can't refer to them in the enable_if condition. 6008 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6009 6010 // Convert the arguments. 6011 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6012 ExprResult R; 6013 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 6014 !cast<CXXMethodDecl>(Function)->isStatic() && 6015 !isa<CXXConstructorDecl>(Function)) { 6016 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6017 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 6018 Method, Method); 6019 } else { 6020 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6021 Context, Function->getParamDecl(I)), 6022 SourceLocation(), Args[I]); 6023 } 6024 6025 if (R.isInvalid()) { 6026 InitializationFailed = true; 6027 break; 6028 } 6029 6030 ConvertedArgs.push_back(R.get()); 6031 } 6032 6033 if (InitializationFailed || Trap.hasErrorOccurred()) 6034 return EnableIfAttrs[0]; 6035 6036 // Push default arguments if needed. 6037 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6038 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6039 ParmVarDecl *P = Function->getParamDecl(i); 6040 ExprResult R = PerformCopyInitialization( 6041 InitializedEntity::InitializeParameter(Context, 6042 Function->getParamDecl(i)), 6043 SourceLocation(), 6044 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6045 : P->getDefaultArg()); 6046 if (R.isInvalid()) { 6047 InitializationFailed = true; 6048 break; 6049 } 6050 ConvertedArgs.push_back(R.get()); 6051 } 6052 6053 if (InitializationFailed || Trap.hasErrorOccurred()) 6054 return EnableIfAttrs[0]; 6055 } 6056 6057 for (auto *EIA : EnableIfAttrs) { 6058 APValue Result; 6059 // FIXME: This doesn't consider value-dependent cases, because doing so is 6060 // very difficult. Ideally, we should handle them more gracefully. 6061 if (!EIA->getCond()->EvaluateWithSubstitution( 6062 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6063 return EIA; 6064 6065 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6066 return EIA; 6067 } 6068 return nullptr; 6069 } 6070 6071 /// \brief Add all of the function declarations in the given function set to 6072 /// the overload candidate set. 6073 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6074 ArrayRef<Expr *> Args, 6075 OverloadCandidateSet& CandidateSet, 6076 TemplateArgumentListInfo *ExplicitTemplateArgs, 6077 bool SuppressUserConversions, 6078 bool PartialOverloading) { 6079 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6080 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6081 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6082 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6083 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6084 cast<CXXMethodDecl>(FD)->getParent(), 6085 Args[0]->getType(), Args[0]->Classify(Context), 6086 Args.slice(1), CandidateSet, 6087 SuppressUserConversions, PartialOverloading); 6088 else 6089 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6090 SuppressUserConversions, PartialOverloading); 6091 } else { 6092 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6093 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6094 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6095 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6096 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6097 ExplicitTemplateArgs, 6098 Args[0]->getType(), 6099 Args[0]->Classify(Context), Args.slice(1), 6100 CandidateSet, SuppressUserConversions, 6101 PartialOverloading); 6102 else 6103 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6104 ExplicitTemplateArgs, Args, 6105 CandidateSet, SuppressUserConversions, 6106 PartialOverloading); 6107 } 6108 } 6109 } 6110 6111 /// AddMethodCandidate - Adds a named decl (which is some kind of 6112 /// method) as a method candidate to the given overload set. 6113 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6114 QualType ObjectType, 6115 Expr::Classification ObjectClassification, 6116 ArrayRef<Expr *> Args, 6117 OverloadCandidateSet& CandidateSet, 6118 bool SuppressUserConversions) { 6119 NamedDecl *Decl = FoundDecl.getDecl(); 6120 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6121 6122 if (isa<UsingShadowDecl>(Decl)) 6123 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6124 6125 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6126 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6127 "Expected a member function template"); 6128 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6129 /*ExplicitArgs*/ nullptr, 6130 ObjectType, ObjectClassification, 6131 Args, CandidateSet, 6132 SuppressUserConversions); 6133 } else { 6134 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6135 ObjectType, ObjectClassification, 6136 Args, 6137 CandidateSet, SuppressUserConversions); 6138 } 6139 } 6140 6141 /// AddMethodCandidate - Adds the given C++ member function to the set 6142 /// of candidate functions, using the given function call arguments 6143 /// and the object argument (@c Object). For example, in a call 6144 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6145 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6146 /// allow user-defined conversions via constructors or conversion 6147 /// operators. 6148 void 6149 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6150 CXXRecordDecl *ActingContext, QualType ObjectType, 6151 Expr::Classification ObjectClassification, 6152 ArrayRef<Expr *> Args, 6153 OverloadCandidateSet &CandidateSet, 6154 bool SuppressUserConversions, 6155 bool PartialOverloading) { 6156 const FunctionProtoType *Proto 6157 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6158 assert(Proto && "Methods without a prototype cannot be overloaded"); 6159 assert(!isa<CXXConstructorDecl>(Method) && 6160 "Use AddOverloadCandidate for constructors"); 6161 6162 if (!CandidateSet.isNewCandidate(Method)) 6163 return; 6164 6165 // C++11 [class.copy]p23: [DR1402] 6166 // A defaulted move assignment operator that is defined as deleted is 6167 // ignored by overload resolution. 6168 if (Method->isDefaulted() && Method->isDeleted() && 6169 Method->isMoveAssignmentOperator()) 6170 return; 6171 6172 // Overload resolution is always an unevaluated context. 6173 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6174 6175 // Add this candidate 6176 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6177 Candidate.FoundDecl = FoundDecl; 6178 Candidate.Function = Method; 6179 Candidate.IsSurrogate = false; 6180 Candidate.IgnoreObjectArgument = false; 6181 Candidate.ExplicitCallArguments = Args.size(); 6182 6183 unsigned NumParams = Proto->getNumParams(); 6184 6185 // (C++ 13.3.2p2): A candidate function having fewer than m 6186 // parameters is viable only if it has an ellipsis in its parameter 6187 // list (8.3.5). 6188 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6189 !Proto->isVariadic()) { 6190 Candidate.Viable = false; 6191 Candidate.FailureKind = ovl_fail_too_many_arguments; 6192 return; 6193 } 6194 6195 // (C++ 13.3.2p2): A candidate function having more than m parameters 6196 // is viable only if the (m+1)st parameter has a default argument 6197 // (8.3.6). For the purposes of overload resolution, the 6198 // parameter list is truncated on the right, so that there are 6199 // exactly m parameters. 6200 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6201 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6202 // Not enough arguments. 6203 Candidate.Viable = false; 6204 Candidate.FailureKind = ovl_fail_too_few_arguments; 6205 return; 6206 } 6207 6208 Candidate.Viable = true; 6209 6210 if (Method->isStatic() || ObjectType.isNull()) 6211 // The implicit object argument is ignored. 6212 Candidate.IgnoreObjectArgument = true; 6213 else { 6214 // Determine the implicit conversion sequence for the object 6215 // parameter. 6216 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6217 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6218 Method, ActingContext); 6219 if (Candidate.Conversions[0].isBad()) { 6220 Candidate.Viable = false; 6221 Candidate.FailureKind = ovl_fail_bad_conversion; 6222 return; 6223 } 6224 } 6225 6226 // (CUDA B.1): Check for invalid calls between targets. 6227 if (getLangOpts().CUDA) 6228 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6229 if (!IsAllowedCUDACall(Caller, Method)) { 6230 Candidate.Viable = false; 6231 Candidate.FailureKind = ovl_fail_bad_target; 6232 return; 6233 } 6234 6235 // Determine the implicit conversion sequences for each of the 6236 // arguments. 6237 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6238 if (ArgIdx < NumParams) { 6239 // (C++ 13.3.2p3): for F to be a viable function, there shall 6240 // exist for each argument an implicit conversion sequence 6241 // (13.3.3.1) that converts that argument to the corresponding 6242 // parameter of F. 6243 QualType ParamType = Proto->getParamType(ArgIdx); 6244 Candidate.Conversions[ArgIdx + 1] 6245 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6246 SuppressUserConversions, 6247 /*InOverloadResolution=*/true, 6248 /*AllowObjCWritebackConversion=*/ 6249 getLangOpts().ObjCAutoRefCount); 6250 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6251 Candidate.Viable = false; 6252 Candidate.FailureKind = ovl_fail_bad_conversion; 6253 return; 6254 } 6255 } else { 6256 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6257 // argument for which there is no corresponding parameter is 6258 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6259 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6260 } 6261 } 6262 6263 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6264 Candidate.Viable = false; 6265 Candidate.FailureKind = ovl_fail_enable_if; 6266 Candidate.DeductionFailure.Data = FailedAttr; 6267 return; 6268 } 6269 } 6270 6271 /// \brief Add a C++ member function template as a candidate to the candidate 6272 /// set, using template argument deduction to produce an appropriate member 6273 /// function template specialization. 6274 void 6275 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6276 DeclAccessPair FoundDecl, 6277 CXXRecordDecl *ActingContext, 6278 TemplateArgumentListInfo *ExplicitTemplateArgs, 6279 QualType ObjectType, 6280 Expr::Classification ObjectClassification, 6281 ArrayRef<Expr *> Args, 6282 OverloadCandidateSet& CandidateSet, 6283 bool SuppressUserConversions, 6284 bool PartialOverloading) { 6285 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6286 return; 6287 6288 // C++ [over.match.funcs]p7: 6289 // In each case where a candidate is a function template, candidate 6290 // function template specializations are generated using template argument 6291 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6292 // candidate functions in the usual way.113) A given name can refer to one 6293 // or more function templates and also to a set of overloaded non-template 6294 // functions. In such a case, the candidate functions generated from each 6295 // function template are combined with the set of non-template candidate 6296 // functions. 6297 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6298 FunctionDecl *Specialization = nullptr; 6299 if (TemplateDeductionResult Result 6300 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6301 Specialization, Info, PartialOverloading)) { 6302 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6303 Candidate.FoundDecl = FoundDecl; 6304 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6305 Candidate.Viable = false; 6306 Candidate.FailureKind = ovl_fail_bad_deduction; 6307 Candidate.IsSurrogate = false; 6308 Candidate.IgnoreObjectArgument = false; 6309 Candidate.ExplicitCallArguments = Args.size(); 6310 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6311 Info); 6312 return; 6313 } 6314 6315 // Add the function template specialization produced by template argument 6316 // deduction as a candidate. 6317 assert(Specialization && "Missing member function template specialization?"); 6318 assert(isa<CXXMethodDecl>(Specialization) && 6319 "Specialization is not a member function?"); 6320 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6321 ActingContext, ObjectType, ObjectClassification, Args, 6322 CandidateSet, SuppressUserConversions, PartialOverloading); 6323 } 6324 6325 /// \brief Add a C++ function template specialization as a candidate 6326 /// in the candidate set, using template argument deduction to produce 6327 /// an appropriate function template specialization. 6328 void 6329 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6330 DeclAccessPair FoundDecl, 6331 TemplateArgumentListInfo *ExplicitTemplateArgs, 6332 ArrayRef<Expr *> Args, 6333 OverloadCandidateSet& CandidateSet, 6334 bool SuppressUserConversions, 6335 bool PartialOverloading) { 6336 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6337 return; 6338 6339 // C++ [over.match.funcs]p7: 6340 // In each case where a candidate is a function template, candidate 6341 // function template specializations are generated using template argument 6342 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6343 // candidate functions in the usual way.113) A given name can refer to one 6344 // or more function templates and also to a set of overloaded non-template 6345 // functions. In such a case, the candidate functions generated from each 6346 // function template are combined with the set of non-template candidate 6347 // functions. 6348 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6349 FunctionDecl *Specialization = nullptr; 6350 if (TemplateDeductionResult Result 6351 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6352 Specialization, Info, PartialOverloading)) { 6353 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6354 Candidate.FoundDecl = FoundDecl; 6355 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6356 Candidate.Viable = false; 6357 Candidate.FailureKind = ovl_fail_bad_deduction; 6358 Candidate.IsSurrogate = false; 6359 Candidate.IgnoreObjectArgument = false; 6360 Candidate.ExplicitCallArguments = Args.size(); 6361 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6362 Info); 6363 return; 6364 } 6365 6366 // Add the function template specialization produced by template argument 6367 // deduction as a candidate. 6368 assert(Specialization && "Missing function template specialization?"); 6369 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6370 SuppressUserConversions, PartialOverloading); 6371 } 6372 6373 /// Determine whether this is an allowable conversion from the result 6374 /// of an explicit conversion operator to the expected type, per C++ 6375 /// [over.match.conv]p1 and [over.match.ref]p1. 6376 /// 6377 /// \param ConvType The return type of the conversion function. 6378 /// 6379 /// \param ToType The type we are converting to. 6380 /// 6381 /// \param AllowObjCPointerConversion Allow a conversion from one 6382 /// Objective-C pointer to another. 6383 /// 6384 /// \returns true if the conversion is allowable, false otherwise. 6385 static bool isAllowableExplicitConversion(Sema &S, 6386 QualType ConvType, QualType ToType, 6387 bool AllowObjCPointerConversion) { 6388 QualType ToNonRefType = ToType.getNonReferenceType(); 6389 6390 // Easy case: the types are the same. 6391 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6392 return true; 6393 6394 // Allow qualification conversions. 6395 bool ObjCLifetimeConversion; 6396 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6397 ObjCLifetimeConversion)) 6398 return true; 6399 6400 // If we're not allowed to consider Objective-C pointer conversions, 6401 // we're done. 6402 if (!AllowObjCPointerConversion) 6403 return false; 6404 6405 // Is this an Objective-C pointer conversion? 6406 bool IncompatibleObjC = false; 6407 QualType ConvertedType; 6408 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6409 IncompatibleObjC); 6410 } 6411 6412 /// AddConversionCandidate - Add a C++ conversion function as a 6413 /// candidate in the candidate set (C++ [over.match.conv], 6414 /// C++ [over.match.copy]). From is the expression we're converting from, 6415 /// and ToType is the type that we're eventually trying to convert to 6416 /// (which may or may not be the same type as the type that the 6417 /// conversion function produces). 6418 void 6419 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6420 DeclAccessPair FoundDecl, 6421 CXXRecordDecl *ActingContext, 6422 Expr *From, QualType ToType, 6423 OverloadCandidateSet& CandidateSet, 6424 bool AllowObjCConversionOnExplicit) { 6425 assert(!Conversion->getDescribedFunctionTemplate() && 6426 "Conversion function templates use AddTemplateConversionCandidate"); 6427 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6428 if (!CandidateSet.isNewCandidate(Conversion)) 6429 return; 6430 6431 // If the conversion function has an undeduced return type, trigger its 6432 // deduction now. 6433 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6434 if (DeduceReturnType(Conversion, From->getExprLoc())) 6435 return; 6436 ConvType = Conversion->getConversionType().getNonReferenceType(); 6437 } 6438 6439 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6440 // operator is only a candidate if its return type is the target type or 6441 // can be converted to the target type with a qualification conversion. 6442 if (Conversion->isExplicit() && 6443 !isAllowableExplicitConversion(*this, ConvType, ToType, 6444 AllowObjCConversionOnExplicit)) 6445 return; 6446 6447 // Overload resolution is always an unevaluated context. 6448 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6449 6450 // Add this candidate 6451 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6452 Candidate.FoundDecl = FoundDecl; 6453 Candidate.Function = Conversion; 6454 Candidate.IsSurrogate = false; 6455 Candidate.IgnoreObjectArgument = false; 6456 Candidate.FinalConversion.setAsIdentityConversion(); 6457 Candidate.FinalConversion.setFromType(ConvType); 6458 Candidate.FinalConversion.setAllToTypes(ToType); 6459 Candidate.Viable = true; 6460 Candidate.ExplicitCallArguments = 1; 6461 6462 // C++ [over.match.funcs]p4: 6463 // For conversion functions, the function is considered to be a member of 6464 // the class of the implicit implied object argument for the purpose of 6465 // defining the type of the implicit object parameter. 6466 // 6467 // Determine the implicit conversion sequence for the implicit 6468 // object parameter. 6469 QualType ImplicitParamType = From->getType(); 6470 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6471 ImplicitParamType = FromPtrType->getPointeeType(); 6472 CXXRecordDecl *ConversionContext 6473 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6474 6475 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6476 *this, CandidateSet.getLocation(), From->getType(), 6477 From->Classify(Context), Conversion, ConversionContext); 6478 6479 if (Candidate.Conversions[0].isBad()) { 6480 Candidate.Viable = false; 6481 Candidate.FailureKind = ovl_fail_bad_conversion; 6482 return; 6483 } 6484 6485 // We won't go through a user-defined type conversion function to convert a 6486 // derived to base as such conversions are given Conversion Rank. They only 6487 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6488 QualType FromCanon 6489 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6490 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6491 if (FromCanon == ToCanon || 6492 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6493 Candidate.Viable = false; 6494 Candidate.FailureKind = ovl_fail_trivial_conversion; 6495 return; 6496 } 6497 6498 // To determine what the conversion from the result of calling the 6499 // conversion function to the type we're eventually trying to 6500 // convert to (ToType), we need to synthesize a call to the 6501 // conversion function and attempt copy initialization from it. This 6502 // makes sure that we get the right semantics with respect to 6503 // lvalues/rvalues and the type. Fortunately, we can allocate this 6504 // call on the stack and we don't need its arguments to be 6505 // well-formed. 6506 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6507 VK_LValue, From->getLocStart()); 6508 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6509 Context.getPointerType(Conversion->getType()), 6510 CK_FunctionToPointerDecay, 6511 &ConversionRef, VK_RValue); 6512 6513 QualType ConversionType = Conversion->getConversionType(); 6514 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6515 Candidate.Viable = false; 6516 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6517 return; 6518 } 6519 6520 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6521 6522 // Note that it is safe to allocate CallExpr on the stack here because 6523 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6524 // allocator). 6525 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6526 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6527 From->getLocStart()); 6528 ImplicitConversionSequence ICS = 6529 TryCopyInitialization(*this, &Call, ToType, 6530 /*SuppressUserConversions=*/true, 6531 /*InOverloadResolution=*/false, 6532 /*AllowObjCWritebackConversion=*/false); 6533 6534 switch (ICS.getKind()) { 6535 case ImplicitConversionSequence::StandardConversion: 6536 Candidate.FinalConversion = ICS.Standard; 6537 6538 // C++ [over.ics.user]p3: 6539 // If the user-defined conversion is specified by a specialization of a 6540 // conversion function template, the second standard conversion sequence 6541 // shall have exact match rank. 6542 if (Conversion->getPrimaryTemplate() && 6543 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6544 Candidate.Viable = false; 6545 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6546 return; 6547 } 6548 6549 // C++0x [dcl.init.ref]p5: 6550 // In the second case, if the reference is an rvalue reference and 6551 // the second standard conversion sequence of the user-defined 6552 // conversion sequence includes an lvalue-to-rvalue conversion, the 6553 // program is ill-formed. 6554 if (ToType->isRValueReferenceType() && 6555 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6556 Candidate.Viable = false; 6557 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6558 return; 6559 } 6560 break; 6561 6562 case ImplicitConversionSequence::BadConversion: 6563 Candidate.Viable = false; 6564 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6565 return; 6566 6567 default: 6568 llvm_unreachable( 6569 "Can only end up with a standard conversion sequence or failure"); 6570 } 6571 6572 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6573 Candidate.Viable = false; 6574 Candidate.FailureKind = ovl_fail_enable_if; 6575 Candidate.DeductionFailure.Data = FailedAttr; 6576 return; 6577 } 6578 } 6579 6580 /// \brief Adds a conversion function template specialization 6581 /// candidate to the overload set, using template argument deduction 6582 /// to deduce the template arguments of the conversion function 6583 /// template from the type that we are converting to (C++ 6584 /// [temp.deduct.conv]). 6585 void 6586 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6587 DeclAccessPair FoundDecl, 6588 CXXRecordDecl *ActingDC, 6589 Expr *From, QualType ToType, 6590 OverloadCandidateSet &CandidateSet, 6591 bool AllowObjCConversionOnExplicit) { 6592 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6593 "Only conversion function templates permitted here"); 6594 6595 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6596 return; 6597 6598 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6599 CXXConversionDecl *Specialization = nullptr; 6600 if (TemplateDeductionResult Result 6601 = DeduceTemplateArguments(FunctionTemplate, ToType, 6602 Specialization, Info)) { 6603 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6604 Candidate.FoundDecl = FoundDecl; 6605 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6606 Candidate.Viable = false; 6607 Candidate.FailureKind = ovl_fail_bad_deduction; 6608 Candidate.IsSurrogate = false; 6609 Candidate.IgnoreObjectArgument = false; 6610 Candidate.ExplicitCallArguments = 1; 6611 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6612 Info); 6613 return; 6614 } 6615 6616 // Add the conversion function template specialization produced by 6617 // template argument deduction as a candidate. 6618 assert(Specialization && "Missing function template specialization?"); 6619 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6620 CandidateSet, AllowObjCConversionOnExplicit); 6621 } 6622 6623 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6624 /// converts the given @c Object to a function pointer via the 6625 /// conversion function @c Conversion, and then attempts to call it 6626 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6627 /// the type of function that we'll eventually be calling. 6628 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6629 DeclAccessPair FoundDecl, 6630 CXXRecordDecl *ActingContext, 6631 const FunctionProtoType *Proto, 6632 Expr *Object, 6633 ArrayRef<Expr *> Args, 6634 OverloadCandidateSet& CandidateSet) { 6635 if (!CandidateSet.isNewCandidate(Conversion)) 6636 return; 6637 6638 // Overload resolution is always an unevaluated context. 6639 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6640 6641 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6642 Candidate.FoundDecl = FoundDecl; 6643 Candidate.Function = nullptr; 6644 Candidate.Surrogate = Conversion; 6645 Candidate.Viable = true; 6646 Candidate.IsSurrogate = true; 6647 Candidate.IgnoreObjectArgument = false; 6648 Candidate.ExplicitCallArguments = Args.size(); 6649 6650 // Determine the implicit conversion sequence for the implicit 6651 // object parameter. 6652 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6653 *this, CandidateSet.getLocation(), Object->getType(), 6654 Object->Classify(Context), Conversion, ActingContext); 6655 if (ObjectInit.isBad()) { 6656 Candidate.Viable = false; 6657 Candidate.FailureKind = ovl_fail_bad_conversion; 6658 Candidate.Conversions[0] = ObjectInit; 6659 return; 6660 } 6661 6662 // The first conversion is actually a user-defined conversion whose 6663 // first conversion is ObjectInit's standard conversion (which is 6664 // effectively a reference binding). Record it as such. 6665 Candidate.Conversions[0].setUserDefined(); 6666 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6667 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6668 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6669 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6670 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6671 Candidate.Conversions[0].UserDefined.After 6672 = Candidate.Conversions[0].UserDefined.Before; 6673 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6674 6675 // Find the 6676 unsigned NumParams = Proto->getNumParams(); 6677 6678 // (C++ 13.3.2p2): A candidate function having fewer than m 6679 // parameters is viable only if it has an ellipsis in its parameter 6680 // list (8.3.5). 6681 if (Args.size() > NumParams && !Proto->isVariadic()) { 6682 Candidate.Viable = false; 6683 Candidate.FailureKind = ovl_fail_too_many_arguments; 6684 return; 6685 } 6686 6687 // Function types don't have any default arguments, so just check if 6688 // we have enough arguments. 6689 if (Args.size() < NumParams) { 6690 // Not enough arguments. 6691 Candidate.Viable = false; 6692 Candidate.FailureKind = ovl_fail_too_few_arguments; 6693 return; 6694 } 6695 6696 // Determine the implicit conversion sequences for each of the 6697 // arguments. 6698 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6699 if (ArgIdx < NumParams) { 6700 // (C++ 13.3.2p3): for F to be a viable function, there shall 6701 // exist for each argument an implicit conversion sequence 6702 // (13.3.3.1) that converts that argument to the corresponding 6703 // parameter of F. 6704 QualType ParamType = Proto->getParamType(ArgIdx); 6705 Candidate.Conversions[ArgIdx + 1] 6706 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6707 /*SuppressUserConversions=*/false, 6708 /*InOverloadResolution=*/false, 6709 /*AllowObjCWritebackConversion=*/ 6710 getLangOpts().ObjCAutoRefCount); 6711 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6712 Candidate.Viable = false; 6713 Candidate.FailureKind = ovl_fail_bad_conversion; 6714 return; 6715 } 6716 } else { 6717 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6718 // argument for which there is no corresponding parameter is 6719 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6720 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6721 } 6722 } 6723 6724 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6725 Candidate.Viable = false; 6726 Candidate.FailureKind = ovl_fail_enable_if; 6727 Candidate.DeductionFailure.Data = FailedAttr; 6728 return; 6729 } 6730 } 6731 6732 /// \brief Add overload candidates for overloaded operators that are 6733 /// member functions. 6734 /// 6735 /// Add the overloaded operator candidates that are member functions 6736 /// for the operator Op that was used in an operator expression such 6737 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6738 /// CandidateSet will store the added overload candidates. (C++ 6739 /// [over.match.oper]). 6740 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6741 SourceLocation OpLoc, 6742 ArrayRef<Expr *> Args, 6743 OverloadCandidateSet& CandidateSet, 6744 SourceRange OpRange) { 6745 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6746 6747 // C++ [over.match.oper]p3: 6748 // For a unary operator @ with an operand of a type whose 6749 // cv-unqualified version is T1, and for a binary operator @ with 6750 // a left operand of a type whose cv-unqualified version is T1 and 6751 // a right operand of a type whose cv-unqualified version is T2, 6752 // three sets of candidate functions, designated member 6753 // candidates, non-member candidates and built-in candidates, are 6754 // constructed as follows: 6755 QualType T1 = Args[0]->getType(); 6756 6757 // -- If T1 is a complete class type or a class currently being 6758 // defined, the set of member candidates is the result of the 6759 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6760 // the set of member candidates is empty. 6761 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6762 // Complete the type if it can be completed. 6763 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6764 return; 6765 // If the type is neither complete nor being defined, bail out now. 6766 if (!T1Rec->getDecl()->getDefinition()) 6767 return; 6768 6769 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6770 LookupQualifiedName(Operators, T1Rec->getDecl()); 6771 Operators.suppressDiagnostics(); 6772 6773 for (LookupResult::iterator Oper = Operators.begin(), 6774 OperEnd = Operators.end(); 6775 Oper != OperEnd; 6776 ++Oper) 6777 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6778 Args[0]->Classify(Context), 6779 Args.slice(1), 6780 CandidateSet, 6781 /* SuppressUserConversions = */ false); 6782 } 6783 } 6784 6785 /// AddBuiltinCandidate - Add a candidate for a built-in 6786 /// operator. ResultTy and ParamTys are the result and parameter types 6787 /// of the built-in candidate, respectively. Args and NumArgs are the 6788 /// arguments being passed to the candidate. IsAssignmentOperator 6789 /// should be true when this built-in candidate is an assignment 6790 /// operator. NumContextualBoolArguments is the number of arguments 6791 /// (at the beginning of the argument list) that will be contextually 6792 /// converted to bool. 6793 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6794 ArrayRef<Expr *> Args, 6795 OverloadCandidateSet& CandidateSet, 6796 bool IsAssignmentOperator, 6797 unsigned NumContextualBoolArguments) { 6798 // Overload resolution is always an unevaluated context. 6799 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6800 6801 // Add this candidate 6802 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6803 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6804 Candidate.Function = nullptr; 6805 Candidate.IsSurrogate = false; 6806 Candidate.IgnoreObjectArgument = false; 6807 Candidate.BuiltinTypes.ResultTy = ResultTy; 6808 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6809 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6810 6811 // Determine the implicit conversion sequences for each of the 6812 // arguments. 6813 Candidate.Viable = true; 6814 Candidate.ExplicitCallArguments = Args.size(); 6815 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6816 // C++ [over.match.oper]p4: 6817 // For the built-in assignment operators, conversions of the 6818 // left operand are restricted as follows: 6819 // -- no temporaries are introduced to hold the left operand, and 6820 // -- no user-defined conversions are applied to the left 6821 // operand to achieve a type match with the left-most 6822 // parameter of a built-in candidate. 6823 // 6824 // We block these conversions by turning off user-defined 6825 // conversions, since that is the only way that initialization of 6826 // a reference to a non-class type can occur from something that 6827 // is not of the same type. 6828 if (ArgIdx < NumContextualBoolArguments) { 6829 assert(ParamTys[ArgIdx] == Context.BoolTy && 6830 "Contextual conversion to bool requires bool type"); 6831 Candidate.Conversions[ArgIdx] 6832 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6833 } else { 6834 Candidate.Conversions[ArgIdx] 6835 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6836 ArgIdx == 0 && IsAssignmentOperator, 6837 /*InOverloadResolution=*/false, 6838 /*AllowObjCWritebackConversion=*/ 6839 getLangOpts().ObjCAutoRefCount); 6840 } 6841 if (Candidate.Conversions[ArgIdx].isBad()) { 6842 Candidate.Viable = false; 6843 Candidate.FailureKind = ovl_fail_bad_conversion; 6844 break; 6845 } 6846 } 6847 } 6848 6849 namespace { 6850 6851 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6852 /// candidate operator functions for built-in operators (C++ 6853 /// [over.built]). The types are separated into pointer types and 6854 /// enumeration types. 6855 class BuiltinCandidateTypeSet { 6856 /// TypeSet - A set of types. 6857 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6858 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6859 6860 /// PointerTypes - The set of pointer types that will be used in the 6861 /// built-in candidates. 6862 TypeSet PointerTypes; 6863 6864 /// MemberPointerTypes - The set of member pointer types that will be 6865 /// used in the built-in candidates. 6866 TypeSet MemberPointerTypes; 6867 6868 /// EnumerationTypes - The set of enumeration types that will be 6869 /// used in the built-in candidates. 6870 TypeSet EnumerationTypes; 6871 6872 /// \brief The set of vector types that will be used in the built-in 6873 /// candidates. 6874 TypeSet VectorTypes; 6875 6876 /// \brief A flag indicating non-record types are viable candidates 6877 bool HasNonRecordTypes; 6878 6879 /// \brief A flag indicating whether either arithmetic or enumeration types 6880 /// were present in the candidate set. 6881 bool HasArithmeticOrEnumeralTypes; 6882 6883 /// \brief A flag indicating whether the nullptr type was present in the 6884 /// candidate set. 6885 bool HasNullPtrType; 6886 6887 /// Sema - The semantic analysis instance where we are building the 6888 /// candidate type set. 6889 Sema &SemaRef; 6890 6891 /// Context - The AST context in which we will build the type sets. 6892 ASTContext &Context; 6893 6894 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6895 const Qualifiers &VisibleQuals); 6896 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6897 6898 public: 6899 /// iterator - Iterates through the types that are part of the set. 6900 typedef TypeSet::iterator iterator; 6901 6902 BuiltinCandidateTypeSet(Sema &SemaRef) 6903 : HasNonRecordTypes(false), 6904 HasArithmeticOrEnumeralTypes(false), 6905 HasNullPtrType(false), 6906 SemaRef(SemaRef), 6907 Context(SemaRef.Context) { } 6908 6909 void AddTypesConvertedFrom(QualType Ty, 6910 SourceLocation Loc, 6911 bool AllowUserConversions, 6912 bool AllowExplicitConversions, 6913 const Qualifiers &VisibleTypeConversionsQuals); 6914 6915 /// pointer_begin - First pointer type found; 6916 iterator pointer_begin() { return PointerTypes.begin(); } 6917 6918 /// pointer_end - Past the last pointer type found; 6919 iterator pointer_end() { return PointerTypes.end(); } 6920 6921 /// member_pointer_begin - First member pointer type found; 6922 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6923 6924 /// member_pointer_end - Past the last member pointer type found; 6925 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6926 6927 /// enumeration_begin - First enumeration type found; 6928 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6929 6930 /// enumeration_end - Past the last enumeration type found; 6931 iterator enumeration_end() { return EnumerationTypes.end(); } 6932 6933 iterator vector_begin() { return VectorTypes.begin(); } 6934 iterator vector_end() { return VectorTypes.end(); } 6935 6936 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6937 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6938 bool hasNullPtrType() const { return HasNullPtrType; } 6939 }; 6940 6941 } // end anonymous namespace 6942 6943 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6944 /// the set of pointer types along with any more-qualified variants of 6945 /// that type. For example, if @p Ty is "int const *", this routine 6946 /// will add "int const *", "int const volatile *", "int const 6947 /// restrict *", and "int const volatile restrict *" to the set of 6948 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6949 /// false otherwise. 6950 /// 6951 /// FIXME: what to do about extended qualifiers? 6952 bool 6953 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6954 const Qualifiers &VisibleQuals) { 6955 6956 // Insert this type. 6957 if (!PointerTypes.insert(Ty)) 6958 return false; 6959 6960 QualType PointeeTy; 6961 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6962 bool buildObjCPtr = false; 6963 if (!PointerTy) { 6964 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6965 PointeeTy = PTy->getPointeeType(); 6966 buildObjCPtr = true; 6967 } else { 6968 PointeeTy = PointerTy->getPointeeType(); 6969 } 6970 6971 // Don't add qualified variants of arrays. For one, they're not allowed 6972 // (the qualifier would sink to the element type), and for another, the 6973 // only overload situation where it matters is subscript or pointer +- int, 6974 // and those shouldn't have qualifier variants anyway. 6975 if (PointeeTy->isArrayType()) 6976 return true; 6977 6978 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6979 bool hasVolatile = VisibleQuals.hasVolatile(); 6980 bool hasRestrict = VisibleQuals.hasRestrict(); 6981 6982 // Iterate through all strict supersets of BaseCVR. 6983 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6984 if ((CVR | BaseCVR) != CVR) continue; 6985 // Skip over volatile if no volatile found anywhere in the types. 6986 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6987 6988 // Skip over restrict if no restrict found anywhere in the types, or if 6989 // the type cannot be restrict-qualified. 6990 if ((CVR & Qualifiers::Restrict) && 6991 (!hasRestrict || 6992 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6993 continue; 6994 6995 // Build qualified pointee type. 6996 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6997 6998 // Build qualified pointer type. 6999 QualType QPointerTy; 7000 if (!buildObjCPtr) 7001 QPointerTy = Context.getPointerType(QPointeeTy); 7002 else 7003 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7004 7005 // Insert qualified pointer type. 7006 PointerTypes.insert(QPointerTy); 7007 } 7008 7009 return true; 7010 } 7011 7012 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7013 /// to the set of pointer types along with any more-qualified variants of 7014 /// that type. For example, if @p Ty is "int const *", this routine 7015 /// will add "int const *", "int const volatile *", "int const 7016 /// restrict *", and "int const volatile restrict *" to the set of 7017 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7018 /// false otherwise. 7019 /// 7020 /// FIXME: what to do about extended qualifiers? 7021 bool 7022 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7023 QualType Ty) { 7024 // Insert this type. 7025 if (!MemberPointerTypes.insert(Ty)) 7026 return false; 7027 7028 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7029 assert(PointerTy && "type was not a member pointer type!"); 7030 7031 QualType PointeeTy = PointerTy->getPointeeType(); 7032 // Don't add qualified variants of arrays. For one, they're not allowed 7033 // (the qualifier would sink to the element type), and for another, the 7034 // only overload situation where it matters is subscript or pointer +- int, 7035 // and those shouldn't have qualifier variants anyway. 7036 if (PointeeTy->isArrayType()) 7037 return true; 7038 const Type *ClassTy = PointerTy->getClass(); 7039 7040 // Iterate through all strict supersets of the pointee type's CVR 7041 // qualifiers. 7042 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7043 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7044 if ((CVR | BaseCVR) != CVR) continue; 7045 7046 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7047 MemberPointerTypes.insert( 7048 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7049 } 7050 7051 return true; 7052 } 7053 7054 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7055 /// Ty can be implicit converted to the given set of @p Types. We're 7056 /// primarily interested in pointer types and enumeration types. We also 7057 /// take member pointer types, for the conditional operator. 7058 /// AllowUserConversions is true if we should look at the conversion 7059 /// functions of a class type, and AllowExplicitConversions if we 7060 /// should also include the explicit conversion functions of a class 7061 /// type. 7062 void 7063 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7064 SourceLocation Loc, 7065 bool AllowUserConversions, 7066 bool AllowExplicitConversions, 7067 const Qualifiers &VisibleQuals) { 7068 // Only deal with canonical types. 7069 Ty = Context.getCanonicalType(Ty); 7070 7071 // Look through reference types; they aren't part of the type of an 7072 // expression for the purposes of conversions. 7073 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7074 Ty = RefTy->getPointeeType(); 7075 7076 // If we're dealing with an array type, decay to the pointer. 7077 if (Ty->isArrayType()) 7078 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7079 7080 // Otherwise, we don't care about qualifiers on the type. 7081 Ty = Ty.getLocalUnqualifiedType(); 7082 7083 // Flag if we ever add a non-record type. 7084 const RecordType *TyRec = Ty->getAs<RecordType>(); 7085 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7086 7087 // Flag if we encounter an arithmetic type. 7088 HasArithmeticOrEnumeralTypes = 7089 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7090 7091 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7092 PointerTypes.insert(Ty); 7093 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7094 // Insert our type, and its more-qualified variants, into the set 7095 // of types. 7096 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7097 return; 7098 } else if (Ty->isMemberPointerType()) { 7099 // Member pointers are far easier, since the pointee can't be converted. 7100 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7101 return; 7102 } else if (Ty->isEnumeralType()) { 7103 HasArithmeticOrEnumeralTypes = true; 7104 EnumerationTypes.insert(Ty); 7105 } else if (Ty->isVectorType()) { 7106 // We treat vector types as arithmetic types in many contexts as an 7107 // extension. 7108 HasArithmeticOrEnumeralTypes = true; 7109 VectorTypes.insert(Ty); 7110 } else if (Ty->isNullPtrType()) { 7111 HasNullPtrType = true; 7112 } else if (AllowUserConversions && TyRec) { 7113 // No conversion functions in incomplete types. 7114 if (!SemaRef.isCompleteType(Loc, Ty)) 7115 return; 7116 7117 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7118 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7119 if (isa<UsingShadowDecl>(D)) 7120 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7121 7122 // Skip conversion function templates; they don't tell us anything 7123 // about which builtin types we can convert to. 7124 if (isa<FunctionTemplateDecl>(D)) 7125 continue; 7126 7127 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7128 if (AllowExplicitConversions || !Conv->isExplicit()) { 7129 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7130 VisibleQuals); 7131 } 7132 } 7133 } 7134 } 7135 7136 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7137 /// the volatile- and non-volatile-qualified assignment operators for the 7138 /// given type to the candidate set. 7139 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7140 QualType T, 7141 ArrayRef<Expr *> Args, 7142 OverloadCandidateSet &CandidateSet) { 7143 QualType ParamTypes[2]; 7144 7145 // T& operator=(T&, T) 7146 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7147 ParamTypes[1] = T; 7148 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7149 /*IsAssignmentOperator=*/true); 7150 7151 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7152 // volatile T& operator=(volatile T&, T) 7153 ParamTypes[0] 7154 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7155 ParamTypes[1] = T; 7156 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7157 /*IsAssignmentOperator=*/true); 7158 } 7159 } 7160 7161 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7162 /// if any, found in visible type conversion functions found in ArgExpr's type. 7163 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7164 Qualifiers VRQuals; 7165 const RecordType *TyRec; 7166 if (const MemberPointerType *RHSMPType = 7167 ArgExpr->getType()->getAs<MemberPointerType>()) 7168 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7169 else 7170 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7171 if (!TyRec) { 7172 // Just to be safe, assume the worst case. 7173 VRQuals.addVolatile(); 7174 VRQuals.addRestrict(); 7175 return VRQuals; 7176 } 7177 7178 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7179 if (!ClassDecl->hasDefinition()) 7180 return VRQuals; 7181 7182 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7183 if (isa<UsingShadowDecl>(D)) 7184 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7185 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7186 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7187 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7188 CanTy = ResTypeRef->getPointeeType(); 7189 // Need to go down the pointer/mempointer chain and add qualifiers 7190 // as see them. 7191 bool done = false; 7192 while (!done) { 7193 if (CanTy.isRestrictQualified()) 7194 VRQuals.addRestrict(); 7195 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7196 CanTy = ResTypePtr->getPointeeType(); 7197 else if (const MemberPointerType *ResTypeMPtr = 7198 CanTy->getAs<MemberPointerType>()) 7199 CanTy = ResTypeMPtr->getPointeeType(); 7200 else 7201 done = true; 7202 if (CanTy.isVolatileQualified()) 7203 VRQuals.addVolatile(); 7204 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7205 return VRQuals; 7206 } 7207 } 7208 } 7209 return VRQuals; 7210 } 7211 7212 namespace { 7213 7214 /// \brief Helper class to manage the addition of builtin operator overload 7215 /// candidates. It provides shared state and utility methods used throughout 7216 /// the process, as well as a helper method to add each group of builtin 7217 /// operator overloads from the standard to a candidate set. 7218 class BuiltinOperatorOverloadBuilder { 7219 // Common instance state available to all overload candidate addition methods. 7220 Sema &S; 7221 ArrayRef<Expr *> Args; 7222 Qualifiers VisibleTypeConversionsQuals; 7223 bool HasArithmeticOrEnumeralCandidateType; 7224 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7225 OverloadCandidateSet &CandidateSet; 7226 7227 // Define some constants used to index and iterate over the arithemetic types 7228 // provided via the getArithmeticType() method below. 7229 // The "promoted arithmetic types" are the arithmetic 7230 // types are that preserved by promotion (C++ [over.built]p2). 7231 static const unsigned FirstIntegralType = 4; 7232 static const unsigned LastIntegralType = 21; 7233 static const unsigned FirstPromotedIntegralType = 4, 7234 LastPromotedIntegralType = 12; 7235 static const unsigned FirstPromotedArithmeticType = 0, 7236 LastPromotedArithmeticType = 12; 7237 static const unsigned NumArithmeticTypes = 21; 7238 7239 /// \brief Get the canonical type for a given arithmetic type index. 7240 CanQualType getArithmeticType(unsigned index) { 7241 assert(index < NumArithmeticTypes); 7242 static CanQualType ASTContext::* const 7243 ArithmeticTypes[NumArithmeticTypes] = { 7244 // Start of promoted types. 7245 &ASTContext::FloatTy, 7246 &ASTContext::DoubleTy, 7247 &ASTContext::LongDoubleTy, 7248 &ASTContext::Float128Ty, 7249 7250 // Start of integral types. 7251 &ASTContext::IntTy, 7252 &ASTContext::LongTy, 7253 &ASTContext::LongLongTy, 7254 &ASTContext::Int128Ty, 7255 &ASTContext::UnsignedIntTy, 7256 &ASTContext::UnsignedLongTy, 7257 &ASTContext::UnsignedLongLongTy, 7258 &ASTContext::UnsignedInt128Ty, 7259 // End of promoted types. 7260 7261 &ASTContext::BoolTy, 7262 &ASTContext::CharTy, 7263 &ASTContext::WCharTy, 7264 &ASTContext::Char16Ty, 7265 &ASTContext::Char32Ty, 7266 &ASTContext::SignedCharTy, 7267 &ASTContext::ShortTy, 7268 &ASTContext::UnsignedCharTy, 7269 &ASTContext::UnsignedShortTy, 7270 // End of integral types. 7271 // FIXME: What about complex? What about half? 7272 }; 7273 return S.Context.*ArithmeticTypes[index]; 7274 } 7275 7276 /// \brief Gets the canonical type resulting from the usual arithemetic 7277 /// converions for the given arithmetic types. 7278 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7279 // Accelerator table for performing the usual arithmetic conversions. 7280 // The rules are basically: 7281 // - if either is floating-point, use the wider floating-point 7282 // - if same signedness, use the higher rank 7283 // - if same size, use unsigned of the higher rank 7284 // - use the larger type 7285 // These rules, together with the axiom that higher ranks are 7286 // never smaller, are sufficient to precompute all of these results 7287 // *except* when dealing with signed types of higher rank. 7288 // (we could precompute SLL x UI for all known platforms, but it's 7289 // better not to make any assumptions). 7290 // We assume that int128 has a higher rank than long long on all platforms. 7291 enum PromotedType : int8_t { 7292 Dep=-1, 7293 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7294 }; 7295 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7296 [LastPromotedArithmeticType] = { 7297 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7298 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7299 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7300 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7301 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7302 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7303 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7304 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7305 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7306 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7307 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7308 }; 7309 7310 assert(L < LastPromotedArithmeticType); 7311 assert(R < LastPromotedArithmeticType); 7312 int Idx = ConversionsTable[L][R]; 7313 7314 // Fast path: the table gives us a concrete answer. 7315 if (Idx != Dep) return getArithmeticType(Idx); 7316 7317 // Slow path: we need to compare widths. 7318 // An invariant is that the signed type has higher rank. 7319 CanQualType LT = getArithmeticType(L), 7320 RT = getArithmeticType(R); 7321 unsigned LW = S.Context.getIntWidth(LT), 7322 RW = S.Context.getIntWidth(RT); 7323 7324 // If they're different widths, use the signed type. 7325 if (LW > RW) return LT; 7326 else if (LW < RW) return RT; 7327 7328 // Otherwise, use the unsigned type of the signed type's rank. 7329 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7330 assert(L == SLL || R == SLL); 7331 return S.Context.UnsignedLongLongTy; 7332 } 7333 7334 /// \brief Helper method to factor out the common pattern of adding overloads 7335 /// for '++' and '--' builtin operators. 7336 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7337 bool HasVolatile, 7338 bool HasRestrict) { 7339 QualType ParamTypes[2] = { 7340 S.Context.getLValueReferenceType(CandidateTy), 7341 S.Context.IntTy 7342 }; 7343 7344 // Non-volatile version. 7345 if (Args.size() == 1) 7346 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7347 else 7348 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7349 7350 // Use a heuristic to reduce number of builtin candidates in the set: 7351 // add volatile version only if there are conversions to a volatile type. 7352 if (HasVolatile) { 7353 ParamTypes[0] = 7354 S.Context.getLValueReferenceType( 7355 S.Context.getVolatileType(CandidateTy)); 7356 if (Args.size() == 1) 7357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7358 else 7359 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7360 } 7361 7362 // Add restrict version only if there are conversions to a restrict type 7363 // and our candidate type is a non-restrict-qualified pointer. 7364 if (HasRestrict && CandidateTy->isAnyPointerType() && 7365 !CandidateTy.isRestrictQualified()) { 7366 ParamTypes[0] 7367 = S.Context.getLValueReferenceType( 7368 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7369 if (Args.size() == 1) 7370 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7371 else 7372 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7373 7374 if (HasVolatile) { 7375 ParamTypes[0] 7376 = S.Context.getLValueReferenceType( 7377 S.Context.getCVRQualifiedType(CandidateTy, 7378 (Qualifiers::Volatile | 7379 Qualifiers::Restrict))); 7380 if (Args.size() == 1) 7381 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7382 else 7383 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7384 } 7385 } 7386 7387 } 7388 7389 public: 7390 BuiltinOperatorOverloadBuilder( 7391 Sema &S, ArrayRef<Expr *> Args, 7392 Qualifiers VisibleTypeConversionsQuals, 7393 bool HasArithmeticOrEnumeralCandidateType, 7394 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7395 OverloadCandidateSet &CandidateSet) 7396 : S(S), Args(Args), 7397 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7398 HasArithmeticOrEnumeralCandidateType( 7399 HasArithmeticOrEnumeralCandidateType), 7400 CandidateTypes(CandidateTypes), 7401 CandidateSet(CandidateSet) { 7402 // Validate some of our static helper constants in debug builds. 7403 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7404 "Invalid first promoted integral type"); 7405 assert(getArithmeticType(LastPromotedIntegralType - 1) 7406 == S.Context.UnsignedInt128Ty && 7407 "Invalid last promoted integral type"); 7408 assert(getArithmeticType(FirstPromotedArithmeticType) 7409 == S.Context.FloatTy && 7410 "Invalid first promoted arithmetic type"); 7411 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7412 == S.Context.UnsignedInt128Ty && 7413 "Invalid last promoted arithmetic type"); 7414 } 7415 7416 // C++ [over.built]p3: 7417 // 7418 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7419 // is either volatile or empty, there exist candidate operator 7420 // functions of the form 7421 // 7422 // VQ T& operator++(VQ T&); 7423 // T operator++(VQ T&, int); 7424 // 7425 // C++ [over.built]p4: 7426 // 7427 // For every pair (T, VQ), where T is an arithmetic type other 7428 // than bool, and VQ is either volatile or empty, there exist 7429 // candidate operator functions of the form 7430 // 7431 // VQ T& operator--(VQ T&); 7432 // T operator--(VQ T&, int); 7433 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7434 if (!HasArithmeticOrEnumeralCandidateType) 7435 return; 7436 7437 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7438 Arith < NumArithmeticTypes; ++Arith) { 7439 addPlusPlusMinusMinusStyleOverloads( 7440 getArithmeticType(Arith), 7441 VisibleTypeConversionsQuals.hasVolatile(), 7442 VisibleTypeConversionsQuals.hasRestrict()); 7443 } 7444 } 7445 7446 // C++ [over.built]p5: 7447 // 7448 // For every pair (T, VQ), where T is a cv-qualified or 7449 // cv-unqualified object type, and VQ is either volatile or 7450 // empty, there exist candidate operator functions of the form 7451 // 7452 // T*VQ& operator++(T*VQ&); 7453 // T*VQ& operator--(T*VQ&); 7454 // T* operator++(T*VQ&, int); 7455 // T* operator--(T*VQ&, int); 7456 void addPlusPlusMinusMinusPointerOverloads() { 7457 for (BuiltinCandidateTypeSet::iterator 7458 Ptr = CandidateTypes[0].pointer_begin(), 7459 PtrEnd = CandidateTypes[0].pointer_end(); 7460 Ptr != PtrEnd; ++Ptr) { 7461 // Skip pointer types that aren't pointers to object types. 7462 if (!(*Ptr)->getPointeeType()->isObjectType()) 7463 continue; 7464 7465 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7466 (!(*Ptr).isVolatileQualified() && 7467 VisibleTypeConversionsQuals.hasVolatile()), 7468 (!(*Ptr).isRestrictQualified() && 7469 VisibleTypeConversionsQuals.hasRestrict())); 7470 } 7471 } 7472 7473 // C++ [over.built]p6: 7474 // For every cv-qualified or cv-unqualified object type T, there 7475 // exist candidate operator functions of the form 7476 // 7477 // T& operator*(T*); 7478 // 7479 // C++ [over.built]p7: 7480 // For every function type T that does not have cv-qualifiers or a 7481 // ref-qualifier, there exist candidate operator functions of the form 7482 // T& operator*(T*); 7483 void addUnaryStarPointerOverloads() { 7484 for (BuiltinCandidateTypeSet::iterator 7485 Ptr = CandidateTypes[0].pointer_begin(), 7486 PtrEnd = CandidateTypes[0].pointer_end(); 7487 Ptr != PtrEnd; ++Ptr) { 7488 QualType ParamTy = *Ptr; 7489 QualType PointeeTy = ParamTy->getPointeeType(); 7490 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7491 continue; 7492 7493 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7494 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7495 continue; 7496 7497 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7498 &ParamTy, Args, CandidateSet); 7499 } 7500 } 7501 7502 // C++ [over.built]p9: 7503 // For every promoted arithmetic type T, there exist candidate 7504 // operator functions of the form 7505 // 7506 // T operator+(T); 7507 // T operator-(T); 7508 void addUnaryPlusOrMinusArithmeticOverloads() { 7509 if (!HasArithmeticOrEnumeralCandidateType) 7510 return; 7511 7512 for (unsigned Arith = FirstPromotedArithmeticType; 7513 Arith < LastPromotedArithmeticType; ++Arith) { 7514 QualType ArithTy = getArithmeticType(Arith); 7515 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7516 } 7517 7518 // Extension: We also add these operators for vector types. 7519 for (BuiltinCandidateTypeSet::iterator 7520 Vec = CandidateTypes[0].vector_begin(), 7521 VecEnd = CandidateTypes[0].vector_end(); 7522 Vec != VecEnd; ++Vec) { 7523 QualType VecTy = *Vec; 7524 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7525 } 7526 } 7527 7528 // C++ [over.built]p8: 7529 // For every type T, there exist candidate operator functions of 7530 // the form 7531 // 7532 // T* operator+(T*); 7533 void addUnaryPlusPointerOverloads() { 7534 for (BuiltinCandidateTypeSet::iterator 7535 Ptr = CandidateTypes[0].pointer_begin(), 7536 PtrEnd = CandidateTypes[0].pointer_end(); 7537 Ptr != PtrEnd; ++Ptr) { 7538 QualType ParamTy = *Ptr; 7539 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7540 } 7541 } 7542 7543 // C++ [over.built]p10: 7544 // For every promoted integral type T, there exist candidate 7545 // operator functions of the form 7546 // 7547 // T operator~(T); 7548 void addUnaryTildePromotedIntegralOverloads() { 7549 if (!HasArithmeticOrEnumeralCandidateType) 7550 return; 7551 7552 for (unsigned Int = FirstPromotedIntegralType; 7553 Int < LastPromotedIntegralType; ++Int) { 7554 QualType IntTy = getArithmeticType(Int); 7555 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7556 } 7557 7558 // Extension: We also add this operator for vector types. 7559 for (BuiltinCandidateTypeSet::iterator 7560 Vec = CandidateTypes[0].vector_begin(), 7561 VecEnd = CandidateTypes[0].vector_end(); 7562 Vec != VecEnd; ++Vec) { 7563 QualType VecTy = *Vec; 7564 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7565 } 7566 } 7567 7568 // C++ [over.match.oper]p16: 7569 // For every pointer to member type T, there exist candidate operator 7570 // functions of the form 7571 // 7572 // bool operator==(T,T); 7573 // bool operator!=(T,T); 7574 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7575 /// Set of (canonical) types that we've already handled. 7576 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7577 7578 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7579 for (BuiltinCandidateTypeSet::iterator 7580 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7581 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7582 MemPtr != MemPtrEnd; 7583 ++MemPtr) { 7584 // Don't add the same builtin candidate twice. 7585 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7586 continue; 7587 7588 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7589 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7590 } 7591 } 7592 } 7593 7594 // C++ [over.built]p15: 7595 // 7596 // For every T, where T is an enumeration type, a pointer type, or 7597 // std::nullptr_t, there exist candidate operator functions of the form 7598 // 7599 // bool operator<(T, T); 7600 // bool operator>(T, T); 7601 // bool operator<=(T, T); 7602 // bool operator>=(T, T); 7603 // bool operator==(T, T); 7604 // bool operator!=(T, T); 7605 void addRelationalPointerOrEnumeralOverloads() { 7606 // C++ [over.match.oper]p3: 7607 // [...]the built-in candidates include all of the candidate operator 7608 // functions defined in 13.6 that, compared to the given operator, [...] 7609 // do not have the same parameter-type-list as any non-template non-member 7610 // candidate. 7611 // 7612 // Note that in practice, this only affects enumeration types because there 7613 // aren't any built-in candidates of record type, and a user-defined operator 7614 // must have an operand of record or enumeration type. Also, the only other 7615 // overloaded operator with enumeration arguments, operator=, 7616 // cannot be overloaded for enumeration types, so this is the only place 7617 // where we must suppress candidates like this. 7618 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7619 UserDefinedBinaryOperators; 7620 7621 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7622 if (CandidateTypes[ArgIdx].enumeration_begin() != 7623 CandidateTypes[ArgIdx].enumeration_end()) { 7624 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7625 CEnd = CandidateSet.end(); 7626 C != CEnd; ++C) { 7627 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7628 continue; 7629 7630 if (C->Function->isFunctionTemplateSpecialization()) 7631 continue; 7632 7633 QualType FirstParamType = 7634 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7635 QualType SecondParamType = 7636 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7637 7638 // Skip if either parameter isn't of enumeral type. 7639 if (!FirstParamType->isEnumeralType() || 7640 !SecondParamType->isEnumeralType()) 7641 continue; 7642 7643 // Add this operator to the set of known user-defined operators. 7644 UserDefinedBinaryOperators.insert( 7645 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7646 S.Context.getCanonicalType(SecondParamType))); 7647 } 7648 } 7649 } 7650 7651 /// Set of (canonical) types that we've already handled. 7652 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7653 7654 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7655 for (BuiltinCandidateTypeSet::iterator 7656 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7657 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7658 Ptr != PtrEnd; ++Ptr) { 7659 // Don't add the same builtin candidate twice. 7660 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7661 continue; 7662 7663 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7664 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7665 } 7666 for (BuiltinCandidateTypeSet::iterator 7667 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7668 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7669 Enum != EnumEnd; ++Enum) { 7670 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7671 7672 // Don't add the same builtin candidate twice, or if a user defined 7673 // candidate exists. 7674 if (!AddedTypes.insert(CanonType).second || 7675 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7676 CanonType))) 7677 continue; 7678 7679 QualType ParamTypes[2] = { *Enum, *Enum }; 7680 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7681 } 7682 7683 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7684 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7685 if (AddedTypes.insert(NullPtrTy).second && 7686 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7687 NullPtrTy))) { 7688 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7689 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7690 CandidateSet); 7691 } 7692 } 7693 } 7694 } 7695 7696 // C++ [over.built]p13: 7697 // 7698 // For every cv-qualified or cv-unqualified object type T 7699 // there exist candidate operator functions of the form 7700 // 7701 // T* operator+(T*, ptrdiff_t); 7702 // T& operator[](T*, ptrdiff_t); [BELOW] 7703 // T* operator-(T*, ptrdiff_t); 7704 // T* operator+(ptrdiff_t, T*); 7705 // T& operator[](ptrdiff_t, T*); [BELOW] 7706 // 7707 // C++ [over.built]p14: 7708 // 7709 // For every T, where T is a pointer to object type, there 7710 // exist candidate operator functions of the form 7711 // 7712 // ptrdiff_t operator-(T, T); 7713 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7714 /// Set of (canonical) types that we've already handled. 7715 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7716 7717 for (int Arg = 0; Arg < 2; ++Arg) { 7718 QualType AsymmetricParamTypes[2] = { 7719 S.Context.getPointerDiffType(), 7720 S.Context.getPointerDiffType(), 7721 }; 7722 for (BuiltinCandidateTypeSet::iterator 7723 Ptr = CandidateTypes[Arg].pointer_begin(), 7724 PtrEnd = CandidateTypes[Arg].pointer_end(); 7725 Ptr != PtrEnd; ++Ptr) { 7726 QualType PointeeTy = (*Ptr)->getPointeeType(); 7727 if (!PointeeTy->isObjectType()) 7728 continue; 7729 7730 AsymmetricParamTypes[Arg] = *Ptr; 7731 if (Arg == 0 || Op == OO_Plus) { 7732 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7733 // T* operator+(ptrdiff_t, T*); 7734 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7735 } 7736 if (Op == OO_Minus) { 7737 // ptrdiff_t operator-(T, T); 7738 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7739 continue; 7740 7741 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7742 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7743 Args, CandidateSet); 7744 } 7745 } 7746 } 7747 } 7748 7749 // C++ [over.built]p12: 7750 // 7751 // For every pair of promoted arithmetic types L and R, there 7752 // exist candidate operator functions of the form 7753 // 7754 // LR operator*(L, R); 7755 // LR operator/(L, R); 7756 // LR operator+(L, R); 7757 // LR operator-(L, R); 7758 // bool operator<(L, R); 7759 // bool operator>(L, R); 7760 // bool operator<=(L, R); 7761 // bool operator>=(L, R); 7762 // bool operator==(L, R); 7763 // bool operator!=(L, R); 7764 // 7765 // where LR is the result of the usual arithmetic conversions 7766 // between types L and R. 7767 // 7768 // C++ [over.built]p24: 7769 // 7770 // For every pair of promoted arithmetic types L and R, there exist 7771 // candidate operator functions of the form 7772 // 7773 // LR operator?(bool, L, R); 7774 // 7775 // where LR is the result of the usual arithmetic conversions 7776 // between types L and R. 7777 // Our candidates ignore the first parameter. 7778 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7779 if (!HasArithmeticOrEnumeralCandidateType) 7780 return; 7781 7782 for (unsigned Left = FirstPromotedArithmeticType; 7783 Left < LastPromotedArithmeticType; ++Left) { 7784 for (unsigned Right = FirstPromotedArithmeticType; 7785 Right < LastPromotedArithmeticType; ++Right) { 7786 QualType LandR[2] = { getArithmeticType(Left), 7787 getArithmeticType(Right) }; 7788 QualType Result = 7789 isComparison ? S.Context.BoolTy 7790 : getUsualArithmeticConversions(Left, Right); 7791 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7792 } 7793 } 7794 7795 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7796 // conditional operator for vector types. 7797 for (BuiltinCandidateTypeSet::iterator 7798 Vec1 = CandidateTypes[0].vector_begin(), 7799 Vec1End = CandidateTypes[0].vector_end(); 7800 Vec1 != Vec1End; ++Vec1) { 7801 for (BuiltinCandidateTypeSet::iterator 7802 Vec2 = CandidateTypes[1].vector_begin(), 7803 Vec2End = CandidateTypes[1].vector_end(); 7804 Vec2 != Vec2End; ++Vec2) { 7805 QualType LandR[2] = { *Vec1, *Vec2 }; 7806 QualType Result = S.Context.BoolTy; 7807 if (!isComparison) { 7808 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7809 Result = *Vec1; 7810 else 7811 Result = *Vec2; 7812 } 7813 7814 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7815 } 7816 } 7817 } 7818 7819 // C++ [over.built]p17: 7820 // 7821 // For every pair of promoted integral types L and R, there 7822 // exist candidate operator functions of the form 7823 // 7824 // LR operator%(L, R); 7825 // LR operator&(L, R); 7826 // LR operator^(L, R); 7827 // LR operator|(L, R); 7828 // L operator<<(L, R); 7829 // L operator>>(L, R); 7830 // 7831 // where LR is the result of the usual arithmetic conversions 7832 // between types L and R. 7833 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7834 if (!HasArithmeticOrEnumeralCandidateType) 7835 return; 7836 7837 for (unsigned Left = FirstPromotedIntegralType; 7838 Left < LastPromotedIntegralType; ++Left) { 7839 for (unsigned Right = FirstPromotedIntegralType; 7840 Right < LastPromotedIntegralType; ++Right) { 7841 QualType LandR[2] = { getArithmeticType(Left), 7842 getArithmeticType(Right) }; 7843 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7844 ? LandR[0] 7845 : getUsualArithmeticConversions(Left, Right); 7846 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7847 } 7848 } 7849 } 7850 7851 // C++ [over.built]p20: 7852 // 7853 // For every pair (T, VQ), where T is an enumeration or 7854 // pointer to member type and VQ is either volatile or 7855 // empty, there exist candidate operator functions of the form 7856 // 7857 // VQ T& operator=(VQ T&, T); 7858 void addAssignmentMemberPointerOrEnumeralOverloads() { 7859 /// Set of (canonical) types that we've already handled. 7860 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7861 7862 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7863 for (BuiltinCandidateTypeSet::iterator 7864 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7865 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7866 Enum != EnumEnd; ++Enum) { 7867 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7868 continue; 7869 7870 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7871 } 7872 7873 for (BuiltinCandidateTypeSet::iterator 7874 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7875 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7876 MemPtr != MemPtrEnd; ++MemPtr) { 7877 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7878 continue; 7879 7880 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7881 } 7882 } 7883 } 7884 7885 // C++ [over.built]p19: 7886 // 7887 // For every pair (T, VQ), where T is any type and VQ is either 7888 // volatile or empty, there exist candidate operator functions 7889 // of the form 7890 // 7891 // T*VQ& operator=(T*VQ&, T*); 7892 // 7893 // C++ [over.built]p21: 7894 // 7895 // For every pair (T, VQ), where T is a cv-qualified or 7896 // cv-unqualified object type and VQ is either volatile or 7897 // empty, there exist candidate operator functions of the form 7898 // 7899 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7900 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7901 void addAssignmentPointerOverloads(bool isEqualOp) { 7902 /// Set of (canonical) types that we've already handled. 7903 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7904 7905 for (BuiltinCandidateTypeSet::iterator 7906 Ptr = CandidateTypes[0].pointer_begin(), 7907 PtrEnd = CandidateTypes[0].pointer_end(); 7908 Ptr != PtrEnd; ++Ptr) { 7909 // If this is operator=, keep track of the builtin candidates we added. 7910 if (isEqualOp) 7911 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7912 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7913 continue; 7914 7915 // non-volatile version 7916 QualType ParamTypes[2] = { 7917 S.Context.getLValueReferenceType(*Ptr), 7918 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7919 }; 7920 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7921 /*IsAssigmentOperator=*/ isEqualOp); 7922 7923 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7924 VisibleTypeConversionsQuals.hasVolatile(); 7925 if (NeedVolatile) { 7926 // volatile version 7927 ParamTypes[0] = 7928 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7929 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7930 /*IsAssigmentOperator=*/isEqualOp); 7931 } 7932 7933 if (!(*Ptr).isRestrictQualified() && 7934 VisibleTypeConversionsQuals.hasRestrict()) { 7935 // restrict version 7936 ParamTypes[0] 7937 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7938 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7939 /*IsAssigmentOperator=*/isEqualOp); 7940 7941 if (NeedVolatile) { 7942 // volatile restrict version 7943 ParamTypes[0] 7944 = S.Context.getLValueReferenceType( 7945 S.Context.getCVRQualifiedType(*Ptr, 7946 (Qualifiers::Volatile | 7947 Qualifiers::Restrict))); 7948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7949 /*IsAssigmentOperator=*/isEqualOp); 7950 } 7951 } 7952 } 7953 7954 if (isEqualOp) { 7955 for (BuiltinCandidateTypeSet::iterator 7956 Ptr = CandidateTypes[1].pointer_begin(), 7957 PtrEnd = CandidateTypes[1].pointer_end(); 7958 Ptr != PtrEnd; ++Ptr) { 7959 // Make sure we don't add the same candidate twice. 7960 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7961 continue; 7962 7963 QualType ParamTypes[2] = { 7964 S.Context.getLValueReferenceType(*Ptr), 7965 *Ptr, 7966 }; 7967 7968 // non-volatile version 7969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7970 /*IsAssigmentOperator=*/true); 7971 7972 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7973 VisibleTypeConversionsQuals.hasVolatile(); 7974 if (NeedVolatile) { 7975 // volatile version 7976 ParamTypes[0] = 7977 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7978 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7979 /*IsAssigmentOperator=*/true); 7980 } 7981 7982 if (!(*Ptr).isRestrictQualified() && 7983 VisibleTypeConversionsQuals.hasRestrict()) { 7984 // restrict version 7985 ParamTypes[0] 7986 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7987 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7988 /*IsAssigmentOperator=*/true); 7989 7990 if (NeedVolatile) { 7991 // volatile restrict version 7992 ParamTypes[0] 7993 = S.Context.getLValueReferenceType( 7994 S.Context.getCVRQualifiedType(*Ptr, 7995 (Qualifiers::Volatile | 7996 Qualifiers::Restrict))); 7997 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7998 /*IsAssigmentOperator=*/true); 7999 } 8000 } 8001 } 8002 } 8003 } 8004 8005 // C++ [over.built]p18: 8006 // 8007 // For every triple (L, VQ, R), where L is an arithmetic type, 8008 // VQ is either volatile or empty, and R is a promoted 8009 // arithmetic type, there exist candidate operator functions of 8010 // the form 8011 // 8012 // VQ L& operator=(VQ L&, R); 8013 // VQ L& operator*=(VQ L&, R); 8014 // VQ L& operator/=(VQ L&, R); 8015 // VQ L& operator+=(VQ L&, R); 8016 // VQ L& operator-=(VQ L&, R); 8017 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8018 if (!HasArithmeticOrEnumeralCandidateType) 8019 return; 8020 8021 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8022 for (unsigned Right = FirstPromotedArithmeticType; 8023 Right < LastPromotedArithmeticType; ++Right) { 8024 QualType ParamTypes[2]; 8025 ParamTypes[1] = getArithmeticType(Right); 8026 8027 // Add this built-in operator as a candidate (VQ is empty). 8028 ParamTypes[0] = 8029 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8030 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8031 /*IsAssigmentOperator=*/isEqualOp); 8032 8033 // Add this built-in operator as a candidate (VQ is 'volatile'). 8034 if (VisibleTypeConversionsQuals.hasVolatile()) { 8035 ParamTypes[0] = 8036 S.Context.getVolatileType(getArithmeticType(Left)); 8037 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8038 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8039 /*IsAssigmentOperator=*/isEqualOp); 8040 } 8041 } 8042 } 8043 8044 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8045 for (BuiltinCandidateTypeSet::iterator 8046 Vec1 = CandidateTypes[0].vector_begin(), 8047 Vec1End = CandidateTypes[0].vector_end(); 8048 Vec1 != Vec1End; ++Vec1) { 8049 for (BuiltinCandidateTypeSet::iterator 8050 Vec2 = CandidateTypes[1].vector_begin(), 8051 Vec2End = CandidateTypes[1].vector_end(); 8052 Vec2 != Vec2End; ++Vec2) { 8053 QualType ParamTypes[2]; 8054 ParamTypes[1] = *Vec2; 8055 // Add this built-in operator as a candidate (VQ is empty). 8056 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8057 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8058 /*IsAssigmentOperator=*/isEqualOp); 8059 8060 // Add this built-in operator as a candidate (VQ is 'volatile'). 8061 if (VisibleTypeConversionsQuals.hasVolatile()) { 8062 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8063 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8064 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8065 /*IsAssigmentOperator=*/isEqualOp); 8066 } 8067 } 8068 } 8069 } 8070 8071 // C++ [over.built]p22: 8072 // 8073 // For every triple (L, VQ, R), where L is an integral type, VQ 8074 // is either volatile or empty, and R is a promoted integral 8075 // type, there exist candidate operator functions of the form 8076 // 8077 // VQ L& operator%=(VQ L&, R); 8078 // VQ L& operator<<=(VQ L&, R); 8079 // VQ L& operator>>=(VQ L&, R); 8080 // VQ L& operator&=(VQ L&, R); 8081 // VQ L& operator^=(VQ L&, R); 8082 // VQ L& operator|=(VQ L&, R); 8083 void addAssignmentIntegralOverloads() { 8084 if (!HasArithmeticOrEnumeralCandidateType) 8085 return; 8086 8087 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8088 for (unsigned Right = FirstPromotedIntegralType; 8089 Right < LastPromotedIntegralType; ++Right) { 8090 QualType ParamTypes[2]; 8091 ParamTypes[1] = getArithmeticType(Right); 8092 8093 // Add this built-in operator as a candidate (VQ is empty). 8094 ParamTypes[0] = 8095 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8096 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8097 if (VisibleTypeConversionsQuals.hasVolatile()) { 8098 // Add this built-in operator as a candidate (VQ is 'volatile'). 8099 ParamTypes[0] = getArithmeticType(Left); 8100 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8101 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8102 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8103 } 8104 } 8105 } 8106 } 8107 8108 // C++ [over.operator]p23: 8109 // 8110 // There also exist candidate operator functions of the form 8111 // 8112 // bool operator!(bool); 8113 // bool operator&&(bool, bool); 8114 // bool operator||(bool, bool); 8115 void addExclaimOverload() { 8116 QualType ParamTy = S.Context.BoolTy; 8117 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8118 /*IsAssignmentOperator=*/false, 8119 /*NumContextualBoolArguments=*/1); 8120 } 8121 void addAmpAmpOrPipePipeOverload() { 8122 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8123 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8124 /*IsAssignmentOperator=*/false, 8125 /*NumContextualBoolArguments=*/2); 8126 } 8127 8128 // C++ [over.built]p13: 8129 // 8130 // For every cv-qualified or cv-unqualified object type T there 8131 // exist candidate operator functions of the form 8132 // 8133 // T* operator+(T*, ptrdiff_t); [ABOVE] 8134 // T& operator[](T*, ptrdiff_t); 8135 // T* operator-(T*, ptrdiff_t); [ABOVE] 8136 // T* operator+(ptrdiff_t, T*); [ABOVE] 8137 // T& operator[](ptrdiff_t, T*); 8138 void addSubscriptOverloads() { 8139 for (BuiltinCandidateTypeSet::iterator 8140 Ptr = CandidateTypes[0].pointer_begin(), 8141 PtrEnd = CandidateTypes[0].pointer_end(); 8142 Ptr != PtrEnd; ++Ptr) { 8143 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8144 QualType PointeeType = (*Ptr)->getPointeeType(); 8145 if (!PointeeType->isObjectType()) 8146 continue; 8147 8148 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8149 8150 // T& operator[](T*, ptrdiff_t) 8151 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8152 } 8153 8154 for (BuiltinCandidateTypeSet::iterator 8155 Ptr = CandidateTypes[1].pointer_begin(), 8156 PtrEnd = CandidateTypes[1].pointer_end(); 8157 Ptr != PtrEnd; ++Ptr) { 8158 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8159 QualType PointeeType = (*Ptr)->getPointeeType(); 8160 if (!PointeeType->isObjectType()) 8161 continue; 8162 8163 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8164 8165 // T& operator[](ptrdiff_t, T*) 8166 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8167 } 8168 } 8169 8170 // C++ [over.built]p11: 8171 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8172 // C1 is the same type as C2 or is a derived class of C2, T is an object 8173 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8174 // there exist candidate operator functions of the form 8175 // 8176 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8177 // 8178 // where CV12 is the union of CV1 and CV2. 8179 void addArrowStarOverloads() { 8180 for (BuiltinCandidateTypeSet::iterator 8181 Ptr = CandidateTypes[0].pointer_begin(), 8182 PtrEnd = CandidateTypes[0].pointer_end(); 8183 Ptr != PtrEnd; ++Ptr) { 8184 QualType C1Ty = (*Ptr); 8185 QualType C1; 8186 QualifierCollector Q1; 8187 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8188 if (!isa<RecordType>(C1)) 8189 continue; 8190 // heuristic to reduce number of builtin candidates in the set. 8191 // Add volatile/restrict version only if there are conversions to a 8192 // volatile/restrict type. 8193 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8194 continue; 8195 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8196 continue; 8197 for (BuiltinCandidateTypeSet::iterator 8198 MemPtr = CandidateTypes[1].member_pointer_begin(), 8199 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8200 MemPtr != MemPtrEnd; ++MemPtr) { 8201 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8202 QualType C2 = QualType(mptr->getClass(), 0); 8203 C2 = C2.getUnqualifiedType(); 8204 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8205 break; 8206 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8207 // build CV12 T& 8208 QualType T = mptr->getPointeeType(); 8209 if (!VisibleTypeConversionsQuals.hasVolatile() && 8210 T.isVolatileQualified()) 8211 continue; 8212 if (!VisibleTypeConversionsQuals.hasRestrict() && 8213 T.isRestrictQualified()) 8214 continue; 8215 T = Q1.apply(S.Context, T); 8216 QualType ResultTy = S.Context.getLValueReferenceType(T); 8217 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8218 } 8219 } 8220 } 8221 8222 // Note that we don't consider the first argument, since it has been 8223 // contextually converted to bool long ago. The candidates below are 8224 // therefore added as binary. 8225 // 8226 // C++ [over.built]p25: 8227 // For every type T, where T is a pointer, pointer-to-member, or scoped 8228 // enumeration type, there exist candidate operator functions of the form 8229 // 8230 // T operator?(bool, T, T); 8231 // 8232 void addConditionalOperatorOverloads() { 8233 /// Set of (canonical) types that we've already handled. 8234 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8235 8236 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8237 for (BuiltinCandidateTypeSet::iterator 8238 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8239 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8240 Ptr != PtrEnd; ++Ptr) { 8241 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8242 continue; 8243 8244 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8245 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8246 } 8247 8248 for (BuiltinCandidateTypeSet::iterator 8249 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8250 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8251 MemPtr != MemPtrEnd; ++MemPtr) { 8252 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8253 continue; 8254 8255 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8256 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8257 } 8258 8259 if (S.getLangOpts().CPlusPlus11) { 8260 for (BuiltinCandidateTypeSet::iterator 8261 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8262 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8263 Enum != EnumEnd; ++Enum) { 8264 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8265 continue; 8266 8267 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8268 continue; 8269 8270 QualType ParamTypes[2] = { *Enum, *Enum }; 8271 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8272 } 8273 } 8274 } 8275 } 8276 }; 8277 8278 } // end anonymous namespace 8279 8280 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8281 /// operator overloads to the candidate set (C++ [over.built]), based 8282 /// on the operator @p Op and the arguments given. For example, if the 8283 /// operator is a binary '+', this routine might add "int 8284 /// operator+(int, int)" to cover integer addition. 8285 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8286 SourceLocation OpLoc, 8287 ArrayRef<Expr *> Args, 8288 OverloadCandidateSet &CandidateSet) { 8289 // Find all of the types that the arguments can convert to, but only 8290 // if the operator we're looking at has built-in operator candidates 8291 // that make use of these types. Also record whether we encounter non-record 8292 // candidate types or either arithmetic or enumeral candidate types. 8293 Qualifiers VisibleTypeConversionsQuals; 8294 VisibleTypeConversionsQuals.addConst(); 8295 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8296 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8297 8298 bool HasNonRecordCandidateType = false; 8299 bool HasArithmeticOrEnumeralCandidateType = false; 8300 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8301 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8302 CandidateTypes.emplace_back(*this); 8303 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8304 OpLoc, 8305 true, 8306 (Op == OO_Exclaim || 8307 Op == OO_AmpAmp || 8308 Op == OO_PipePipe), 8309 VisibleTypeConversionsQuals); 8310 HasNonRecordCandidateType = HasNonRecordCandidateType || 8311 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8312 HasArithmeticOrEnumeralCandidateType = 8313 HasArithmeticOrEnumeralCandidateType || 8314 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8315 } 8316 8317 // Exit early when no non-record types have been added to the candidate set 8318 // for any of the arguments to the operator. 8319 // 8320 // We can't exit early for !, ||, or &&, since there we have always have 8321 // 'bool' overloads. 8322 if (!HasNonRecordCandidateType && 8323 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8324 return; 8325 8326 // Setup an object to manage the common state for building overloads. 8327 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8328 VisibleTypeConversionsQuals, 8329 HasArithmeticOrEnumeralCandidateType, 8330 CandidateTypes, CandidateSet); 8331 8332 // Dispatch over the operation to add in only those overloads which apply. 8333 switch (Op) { 8334 case OO_None: 8335 case NUM_OVERLOADED_OPERATORS: 8336 llvm_unreachable("Expected an overloaded operator"); 8337 8338 case OO_New: 8339 case OO_Delete: 8340 case OO_Array_New: 8341 case OO_Array_Delete: 8342 case OO_Call: 8343 llvm_unreachable( 8344 "Special operators don't use AddBuiltinOperatorCandidates"); 8345 8346 case OO_Comma: 8347 case OO_Arrow: 8348 case OO_Coawait: 8349 // C++ [over.match.oper]p3: 8350 // -- For the operator ',', the unary operator '&', the 8351 // operator '->', or the operator 'co_await', the 8352 // built-in candidates set is empty. 8353 break; 8354 8355 case OO_Plus: // '+' is either unary or binary 8356 if (Args.size() == 1) 8357 OpBuilder.addUnaryPlusPointerOverloads(); 8358 // Fall through. 8359 8360 case OO_Minus: // '-' is either unary or binary 8361 if (Args.size() == 1) { 8362 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8363 } else { 8364 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8365 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8366 } 8367 break; 8368 8369 case OO_Star: // '*' is either unary or binary 8370 if (Args.size() == 1) 8371 OpBuilder.addUnaryStarPointerOverloads(); 8372 else 8373 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8374 break; 8375 8376 case OO_Slash: 8377 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8378 break; 8379 8380 case OO_PlusPlus: 8381 case OO_MinusMinus: 8382 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8383 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8384 break; 8385 8386 case OO_EqualEqual: 8387 case OO_ExclaimEqual: 8388 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8389 // Fall through. 8390 8391 case OO_Less: 8392 case OO_Greater: 8393 case OO_LessEqual: 8394 case OO_GreaterEqual: 8395 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8396 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8397 break; 8398 8399 case OO_Percent: 8400 case OO_Caret: 8401 case OO_Pipe: 8402 case OO_LessLess: 8403 case OO_GreaterGreater: 8404 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8405 break; 8406 8407 case OO_Amp: // '&' is either unary or binary 8408 if (Args.size() == 1) 8409 // C++ [over.match.oper]p3: 8410 // -- For the operator ',', the unary operator '&', or the 8411 // operator '->', the built-in candidates set is empty. 8412 break; 8413 8414 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8415 break; 8416 8417 case OO_Tilde: 8418 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8419 break; 8420 8421 case OO_Equal: 8422 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8423 // Fall through. 8424 8425 case OO_PlusEqual: 8426 case OO_MinusEqual: 8427 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8428 // Fall through. 8429 8430 case OO_StarEqual: 8431 case OO_SlashEqual: 8432 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8433 break; 8434 8435 case OO_PercentEqual: 8436 case OO_LessLessEqual: 8437 case OO_GreaterGreaterEqual: 8438 case OO_AmpEqual: 8439 case OO_CaretEqual: 8440 case OO_PipeEqual: 8441 OpBuilder.addAssignmentIntegralOverloads(); 8442 break; 8443 8444 case OO_Exclaim: 8445 OpBuilder.addExclaimOverload(); 8446 break; 8447 8448 case OO_AmpAmp: 8449 case OO_PipePipe: 8450 OpBuilder.addAmpAmpOrPipePipeOverload(); 8451 break; 8452 8453 case OO_Subscript: 8454 OpBuilder.addSubscriptOverloads(); 8455 break; 8456 8457 case OO_ArrowStar: 8458 OpBuilder.addArrowStarOverloads(); 8459 break; 8460 8461 case OO_Conditional: 8462 OpBuilder.addConditionalOperatorOverloads(); 8463 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8464 break; 8465 } 8466 } 8467 8468 /// \brief Add function candidates found via argument-dependent lookup 8469 /// to the set of overloading candidates. 8470 /// 8471 /// This routine performs argument-dependent name lookup based on the 8472 /// given function name (which may also be an operator name) and adds 8473 /// all of the overload candidates found by ADL to the overload 8474 /// candidate set (C++ [basic.lookup.argdep]). 8475 void 8476 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8477 SourceLocation Loc, 8478 ArrayRef<Expr *> Args, 8479 TemplateArgumentListInfo *ExplicitTemplateArgs, 8480 OverloadCandidateSet& CandidateSet, 8481 bool PartialOverloading) { 8482 ADLResult Fns; 8483 8484 // FIXME: This approach for uniquing ADL results (and removing 8485 // redundant candidates from the set) relies on pointer-equality, 8486 // which means we need to key off the canonical decl. However, 8487 // always going back to the canonical decl might not get us the 8488 // right set of default arguments. What default arguments are 8489 // we supposed to consider on ADL candidates, anyway? 8490 8491 // FIXME: Pass in the explicit template arguments? 8492 ArgumentDependentLookup(Name, Loc, Args, Fns); 8493 8494 // Erase all of the candidates we already knew about. 8495 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8496 CandEnd = CandidateSet.end(); 8497 Cand != CandEnd; ++Cand) 8498 if (Cand->Function) { 8499 Fns.erase(Cand->Function); 8500 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8501 Fns.erase(FunTmpl); 8502 } 8503 8504 // For each of the ADL candidates we found, add it to the overload 8505 // set. 8506 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8507 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8508 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8509 if (ExplicitTemplateArgs) 8510 continue; 8511 8512 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8513 PartialOverloading); 8514 } else 8515 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8516 FoundDecl, ExplicitTemplateArgs, 8517 Args, CandidateSet, PartialOverloading); 8518 } 8519 } 8520 8521 namespace { 8522 enum class Comparison { Equal, Better, Worse }; 8523 } 8524 8525 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8526 /// overload resolution. 8527 /// 8528 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8529 /// Cand1's first N enable_if attributes have precisely the same conditions as 8530 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8531 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8532 /// 8533 /// Note that you can have a pair of candidates such that Cand1's enable_if 8534 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8535 /// worse than Cand1's. 8536 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8537 const FunctionDecl *Cand2) { 8538 // Common case: One (or both) decls don't have enable_if attrs. 8539 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8540 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8541 if (!Cand1Attr || !Cand2Attr) { 8542 if (Cand1Attr == Cand2Attr) 8543 return Comparison::Equal; 8544 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8545 } 8546 8547 // FIXME: The next several lines are just 8548 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8549 // instead of reverse order which is how they're stored in the AST. 8550 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8551 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8552 8553 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8554 // has fewer enable_if attributes than Cand2. 8555 if (Cand1Attrs.size() < Cand2Attrs.size()) 8556 return Comparison::Worse; 8557 8558 auto Cand1I = Cand1Attrs.begin(); 8559 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8560 for (auto &Cand2A : Cand2Attrs) { 8561 Cand1ID.clear(); 8562 Cand2ID.clear(); 8563 8564 auto &Cand1A = *Cand1I++; 8565 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8566 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8567 if (Cand1ID != Cand2ID) 8568 return Comparison::Worse; 8569 } 8570 8571 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8572 } 8573 8574 /// isBetterOverloadCandidate - Determines whether the first overload 8575 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8576 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8577 const OverloadCandidate &Cand2, 8578 SourceLocation Loc, 8579 bool UserDefinedConversion) { 8580 // Define viable functions to be better candidates than non-viable 8581 // functions. 8582 if (!Cand2.Viable) 8583 return Cand1.Viable; 8584 else if (!Cand1.Viable) 8585 return false; 8586 8587 // C++ [over.match.best]p1: 8588 // 8589 // -- if F is a static member function, ICS1(F) is defined such 8590 // that ICS1(F) is neither better nor worse than ICS1(G) for 8591 // any function G, and, symmetrically, ICS1(G) is neither 8592 // better nor worse than ICS1(F). 8593 unsigned StartArg = 0; 8594 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8595 StartArg = 1; 8596 8597 // C++ [over.match.best]p1: 8598 // A viable function F1 is defined to be a better function than another 8599 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8600 // conversion sequence than ICSi(F2), and then... 8601 unsigned NumArgs = Cand1.NumConversions; 8602 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8603 bool HasBetterConversion = false; 8604 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8605 switch (CompareImplicitConversionSequences(S, Loc, 8606 Cand1.Conversions[ArgIdx], 8607 Cand2.Conversions[ArgIdx])) { 8608 case ImplicitConversionSequence::Better: 8609 // Cand1 has a better conversion sequence. 8610 HasBetterConversion = true; 8611 break; 8612 8613 case ImplicitConversionSequence::Worse: 8614 // Cand1 can't be better than Cand2. 8615 return false; 8616 8617 case ImplicitConversionSequence::Indistinguishable: 8618 // Do nothing. 8619 break; 8620 } 8621 } 8622 8623 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8624 // ICSj(F2), or, if not that, 8625 if (HasBetterConversion) 8626 return true; 8627 8628 // -- the context is an initialization by user-defined conversion 8629 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8630 // from the return type of F1 to the destination type (i.e., 8631 // the type of the entity being initialized) is a better 8632 // conversion sequence than the standard conversion sequence 8633 // from the return type of F2 to the destination type. 8634 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8635 isa<CXXConversionDecl>(Cand1.Function) && 8636 isa<CXXConversionDecl>(Cand2.Function)) { 8637 // First check whether we prefer one of the conversion functions over the 8638 // other. This only distinguishes the results in non-standard, extension 8639 // cases such as the conversion from a lambda closure type to a function 8640 // pointer or block. 8641 ImplicitConversionSequence::CompareKind Result = 8642 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8643 if (Result == ImplicitConversionSequence::Indistinguishable) 8644 Result = CompareStandardConversionSequences(S, Loc, 8645 Cand1.FinalConversion, 8646 Cand2.FinalConversion); 8647 8648 if (Result != ImplicitConversionSequence::Indistinguishable) 8649 return Result == ImplicitConversionSequence::Better; 8650 8651 // FIXME: Compare kind of reference binding if conversion functions 8652 // convert to a reference type used in direct reference binding, per 8653 // C++14 [over.match.best]p1 section 2 bullet 3. 8654 } 8655 8656 // -- F1 is a non-template function and F2 is a function template 8657 // specialization, or, if not that, 8658 bool Cand1IsSpecialization = Cand1.Function && 8659 Cand1.Function->getPrimaryTemplate(); 8660 bool Cand2IsSpecialization = Cand2.Function && 8661 Cand2.Function->getPrimaryTemplate(); 8662 if (Cand1IsSpecialization != Cand2IsSpecialization) 8663 return Cand2IsSpecialization; 8664 8665 // -- F1 and F2 are function template specializations, and the function 8666 // template for F1 is more specialized than the template for F2 8667 // according to the partial ordering rules described in 14.5.5.2, or, 8668 // if not that, 8669 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8670 if (FunctionTemplateDecl *BetterTemplate 8671 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8672 Cand2.Function->getPrimaryTemplate(), 8673 Loc, 8674 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8675 : TPOC_Call, 8676 Cand1.ExplicitCallArguments, 8677 Cand2.ExplicitCallArguments)) 8678 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8679 } 8680 8681 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8682 // A derived-class constructor beats an (inherited) base class constructor. 8683 bool Cand1IsInherited = 8684 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8685 bool Cand2IsInherited = 8686 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8687 if (Cand1IsInherited != Cand2IsInherited) 8688 return Cand2IsInherited; 8689 else if (Cand1IsInherited) { 8690 assert(Cand2IsInherited); 8691 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8692 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8693 if (Cand1Class->isDerivedFrom(Cand2Class)) 8694 return true; 8695 if (Cand2Class->isDerivedFrom(Cand1Class)) 8696 return false; 8697 // Inherited from sibling base classes: still ambiguous. 8698 } 8699 8700 // Check for enable_if value-based overload resolution. 8701 if (Cand1.Function && Cand2.Function) { 8702 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8703 if (Cmp != Comparison::Equal) 8704 return Cmp == Comparison::Better; 8705 } 8706 8707 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8708 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8709 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8710 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8711 } 8712 8713 bool HasPS1 = Cand1.Function != nullptr && 8714 functionHasPassObjectSizeParams(Cand1.Function); 8715 bool HasPS2 = Cand2.Function != nullptr && 8716 functionHasPassObjectSizeParams(Cand2.Function); 8717 return HasPS1 != HasPS2 && HasPS1; 8718 } 8719 8720 /// Determine whether two declarations are "equivalent" for the purposes of 8721 /// name lookup and overload resolution. This applies when the same internal/no 8722 /// linkage entity is defined by two modules (probably by textually including 8723 /// the same header). In such a case, we don't consider the declarations to 8724 /// declare the same entity, but we also don't want lookups with both 8725 /// declarations visible to be ambiguous in some cases (this happens when using 8726 /// a modularized libstdc++). 8727 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8728 const NamedDecl *B) { 8729 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8730 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8731 if (!VA || !VB) 8732 return false; 8733 8734 // The declarations must be declaring the same name as an internal linkage 8735 // entity in different modules. 8736 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8737 VB->getDeclContext()->getRedeclContext()) || 8738 getOwningModule(const_cast<ValueDecl *>(VA)) == 8739 getOwningModule(const_cast<ValueDecl *>(VB)) || 8740 VA->isExternallyVisible() || VB->isExternallyVisible()) 8741 return false; 8742 8743 // Check that the declarations appear to be equivalent. 8744 // 8745 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8746 // For constants and functions, we should check the initializer or body is 8747 // the same. For non-constant variables, we shouldn't allow it at all. 8748 if (Context.hasSameType(VA->getType(), VB->getType())) 8749 return true; 8750 8751 // Enum constants within unnamed enumerations will have different types, but 8752 // may still be similar enough to be interchangeable for our purposes. 8753 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8754 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8755 // Only handle anonymous enums. If the enumerations were named and 8756 // equivalent, they would have been merged to the same type. 8757 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8758 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8759 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8760 !Context.hasSameType(EnumA->getIntegerType(), 8761 EnumB->getIntegerType())) 8762 return false; 8763 // Allow this only if the value is the same for both enumerators. 8764 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8765 } 8766 } 8767 8768 // Nothing else is sufficiently similar. 8769 return false; 8770 } 8771 8772 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8773 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8774 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8775 8776 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8777 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8778 << !M << (M ? M->getFullModuleName() : ""); 8779 8780 for (auto *E : Equiv) { 8781 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8782 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8783 << !M << (M ? M->getFullModuleName() : ""); 8784 } 8785 } 8786 8787 /// \brief Computes the best viable function (C++ 13.3.3) 8788 /// within an overload candidate set. 8789 /// 8790 /// \param Loc The location of the function name (or operator symbol) for 8791 /// which overload resolution occurs. 8792 /// 8793 /// \param Best If overload resolution was successful or found a deleted 8794 /// function, \p Best points to the candidate function found. 8795 /// 8796 /// \returns The result of overload resolution. 8797 OverloadingResult 8798 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8799 iterator &Best, 8800 bool UserDefinedConversion) { 8801 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8802 std::transform(begin(), end(), std::back_inserter(Candidates), 8803 [](OverloadCandidate &Cand) { return &Cand; }); 8804 8805 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8806 // are accepted by both clang and NVCC. However, during a particular 8807 // compilation mode only one call variant is viable. We need to 8808 // exclude non-viable overload candidates from consideration based 8809 // only on their host/device attributes. Specifically, if one 8810 // candidate call is WrongSide and the other is SameSide, we ignore 8811 // the WrongSide candidate. 8812 if (S.getLangOpts().CUDA) { 8813 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8814 bool ContainsSameSideCandidate = 8815 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8816 return Cand->Function && 8817 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8818 Sema::CFP_SameSide; 8819 }); 8820 if (ContainsSameSideCandidate) { 8821 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8822 return Cand->Function && 8823 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8824 Sema::CFP_WrongSide; 8825 }; 8826 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8827 IsWrongSideCandidate), 8828 Candidates.end()); 8829 } 8830 } 8831 8832 // Find the best viable function. 8833 Best = end(); 8834 for (auto *Cand : Candidates) 8835 if (Cand->Viable) 8836 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8837 UserDefinedConversion)) 8838 Best = Cand; 8839 8840 // If we didn't find any viable functions, abort. 8841 if (Best == end()) 8842 return OR_No_Viable_Function; 8843 8844 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8845 8846 // Make sure that this function is better than every other viable 8847 // function. If not, we have an ambiguity. 8848 for (auto *Cand : Candidates) { 8849 if (Cand->Viable && 8850 Cand != Best && 8851 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8852 UserDefinedConversion)) { 8853 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8854 Cand->Function)) { 8855 EquivalentCands.push_back(Cand->Function); 8856 continue; 8857 } 8858 8859 Best = end(); 8860 return OR_Ambiguous; 8861 } 8862 } 8863 8864 // Best is the best viable function. 8865 if (Best->Function && 8866 (Best->Function->isDeleted() || 8867 S.isFunctionConsideredUnavailable(Best->Function))) 8868 return OR_Deleted; 8869 8870 if (!EquivalentCands.empty()) 8871 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8872 EquivalentCands); 8873 8874 return OR_Success; 8875 } 8876 8877 namespace { 8878 8879 enum OverloadCandidateKind { 8880 oc_function, 8881 oc_method, 8882 oc_constructor, 8883 oc_function_template, 8884 oc_method_template, 8885 oc_constructor_template, 8886 oc_implicit_default_constructor, 8887 oc_implicit_copy_constructor, 8888 oc_implicit_move_constructor, 8889 oc_implicit_copy_assignment, 8890 oc_implicit_move_assignment, 8891 oc_inherited_constructor, 8892 oc_inherited_constructor_template 8893 }; 8894 8895 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8896 NamedDecl *Found, 8897 FunctionDecl *Fn, 8898 std::string &Description) { 8899 bool isTemplate = false; 8900 8901 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8902 isTemplate = true; 8903 Description = S.getTemplateArgumentBindingsText( 8904 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8905 } 8906 8907 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8908 if (!Ctor->isImplicit()) { 8909 if (isa<ConstructorUsingShadowDecl>(Found)) 8910 return isTemplate ? oc_inherited_constructor_template 8911 : oc_inherited_constructor; 8912 else 8913 return isTemplate ? oc_constructor_template : oc_constructor; 8914 } 8915 8916 if (Ctor->isDefaultConstructor()) 8917 return oc_implicit_default_constructor; 8918 8919 if (Ctor->isMoveConstructor()) 8920 return oc_implicit_move_constructor; 8921 8922 assert(Ctor->isCopyConstructor() && 8923 "unexpected sort of implicit constructor"); 8924 return oc_implicit_copy_constructor; 8925 } 8926 8927 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8928 // This actually gets spelled 'candidate function' for now, but 8929 // it doesn't hurt to split it out. 8930 if (!Meth->isImplicit()) 8931 return isTemplate ? oc_method_template : oc_method; 8932 8933 if (Meth->isMoveAssignmentOperator()) 8934 return oc_implicit_move_assignment; 8935 8936 if (Meth->isCopyAssignmentOperator()) 8937 return oc_implicit_copy_assignment; 8938 8939 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8940 return oc_method; 8941 } 8942 8943 return isTemplate ? oc_function_template : oc_function; 8944 } 8945 8946 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 8947 // FIXME: It'd be nice to only emit a note once per using-decl per overload 8948 // set. 8949 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 8950 S.Diag(FoundDecl->getLocation(), 8951 diag::note_ovl_candidate_inherited_constructor) 8952 << Shadow->getNominatedBaseClass(); 8953 } 8954 8955 } // end anonymous namespace 8956 8957 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8958 const FunctionDecl *FD) { 8959 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8960 bool AlwaysTrue; 8961 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8962 return false; 8963 if (!AlwaysTrue) 8964 return false; 8965 } 8966 return true; 8967 } 8968 8969 /// \brief Returns true if we can take the address of the function. 8970 /// 8971 /// \param Complain - If true, we'll emit a diagnostic 8972 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8973 /// we in overload resolution? 8974 /// \param Loc - The location of the statement we're complaining about. Ignored 8975 /// if we're not complaining, or if we're in overload resolution. 8976 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8977 bool Complain, 8978 bool InOverloadResolution, 8979 SourceLocation Loc) { 8980 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8981 if (Complain) { 8982 if (InOverloadResolution) 8983 S.Diag(FD->getLocStart(), 8984 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8985 else 8986 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8987 } 8988 return false; 8989 } 8990 8991 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 8992 return P->hasAttr<PassObjectSizeAttr>(); 8993 }); 8994 if (I == FD->param_end()) 8995 return true; 8996 8997 if (Complain) { 8998 // Add one to ParamNo because it's user-facing 8999 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9000 if (InOverloadResolution) 9001 S.Diag(FD->getLocation(), 9002 diag::note_ovl_candidate_has_pass_object_size_params) 9003 << ParamNo; 9004 else 9005 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9006 << FD << ParamNo; 9007 } 9008 return false; 9009 } 9010 9011 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9012 const FunctionDecl *FD) { 9013 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9014 /*InOverloadResolution=*/true, 9015 /*Loc=*/SourceLocation()); 9016 } 9017 9018 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9019 bool Complain, 9020 SourceLocation Loc) { 9021 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9022 /*InOverloadResolution=*/false, 9023 Loc); 9024 } 9025 9026 // Notes the location of an overload candidate. 9027 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9028 QualType DestType, bool TakingAddress) { 9029 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9030 return; 9031 9032 std::string FnDesc; 9033 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9034 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9035 << (unsigned) K << FnDesc; 9036 9037 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9038 Diag(Fn->getLocation(), PD); 9039 MaybeEmitInheritedConstructorNote(*this, Found); 9040 } 9041 9042 // Notes the location of all overload candidates designated through 9043 // OverloadedExpr 9044 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9045 bool TakingAddress) { 9046 assert(OverloadedExpr->getType() == Context.OverloadTy); 9047 9048 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9049 OverloadExpr *OvlExpr = Ovl.Expression; 9050 9051 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9052 IEnd = OvlExpr->decls_end(); 9053 I != IEnd; ++I) { 9054 if (FunctionTemplateDecl *FunTmpl = 9055 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9056 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9057 TakingAddress); 9058 } else if (FunctionDecl *Fun 9059 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9060 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9061 } 9062 } 9063 } 9064 9065 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9066 /// "lead" diagnostic; it will be given two arguments, the source and 9067 /// target types of the conversion. 9068 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9069 Sema &S, 9070 SourceLocation CaretLoc, 9071 const PartialDiagnostic &PDiag) const { 9072 S.Diag(CaretLoc, PDiag) 9073 << Ambiguous.getFromType() << Ambiguous.getToType(); 9074 // FIXME: The note limiting machinery is borrowed from 9075 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9076 // refactoring here. 9077 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9078 unsigned CandsShown = 0; 9079 AmbiguousConversionSequence::const_iterator I, E; 9080 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9081 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9082 break; 9083 ++CandsShown; 9084 S.NoteOverloadCandidate(I->first, I->second); 9085 } 9086 if (I != E) 9087 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9088 } 9089 9090 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9091 unsigned I, bool TakingCandidateAddress) { 9092 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9093 assert(Conv.isBad()); 9094 assert(Cand->Function && "for now, candidate must be a function"); 9095 FunctionDecl *Fn = Cand->Function; 9096 9097 // There's a conversion slot for the object argument if this is a 9098 // non-constructor method. Note that 'I' corresponds the 9099 // conversion-slot index. 9100 bool isObjectArgument = false; 9101 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9102 if (I == 0) 9103 isObjectArgument = true; 9104 else 9105 I--; 9106 } 9107 9108 std::string FnDesc; 9109 OverloadCandidateKind FnKind = 9110 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9111 9112 Expr *FromExpr = Conv.Bad.FromExpr; 9113 QualType FromTy = Conv.Bad.getFromType(); 9114 QualType ToTy = Conv.Bad.getToType(); 9115 9116 if (FromTy == S.Context.OverloadTy) { 9117 assert(FromExpr && "overload set argument came from implicit argument?"); 9118 Expr *E = FromExpr->IgnoreParens(); 9119 if (isa<UnaryOperator>(E)) 9120 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9121 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9122 9123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9124 << (unsigned) FnKind << FnDesc 9125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9126 << ToTy << Name << I+1; 9127 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9128 return; 9129 } 9130 9131 // Do some hand-waving analysis to see if the non-viability is due 9132 // to a qualifier mismatch. 9133 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9134 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9135 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9136 CToTy = RT->getPointeeType(); 9137 else { 9138 // TODO: detect and diagnose the full richness of const mismatches. 9139 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9140 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9141 CFromTy = FromPT->getPointeeType(); 9142 CToTy = ToPT->getPointeeType(); 9143 } 9144 } 9145 9146 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9147 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9148 Qualifiers FromQs = CFromTy.getQualifiers(); 9149 Qualifiers ToQs = CToTy.getQualifiers(); 9150 9151 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9153 << (unsigned) FnKind << FnDesc 9154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9155 << FromTy 9156 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9157 << (unsigned) isObjectArgument << I+1; 9158 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9159 return; 9160 } 9161 9162 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9164 << (unsigned) FnKind << FnDesc 9165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9166 << FromTy 9167 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9168 << (unsigned) isObjectArgument << I+1; 9169 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9170 return; 9171 } 9172 9173 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9175 << (unsigned) FnKind << FnDesc 9176 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9177 << FromTy 9178 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9179 << (unsigned) isObjectArgument << I+1; 9180 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9181 return; 9182 } 9183 9184 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9185 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9186 << (unsigned) FnKind << FnDesc 9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9188 << FromTy << FromQs.hasUnaligned() << I+1; 9189 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9190 return; 9191 } 9192 9193 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9194 assert(CVR && "unexpected qualifiers mismatch"); 9195 9196 if (isObjectArgument) { 9197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9198 << (unsigned) FnKind << FnDesc 9199 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9200 << FromTy << (CVR - 1); 9201 } else { 9202 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9203 << (unsigned) FnKind << FnDesc 9204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9205 << FromTy << (CVR - 1) << I+1; 9206 } 9207 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9208 return; 9209 } 9210 9211 // Special diagnostic for failure to convert an initializer list, since 9212 // telling the user that it has type void is not useful. 9213 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9214 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9215 << (unsigned) FnKind << FnDesc 9216 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9217 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9219 return; 9220 } 9221 9222 // Diagnose references or pointers to incomplete types differently, 9223 // since it's far from impossible that the incompleteness triggered 9224 // the failure. 9225 QualType TempFromTy = FromTy.getNonReferenceType(); 9226 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9227 TempFromTy = PTy->getPointeeType(); 9228 if (TempFromTy->isIncompleteType()) { 9229 // Emit the generic diagnostic and, optionally, add the hints to it. 9230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9231 << (unsigned) FnKind << FnDesc 9232 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9233 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9234 << (unsigned) (Cand->Fix.Kind); 9235 9236 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9237 return; 9238 } 9239 9240 // Diagnose base -> derived pointer conversions. 9241 unsigned BaseToDerivedConversion = 0; 9242 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9243 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9244 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9245 FromPtrTy->getPointeeType()) && 9246 !FromPtrTy->getPointeeType()->isIncompleteType() && 9247 !ToPtrTy->getPointeeType()->isIncompleteType() && 9248 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9249 FromPtrTy->getPointeeType())) 9250 BaseToDerivedConversion = 1; 9251 } 9252 } else if (const ObjCObjectPointerType *FromPtrTy 9253 = FromTy->getAs<ObjCObjectPointerType>()) { 9254 if (const ObjCObjectPointerType *ToPtrTy 9255 = ToTy->getAs<ObjCObjectPointerType>()) 9256 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9257 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9258 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9259 FromPtrTy->getPointeeType()) && 9260 FromIface->isSuperClassOf(ToIface)) 9261 BaseToDerivedConversion = 2; 9262 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9263 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9264 !FromTy->isIncompleteType() && 9265 !ToRefTy->getPointeeType()->isIncompleteType() && 9266 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9267 BaseToDerivedConversion = 3; 9268 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9269 ToTy.getNonReferenceType().getCanonicalType() == 9270 FromTy.getNonReferenceType().getCanonicalType()) { 9271 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9272 << (unsigned) FnKind << FnDesc 9273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9274 << (unsigned) isObjectArgument << I + 1; 9275 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9276 return; 9277 } 9278 } 9279 9280 if (BaseToDerivedConversion) { 9281 S.Diag(Fn->getLocation(), 9282 diag::note_ovl_candidate_bad_base_to_derived_conv) 9283 << (unsigned) FnKind << FnDesc 9284 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9285 << (BaseToDerivedConversion - 1) 9286 << FromTy << ToTy << I+1; 9287 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9288 return; 9289 } 9290 9291 if (isa<ObjCObjectPointerType>(CFromTy) && 9292 isa<PointerType>(CToTy)) { 9293 Qualifiers FromQs = CFromTy.getQualifiers(); 9294 Qualifiers ToQs = CToTy.getQualifiers(); 9295 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9297 << (unsigned) FnKind << FnDesc 9298 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9299 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9300 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9301 return; 9302 } 9303 } 9304 9305 if (TakingCandidateAddress && 9306 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9307 return; 9308 9309 // Emit the generic diagnostic and, optionally, add the hints to it. 9310 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9311 FDiag << (unsigned) FnKind << FnDesc 9312 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9313 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9314 << (unsigned) (Cand->Fix.Kind); 9315 9316 // If we can fix the conversion, suggest the FixIts. 9317 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9318 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9319 FDiag << *HI; 9320 S.Diag(Fn->getLocation(), FDiag); 9321 9322 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9323 } 9324 9325 /// Additional arity mismatch diagnosis specific to a function overload 9326 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9327 /// over a candidate in any candidate set. 9328 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9329 unsigned NumArgs) { 9330 FunctionDecl *Fn = Cand->Function; 9331 unsigned MinParams = Fn->getMinRequiredArguments(); 9332 9333 // With invalid overloaded operators, it's possible that we think we 9334 // have an arity mismatch when in fact it looks like we have the 9335 // right number of arguments, because only overloaded operators have 9336 // the weird behavior of overloading member and non-member functions. 9337 // Just don't report anything. 9338 if (Fn->isInvalidDecl() && 9339 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9340 return true; 9341 9342 if (NumArgs < MinParams) { 9343 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9344 (Cand->FailureKind == ovl_fail_bad_deduction && 9345 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9346 } else { 9347 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9348 (Cand->FailureKind == ovl_fail_bad_deduction && 9349 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9350 } 9351 9352 return false; 9353 } 9354 9355 /// General arity mismatch diagnosis over a candidate in a candidate set. 9356 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9357 unsigned NumFormalArgs) { 9358 assert(isa<FunctionDecl>(D) && 9359 "The templated declaration should at least be a function" 9360 " when diagnosing bad template argument deduction due to too many" 9361 " or too few arguments"); 9362 9363 FunctionDecl *Fn = cast<FunctionDecl>(D); 9364 9365 // TODO: treat calls to a missing default constructor as a special case 9366 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9367 unsigned MinParams = Fn->getMinRequiredArguments(); 9368 9369 // at least / at most / exactly 9370 unsigned mode, modeCount; 9371 if (NumFormalArgs < MinParams) { 9372 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9373 FnTy->isTemplateVariadic()) 9374 mode = 0; // "at least" 9375 else 9376 mode = 2; // "exactly" 9377 modeCount = MinParams; 9378 } else { 9379 if (MinParams != FnTy->getNumParams()) 9380 mode = 1; // "at most" 9381 else 9382 mode = 2; // "exactly" 9383 modeCount = FnTy->getNumParams(); 9384 } 9385 9386 std::string Description; 9387 OverloadCandidateKind FnKind = 9388 ClassifyOverloadCandidate(S, Found, Fn, Description); 9389 9390 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9392 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9393 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9394 else 9395 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9396 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9397 << mode << modeCount << NumFormalArgs; 9398 MaybeEmitInheritedConstructorNote(S, Found); 9399 } 9400 9401 /// Arity mismatch diagnosis specific to a function overload candidate. 9402 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9403 unsigned NumFormalArgs) { 9404 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9405 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9406 } 9407 9408 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9409 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9410 return TD; 9411 llvm_unreachable("Unsupported: Getting the described template declaration" 9412 " for bad deduction diagnosis"); 9413 } 9414 9415 /// Diagnose a failed template-argument deduction. 9416 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9417 DeductionFailureInfo &DeductionFailure, 9418 unsigned NumArgs, 9419 bool TakingCandidateAddress) { 9420 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9421 NamedDecl *ParamD; 9422 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9423 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9424 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9425 switch (DeductionFailure.Result) { 9426 case Sema::TDK_Success: 9427 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9428 9429 case Sema::TDK_Incomplete: { 9430 assert(ParamD && "no parameter found for incomplete deduction result"); 9431 S.Diag(Templated->getLocation(), 9432 diag::note_ovl_candidate_incomplete_deduction) 9433 << ParamD->getDeclName(); 9434 MaybeEmitInheritedConstructorNote(S, Found); 9435 return; 9436 } 9437 9438 case Sema::TDK_Underqualified: { 9439 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9440 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9441 9442 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9443 9444 // Param will have been canonicalized, but it should just be a 9445 // qualified version of ParamD, so move the qualifiers to that. 9446 QualifierCollector Qs; 9447 Qs.strip(Param); 9448 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9449 assert(S.Context.hasSameType(Param, NonCanonParam)); 9450 9451 // Arg has also been canonicalized, but there's nothing we can do 9452 // about that. It also doesn't matter as much, because it won't 9453 // have any template parameters in it (because deduction isn't 9454 // done on dependent types). 9455 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9456 9457 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9458 << ParamD->getDeclName() << Arg << NonCanonParam; 9459 MaybeEmitInheritedConstructorNote(S, Found); 9460 return; 9461 } 9462 9463 case Sema::TDK_Inconsistent: { 9464 assert(ParamD && "no parameter found for inconsistent deduction result"); 9465 int which = 0; 9466 if (isa<TemplateTypeParmDecl>(ParamD)) 9467 which = 0; 9468 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9469 which = 1; 9470 else { 9471 which = 2; 9472 } 9473 9474 S.Diag(Templated->getLocation(), 9475 diag::note_ovl_candidate_inconsistent_deduction) 9476 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9477 << *DeductionFailure.getSecondArg(); 9478 MaybeEmitInheritedConstructorNote(S, Found); 9479 return; 9480 } 9481 9482 case Sema::TDK_InvalidExplicitArguments: 9483 assert(ParamD && "no parameter found for invalid explicit arguments"); 9484 if (ParamD->getDeclName()) 9485 S.Diag(Templated->getLocation(), 9486 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9487 << ParamD->getDeclName(); 9488 else { 9489 int index = 0; 9490 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9491 index = TTP->getIndex(); 9492 else if (NonTypeTemplateParmDecl *NTTP 9493 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9494 index = NTTP->getIndex(); 9495 else 9496 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9497 S.Diag(Templated->getLocation(), 9498 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9499 << (index + 1); 9500 } 9501 MaybeEmitInheritedConstructorNote(S, Found); 9502 return; 9503 9504 case Sema::TDK_TooManyArguments: 9505 case Sema::TDK_TooFewArguments: 9506 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9507 return; 9508 9509 case Sema::TDK_InstantiationDepth: 9510 S.Diag(Templated->getLocation(), 9511 diag::note_ovl_candidate_instantiation_depth); 9512 MaybeEmitInheritedConstructorNote(S, Found); 9513 return; 9514 9515 case Sema::TDK_SubstitutionFailure: { 9516 // Format the template argument list into the argument string. 9517 SmallString<128> TemplateArgString; 9518 if (TemplateArgumentList *Args = 9519 DeductionFailure.getTemplateArgumentList()) { 9520 TemplateArgString = " "; 9521 TemplateArgString += S.getTemplateArgumentBindingsText( 9522 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9523 } 9524 9525 // If this candidate was disabled by enable_if, say so. 9526 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9527 if (PDiag && PDiag->second.getDiagID() == 9528 diag::err_typename_nested_not_found_enable_if) { 9529 // FIXME: Use the source range of the condition, and the fully-qualified 9530 // name of the enable_if template. These are both present in PDiag. 9531 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9532 << "'enable_if'" << TemplateArgString; 9533 return; 9534 } 9535 9536 // Format the SFINAE diagnostic into the argument string. 9537 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9538 // formatted message in another diagnostic. 9539 SmallString<128> SFINAEArgString; 9540 SourceRange R; 9541 if (PDiag) { 9542 SFINAEArgString = ": "; 9543 R = SourceRange(PDiag->first, PDiag->first); 9544 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9545 } 9546 9547 S.Diag(Templated->getLocation(), 9548 diag::note_ovl_candidate_substitution_failure) 9549 << TemplateArgString << SFINAEArgString << R; 9550 MaybeEmitInheritedConstructorNote(S, Found); 9551 return; 9552 } 9553 9554 case Sema::TDK_FailedOverloadResolution: { 9555 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9556 S.Diag(Templated->getLocation(), 9557 diag::note_ovl_candidate_failed_overload_resolution) 9558 << R.Expression->getName(); 9559 return; 9560 } 9561 9562 case Sema::TDK_DeducedMismatch: { 9563 // Format the template argument list into the argument string. 9564 SmallString<128> TemplateArgString; 9565 if (TemplateArgumentList *Args = 9566 DeductionFailure.getTemplateArgumentList()) { 9567 TemplateArgString = " "; 9568 TemplateArgString += S.getTemplateArgumentBindingsText( 9569 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9570 } 9571 9572 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9573 << (*DeductionFailure.getCallArgIndex() + 1) 9574 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9575 << TemplateArgString; 9576 break; 9577 } 9578 9579 case Sema::TDK_NonDeducedMismatch: { 9580 // FIXME: Provide a source location to indicate what we couldn't match. 9581 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9582 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9583 if (FirstTA.getKind() == TemplateArgument::Template && 9584 SecondTA.getKind() == TemplateArgument::Template) { 9585 TemplateName FirstTN = FirstTA.getAsTemplate(); 9586 TemplateName SecondTN = SecondTA.getAsTemplate(); 9587 if (FirstTN.getKind() == TemplateName::Template && 9588 SecondTN.getKind() == TemplateName::Template) { 9589 if (FirstTN.getAsTemplateDecl()->getName() == 9590 SecondTN.getAsTemplateDecl()->getName()) { 9591 // FIXME: This fixes a bad diagnostic where both templates are named 9592 // the same. This particular case is a bit difficult since: 9593 // 1) It is passed as a string to the diagnostic printer. 9594 // 2) The diagnostic printer only attempts to find a better 9595 // name for types, not decls. 9596 // Ideally, this should folded into the diagnostic printer. 9597 S.Diag(Templated->getLocation(), 9598 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9599 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9600 return; 9601 } 9602 } 9603 } 9604 9605 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9606 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9607 return; 9608 9609 // FIXME: For generic lambda parameters, check if the function is a lambda 9610 // call operator, and if so, emit a prettier and more informative 9611 // diagnostic that mentions 'auto' and lambda in addition to 9612 // (or instead of?) the canonical template type parameters. 9613 S.Diag(Templated->getLocation(), 9614 diag::note_ovl_candidate_non_deduced_mismatch) 9615 << FirstTA << SecondTA; 9616 return; 9617 } 9618 // TODO: diagnose these individually, then kill off 9619 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9620 case Sema::TDK_MiscellaneousDeductionFailure: 9621 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9622 MaybeEmitInheritedConstructorNote(S, Found); 9623 return; 9624 } 9625 } 9626 9627 /// Diagnose a failed template-argument deduction, for function calls. 9628 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9629 unsigned NumArgs, 9630 bool TakingCandidateAddress) { 9631 unsigned TDK = Cand->DeductionFailure.Result; 9632 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9633 if (CheckArityMismatch(S, Cand, NumArgs)) 9634 return; 9635 } 9636 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9637 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9638 } 9639 9640 /// CUDA: diagnose an invalid call across targets. 9641 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9642 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9643 FunctionDecl *Callee = Cand->Function; 9644 9645 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9646 CalleeTarget = S.IdentifyCUDATarget(Callee); 9647 9648 std::string FnDesc; 9649 OverloadCandidateKind FnKind = 9650 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9651 9652 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9653 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9654 9655 // This could be an implicit constructor for which we could not infer the 9656 // target due to a collsion. Diagnose that case. 9657 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9658 if (Meth != nullptr && Meth->isImplicit()) { 9659 CXXRecordDecl *ParentClass = Meth->getParent(); 9660 Sema::CXXSpecialMember CSM; 9661 9662 switch (FnKind) { 9663 default: 9664 return; 9665 case oc_implicit_default_constructor: 9666 CSM = Sema::CXXDefaultConstructor; 9667 break; 9668 case oc_implicit_copy_constructor: 9669 CSM = Sema::CXXCopyConstructor; 9670 break; 9671 case oc_implicit_move_constructor: 9672 CSM = Sema::CXXMoveConstructor; 9673 break; 9674 case oc_implicit_copy_assignment: 9675 CSM = Sema::CXXCopyAssignment; 9676 break; 9677 case oc_implicit_move_assignment: 9678 CSM = Sema::CXXMoveAssignment; 9679 break; 9680 }; 9681 9682 bool ConstRHS = false; 9683 if (Meth->getNumParams()) { 9684 if (const ReferenceType *RT = 9685 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9686 ConstRHS = RT->getPointeeType().isConstQualified(); 9687 } 9688 } 9689 9690 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9691 /* ConstRHS */ ConstRHS, 9692 /* Diagnose */ true); 9693 } 9694 } 9695 9696 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9697 FunctionDecl *Callee = Cand->Function; 9698 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9699 9700 S.Diag(Callee->getLocation(), 9701 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9702 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9703 } 9704 9705 /// Generates a 'note' diagnostic for an overload candidate. We've 9706 /// already generated a primary error at the call site. 9707 /// 9708 /// It really does need to be a single diagnostic with its caret 9709 /// pointed at the candidate declaration. Yes, this creates some 9710 /// major challenges of technical writing. Yes, this makes pointing 9711 /// out problems with specific arguments quite awkward. It's still 9712 /// better than generating twenty screens of text for every failed 9713 /// overload. 9714 /// 9715 /// It would be great to be able to express per-candidate problems 9716 /// more richly for those diagnostic clients that cared, but we'd 9717 /// still have to be just as careful with the default diagnostics. 9718 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9719 unsigned NumArgs, 9720 bool TakingCandidateAddress) { 9721 FunctionDecl *Fn = Cand->Function; 9722 9723 // Note deleted candidates, but only if they're viable. 9724 if (Cand->Viable && (Fn->isDeleted() || 9725 S.isFunctionConsideredUnavailable(Fn))) { 9726 std::string FnDesc; 9727 OverloadCandidateKind FnKind = 9728 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9729 9730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9731 << FnKind << FnDesc 9732 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9734 return; 9735 } 9736 9737 // We don't really have anything else to say about viable candidates. 9738 if (Cand->Viable) { 9739 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9740 return; 9741 } 9742 9743 switch (Cand->FailureKind) { 9744 case ovl_fail_too_many_arguments: 9745 case ovl_fail_too_few_arguments: 9746 return DiagnoseArityMismatch(S, Cand, NumArgs); 9747 9748 case ovl_fail_bad_deduction: 9749 return DiagnoseBadDeduction(S, Cand, NumArgs, 9750 TakingCandidateAddress); 9751 9752 case ovl_fail_illegal_constructor: { 9753 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9754 << (Fn->getPrimaryTemplate() ? 1 : 0); 9755 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9756 return; 9757 } 9758 9759 case ovl_fail_trivial_conversion: 9760 case ovl_fail_bad_final_conversion: 9761 case ovl_fail_final_conversion_not_exact: 9762 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9763 9764 case ovl_fail_bad_conversion: { 9765 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9766 for (unsigned N = Cand->NumConversions; I != N; ++I) 9767 if (Cand->Conversions[I].isBad()) 9768 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9769 9770 // FIXME: this currently happens when we're called from SemaInit 9771 // when user-conversion overload fails. Figure out how to handle 9772 // those conditions and diagnose them well. 9773 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9774 } 9775 9776 case ovl_fail_bad_target: 9777 return DiagnoseBadTarget(S, Cand); 9778 9779 case ovl_fail_enable_if: 9780 return DiagnoseFailedEnableIfAttr(S, Cand); 9781 9782 case ovl_fail_addr_not_available: { 9783 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9784 (void)Available; 9785 assert(!Available); 9786 break; 9787 } 9788 } 9789 } 9790 9791 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9792 // Desugar the type of the surrogate down to a function type, 9793 // retaining as many typedefs as possible while still showing 9794 // the function type (and, therefore, its parameter types). 9795 QualType FnType = Cand->Surrogate->getConversionType(); 9796 bool isLValueReference = false; 9797 bool isRValueReference = false; 9798 bool isPointer = false; 9799 if (const LValueReferenceType *FnTypeRef = 9800 FnType->getAs<LValueReferenceType>()) { 9801 FnType = FnTypeRef->getPointeeType(); 9802 isLValueReference = true; 9803 } else if (const RValueReferenceType *FnTypeRef = 9804 FnType->getAs<RValueReferenceType>()) { 9805 FnType = FnTypeRef->getPointeeType(); 9806 isRValueReference = true; 9807 } 9808 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9809 FnType = FnTypePtr->getPointeeType(); 9810 isPointer = true; 9811 } 9812 // Desugar down to a function type. 9813 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9814 // Reconstruct the pointer/reference as appropriate. 9815 if (isPointer) FnType = S.Context.getPointerType(FnType); 9816 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9817 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9818 9819 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9820 << FnType; 9821 } 9822 9823 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9824 SourceLocation OpLoc, 9825 OverloadCandidate *Cand) { 9826 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9827 std::string TypeStr("operator"); 9828 TypeStr += Opc; 9829 TypeStr += "("; 9830 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9831 if (Cand->NumConversions == 1) { 9832 TypeStr += ")"; 9833 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9834 } else { 9835 TypeStr += ", "; 9836 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9837 TypeStr += ")"; 9838 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9839 } 9840 } 9841 9842 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9843 OverloadCandidate *Cand) { 9844 unsigned NoOperands = Cand->NumConversions; 9845 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9846 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9847 if (ICS.isBad()) break; // all meaningless after first invalid 9848 if (!ICS.isAmbiguous()) continue; 9849 9850 ICS.DiagnoseAmbiguousConversion( 9851 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9852 } 9853 } 9854 9855 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9856 if (Cand->Function) 9857 return Cand->Function->getLocation(); 9858 if (Cand->IsSurrogate) 9859 return Cand->Surrogate->getLocation(); 9860 return SourceLocation(); 9861 } 9862 9863 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9864 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9865 case Sema::TDK_Success: 9866 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9867 9868 case Sema::TDK_Invalid: 9869 case Sema::TDK_Incomplete: 9870 return 1; 9871 9872 case Sema::TDK_Underqualified: 9873 case Sema::TDK_Inconsistent: 9874 return 2; 9875 9876 case Sema::TDK_SubstitutionFailure: 9877 case Sema::TDK_DeducedMismatch: 9878 case Sema::TDK_NonDeducedMismatch: 9879 case Sema::TDK_MiscellaneousDeductionFailure: 9880 return 3; 9881 9882 case Sema::TDK_InstantiationDepth: 9883 case Sema::TDK_FailedOverloadResolution: 9884 return 4; 9885 9886 case Sema::TDK_InvalidExplicitArguments: 9887 return 5; 9888 9889 case Sema::TDK_TooManyArguments: 9890 case Sema::TDK_TooFewArguments: 9891 return 6; 9892 } 9893 llvm_unreachable("Unhandled deduction result"); 9894 } 9895 9896 namespace { 9897 struct CompareOverloadCandidatesForDisplay { 9898 Sema &S; 9899 SourceLocation Loc; 9900 size_t NumArgs; 9901 9902 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9903 : S(S), NumArgs(nArgs) {} 9904 9905 bool operator()(const OverloadCandidate *L, 9906 const OverloadCandidate *R) { 9907 // Fast-path this check. 9908 if (L == R) return false; 9909 9910 // Order first by viability. 9911 if (L->Viable) { 9912 if (!R->Viable) return true; 9913 9914 // TODO: introduce a tri-valued comparison for overload 9915 // candidates. Would be more worthwhile if we had a sort 9916 // that could exploit it. 9917 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9918 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9919 } else if (R->Viable) 9920 return false; 9921 9922 assert(L->Viable == R->Viable); 9923 9924 // Criteria by which we can sort non-viable candidates: 9925 if (!L->Viable) { 9926 // 1. Arity mismatches come after other candidates. 9927 if (L->FailureKind == ovl_fail_too_many_arguments || 9928 L->FailureKind == ovl_fail_too_few_arguments) { 9929 if (R->FailureKind == ovl_fail_too_many_arguments || 9930 R->FailureKind == ovl_fail_too_few_arguments) { 9931 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9932 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9933 if (LDist == RDist) { 9934 if (L->FailureKind == R->FailureKind) 9935 // Sort non-surrogates before surrogates. 9936 return !L->IsSurrogate && R->IsSurrogate; 9937 // Sort candidates requiring fewer parameters than there were 9938 // arguments given after candidates requiring more parameters 9939 // than there were arguments given. 9940 return L->FailureKind == ovl_fail_too_many_arguments; 9941 } 9942 return LDist < RDist; 9943 } 9944 return false; 9945 } 9946 if (R->FailureKind == ovl_fail_too_many_arguments || 9947 R->FailureKind == ovl_fail_too_few_arguments) 9948 return true; 9949 9950 // 2. Bad conversions come first and are ordered by the number 9951 // of bad conversions and quality of good conversions. 9952 if (L->FailureKind == ovl_fail_bad_conversion) { 9953 if (R->FailureKind != ovl_fail_bad_conversion) 9954 return true; 9955 9956 // The conversion that can be fixed with a smaller number of changes, 9957 // comes first. 9958 unsigned numLFixes = L->Fix.NumConversionsFixed; 9959 unsigned numRFixes = R->Fix.NumConversionsFixed; 9960 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9961 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9962 if (numLFixes != numRFixes) { 9963 return numLFixes < numRFixes; 9964 } 9965 9966 // If there's any ordering between the defined conversions... 9967 // FIXME: this might not be transitive. 9968 assert(L->NumConversions == R->NumConversions); 9969 9970 int leftBetter = 0; 9971 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9972 for (unsigned E = L->NumConversions; I != E; ++I) { 9973 switch (CompareImplicitConversionSequences(S, Loc, 9974 L->Conversions[I], 9975 R->Conversions[I])) { 9976 case ImplicitConversionSequence::Better: 9977 leftBetter++; 9978 break; 9979 9980 case ImplicitConversionSequence::Worse: 9981 leftBetter--; 9982 break; 9983 9984 case ImplicitConversionSequence::Indistinguishable: 9985 break; 9986 } 9987 } 9988 if (leftBetter > 0) return true; 9989 if (leftBetter < 0) return false; 9990 9991 } else if (R->FailureKind == ovl_fail_bad_conversion) 9992 return false; 9993 9994 if (L->FailureKind == ovl_fail_bad_deduction) { 9995 if (R->FailureKind != ovl_fail_bad_deduction) 9996 return true; 9997 9998 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9999 return RankDeductionFailure(L->DeductionFailure) 10000 < RankDeductionFailure(R->DeductionFailure); 10001 } else if (R->FailureKind == ovl_fail_bad_deduction) 10002 return false; 10003 10004 // TODO: others? 10005 } 10006 10007 // Sort everything else by location. 10008 SourceLocation LLoc = GetLocationForCandidate(L); 10009 SourceLocation RLoc = GetLocationForCandidate(R); 10010 10011 // Put candidates without locations (e.g. builtins) at the end. 10012 if (LLoc.isInvalid()) return false; 10013 if (RLoc.isInvalid()) return true; 10014 10015 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10016 } 10017 }; 10018 } 10019 10020 /// CompleteNonViableCandidate - Normally, overload resolution only 10021 /// computes up to the first. Produces the FixIt set if possible. 10022 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10023 ArrayRef<Expr *> Args) { 10024 assert(!Cand->Viable); 10025 10026 // Don't do anything on failures other than bad conversion. 10027 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10028 10029 // We only want the FixIts if all the arguments can be corrected. 10030 bool Unfixable = false; 10031 // Use a implicit copy initialization to check conversion fixes. 10032 Cand->Fix.setConversionChecker(TryCopyInitialization); 10033 10034 // Skip forward to the first bad conversion. 10035 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10036 unsigned ConvCount = Cand->NumConversions; 10037 while (true) { 10038 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10039 ConvIdx++; 10040 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10041 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10042 break; 10043 } 10044 } 10045 10046 if (ConvIdx == ConvCount) 10047 return; 10048 10049 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10050 "remaining conversion is initialized?"); 10051 10052 // FIXME: this should probably be preserved from the overload 10053 // operation somehow. 10054 bool SuppressUserConversions = false; 10055 10056 const FunctionProtoType* Proto; 10057 unsigned ArgIdx = ConvIdx; 10058 10059 if (Cand->IsSurrogate) { 10060 QualType ConvType 10061 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10062 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10063 ConvType = ConvPtrType->getPointeeType(); 10064 Proto = ConvType->getAs<FunctionProtoType>(); 10065 ArgIdx--; 10066 } else if (Cand->Function) { 10067 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10068 if (isa<CXXMethodDecl>(Cand->Function) && 10069 !isa<CXXConstructorDecl>(Cand->Function)) 10070 ArgIdx--; 10071 } else { 10072 // Builtin binary operator with a bad first conversion. 10073 assert(ConvCount <= 3); 10074 for (; ConvIdx != ConvCount; ++ConvIdx) 10075 Cand->Conversions[ConvIdx] 10076 = TryCopyInitialization(S, Args[ConvIdx], 10077 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10078 SuppressUserConversions, 10079 /*InOverloadResolution*/ true, 10080 /*AllowObjCWritebackConversion=*/ 10081 S.getLangOpts().ObjCAutoRefCount); 10082 return; 10083 } 10084 10085 // Fill in the rest of the conversions. 10086 unsigned NumParams = Proto->getNumParams(); 10087 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10088 if (ArgIdx < NumParams) { 10089 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10090 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10091 /*InOverloadResolution=*/true, 10092 /*AllowObjCWritebackConversion=*/ 10093 S.getLangOpts().ObjCAutoRefCount); 10094 // Store the FixIt in the candidate if it exists. 10095 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10096 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10097 } 10098 else 10099 Cand->Conversions[ConvIdx].setEllipsis(); 10100 } 10101 } 10102 10103 /// PrintOverloadCandidates - When overload resolution fails, prints 10104 /// diagnostic messages containing the candidates in the candidate 10105 /// set. 10106 void OverloadCandidateSet::NoteCandidates(Sema &S, 10107 OverloadCandidateDisplayKind OCD, 10108 ArrayRef<Expr *> Args, 10109 StringRef Opc, 10110 SourceLocation OpLoc) { 10111 // Sort the candidates by viability and position. Sorting directly would 10112 // be prohibitive, so we make a set of pointers and sort those. 10113 SmallVector<OverloadCandidate*, 32> Cands; 10114 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10115 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10116 if (Cand->Viable) 10117 Cands.push_back(Cand); 10118 else if (OCD == OCD_AllCandidates) { 10119 CompleteNonViableCandidate(S, Cand, Args); 10120 if (Cand->Function || Cand->IsSurrogate) 10121 Cands.push_back(Cand); 10122 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10123 // want to list every possible builtin candidate. 10124 } 10125 } 10126 10127 std::sort(Cands.begin(), Cands.end(), 10128 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10129 10130 bool ReportedAmbiguousConversions = false; 10131 10132 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10133 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10134 unsigned CandsShown = 0; 10135 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10136 OverloadCandidate *Cand = *I; 10137 10138 // Set an arbitrary limit on the number of candidate functions we'll spam 10139 // the user with. FIXME: This limit should depend on details of the 10140 // candidate list. 10141 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10142 break; 10143 } 10144 ++CandsShown; 10145 10146 if (Cand->Function) 10147 NoteFunctionCandidate(S, Cand, Args.size(), 10148 /*TakingCandidateAddress=*/false); 10149 else if (Cand->IsSurrogate) 10150 NoteSurrogateCandidate(S, Cand); 10151 else { 10152 assert(Cand->Viable && 10153 "Non-viable built-in candidates are not added to Cands."); 10154 // Generally we only see ambiguities including viable builtin 10155 // operators if overload resolution got screwed up by an 10156 // ambiguous user-defined conversion. 10157 // 10158 // FIXME: It's quite possible for different conversions to see 10159 // different ambiguities, though. 10160 if (!ReportedAmbiguousConversions) { 10161 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10162 ReportedAmbiguousConversions = true; 10163 } 10164 10165 // If this is a viable builtin, print it. 10166 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10167 } 10168 } 10169 10170 if (I != E) 10171 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10172 } 10173 10174 static SourceLocation 10175 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10176 return Cand->Specialization ? Cand->Specialization->getLocation() 10177 : SourceLocation(); 10178 } 10179 10180 namespace { 10181 struct CompareTemplateSpecCandidatesForDisplay { 10182 Sema &S; 10183 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10184 10185 bool operator()(const TemplateSpecCandidate *L, 10186 const TemplateSpecCandidate *R) { 10187 // Fast-path this check. 10188 if (L == R) 10189 return false; 10190 10191 // Assuming that both candidates are not matches... 10192 10193 // Sort by the ranking of deduction failures. 10194 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10195 return RankDeductionFailure(L->DeductionFailure) < 10196 RankDeductionFailure(R->DeductionFailure); 10197 10198 // Sort everything else by location. 10199 SourceLocation LLoc = GetLocationForCandidate(L); 10200 SourceLocation RLoc = GetLocationForCandidate(R); 10201 10202 // Put candidates without locations (e.g. builtins) at the end. 10203 if (LLoc.isInvalid()) 10204 return false; 10205 if (RLoc.isInvalid()) 10206 return true; 10207 10208 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10209 } 10210 }; 10211 } 10212 10213 /// Diagnose a template argument deduction failure. 10214 /// We are treating these failures as overload failures due to bad 10215 /// deductions. 10216 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10217 bool ForTakingAddress) { 10218 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10219 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10220 } 10221 10222 void TemplateSpecCandidateSet::destroyCandidates() { 10223 for (iterator i = begin(), e = end(); i != e; ++i) { 10224 i->DeductionFailure.Destroy(); 10225 } 10226 } 10227 10228 void TemplateSpecCandidateSet::clear() { 10229 destroyCandidates(); 10230 Candidates.clear(); 10231 } 10232 10233 /// NoteCandidates - When no template specialization match is found, prints 10234 /// diagnostic messages containing the non-matching specializations that form 10235 /// the candidate set. 10236 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10237 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10238 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10239 // Sort the candidates by position (assuming no candidate is a match). 10240 // Sorting directly would be prohibitive, so we make a set of pointers 10241 // and sort those. 10242 SmallVector<TemplateSpecCandidate *, 32> Cands; 10243 Cands.reserve(size()); 10244 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10245 if (Cand->Specialization) 10246 Cands.push_back(Cand); 10247 // Otherwise, this is a non-matching builtin candidate. We do not, 10248 // in general, want to list every possible builtin candidate. 10249 } 10250 10251 std::sort(Cands.begin(), Cands.end(), 10252 CompareTemplateSpecCandidatesForDisplay(S)); 10253 10254 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10255 // for generalization purposes (?). 10256 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10257 10258 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10259 unsigned CandsShown = 0; 10260 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10261 TemplateSpecCandidate *Cand = *I; 10262 10263 // Set an arbitrary limit on the number of candidates we'll spam 10264 // the user with. FIXME: This limit should depend on details of the 10265 // candidate list. 10266 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10267 break; 10268 ++CandsShown; 10269 10270 assert(Cand->Specialization && 10271 "Non-matching built-in candidates are not added to Cands."); 10272 Cand->NoteDeductionFailure(S, ForTakingAddress); 10273 } 10274 10275 if (I != E) 10276 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10277 } 10278 10279 // [PossiblyAFunctionType] --> [Return] 10280 // NonFunctionType --> NonFunctionType 10281 // R (A) --> R(A) 10282 // R (*)(A) --> R (A) 10283 // R (&)(A) --> R (A) 10284 // R (S::*)(A) --> R (A) 10285 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10286 QualType Ret = PossiblyAFunctionType; 10287 if (const PointerType *ToTypePtr = 10288 PossiblyAFunctionType->getAs<PointerType>()) 10289 Ret = ToTypePtr->getPointeeType(); 10290 else if (const ReferenceType *ToTypeRef = 10291 PossiblyAFunctionType->getAs<ReferenceType>()) 10292 Ret = ToTypeRef->getPointeeType(); 10293 else if (const MemberPointerType *MemTypePtr = 10294 PossiblyAFunctionType->getAs<MemberPointerType>()) 10295 Ret = MemTypePtr->getPointeeType(); 10296 Ret = 10297 Context.getCanonicalType(Ret).getUnqualifiedType(); 10298 return Ret; 10299 } 10300 10301 namespace { 10302 // A helper class to help with address of function resolution 10303 // - allows us to avoid passing around all those ugly parameters 10304 class AddressOfFunctionResolver { 10305 Sema& S; 10306 Expr* SourceExpr; 10307 const QualType& TargetType; 10308 QualType TargetFunctionType; // Extracted function type from target type 10309 10310 bool Complain; 10311 //DeclAccessPair& ResultFunctionAccessPair; 10312 ASTContext& Context; 10313 10314 bool TargetTypeIsNonStaticMemberFunction; 10315 bool FoundNonTemplateFunction; 10316 bool StaticMemberFunctionFromBoundPointer; 10317 bool HasComplained; 10318 10319 OverloadExpr::FindResult OvlExprInfo; 10320 OverloadExpr *OvlExpr; 10321 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10322 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10323 TemplateSpecCandidateSet FailedCandidates; 10324 10325 public: 10326 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10327 const QualType &TargetType, bool Complain) 10328 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10329 Complain(Complain), Context(S.getASTContext()), 10330 TargetTypeIsNonStaticMemberFunction( 10331 !!TargetType->getAs<MemberPointerType>()), 10332 FoundNonTemplateFunction(false), 10333 StaticMemberFunctionFromBoundPointer(false), 10334 HasComplained(false), 10335 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10336 OvlExpr(OvlExprInfo.Expression), 10337 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10338 ExtractUnqualifiedFunctionTypeFromTargetType(); 10339 10340 if (TargetFunctionType->isFunctionType()) { 10341 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10342 if (!UME->isImplicitAccess() && 10343 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10344 StaticMemberFunctionFromBoundPointer = true; 10345 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10346 DeclAccessPair dap; 10347 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10348 OvlExpr, false, &dap)) { 10349 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10350 if (!Method->isStatic()) { 10351 // If the target type is a non-function type and the function found 10352 // is a non-static member function, pretend as if that was the 10353 // target, it's the only possible type to end up with. 10354 TargetTypeIsNonStaticMemberFunction = true; 10355 10356 // And skip adding the function if its not in the proper form. 10357 // We'll diagnose this due to an empty set of functions. 10358 if (!OvlExprInfo.HasFormOfMemberPointer) 10359 return; 10360 } 10361 10362 Matches.push_back(std::make_pair(dap, Fn)); 10363 } 10364 return; 10365 } 10366 10367 if (OvlExpr->hasExplicitTemplateArgs()) 10368 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10369 10370 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10371 // C++ [over.over]p4: 10372 // If more than one function is selected, [...] 10373 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10374 if (FoundNonTemplateFunction) 10375 EliminateAllTemplateMatches(); 10376 else 10377 EliminateAllExceptMostSpecializedTemplate(); 10378 } 10379 } 10380 10381 if (S.getLangOpts().CUDA && Matches.size() > 1) 10382 EliminateSuboptimalCudaMatches(); 10383 } 10384 10385 bool hasComplained() const { return HasComplained; } 10386 10387 private: 10388 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10389 QualType Discard; 10390 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10391 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard); 10392 } 10393 10394 /// \return true if A is considered a better overload candidate for the 10395 /// desired type than B. 10396 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10397 // If A doesn't have exactly the correct type, we don't want to classify it 10398 // as "better" than anything else. This way, the user is required to 10399 // disambiguate for us if there are multiple candidates and no exact match. 10400 return candidateHasExactlyCorrectType(A) && 10401 (!candidateHasExactlyCorrectType(B) || 10402 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10403 } 10404 10405 /// \return true if we were able to eliminate all but one overload candidate, 10406 /// false otherwise. 10407 bool eliminiateSuboptimalOverloadCandidates() { 10408 // Same algorithm as overload resolution -- one pass to pick the "best", 10409 // another pass to be sure that nothing is better than the best. 10410 auto Best = Matches.begin(); 10411 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10412 if (isBetterCandidate(I->second, Best->second)) 10413 Best = I; 10414 10415 const FunctionDecl *BestFn = Best->second; 10416 auto IsBestOrInferiorToBest = [this, BestFn]( 10417 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10418 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10419 }; 10420 10421 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10422 // option, so we can potentially give the user a better error 10423 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10424 return false; 10425 Matches[0] = *Best; 10426 Matches.resize(1); 10427 return true; 10428 } 10429 10430 bool isTargetTypeAFunction() const { 10431 return TargetFunctionType->isFunctionType(); 10432 } 10433 10434 // [ToType] [Return] 10435 10436 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10437 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10438 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10439 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10440 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10441 } 10442 10443 // return true if any matching specializations were found 10444 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10445 const DeclAccessPair& CurAccessFunPair) { 10446 if (CXXMethodDecl *Method 10447 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10448 // Skip non-static function templates when converting to pointer, and 10449 // static when converting to member pointer. 10450 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10451 return false; 10452 } 10453 else if (TargetTypeIsNonStaticMemberFunction) 10454 return false; 10455 10456 // C++ [over.over]p2: 10457 // If the name is a function template, template argument deduction is 10458 // done (14.8.2.2), and if the argument deduction succeeds, the 10459 // resulting template argument list is used to generate a single 10460 // function template specialization, which is added to the set of 10461 // overloaded functions considered. 10462 FunctionDecl *Specialization = nullptr; 10463 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10464 if (Sema::TemplateDeductionResult Result 10465 = S.DeduceTemplateArguments(FunctionTemplate, 10466 &OvlExplicitTemplateArgs, 10467 TargetFunctionType, Specialization, 10468 Info, /*InOverloadResolution=*/true)) { 10469 // Make a note of the failed deduction for diagnostics. 10470 FailedCandidates.addCandidate() 10471 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10472 MakeDeductionFailureInfo(Context, Result, Info)); 10473 return false; 10474 } 10475 10476 // Template argument deduction ensures that we have an exact match or 10477 // compatible pointer-to-function arguments that would be adjusted by ICS. 10478 // This function template specicalization works. 10479 assert(S.isSameOrCompatibleFunctionType( 10480 Context.getCanonicalType(Specialization->getType()), 10481 Context.getCanonicalType(TargetFunctionType))); 10482 10483 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10484 return false; 10485 10486 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10487 return true; 10488 } 10489 10490 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10491 const DeclAccessPair& CurAccessFunPair) { 10492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10493 // Skip non-static functions when converting to pointer, and static 10494 // when converting to member pointer. 10495 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10496 return false; 10497 } 10498 else if (TargetTypeIsNonStaticMemberFunction) 10499 return false; 10500 10501 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10502 if (S.getLangOpts().CUDA) 10503 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10504 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10505 return false; 10506 10507 // If any candidate has a placeholder return type, trigger its deduction 10508 // now. 10509 if (S.getLangOpts().CPlusPlus14 && 10510 FunDecl->getReturnType()->isUndeducedType() && 10511 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10512 HasComplained |= Complain; 10513 return false; 10514 } 10515 10516 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10517 return false; 10518 10519 // If we're in C, we need to support types that aren't exactly identical. 10520 if (!S.getLangOpts().CPlusPlus || 10521 candidateHasExactlyCorrectType(FunDecl)) { 10522 Matches.push_back(std::make_pair( 10523 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10524 FoundNonTemplateFunction = true; 10525 return true; 10526 } 10527 } 10528 10529 return false; 10530 } 10531 10532 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10533 bool Ret = false; 10534 10535 // If the overload expression doesn't have the form of a pointer to 10536 // member, don't try to convert it to a pointer-to-member type. 10537 if (IsInvalidFormOfPointerToMemberFunction()) 10538 return false; 10539 10540 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10541 E = OvlExpr->decls_end(); 10542 I != E; ++I) { 10543 // Look through any using declarations to find the underlying function. 10544 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10545 10546 // C++ [over.over]p3: 10547 // Non-member functions and static member functions match 10548 // targets of type "pointer-to-function" or "reference-to-function." 10549 // Nonstatic member functions match targets of 10550 // type "pointer-to-member-function." 10551 // Note that according to DR 247, the containing class does not matter. 10552 if (FunctionTemplateDecl *FunctionTemplate 10553 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10554 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10555 Ret = true; 10556 } 10557 // If we have explicit template arguments supplied, skip non-templates. 10558 else if (!OvlExpr->hasExplicitTemplateArgs() && 10559 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10560 Ret = true; 10561 } 10562 assert(Ret || Matches.empty()); 10563 return Ret; 10564 } 10565 10566 void EliminateAllExceptMostSpecializedTemplate() { 10567 // [...] and any given function template specialization F1 is 10568 // eliminated if the set contains a second function template 10569 // specialization whose function template is more specialized 10570 // than the function template of F1 according to the partial 10571 // ordering rules of 14.5.5.2. 10572 10573 // The algorithm specified above is quadratic. We instead use a 10574 // two-pass algorithm (similar to the one used to identify the 10575 // best viable function in an overload set) that identifies the 10576 // best function template (if it exists). 10577 10578 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10579 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10580 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10581 10582 // TODO: It looks like FailedCandidates does not serve much purpose 10583 // here, since the no_viable diagnostic has index 0. 10584 UnresolvedSetIterator Result = S.getMostSpecialized( 10585 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10586 SourceExpr->getLocStart(), S.PDiag(), 10587 S.PDiag(diag::err_addr_ovl_ambiguous) 10588 << Matches[0].second->getDeclName(), 10589 S.PDiag(diag::note_ovl_candidate) 10590 << (unsigned)oc_function_template, 10591 Complain, TargetFunctionType); 10592 10593 if (Result != MatchesCopy.end()) { 10594 // Make it the first and only element 10595 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10596 Matches[0].second = cast<FunctionDecl>(*Result); 10597 Matches.resize(1); 10598 } else 10599 HasComplained |= Complain; 10600 } 10601 10602 void EliminateAllTemplateMatches() { 10603 // [...] any function template specializations in the set are 10604 // eliminated if the set also contains a non-template function, [...] 10605 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10606 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10607 ++I; 10608 else { 10609 Matches[I] = Matches[--N]; 10610 Matches.resize(N); 10611 } 10612 } 10613 } 10614 10615 void EliminateSuboptimalCudaMatches() { 10616 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10617 } 10618 10619 public: 10620 void ComplainNoMatchesFound() const { 10621 assert(Matches.empty()); 10622 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10623 << OvlExpr->getName() << TargetFunctionType 10624 << OvlExpr->getSourceRange(); 10625 if (FailedCandidates.empty()) 10626 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10627 /*TakingAddress=*/true); 10628 else { 10629 // We have some deduction failure messages. Use them to diagnose 10630 // the function templates, and diagnose the non-template candidates 10631 // normally. 10632 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10633 IEnd = OvlExpr->decls_end(); 10634 I != IEnd; ++I) 10635 if (FunctionDecl *Fun = 10636 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10637 if (!functionHasPassObjectSizeParams(Fun)) 10638 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10639 /*TakingAddress=*/true); 10640 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10641 } 10642 } 10643 10644 bool IsInvalidFormOfPointerToMemberFunction() const { 10645 return TargetTypeIsNonStaticMemberFunction && 10646 !OvlExprInfo.HasFormOfMemberPointer; 10647 } 10648 10649 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10650 // TODO: Should we condition this on whether any functions might 10651 // have matched, or is it more appropriate to do that in callers? 10652 // TODO: a fixit wouldn't hurt. 10653 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10654 << TargetType << OvlExpr->getSourceRange(); 10655 } 10656 10657 bool IsStaticMemberFunctionFromBoundPointer() const { 10658 return StaticMemberFunctionFromBoundPointer; 10659 } 10660 10661 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10662 S.Diag(OvlExpr->getLocStart(), 10663 diag::err_invalid_form_pointer_member_function) 10664 << OvlExpr->getSourceRange(); 10665 } 10666 10667 void ComplainOfInvalidConversion() const { 10668 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10669 << OvlExpr->getName() << TargetType; 10670 } 10671 10672 void ComplainMultipleMatchesFound() const { 10673 assert(Matches.size() > 1); 10674 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10675 << OvlExpr->getName() 10676 << OvlExpr->getSourceRange(); 10677 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10678 /*TakingAddress=*/true); 10679 } 10680 10681 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10682 10683 int getNumMatches() const { return Matches.size(); } 10684 10685 FunctionDecl* getMatchingFunctionDecl() const { 10686 if (Matches.size() != 1) return nullptr; 10687 return Matches[0].second; 10688 } 10689 10690 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10691 if (Matches.size() != 1) return nullptr; 10692 return &Matches[0].first; 10693 } 10694 }; 10695 } 10696 10697 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10698 /// an overloaded function (C++ [over.over]), where @p From is an 10699 /// expression with overloaded function type and @p ToType is the type 10700 /// we're trying to resolve to. For example: 10701 /// 10702 /// @code 10703 /// int f(double); 10704 /// int f(int); 10705 /// 10706 /// int (*pfd)(double) = f; // selects f(double) 10707 /// @endcode 10708 /// 10709 /// This routine returns the resulting FunctionDecl if it could be 10710 /// resolved, and NULL otherwise. When @p Complain is true, this 10711 /// routine will emit diagnostics if there is an error. 10712 FunctionDecl * 10713 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10714 QualType TargetType, 10715 bool Complain, 10716 DeclAccessPair &FoundResult, 10717 bool *pHadMultipleCandidates) { 10718 assert(AddressOfExpr->getType() == Context.OverloadTy); 10719 10720 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10721 Complain); 10722 int NumMatches = Resolver.getNumMatches(); 10723 FunctionDecl *Fn = nullptr; 10724 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10725 if (NumMatches == 0 && ShouldComplain) { 10726 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10727 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10728 else 10729 Resolver.ComplainNoMatchesFound(); 10730 } 10731 else if (NumMatches > 1 && ShouldComplain) 10732 Resolver.ComplainMultipleMatchesFound(); 10733 else if (NumMatches == 1) { 10734 Fn = Resolver.getMatchingFunctionDecl(); 10735 assert(Fn); 10736 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10737 if (Complain) { 10738 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10739 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10740 else 10741 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10742 } 10743 } 10744 10745 if (pHadMultipleCandidates) 10746 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10747 return Fn; 10748 } 10749 10750 /// \brief Given an expression that refers to an overloaded function, try to 10751 /// resolve that function to a single function that can have its address taken. 10752 /// This will modify `Pair` iff it returns non-null. 10753 /// 10754 /// This routine can only realistically succeed if all but one candidates in the 10755 /// overload set for SrcExpr cannot have their addresses taken. 10756 FunctionDecl * 10757 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10758 DeclAccessPair &Pair) { 10759 OverloadExpr::FindResult R = OverloadExpr::find(E); 10760 OverloadExpr *Ovl = R.Expression; 10761 FunctionDecl *Result = nullptr; 10762 DeclAccessPair DAP; 10763 // Don't use the AddressOfResolver because we're specifically looking for 10764 // cases where we have one overload candidate that lacks 10765 // enable_if/pass_object_size/... 10766 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10767 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10768 if (!FD) 10769 return nullptr; 10770 10771 if (!checkAddressOfFunctionIsAvailable(FD)) 10772 continue; 10773 10774 // We have more than one result; quit. 10775 if (Result) 10776 return nullptr; 10777 DAP = I.getPair(); 10778 Result = FD; 10779 } 10780 10781 if (Result) 10782 Pair = DAP; 10783 return Result; 10784 } 10785 10786 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10787 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10788 /// will perform access checks, diagnose the use of the resultant decl, and, if 10789 /// necessary, perform a function-to-pointer decay. 10790 /// 10791 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10792 /// Otherwise, returns true. This may emit diagnostics and return true. 10793 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10794 ExprResult &SrcExpr) { 10795 Expr *E = SrcExpr.get(); 10796 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10797 10798 DeclAccessPair DAP; 10799 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10800 if (!Found) 10801 return false; 10802 10803 // Emitting multiple diagnostics for a function that is both inaccessible and 10804 // unavailable is consistent with our behavior elsewhere. So, always check 10805 // for both. 10806 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10807 CheckAddressOfMemberAccess(E, DAP); 10808 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10809 if (Fixed->getType()->isFunctionType()) 10810 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10811 else 10812 SrcExpr = Fixed; 10813 return true; 10814 } 10815 10816 /// \brief Given an expression that refers to an overloaded function, try to 10817 /// resolve that overloaded function expression down to a single function. 10818 /// 10819 /// This routine can only resolve template-ids that refer to a single function 10820 /// template, where that template-id refers to a single template whose template 10821 /// arguments are either provided by the template-id or have defaults, 10822 /// as described in C++0x [temp.arg.explicit]p3. 10823 /// 10824 /// If no template-ids are found, no diagnostics are emitted and NULL is 10825 /// returned. 10826 FunctionDecl * 10827 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10828 bool Complain, 10829 DeclAccessPair *FoundResult) { 10830 // C++ [over.over]p1: 10831 // [...] [Note: any redundant set of parentheses surrounding the 10832 // overloaded function name is ignored (5.1). ] 10833 // C++ [over.over]p1: 10834 // [...] The overloaded function name can be preceded by the & 10835 // operator. 10836 10837 // If we didn't actually find any template-ids, we're done. 10838 if (!ovl->hasExplicitTemplateArgs()) 10839 return nullptr; 10840 10841 TemplateArgumentListInfo ExplicitTemplateArgs; 10842 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10843 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10844 10845 // Look through all of the overloaded functions, searching for one 10846 // whose type matches exactly. 10847 FunctionDecl *Matched = nullptr; 10848 for (UnresolvedSetIterator I = ovl->decls_begin(), 10849 E = ovl->decls_end(); I != E; ++I) { 10850 // C++0x [temp.arg.explicit]p3: 10851 // [...] In contexts where deduction is done and fails, or in contexts 10852 // where deduction is not done, if a template argument list is 10853 // specified and it, along with any default template arguments, 10854 // identifies a single function template specialization, then the 10855 // template-id is an lvalue for the function template specialization. 10856 FunctionTemplateDecl *FunctionTemplate 10857 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10858 10859 // C++ [over.over]p2: 10860 // If the name is a function template, template argument deduction is 10861 // done (14.8.2.2), and if the argument deduction succeeds, the 10862 // resulting template argument list is used to generate a single 10863 // function template specialization, which is added to the set of 10864 // overloaded functions considered. 10865 FunctionDecl *Specialization = nullptr; 10866 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10867 if (TemplateDeductionResult Result 10868 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10869 Specialization, Info, 10870 /*InOverloadResolution=*/true)) { 10871 // Make a note of the failed deduction for diagnostics. 10872 // TODO: Actually use the failed-deduction info? 10873 FailedCandidates.addCandidate() 10874 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 10875 MakeDeductionFailureInfo(Context, Result, Info)); 10876 continue; 10877 } 10878 10879 assert(Specialization && "no specialization and no error?"); 10880 10881 // Multiple matches; we can't resolve to a single declaration. 10882 if (Matched) { 10883 if (Complain) { 10884 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10885 << ovl->getName(); 10886 NoteAllOverloadCandidates(ovl); 10887 } 10888 return nullptr; 10889 } 10890 10891 Matched = Specialization; 10892 if (FoundResult) *FoundResult = I.getPair(); 10893 } 10894 10895 if (Matched && getLangOpts().CPlusPlus14 && 10896 Matched->getReturnType()->isUndeducedType() && 10897 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10898 return nullptr; 10899 10900 return Matched; 10901 } 10902 10903 10904 10905 10906 // Resolve and fix an overloaded expression that can be resolved 10907 // because it identifies a single function template specialization. 10908 // 10909 // Last three arguments should only be supplied if Complain = true 10910 // 10911 // Return true if it was logically possible to so resolve the 10912 // expression, regardless of whether or not it succeeded. Always 10913 // returns true if 'complain' is set. 10914 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10915 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10916 bool complain, SourceRange OpRangeForComplaining, 10917 QualType DestTypeForComplaining, 10918 unsigned DiagIDForComplaining) { 10919 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10920 10921 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10922 10923 DeclAccessPair found; 10924 ExprResult SingleFunctionExpression; 10925 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10926 ovl.Expression, /*complain*/ false, &found)) { 10927 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10928 SrcExpr = ExprError(); 10929 return true; 10930 } 10931 10932 // It is only correct to resolve to an instance method if we're 10933 // resolving a form that's permitted to be a pointer to member. 10934 // Otherwise we'll end up making a bound member expression, which 10935 // is illegal in all the contexts we resolve like this. 10936 if (!ovl.HasFormOfMemberPointer && 10937 isa<CXXMethodDecl>(fn) && 10938 cast<CXXMethodDecl>(fn)->isInstance()) { 10939 if (!complain) return false; 10940 10941 Diag(ovl.Expression->getExprLoc(), 10942 diag::err_bound_member_function) 10943 << 0 << ovl.Expression->getSourceRange(); 10944 10945 // TODO: I believe we only end up here if there's a mix of 10946 // static and non-static candidates (otherwise the expression 10947 // would have 'bound member' type, not 'overload' type). 10948 // Ideally we would note which candidate was chosen and why 10949 // the static candidates were rejected. 10950 SrcExpr = ExprError(); 10951 return true; 10952 } 10953 10954 // Fix the expression to refer to 'fn'. 10955 SingleFunctionExpression = 10956 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10957 10958 // If desired, do function-to-pointer decay. 10959 if (doFunctionPointerConverion) { 10960 SingleFunctionExpression = 10961 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10962 if (SingleFunctionExpression.isInvalid()) { 10963 SrcExpr = ExprError(); 10964 return true; 10965 } 10966 } 10967 } 10968 10969 if (!SingleFunctionExpression.isUsable()) { 10970 if (complain) { 10971 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10972 << ovl.Expression->getName() 10973 << DestTypeForComplaining 10974 << OpRangeForComplaining 10975 << ovl.Expression->getQualifierLoc().getSourceRange(); 10976 NoteAllOverloadCandidates(SrcExpr.get()); 10977 10978 SrcExpr = ExprError(); 10979 return true; 10980 } 10981 10982 return false; 10983 } 10984 10985 SrcExpr = SingleFunctionExpression; 10986 return true; 10987 } 10988 10989 /// \brief Add a single candidate to the overload set. 10990 static void AddOverloadedCallCandidate(Sema &S, 10991 DeclAccessPair FoundDecl, 10992 TemplateArgumentListInfo *ExplicitTemplateArgs, 10993 ArrayRef<Expr *> Args, 10994 OverloadCandidateSet &CandidateSet, 10995 bool PartialOverloading, 10996 bool KnownValid) { 10997 NamedDecl *Callee = FoundDecl.getDecl(); 10998 if (isa<UsingShadowDecl>(Callee)) 10999 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11000 11001 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11002 if (ExplicitTemplateArgs) { 11003 assert(!KnownValid && "Explicit template arguments?"); 11004 return; 11005 } 11006 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11007 /*SuppressUsedConversions=*/false, 11008 PartialOverloading); 11009 return; 11010 } 11011 11012 if (FunctionTemplateDecl *FuncTemplate 11013 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11014 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11015 ExplicitTemplateArgs, Args, CandidateSet, 11016 /*SuppressUsedConversions=*/false, 11017 PartialOverloading); 11018 return; 11019 } 11020 11021 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11022 } 11023 11024 /// \brief Add the overload candidates named by callee and/or found by argument 11025 /// dependent lookup to the given overload set. 11026 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11027 ArrayRef<Expr *> Args, 11028 OverloadCandidateSet &CandidateSet, 11029 bool PartialOverloading) { 11030 11031 #ifndef NDEBUG 11032 // Verify that ArgumentDependentLookup is consistent with the rules 11033 // in C++0x [basic.lookup.argdep]p3: 11034 // 11035 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11036 // and let Y be the lookup set produced by argument dependent 11037 // lookup (defined as follows). If X contains 11038 // 11039 // -- a declaration of a class member, or 11040 // 11041 // -- a block-scope function declaration that is not a 11042 // using-declaration, or 11043 // 11044 // -- a declaration that is neither a function or a function 11045 // template 11046 // 11047 // then Y is empty. 11048 11049 if (ULE->requiresADL()) { 11050 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11051 E = ULE->decls_end(); I != E; ++I) { 11052 assert(!(*I)->getDeclContext()->isRecord()); 11053 assert(isa<UsingShadowDecl>(*I) || 11054 !(*I)->getDeclContext()->isFunctionOrMethod()); 11055 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11056 } 11057 } 11058 #endif 11059 11060 // It would be nice to avoid this copy. 11061 TemplateArgumentListInfo TABuffer; 11062 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11063 if (ULE->hasExplicitTemplateArgs()) { 11064 ULE->copyTemplateArgumentsInto(TABuffer); 11065 ExplicitTemplateArgs = &TABuffer; 11066 } 11067 11068 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11069 E = ULE->decls_end(); I != E; ++I) 11070 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11071 CandidateSet, PartialOverloading, 11072 /*KnownValid*/ true); 11073 11074 if (ULE->requiresADL()) 11075 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11076 Args, ExplicitTemplateArgs, 11077 CandidateSet, PartialOverloading); 11078 } 11079 11080 /// Determine whether a declaration with the specified name could be moved into 11081 /// a different namespace. 11082 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11083 switch (Name.getCXXOverloadedOperator()) { 11084 case OO_New: case OO_Array_New: 11085 case OO_Delete: case OO_Array_Delete: 11086 return false; 11087 11088 default: 11089 return true; 11090 } 11091 } 11092 11093 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11094 /// template, where the non-dependent name was declared after the template 11095 /// was defined. This is common in code written for a compilers which do not 11096 /// correctly implement two-stage name lookup. 11097 /// 11098 /// Returns true if a viable candidate was found and a diagnostic was issued. 11099 static bool 11100 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11101 const CXXScopeSpec &SS, LookupResult &R, 11102 OverloadCandidateSet::CandidateSetKind CSK, 11103 TemplateArgumentListInfo *ExplicitTemplateArgs, 11104 ArrayRef<Expr *> Args, 11105 bool *DoDiagnoseEmptyLookup = nullptr) { 11106 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11107 return false; 11108 11109 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11110 if (DC->isTransparentContext()) 11111 continue; 11112 11113 SemaRef.LookupQualifiedName(R, DC); 11114 11115 if (!R.empty()) { 11116 R.suppressDiagnostics(); 11117 11118 if (isa<CXXRecordDecl>(DC)) { 11119 // Don't diagnose names we find in classes; we get much better 11120 // diagnostics for these from DiagnoseEmptyLookup. 11121 R.clear(); 11122 if (DoDiagnoseEmptyLookup) 11123 *DoDiagnoseEmptyLookup = true; 11124 return false; 11125 } 11126 11127 OverloadCandidateSet Candidates(FnLoc, CSK); 11128 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11129 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11130 ExplicitTemplateArgs, Args, 11131 Candidates, false, /*KnownValid*/ false); 11132 11133 OverloadCandidateSet::iterator Best; 11134 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11135 // No viable functions. Don't bother the user with notes for functions 11136 // which don't work and shouldn't be found anyway. 11137 R.clear(); 11138 return false; 11139 } 11140 11141 // Find the namespaces where ADL would have looked, and suggest 11142 // declaring the function there instead. 11143 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11144 Sema::AssociatedClassSet AssociatedClasses; 11145 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11146 AssociatedNamespaces, 11147 AssociatedClasses); 11148 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11149 if (canBeDeclaredInNamespace(R.getLookupName())) { 11150 DeclContext *Std = SemaRef.getStdNamespace(); 11151 for (Sema::AssociatedNamespaceSet::iterator 11152 it = AssociatedNamespaces.begin(), 11153 end = AssociatedNamespaces.end(); it != end; ++it) { 11154 // Never suggest declaring a function within namespace 'std'. 11155 if (Std && Std->Encloses(*it)) 11156 continue; 11157 11158 // Never suggest declaring a function within a namespace with a 11159 // reserved name, like __gnu_cxx. 11160 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11161 if (NS && 11162 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11163 continue; 11164 11165 SuggestedNamespaces.insert(*it); 11166 } 11167 } 11168 11169 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11170 << R.getLookupName(); 11171 if (SuggestedNamespaces.empty()) { 11172 SemaRef.Diag(Best->Function->getLocation(), 11173 diag::note_not_found_by_two_phase_lookup) 11174 << R.getLookupName() << 0; 11175 } else if (SuggestedNamespaces.size() == 1) { 11176 SemaRef.Diag(Best->Function->getLocation(), 11177 diag::note_not_found_by_two_phase_lookup) 11178 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11179 } else { 11180 // FIXME: It would be useful to list the associated namespaces here, 11181 // but the diagnostics infrastructure doesn't provide a way to produce 11182 // a localized representation of a list of items. 11183 SemaRef.Diag(Best->Function->getLocation(), 11184 diag::note_not_found_by_two_phase_lookup) 11185 << R.getLookupName() << 2; 11186 } 11187 11188 // Try to recover by calling this function. 11189 return true; 11190 } 11191 11192 R.clear(); 11193 } 11194 11195 return false; 11196 } 11197 11198 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11199 /// template, where the non-dependent operator was declared after the template 11200 /// was defined. 11201 /// 11202 /// Returns true if a viable candidate was found and a diagnostic was issued. 11203 static bool 11204 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11205 SourceLocation OpLoc, 11206 ArrayRef<Expr *> Args) { 11207 DeclarationName OpName = 11208 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11209 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11210 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11211 OverloadCandidateSet::CSK_Operator, 11212 /*ExplicitTemplateArgs=*/nullptr, Args); 11213 } 11214 11215 namespace { 11216 class BuildRecoveryCallExprRAII { 11217 Sema &SemaRef; 11218 public: 11219 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11220 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11221 SemaRef.IsBuildingRecoveryCallExpr = true; 11222 } 11223 11224 ~BuildRecoveryCallExprRAII() { 11225 SemaRef.IsBuildingRecoveryCallExpr = false; 11226 } 11227 }; 11228 11229 } 11230 11231 static std::unique_ptr<CorrectionCandidateCallback> 11232 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11233 bool HasTemplateArgs, bool AllowTypoCorrection) { 11234 if (!AllowTypoCorrection) 11235 return llvm::make_unique<NoTypoCorrectionCCC>(); 11236 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11237 HasTemplateArgs, ME); 11238 } 11239 11240 /// Attempts to recover from a call where no functions were found. 11241 /// 11242 /// Returns true if new candidates were found. 11243 static ExprResult 11244 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11245 UnresolvedLookupExpr *ULE, 11246 SourceLocation LParenLoc, 11247 MutableArrayRef<Expr *> Args, 11248 SourceLocation RParenLoc, 11249 bool EmptyLookup, bool AllowTypoCorrection) { 11250 // Do not try to recover if it is already building a recovery call. 11251 // This stops infinite loops for template instantiations like 11252 // 11253 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11254 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11255 // 11256 if (SemaRef.IsBuildingRecoveryCallExpr) 11257 return ExprError(); 11258 BuildRecoveryCallExprRAII RCE(SemaRef); 11259 11260 CXXScopeSpec SS; 11261 SS.Adopt(ULE->getQualifierLoc()); 11262 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11263 11264 TemplateArgumentListInfo TABuffer; 11265 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11266 if (ULE->hasExplicitTemplateArgs()) { 11267 ULE->copyTemplateArgumentsInto(TABuffer); 11268 ExplicitTemplateArgs = &TABuffer; 11269 } 11270 11271 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11272 Sema::LookupOrdinaryName); 11273 bool DoDiagnoseEmptyLookup = EmptyLookup; 11274 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11275 OverloadCandidateSet::CSK_Normal, 11276 ExplicitTemplateArgs, Args, 11277 &DoDiagnoseEmptyLookup) && 11278 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11279 S, SS, R, 11280 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11281 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11282 ExplicitTemplateArgs, Args))) 11283 return ExprError(); 11284 11285 assert(!R.empty() && "lookup results empty despite recovery"); 11286 11287 // Build an implicit member call if appropriate. Just drop the 11288 // casts and such from the call, we don't really care. 11289 ExprResult NewFn = ExprError(); 11290 if ((*R.begin())->isCXXClassMember()) 11291 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11292 ExplicitTemplateArgs, S); 11293 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11294 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11295 ExplicitTemplateArgs); 11296 else 11297 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11298 11299 if (NewFn.isInvalid()) 11300 return ExprError(); 11301 11302 // This shouldn't cause an infinite loop because we're giving it 11303 // an expression with viable lookup results, which should never 11304 // end up here. 11305 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11306 MultiExprArg(Args.data(), Args.size()), 11307 RParenLoc); 11308 } 11309 11310 /// \brief Constructs and populates an OverloadedCandidateSet from 11311 /// the given function. 11312 /// \returns true when an the ExprResult output parameter has been set. 11313 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11314 UnresolvedLookupExpr *ULE, 11315 MultiExprArg Args, 11316 SourceLocation RParenLoc, 11317 OverloadCandidateSet *CandidateSet, 11318 ExprResult *Result) { 11319 #ifndef NDEBUG 11320 if (ULE->requiresADL()) { 11321 // To do ADL, we must have found an unqualified name. 11322 assert(!ULE->getQualifier() && "qualified name with ADL"); 11323 11324 // We don't perform ADL for implicit declarations of builtins. 11325 // Verify that this was correctly set up. 11326 FunctionDecl *F; 11327 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11328 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11329 F->getBuiltinID() && F->isImplicit()) 11330 llvm_unreachable("performing ADL for builtin"); 11331 11332 // We don't perform ADL in C. 11333 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11334 } 11335 #endif 11336 11337 UnbridgedCastsSet UnbridgedCasts; 11338 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11339 *Result = ExprError(); 11340 return true; 11341 } 11342 11343 // Add the functions denoted by the callee to the set of candidate 11344 // functions, including those from argument-dependent lookup. 11345 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11346 11347 if (getLangOpts().MSVCCompat && 11348 CurContext->isDependentContext() && !isSFINAEContext() && 11349 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11350 11351 OverloadCandidateSet::iterator Best; 11352 if (CandidateSet->empty() || 11353 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11354 OR_No_Viable_Function) { 11355 // In Microsoft mode, if we are inside a template class member function then 11356 // create a type dependent CallExpr. The goal is to postpone name lookup 11357 // to instantiation time to be able to search into type dependent base 11358 // classes. 11359 CallExpr *CE = new (Context) CallExpr( 11360 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11361 CE->setTypeDependent(true); 11362 CE->setValueDependent(true); 11363 CE->setInstantiationDependent(true); 11364 *Result = CE; 11365 return true; 11366 } 11367 } 11368 11369 if (CandidateSet->empty()) 11370 return false; 11371 11372 UnbridgedCasts.restore(); 11373 return false; 11374 } 11375 11376 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11377 /// the completed call expression. If overload resolution fails, emits 11378 /// diagnostics and returns ExprError() 11379 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11380 UnresolvedLookupExpr *ULE, 11381 SourceLocation LParenLoc, 11382 MultiExprArg Args, 11383 SourceLocation RParenLoc, 11384 Expr *ExecConfig, 11385 OverloadCandidateSet *CandidateSet, 11386 OverloadCandidateSet::iterator *Best, 11387 OverloadingResult OverloadResult, 11388 bool AllowTypoCorrection) { 11389 if (CandidateSet->empty()) 11390 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11391 RParenLoc, /*EmptyLookup=*/true, 11392 AllowTypoCorrection); 11393 11394 switch (OverloadResult) { 11395 case OR_Success: { 11396 FunctionDecl *FDecl = (*Best)->Function; 11397 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11398 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11399 return ExprError(); 11400 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11401 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11402 ExecConfig); 11403 } 11404 11405 case OR_No_Viable_Function: { 11406 // Try to recover by looking for viable functions which the user might 11407 // have meant to call. 11408 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11409 Args, RParenLoc, 11410 /*EmptyLookup=*/false, 11411 AllowTypoCorrection); 11412 if (!Recovery.isInvalid()) 11413 return Recovery; 11414 11415 // If the user passes in a function that we can't take the address of, we 11416 // generally end up emitting really bad error messages. Here, we attempt to 11417 // emit better ones. 11418 for (const Expr *Arg : Args) { 11419 if (!Arg->getType()->isFunctionType()) 11420 continue; 11421 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11422 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11423 if (FD && 11424 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11425 Arg->getExprLoc())) 11426 return ExprError(); 11427 } 11428 } 11429 11430 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11431 << ULE->getName() << Fn->getSourceRange(); 11432 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11433 break; 11434 } 11435 11436 case OR_Ambiguous: 11437 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11438 << ULE->getName() << Fn->getSourceRange(); 11439 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11440 break; 11441 11442 case OR_Deleted: { 11443 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11444 << (*Best)->Function->isDeleted() 11445 << ULE->getName() 11446 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11447 << Fn->getSourceRange(); 11448 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11449 11450 // We emitted an error for the unvailable/deleted function call but keep 11451 // the call in the AST. 11452 FunctionDecl *FDecl = (*Best)->Function; 11453 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11454 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11455 ExecConfig); 11456 } 11457 } 11458 11459 // Overload resolution failed. 11460 return ExprError(); 11461 } 11462 11463 static void markUnaddressableCandidatesUnviable(Sema &S, 11464 OverloadCandidateSet &CS) { 11465 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11466 if (I->Viable && 11467 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11468 I->Viable = false; 11469 I->FailureKind = ovl_fail_addr_not_available; 11470 } 11471 } 11472 } 11473 11474 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11475 /// (which eventually refers to the declaration Func) and the call 11476 /// arguments Args/NumArgs, attempt to resolve the function call down 11477 /// to a specific function. If overload resolution succeeds, returns 11478 /// the call expression produced by overload resolution. 11479 /// Otherwise, emits diagnostics and returns ExprError. 11480 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11481 UnresolvedLookupExpr *ULE, 11482 SourceLocation LParenLoc, 11483 MultiExprArg Args, 11484 SourceLocation RParenLoc, 11485 Expr *ExecConfig, 11486 bool AllowTypoCorrection, 11487 bool CalleesAddressIsTaken) { 11488 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11489 OverloadCandidateSet::CSK_Normal); 11490 ExprResult result; 11491 11492 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11493 &result)) 11494 return result; 11495 11496 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11497 // functions that aren't addressible are considered unviable. 11498 if (CalleesAddressIsTaken) 11499 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11500 11501 OverloadCandidateSet::iterator Best; 11502 OverloadingResult OverloadResult = 11503 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11504 11505 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11506 RParenLoc, ExecConfig, &CandidateSet, 11507 &Best, OverloadResult, 11508 AllowTypoCorrection); 11509 } 11510 11511 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11512 return Functions.size() > 1 || 11513 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11514 } 11515 11516 /// \brief Create a unary operation that may resolve to an overloaded 11517 /// operator. 11518 /// 11519 /// \param OpLoc The location of the operator itself (e.g., '*'). 11520 /// 11521 /// \param Opc The UnaryOperatorKind that describes this operator. 11522 /// 11523 /// \param Fns The set of non-member functions that will be 11524 /// considered by overload resolution. The caller needs to build this 11525 /// set based on the context using, e.g., 11526 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11527 /// set should not contain any member functions; those will be added 11528 /// by CreateOverloadedUnaryOp(). 11529 /// 11530 /// \param Input The input argument. 11531 ExprResult 11532 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11533 const UnresolvedSetImpl &Fns, 11534 Expr *Input) { 11535 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11536 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11537 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11538 // TODO: provide better source location info. 11539 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11540 11541 if (checkPlaceholderForOverload(*this, Input)) 11542 return ExprError(); 11543 11544 Expr *Args[2] = { Input, nullptr }; 11545 unsigned NumArgs = 1; 11546 11547 // For post-increment and post-decrement, add the implicit '0' as 11548 // the second argument, so that we know this is a post-increment or 11549 // post-decrement. 11550 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11551 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11552 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11553 SourceLocation()); 11554 NumArgs = 2; 11555 } 11556 11557 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11558 11559 if (Input->isTypeDependent()) { 11560 if (Fns.empty()) 11561 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11562 VK_RValue, OK_Ordinary, OpLoc); 11563 11564 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11565 UnresolvedLookupExpr *Fn 11566 = UnresolvedLookupExpr::Create(Context, NamingClass, 11567 NestedNameSpecifierLoc(), OpNameInfo, 11568 /*ADL*/ true, IsOverloaded(Fns), 11569 Fns.begin(), Fns.end()); 11570 return new (Context) 11571 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11572 VK_RValue, OpLoc, false); 11573 } 11574 11575 // Build an empty overload set. 11576 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11577 11578 // Add the candidates from the given function set. 11579 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11580 11581 // Add operator candidates that are member functions. 11582 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11583 11584 // Add candidates from ADL. 11585 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11586 /*ExplicitTemplateArgs*/nullptr, 11587 CandidateSet); 11588 11589 // Add builtin operator candidates. 11590 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11591 11592 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11593 11594 // Perform overload resolution. 11595 OverloadCandidateSet::iterator Best; 11596 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11597 case OR_Success: { 11598 // We found a built-in operator or an overloaded operator. 11599 FunctionDecl *FnDecl = Best->Function; 11600 11601 if (FnDecl) { 11602 // We matched an overloaded operator. Build a call to that 11603 // operator. 11604 11605 // Convert the arguments. 11606 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11607 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11608 11609 ExprResult InputRes = 11610 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11611 Best->FoundDecl, Method); 11612 if (InputRes.isInvalid()) 11613 return ExprError(); 11614 Input = InputRes.get(); 11615 } else { 11616 // Convert the arguments. 11617 ExprResult InputInit 11618 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11619 Context, 11620 FnDecl->getParamDecl(0)), 11621 SourceLocation(), 11622 Input); 11623 if (InputInit.isInvalid()) 11624 return ExprError(); 11625 Input = InputInit.get(); 11626 } 11627 11628 // Build the actual expression node. 11629 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11630 HadMultipleCandidates, OpLoc); 11631 if (FnExpr.isInvalid()) 11632 return ExprError(); 11633 11634 // Determine the result type. 11635 QualType ResultTy = FnDecl->getReturnType(); 11636 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11637 ResultTy = ResultTy.getNonLValueExprType(Context); 11638 11639 Args[0] = Input; 11640 CallExpr *TheCall = 11641 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11642 ResultTy, VK, OpLoc, false); 11643 11644 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11645 return ExprError(); 11646 11647 return MaybeBindToTemporary(TheCall); 11648 } else { 11649 // We matched a built-in operator. Convert the arguments, then 11650 // break out so that we will build the appropriate built-in 11651 // operator node. 11652 ExprResult InputRes = 11653 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11654 Best->Conversions[0], AA_Passing); 11655 if (InputRes.isInvalid()) 11656 return ExprError(); 11657 Input = InputRes.get(); 11658 break; 11659 } 11660 } 11661 11662 case OR_No_Viable_Function: 11663 // This is an erroneous use of an operator which can be overloaded by 11664 // a non-member function. Check for non-member operators which were 11665 // defined too late to be candidates. 11666 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11667 // FIXME: Recover by calling the found function. 11668 return ExprError(); 11669 11670 // No viable function; fall through to handling this as a 11671 // built-in operator, which will produce an error message for us. 11672 break; 11673 11674 case OR_Ambiguous: 11675 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11676 << UnaryOperator::getOpcodeStr(Opc) 11677 << Input->getType() 11678 << Input->getSourceRange(); 11679 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11680 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11681 return ExprError(); 11682 11683 case OR_Deleted: 11684 Diag(OpLoc, diag::err_ovl_deleted_oper) 11685 << Best->Function->isDeleted() 11686 << UnaryOperator::getOpcodeStr(Opc) 11687 << getDeletedOrUnavailableSuffix(Best->Function) 11688 << Input->getSourceRange(); 11689 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11690 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11691 return ExprError(); 11692 } 11693 11694 // Either we found no viable overloaded operator or we matched a 11695 // built-in operator. In either case, fall through to trying to 11696 // build a built-in operation. 11697 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11698 } 11699 11700 /// \brief Create a binary operation that may resolve to an overloaded 11701 /// operator. 11702 /// 11703 /// \param OpLoc The location of the operator itself (e.g., '+'). 11704 /// 11705 /// \param Opc The BinaryOperatorKind that describes this operator. 11706 /// 11707 /// \param Fns The set of non-member functions that will be 11708 /// considered by overload resolution. The caller needs to build this 11709 /// set based on the context using, e.g., 11710 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11711 /// set should not contain any member functions; those will be added 11712 /// by CreateOverloadedBinOp(). 11713 /// 11714 /// \param LHS Left-hand argument. 11715 /// \param RHS Right-hand argument. 11716 ExprResult 11717 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11718 BinaryOperatorKind Opc, 11719 const UnresolvedSetImpl &Fns, 11720 Expr *LHS, Expr *RHS) { 11721 Expr *Args[2] = { LHS, RHS }; 11722 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11723 11724 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11725 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11726 11727 // If either side is type-dependent, create an appropriate dependent 11728 // expression. 11729 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11730 if (Fns.empty()) { 11731 // If there are no functions to store, just build a dependent 11732 // BinaryOperator or CompoundAssignment. 11733 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11734 return new (Context) BinaryOperator( 11735 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11736 OpLoc, FPFeatures.fp_contract); 11737 11738 return new (Context) CompoundAssignOperator( 11739 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11740 Context.DependentTy, Context.DependentTy, OpLoc, 11741 FPFeatures.fp_contract); 11742 } 11743 11744 // FIXME: save results of ADL from here? 11745 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11746 // TODO: provide better source location info in DNLoc component. 11747 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11748 UnresolvedLookupExpr *Fn 11749 = UnresolvedLookupExpr::Create(Context, NamingClass, 11750 NestedNameSpecifierLoc(), OpNameInfo, 11751 /*ADL*/ true, IsOverloaded(Fns), 11752 Fns.begin(), Fns.end()); 11753 return new (Context) 11754 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11755 VK_RValue, OpLoc, FPFeatures.fp_contract); 11756 } 11757 11758 // Always do placeholder-like conversions on the RHS. 11759 if (checkPlaceholderForOverload(*this, Args[1])) 11760 return ExprError(); 11761 11762 // Do placeholder-like conversion on the LHS; note that we should 11763 // not get here with a PseudoObject LHS. 11764 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11765 if (checkPlaceholderForOverload(*this, Args[0])) 11766 return ExprError(); 11767 11768 // If this is the assignment operator, we only perform overload resolution 11769 // if the left-hand side is a class or enumeration type. This is actually 11770 // a hack. The standard requires that we do overload resolution between the 11771 // various built-in candidates, but as DR507 points out, this can lead to 11772 // problems. So we do it this way, which pretty much follows what GCC does. 11773 // Note that we go the traditional code path for compound assignment forms. 11774 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11775 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11776 11777 // If this is the .* operator, which is not overloadable, just 11778 // create a built-in binary operator. 11779 if (Opc == BO_PtrMemD) 11780 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11781 11782 // Build an empty overload set. 11783 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11784 11785 // Add the candidates from the given function set. 11786 AddFunctionCandidates(Fns, Args, CandidateSet); 11787 11788 // Add operator candidates that are member functions. 11789 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11790 11791 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11792 // performed for an assignment operator (nor for operator[] nor operator->, 11793 // which don't get here). 11794 if (Opc != BO_Assign) 11795 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11796 /*ExplicitTemplateArgs*/ nullptr, 11797 CandidateSet); 11798 11799 // Add builtin operator candidates. 11800 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11801 11802 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11803 11804 // Perform overload resolution. 11805 OverloadCandidateSet::iterator Best; 11806 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11807 case OR_Success: { 11808 // We found a built-in operator or an overloaded operator. 11809 FunctionDecl *FnDecl = Best->Function; 11810 11811 if (FnDecl) { 11812 // We matched an overloaded operator. Build a call to that 11813 // operator. 11814 11815 // Convert the arguments. 11816 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11817 // Best->Access is only meaningful for class members. 11818 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11819 11820 ExprResult Arg1 = 11821 PerformCopyInitialization( 11822 InitializedEntity::InitializeParameter(Context, 11823 FnDecl->getParamDecl(0)), 11824 SourceLocation(), Args[1]); 11825 if (Arg1.isInvalid()) 11826 return ExprError(); 11827 11828 ExprResult Arg0 = 11829 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11830 Best->FoundDecl, Method); 11831 if (Arg0.isInvalid()) 11832 return ExprError(); 11833 Args[0] = Arg0.getAs<Expr>(); 11834 Args[1] = RHS = Arg1.getAs<Expr>(); 11835 } else { 11836 // Convert the arguments. 11837 ExprResult Arg0 = PerformCopyInitialization( 11838 InitializedEntity::InitializeParameter(Context, 11839 FnDecl->getParamDecl(0)), 11840 SourceLocation(), Args[0]); 11841 if (Arg0.isInvalid()) 11842 return ExprError(); 11843 11844 ExprResult Arg1 = 11845 PerformCopyInitialization( 11846 InitializedEntity::InitializeParameter(Context, 11847 FnDecl->getParamDecl(1)), 11848 SourceLocation(), Args[1]); 11849 if (Arg1.isInvalid()) 11850 return ExprError(); 11851 Args[0] = LHS = Arg0.getAs<Expr>(); 11852 Args[1] = RHS = Arg1.getAs<Expr>(); 11853 } 11854 11855 // Build the actual expression node. 11856 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11857 Best->FoundDecl, 11858 HadMultipleCandidates, OpLoc); 11859 if (FnExpr.isInvalid()) 11860 return ExprError(); 11861 11862 // Determine the result type. 11863 QualType ResultTy = FnDecl->getReturnType(); 11864 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11865 ResultTy = ResultTy.getNonLValueExprType(Context); 11866 11867 CXXOperatorCallExpr *TheCall = 11868 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11869 Args, ResultTy, VK, OpLoc, 11870 FPFeatures.fp_contract); 11871 11872 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11873 FnDecl)) 11874 return ExprError(); 11875 11876 ArrayRef<const Expr *> ArgsArray(Args, 2); 11877 // Cut off the implicit 'this'. 11878 if (isa<CXXMethodDecl>(FnDecl)) 11879 ArgsArray = ArgsArray.slice(1); 11880 11881 // Check for a self move. 11882 if (Op == OO_Equal) 11883 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11884 11885 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11886 TheCall->getSourceRange(), VariadicDoesNotApply); 11887 11888 return MaybeBindToTemporary(TheCall); 11889 } else { 11890 // We matched a built-in operator. Convert the arguments, then 11891 // break out so that we will build the appropriate built-in 11892 // operator node. 11893 ExprResult ArgsRes0 = 11894 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11895 Best->Conversions[0], AA_Passing); 11896 if (ArgsRes0.isInvalid()) 11897 return ExprError(); 11898 Args[0] = ArgsRes0.get(); 11899 11900 ExprResult ArgsRes1 = 11901 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11902 Best->Conversions[1], AA_Passing); 11903 if (ArgsRes1.isInvalid()) 11904 return ExprError(); 11905 Args[1] = ArgsRes1.get(); 11906 break; 11907 } 11908 } 11909 11910 case OR_No_Viable_Function: { 11911 // C++ [over.match.oper]p9: 11912 // If the operator is the operator , [...] and there are no 11913 // viable functions, then the operator is assumed to be the 11914 // built-in operator and interpreted according to clause 5. 11915 if (Opc == BO_Comma) 11916 break; 11917 11918 // For class as left operand for assignment or compound assigment 11919 // operator do not fall through to handling in built-in, but report that 11920 // no overloaded assignment operator found 11921 ExprResult Result = ExprError(); 11922 if (Args[0]->getType()->isRecordType() && 11923 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11924 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11925 << BinaryOperator::getOpcodeStr(Opc) 11926 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11927 if (Args[0]->getType()->isIncompleteType()) { 11928 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11929 << Args[0]->getType() 11930 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11931 } 11932 } else { 11933 // This is an erroneous use of an operator which can be overloaded by 11934 // a non-member function. Check for non-member operators which were 11935 // defined too late to be candidates. 11936 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11937 // FIXME: Recover by calling the found function. 11938 return ExprError(); 11939 11940 // No viable function; try to create a built-in operation, which will 11941 // produce an error. Then, show the non-viable candidates. 11942 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11943 } 11944 assert(Result.isInvalid() && 11945 "C++ binary operator overloading is missing candidates!"); 11946 if (Result.isInvalid()) 11947 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11948 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11949 return Result; 11950 } 11951 11952 case OR_Ambiguous: 11953 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11954 << BinaryOperator::getOpcodeStr(Opc) 11955 << Args[0]->getType() << Args[1]->getType() 11956 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11957 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11958 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11959 return ExprError(); 11960 11961 case OR_Deleted: 11962 if (isImplicitlyDeleted(Best->Function)) { 11963 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11964 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11965 << Context.getRecordType(Method->getParent()) 11966 << getSpecialMember(Method); 11967 11968 // The user probably meant to call this special member. Just 11969 // explain why it's deleted. 11970 NoteDeletedFunction(Method); 11971 return ExprError(); 11972 } else { 11973 Diag(OpLoc, diag::err_ovl_deleted_oper) 11974 << Best->Function->isDeleted() 11975 << BinaryOperator::getOpcodeStr(Opc) 11976 << getDeletedOrUnavailableSuffix(Best->Function) 11977 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11978 } 11979 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11980 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11981 return ExprError(); 11982 } 11983 11984 // We matched a built-in operator; build it. 11985 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11986 } 11987 11988 ExprResult 11989 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11990 SourceLocation RLoc, 11991 Expr *Base, Expr *Idx) { 11992 Expr *Args[2] = { Base, Idx }; 11993 DeclarationName OpName = 11994 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11995 11996 // If either side is type-dependent, create an appropriate dependent 11997 // expression. 11998 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11999 12000 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12001 // CHECKME: no 'operator' keyword? 12002 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12003 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12004 UnresolvedLookupExpr *Fn 12005 = UnresolvedLookupExpr::Create(Context, NamingClass, 12006 NestedNameSpecifierLoc(), OpNameInfo, 12007 /*ADL*/ true, /*Overloaded*/ false, 12008 UnresolvedSetIterator(), 12009 UnresolvedSetIterator()); 12010 // Can't add any actual overloads yet 12011 12012 return new (Context) 12013 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12014 Context.DependentTy, VK_RValue, RLoc, false); 12015 } 12016 12017 // Handle placeholders on both operands. 12018 if (checkPlaceholderForOverload(*this, Args[0])) 12019 return ExprError(); 12020 if (checkPlaceholderForOverload(*this, Args[1])) 12021 return ExprError(); 12022 12023 // Build an empty overload set. 12024 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12025 12026 // Subscript can only be overloaded as a member function. 12027 12028 // Add operator candidates that are member functions. 12029 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12030 12031 // Add builtin operator candidates. 12032 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12033 12034 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12035 12036 // Perform overload resolution. 12037 OverloadCandidateSet::iterator Best; 12038 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12039 case OR_Success: { 12040 // We found a built-in operator or an overloaded operator. 12041 FunctionDecl *FnDecl = Best->Function; 12042 12043 if (FnDecl) { 12044 // We matched an overloaded operator. Build a call to that 12045 // operator. 12046 12047 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12048 12049 // Convert the arguments. 12050 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12051 ExprResult Arg0 = 12052 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12053 Best->FoundDecl, Method); 12054 if (Arg0.isInvalid()) 12055 return ExprError(); 12056 Args[0] = Arg0.get(); 12057 12058 // Convert the arguments. 12059 ExprResult InputInit 12060 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12061 Context, 12062 FnDecl->getParamDecl(0)), 12063 SourceLocation(), 12064 Args[1]); 12065 if (InputInit.isInvalid()) 12066 return ExprError(); 12067 12068 Args[1] = InputInit.getAs<Expr>(); 12069 12070 // Build the actual expression node. 12071 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12072 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12073 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12074 Best->FoundDecl, 12075 HadMultipleCandidates, 12076 OpLocInfo.getLoc(), 12077 OpLocInfo.getInfo()); 12078 if (FnExpr.isInvalid()) 12079 return ExprError(); 12080 12081 // Determine the result type 12082 QualType ResultTy = FnDecl->getReturnType(); 12083 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12084 ResultTy = ResultTy.getNonLValueExprType(Context); 12085 12086 CXXOperatorCallExpr *TheCall = 12087 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12088 FnExpr.get(), Args, 12089 ResultTy, VK, RLoc, 12090 false); 12091 12092 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12093 return ExprError(); 12094 12095 return MaybeBindToTemporary(TheCall); 12096 } else { 12097 // We matched a built-in operator. Convert the arguments, then 12098 // break out so that we will build the appropriate built-in 12099 // operator node. 12100 ExprResult ArgsRes0 = 12101 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12102 Best->Conversions[0], AA_Passing); 12103 if (ArgsRes0.isInvalid()) 12104 return ExprError(); 12105 Args[0] = ArgsRes0.get(); 12106 12107 ExprResult ArgsRes1 = 12108 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12109 Best->Conversions[1], AA_Passing); 12110 if (ArgsRes1.isInvalid()) 12111 return ExprError(); 12112 Args[1] = ArgsRes1.get(); 12113 12114 break; 12115 } 12116 } 12117 12118 case OR_No_Viable_Function: { 12119 if (CandidateSet.empty()) 12120 Diag(LLoc, diag::err_ovl_no_oper) 12121 << Args[0]->getType() << /*subscript*/ 0 12122 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12123 else 12124 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12125 << Args[0]->getType() 12126 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12127 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12128 "[]", LLoc); 12129 return ExprError(); 12130 } 12131 12132 case OR_Ambiguous: 12133 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12134 << "[]" 12135 << Args[0]->getType() << Args[1]->getType() 12136 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12137 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12138 "[]", LLoc); 12139 return ExprError(); 12140 12141 case OR_Deleted: 12142 Diag(LLoc, diag::err_ovl_deleted_oper) 12143 << Best->Function->isDeleted() << "[]" 12144 << getDeletedOrUnavailableSuffix(Best->Function) 12145 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12146 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12147 "[]", LLoc); 12148 return ExprError(); 12149 } 12150 12151 // We matched a built-in operator; build it. 12152 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12153 } 12154 12155 /// BuildCallToMemberFunction - Build a call to a member 12156 /// function. MemExpr is the expression that refers to the member 12157 /// function (and includes the object parameter), Args/NumArgs are the 12158 /// arguments to the function call (not including the object 12159 /// parameter). The caller needs to validate that the member 12160 /// expression refers to a non-static member function or an overloaded 12161 /// member function. 12162 ExprResult 12163 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12164 SourceLocation LParenLoc, 12165 MultiExprArg Args, 12166 SourceLocation RParenLoc) { 12167 assert(MemExprE->getType() == Context.BoundMemberTy || 12168 MemExprE->getType() == Context.OverloadTy); 12169 12170 // Dig out the member expression. This holds both the object 12171 // argument and the member function we're referring to. 12172 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12173 12174 // Determine whether this is a call to a pointer-to-member function. 12175 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12176 assert(op->getType() == Context.BoundMemberTy); 12177 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12178 12179 QualType fnType = 12180 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12181 12182 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12183 QualType resultType = proto->getCallResultType(Context); 12184 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12185 12186 // Check that the object type isn't more qualified than the 12187 // member function we're calling. 12188 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12189 12190 QualType objectType = op->getLHS()->getType(); 12191 if (op->getOpcode() == BO_PtrMemI) 12192 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12193 Qualifiers objectQuals = objectType.getQualifiers(); 12194 12195 Qualifiers difference = objectQuals - funcQuals; 12196 difference.removeObjCGCAttr(); 12197 difference.removeAddressSpace(); 12198 if (difference) { 12199 std::string qualsString = difference.getAsString(); 12200 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12201 << fnType.getUnqualifiedType() 12202 << qualsString 12203 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12204 } 12205 12206 CXXMemberCallExpr *call 12207 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12208 resultType, valueKind, RParenLoc); 12209 12210 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12211 call, nullptr)) 12212 return ExprError(); 12213 12214 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12215 return ExprError(); 12216 12217 if (CheckOtherCall(call, proto)) 12218 return ExprError(); 12219 12220 return MaybeBindToTemporary(call); 12221 } 12222 12223 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12224 return new (Context) 12225 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12226 12227 UnbridgedCastsSet UnbridgedCasts; 12228 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12229 return ExprError(); 12230 12231 MemberExpr *MemExpr; 12232 CXXMethodDecl *Method = nullptr; 12233 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12234 NestedNameSpecifier *Qualifier = nullptr; 12235 if (isa<MemberExpr>(NakedMemExpr)) { 12236 MemExpr = cast<MemberExpr>(NakedMemExpr); 12237 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12238 FoundDecl = MemExpr->getFoundDecl(); 12239 Qualifier = MemExpr->getQualifier(); 12240 UnbridgedCasts.restore(); 12241 } else { 12242 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12243 Qualifier = UnresExpr->getQualifier(); 12244 12245 QualType ObjectType = UnresExpr->getBaseType(); 12246 Expr::Classification ObjectClassification 12247 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12248 : UnresExpr->getBase()->Classify(Context); 12249 12250 // Add overload candidates 12251 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12252 OverloadCandidateSet::CSK_Normal); 12253 12254 // FIXME: avoid copy. 12255 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12256 if (UnresExpr->hasExplicitTemplateArgs()) { 12257 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12258 TemplateArgs = &TemplateArgsBuffer; 12259 } 12260 12261 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12262 E = UnresExpr->decls_end(); I != E; ++I) { 12263 12264 NamedDecl *Func = *I; 12265 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12266 if (isa<UsingShadowDecl>(Func)) 12267 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12268 12269 12270 // Microsoft supports direct constructor calls. 12271 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12272 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12273 Args, CandidateSet); 12274 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12275 // If explicit template arguments were provided, we can't call a 12276 // non-template member function. 12277 if (TemplateArgs) 12278 continue; 12279 12280 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12281 ObjectClassification, Args, CandidateSet, 12282 /*SuppressUserConversions=*/false); 12283 } else { 12284 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12285 I.getPair(), ActingDC, TemplateArgs, 12286 ObjectType, ObjectClassification, 12287 Args, CandidateSet, 12288 /*SuppressUsedConversions=*/false); 12289 } 12290 } 12291 12292 DeclarationName DeclName = UnresExpr->getMemberName(); 12293 12294 UnbridgedCasts.restore(); 12295 12296 OverloadCandidateSet::iterator Best; 12297 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12298 Best)) { 12299 case OR_Success: 12300 Method = cast<CXXMethodDecl>(Best->Function); 12301 FoundDecl = Best->FoundDecl; 12302 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12303 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12304 return ExprError(); 12305 // If FoundDecl is different from Method (such as if one is a template 12306 // and the other a specialization), make sure DiagnoseUseOfDecl is 12307 // called on both. 12308 // FIXME: This would be more comprehensively addressed by modifying 12309 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12310 // being used. 12311 if (Method != FoundDecl.getDecl() && 12312 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12313 return ExprError(); 12314 break; 12315 12316 case OR_No_Viable_Function: 12317 Diag(UnresExpr->getMemberLoc(), 12318 diag::err_ovl_no_viable_member_function_in_call) 12319 << DeclName << MemExprE->getSourceRange(); 12320 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12321 // FIXME: Leaking incoming expressions! 12322 return ExprError(); 12323 12324 case OR_Ambiguous: 12325 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12326 << DeclName << MemExprE->getSourceRange(); 12327 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12328 // FIXME: Leaking incoming expressions! 12329 return ExprError(); 12330 12331 case OR_Deleted: 12332 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12333 << Best->Function->isDeleted() 12334 << DeclName 12335 << getDeletedOrUnavailableSuffix(Best->Function) 12336 << MemExprE->getSourceRange(); 12337 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12338 // FIXME: Leaking incoming expressions! 12339 return ExprError(); 12340 } 12341 12342 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12343 12344 // If overload resolution picked a static member, build a 12345 // non-member call based on that function. 12346 if (Method->isStatic()) { 12347 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12348 RParenLoc); 12349 } 12350 12351 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12352 } 12353 12354 QualType ResultType = Method->getReturnType(); 12355 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12356 ResultType = ResultType.getNonLValueExprType(Context); 12357 12358 assert(Method && "Member call to something that isn't a method?"); 12359 CXXMemberCallExpr *TheCall = 12360 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12361 ResultType, VK, RParenLoc); 12362 12363 // Check for a valid return type. 12364 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12365 TheCall, Method)) 12366 return ExprError(); 12367 12368 // Convert the object argument (for a non-static member function call). 12369 // We only need to do this if there was actually an overload; otherwise 12370 // it was done at lookup. 12371 if (!Method->isStatic()) { 12372 ExprResult ObjectArg = 12373 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12374 FoundDecl, Method); 12375 if (ObjectArg.isInvalid()) 12376 return ExprError(); 12377 MemExpr->setBase(ObjectArg.get()); 12378 } 12379 12380 // Convert the rest of the arguments 12381 const FunctionProtoType *Proto = 12382 Method->getType()->getAs<FunctionProtoType>(); 12383 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12384 RParenLoc)) 12385 return ExprError(); 12386 12387 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12388 12389 if (CheckFunctionCall(Method, TheCall, Proto)) 12390 return ExprError(); 12391 12392 // In the case the method to call was not selected by the overloading 12393 // resolution process, we still need to handle the enable_if attribute. Do 12394 // that here, so it will not hide previous -- and more relevant -- errors 12395 if (isa<MemberExpr>(NakedMemExpr)) { 12396 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12397 Diag(MemExprE->getLocStart(), 12398 diag::err_ovl_no_viable_member_function_in_call) 12399 << Method << Method->getSourceRange(); 12400 Diag(Method->getLocation(), 12401 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12402 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12403 return ExprError(); 12404 } 12405 } 12406 12407 if ((isa<CXXConstructorDecl>(CurContext) || 12408 isa<CXXDestructorDecl>(CurContext)) && 12409 TheCall->getMethodDecl()->isPure()) { 12410 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12411 12412 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12413 MemExpr->performsVirtualDispatch(getLangOpts())) { 12414 Diag(MemExpr->getLocStart(), 12415 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12416 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12417 << MD->getParent()->getDeclName(); 12418 12419 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12420 if (getLangOpts().AppleKext) 12421 Diag(MemExpr->getLocStart(), 12422 diag::note_pure_qualified_call_kext) 12423 << MD->getParent()->getDeclName() 12424 << MD->getDeclName(); 12425 } 12426 } 12427 12428 if (CXXDestructorDecl *DD = 12429 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12430 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12431 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12432 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12433 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12434 MemExpr->getMemberLoc()); 12435 } 12436 12437 return MaybeBindToTemporary(TheCall); 12438 } 12439 12440 /// BuildCallToObjectOfClassType - Build a call to an object of class 12441 /// type (C++ [over.call.object]), which can end up invoking an 12442 /// overloaded function call operator (@c operator()) or performing a 12443 /// user-defined conversion on the object argument. 12444 ExprResult 12445 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12446 SourceLocation LParenLoc, 12447 MultiExprArg Args, 12448 SourceLocation RParenLoc) { 12449 if (checkPlaceholderForOverload(*this, Obj)) 12450 return ExprError(); 12451 ExprResult Object = Obj; 12452 12453 UnbridgedCastsSet UnbridgedCasts; 12454 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12455 return ExprError(); 12456 12457 assert(Object.get()->getType()->isRecordType() && 12458 "Requires object type argument"); 12459 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12460 12461 // C++ [over.call.object]p1: 12462 // If the primary-expression E in the function call syntax 12463 // evaluates to a class object of type "cv T", then the set of 12464 // candidate functions includes at least the function call 12465 // operators of T. The function call operators of T are obtained by 12466 // ordinary lookup of the name operator() in the context of 12467 // (E).operator(). 12468 OverloadCandidateSet CandidateSet(LParenLoc, 12469 OverloadCandidateSet::CSK_Operator); 12470 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12471 12472 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12473 diag::err_incomplete_object_call, Object.get())) 12474 return true; 12475 12476 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12477 LookupQualifiedName(R, Record->getDecl()); 12478 R.suppressDiagnostics(); 12479 12480 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12481 Oper != OperEnd; ++Oper) { 12482 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12483 Object.get()->Classify(Context), 12484 Args, CandidateSet, 12485 /*SuppressUserConversions=*/ false); 12486 } 12487 12488 // C++ [over.call.object]p2: 12489 // In addition, for each (non-explicit in C++0x) conversion function 12490 // declared in T of the form 12491 // 12492 // operator conversion-type-id () cv-qualifier; 12493 // 12494 // where cv-qualifier is the same cv-qualification as, or a 12495 // greater cv-qualification than, cv, and where conversion-type-id 12496 // denotes the type "pointer to function of (P1,...,Pn) returning 12497 // R", or the type "reference to pointer to function of 12498 // (P1,...,Pn) returning R", or the type "reference to function 12499 // of (P1,...,Pn) returning R", a surrogate call function [...] 12500 // is also considered as a candidate function. Similarly, 12501 // surrogate call functions are added to the set of candidate 12502 // functions for each conversion function declared in an 12503 // accessible base class provided the function is not hidden 12504 // within T by another intervening declaration. 12505 const auto &Conversions = 12506 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12507 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12508 NamedDecl *D = *I; 12509 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12510 if (isa<UsingShadowDecl>(D)) 12511 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12512 12513 // Skip over templated conversion functions; they aren't 12514 // surrogates. 12515 if (isa<FunctionTemplateDecl>(D)) 12516 continue; 12517 12518 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12519 if (!Conv->isExplicit()) { 12520 // Strip the reference type (if any) and then the pointer type (if 12521 // any) to get down to what might be a function type. 12522 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12523 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12524 ConvType = ConvPtrType->getPointeeType(); 12525 12526 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12527 { 12528 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12529 Object.get(), Args, CandidateSet); 12530 } 12531 } 12532 } 12533 12534 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12535 12536 // Perform overload resolution. 12537 OverloadCandidateSet::iterator Best; 12538 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12539 Best)) { 12540 case OR_Success: 12541 // Overload resolution succeeded; we'll build the appropriate call 12542 // below. 12543 break; 12544 12545 case OR_No_Viable_Function: 12546 if (CandidateSet.empty()) 12547 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12548 << Object.get()->getType() << /*call*/ 1 12549 << Object.get()->getSourceRange(); 12550 else 12551 Diag(Object.get()->getLocStart(), 12552 diag::err_ovl_no_viable_object_call) 12553 << Object.get()->getType() << Object.get()->getSourceRange(); 12554 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12555 break; 12556 12557 case OR_Ambiguous: 12558 Diag(Object.get()->getLocStart(), 12559 diag::err_ovl_ambiguous_object_call) 12560 << Object.get()->getType() << Object.get()->getSourceRange(); 12561 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12562 break; 12563 12564 case OR_Deleted: 12565 Diag(Object.get()->getLocStart(), 12566 diag::err_ovl_deleted_object_call) 12567 << Best->Function->isDeleted() 12568 << Object.get()->getType() 12569 << getDeletedOrUnavailableSuffix(Best->Function) 12570 << Object.get()->getSourceRange(); 12571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12572 break; 12573 } 12574 12575 if (Best == CandidateSet.end()) 12576 return true; 12577 12578 UnbridgedCasts.restore(); 12579 12580 if (Best->Function == nullptr) { 12581 // Since there is no function declaration, this is one of the 12582 // surrogate candidates. Dig out the conversion function. 12583 CXXConversionDecl *Conv 12584 = cast<CXXConversionDecl>( 12585 Best->Conversions[0].UserDefined.ConversionFunction); 12586 12587 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12588 Best->FoundDecl); 12589 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12590 return ExprError(); 12591 assert(Conv == Best->FoundDecl.getDecl() && 12592 "Found Decl & conversion-to-functionptr should be same, right?!"); 12593 // We selected one of the surrogate functions that converts the 12594 // object parameter to a function pointer. Perform the conversion 12595 // on the object argument, then let ActOnCallExpr finish the job. 12596 12597 // Create an implicit member expr to refer to the conversion operator. 12598 // and then call it. 12599 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12600 Conv, HadMultipleCandidates); 12601 if (Call.isInvalid()) 12602 return ExprError(); 12603 // Record usage of conversion in an implicit cast. 12604 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12605 CK_UserDefinedConversion, Call.get(), 12606 nullptr, VK_RValue); 12607 12608 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12609 } 12610 12611 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12612 12613 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12614 // that calls this method, using Object for the implicit object 12615 // parameter and passing along the remaining arguments. 12616 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12617 12618 // An error diagnostic has already been printed when parsing the declaration. 12619 if (Method->isInvalidDecl()) 12620 return ExprError(); 12621 12622 const FunctionProtoType *Proto = 12623 Method->getType()->getAs<FunctionProtoType>(); 12624 12625 unsigned NumParams = Proto->getNumParams(); 12626 12627 DeclarationNameInfo OpLocInfo( 12628 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12629 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12630 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12631 HadMultipleCandidates, 12632 OpLocInfo.getLoc(), 12633 OpLocInfo.getInfo()); 12634 if (NewFn.isInvalid()) 12635 return true; 12636 12637 // Build the full argument list for the method call (the implicit object 12638 // parameter is placed at the beginning of the list). 12639 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12640 MethodArgs[0] = Object.get(); 12641 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12642 12643 // Once we've built TheCall, all of the expressions are properly 12644 // owned. 12645 QualType ResultTy = Method->getReturnType(); 12646 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12647 ResultTy = ResultTy.getNonLValueExprType(Context); 12648 12649 CXXOperatorCallExpr *TheCall = new (Context) 12650 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12651 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12652 ResultTy, VK, RParenLoc, false); 12653 MethodArgs.reset(); 12654 12655 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12656 return true; 12657 12658 // We may have default arguments. If so, we need to allocate more 12659 // slots in the call for them. 12660 if (Args.size() < NumParams) 12661 TheCall->setNumArgs(Context, NumParams + 1); 12662 12663 bool IsError = false; 12664 12665 // Initialize the implicit object parameter. 12666 ExprResult ObjRes = 12667 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12668 Best->FoundDecl, Method); 12669 if (ObjRes.isInvalid()) 12670 IsError = true; 12671 else 12672 Object = ObjRes; 12673 TheCall->setArg(0, Object.get()); 12674 12675 // Check the argument types. 12676 for (unsigned i = 0; i != NumParams; i++) { 12677 Expr *Arg; 12678 if (i < Args.size()) { 12679 Arg = Args[i]; 12680 12681 // Pass the argument. 12682 12683 ExprResult InputInit 12684 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12685 Context, 12686 Method->getParamDecl(i)), 12687 SourceLocation(), Arg); 12688 12689 IsError |= InputInit.isInvalid(); 12690 Arg = InputInit.getAs<Expr>(); 12691 } else { 12692 ExprResult DefArg 12693 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12694 if (DefArg.isInvalid()) { 12695 IsError = true; 12696 break; 12697 } 12698 12699 Arg = DefArg.getAs<Expr>(); 12700 } 12701 12702 TheCall->setArg(i + 1, Arg); 12703 } 12704 12705 // If this is a variadic call, handle args passed through "...". 12706 if (Proto->isVariadic()) { 12707 // Promote the arguments (C99 6.5.2.2p7). 12708 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12709 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12710 nullptr); 12711 IsError |= Arg.isInvalid(); 12712 TheCall->setArg(i + 1, Arg.get()); 12713 } 12714 } 12715 12716 if (IsError) return true; 12717 12718 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12719 12720 if (CheckFunctionCall(Method, TheCall, Proto)) 12721 return true; 12722 12723 return MaybeBindToTemporary(TheCall); 12724 } 12725 12726 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12727 /// (if one exists), where @c Base is an expression of class type and 12728 /// @c Member is the name of the member we're trying to find. 12729 ExprResult 12730 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12731 bool *NoArrowOperatorFound) { 12732 assert(Base->getType()->isRecordType() && 12733 "left-hand side must have class type"); 12734 12735 if (checkPlaceholderForOverload(*this, Base)) 12736 return ExprError(); 12737 12738 SourceLocation Loc = Base->getExprLoc(); 12739 12740 // C++ [over.ref]p1: 12741 // 12742 // [...] An expression x->m is interpreted as (x.operator->())->m 12743 // for a class object x of type T if T::operator->() exists and if 12744 // the operator is selected as the best match function by the 12745 // overload resolution mechanism (13.3). 12746 DeclarationName OpName = 12747 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12748 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12749 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12750 12751 if (RequireCompleteType(Loc, Base->getType(), 12752 diag::err_typecheck_incomplete_tag, Base)) 12753 return ExprError(); 12754 12755 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12756 LookupQualifiedName(R, BaseRecord->getDecl()); 12757 R.suppressDiagnostics(); 12758 12759 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12760 Oper != OperEnd; ++Oper) { 12761 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12762 None, CandidateSet, /*SuppressUserConversions=*/false); 12763 } 12764 12765 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12766 12767 // Perform overload resolution. 12768 OverloadCandidateSet::iterator Best; 12769 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12770 case OR_Success: 12771 // Overload resolution succeeded; we'll build the call below. 12772 break; 12773 12774 case OR_No_Viable_Function: 12775 if (CandidateSet.empty()) { 12776 QualType BaseType = Base->getType(); 12777 if (NoArrowOperatorFound) { 12778 // Report this specific error to the caller instead of emitting a 12779 // diagnostic, as requested. 12780 *NoArrowOperatorFound = true; 12781 return ExprError(); 12782 } 12783 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12784 << BaseType << Base->getSourceRange(); 12785 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12786 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12787 << FixItHint::CreateReplacement(OpLoc, "."); 12788 } 12789 } else 12790 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12791 << "operator->" << Base->getSourceRange(); 12792 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12793 return ExprError(); 12794 12795 case OR_Ambiguous: 12796 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12797 << "->" << Base->getType() << Base->getSourceRange(); 12798 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12799 return ExprError(); 12800 12801 case OR_Deleted: 12802 Diag(OpLoc, diag::err_ovl_deleted_oper) 12803 << Best->Function->isDeleted() 12804 << "->" 12805 << getDeletedOrUnavailableSuffix(Best->Function) 12806 << Base->getSourceRange(); 12807 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12808 return ExprError(); 12809 } 12810 12811 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12812 12813 // Convert the object parameter. 12814 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12815 ExprResult BaseResult = 12816 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12817 Best->FoundDecl, Method); 12818 if (BaseResult.isInvalid()) 12819 return ExprError(); 12820 Base = BaseResult.get(); 12821 12822 // Build the operator call. 12823 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12824 HadMultipleCandidates, OpLoc); 12825 if (FnExpr.isInvalid()) 12826 return ExprError(); 12827 12828 QualType ResultTy = Method->getReturnType(); 12829 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12830 ResultTy = ResultTy.getNonLValueExprType(Context); 12831 CXXOperatorCallExpr *TheCall = 12832 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12833 Base, ResultTy, VK, OpLoc, false); 12834 12835 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12836 return ExprError(); 12837 12838 return MaybeBindToTemporary(TheCall); 12839 } 12840 12841 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12842 /// a literal operator described by the provided lookup results. 12843 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12844 DeclarationNameInfo &SuffixInfo, 12845 ArrayRef<Expr*> Args, 12846 SourceLocation LitEndLoc, 12847 TemplateArgumentListInfo *TemplateArgs) { 12848 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12849 12850 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12851 OverloadCandidateSet::CSK_Normal); 12852 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12853 /*SuppressUserConversions=*/true); 12854 12855 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12856 12857 // Perform overload resolution. This will usually be trivial, but might need 12858 // to perform substitutions for a literal operator template. 12859 OverloadCandidateSet::iterator Best; 12860 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12861 case OR_Success: 12862 case OR_Deleted: 12863 break; 12864 12865 case OR_No_Viable_Function: 12866 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12867 << R.getLookupName(); 12868 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12869 return ExprError(); 12870 12871 case OR_Ambiguous: 12872 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12873 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12874 return ExprError(); 12875 } 12876 12877 FunctionDecl *FD = Best->Function; 12878 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12879 HadMultipleCandidates, 12880 SuffixInfo.getLoc(), 12881 SuffixInfo.getInfo()); 12882 if (Fn.isInvalid()) 12883 return true; 12884 12885 // Check the argument types. This should almost always be a no-op, except 12886 // that array-to-pointer decay is applied to string literals. 12887 Expr *ConvArgs[2]; 12888 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12889 ExprResult InputInit = PerformCopyInitialization( 12890 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12891 SourceLocation(), Args[ArgIdx]); 12892 if (InputInit.isInvalid()) 12893 return true; 12894 ConvArgs[ArgIdx] = InputInit.get(); 12895 } 12896 12897 QualType ResultTy = FD->getReturnType(); 12898 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12899 ResultTy = ResultTy.getNonLValueExprType(Context); 12900 12901 UserDefinedLiteral *UDL = 12902 new (Context) UserDefinedLiteral(Context, Fn.get(), 12903 llvm::makeArrayRef(ConvArgs, Args.size()), 12904 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12905 12906 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12907 return ExprError(); 12908 12909 if (CheckFunctionCall(FD, UDL, nullptr)) 12910 return ExprError(); 12911 12912 return MaybeBindToTemporary(UDL); 12913 } 12914 12915 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12916 /// given LookupResult is non-empty, it is assumed to describe a member which 12917 /// will be invoked. Otherwise, the function will be found via argument 12918 /// dependent lookup. 12919 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12920 /// otherwise CallExpr is set to ExprError() and some non-success value 12921 /// is returned. 12922 Sema::ForRangeStatus 12923 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12924 SourceLocation RangeLoc, 12925 const DeclarationNameInfo &NameInfo, 12926 LookupResult &MemberLookup, 12927 OverloadCandidateSet *CandidateSet, 12928 Expr *Range, ExprResult *CallExpr) { 12929 Scope *S = nullptr; 12930 12931 CandidateSet->clear(); 12932 if (!MemberLookup.empty()) { 12933 ExprResult MemberRef = 12934 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12935 /*IsPtr=*/false, CXXScopeSpec(), 12936 /*TemplateKWLoc=*/SourceLocation(), 12937 /*FirstQualifierInScope=*/nullptr, 12938 MemberLookup, 12939 /*TemplateArgs=*/nullptr, S); 12940 if (MemberRef.isInvalid()) { 12941 *CallExpr = ExprError(); 12942 return FRS_DiagnosticIssued; 12943 } 12944 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12945 if (CallExpr->isInvalid()) { 12946 *CallExpr = ExprError(); 12947 return FRS_DiagnosticIssued; 12948 } 12949 } else { 12950 UnresolvedSet<0> FoundNames; 12951 UnresolvedLookupExpr *Fn = 12952 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12953 NestedNameSpecifierLoc(), NameInfo, 12954 /*NeedsADL=*/true, /*Overloaded=*/false, 12955 FoundNames.begin(), FoundNames.end()); 12956 12957 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12958 CandidateSet, CallExpr); 12959 if (CandidateSet->empty() || CandidateSetError) { 12960 *CallExpr = ExprError(); 12961 return FRS_NoViableFunction; 12962 } 12963 OverloadCandidateSet::iterator Best; 12964 OverloadingResult OverloadResult = 12965 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12966 12967 if (OverloadResult == OR_No_Viable_Function) { 12968 *CallExpr = ExprError(); 12969 return FRS_NoViableFunction; 12970 } 12971 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12972 Loc, nullptr, CandidateSet, &Best, 12973 OverloadResult, 12974 /*AllowTypoCorrection=*/false); 12975 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12976 *CallExpr = ExprError(); 12977 return FRS_DiagnosticIssued; 12978 } 12979 } 12980 return FRS_Success; 12981 } 12982 12983 12984 /// FixOverloadedFunctionReference - E is an expression that refers to 12985 /// a C++ overloaded function (possibly with some parentheses and 12986 /// perhaps a '&' around it). We have resolved the overloaded function 12987 /// to the function declaration Fn, so patch up the expression E to 12988 /// refer (possibly indirectly) to Fn. Returns the new expr. 12989 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12990 FunctionDecl *Fn) { 12991 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12992 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12993 Found, Fn); 12994 if (SubExpr == PE->getSubExpr()) 12995 return PE; 12996 12997 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12998 } 12999 13000 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13001 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13002 Found, Fn); 13003 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13004 SubExpr->getType()) && 13005 "Implicit cast type cannot be determined from overload"); 13006 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13007 if (SubExpr == ICE->getSubExpr()) 13008 return ICE; 13009 13010 return ImplicitCastExpr::Create(Context, ICE->getType(), 13011 ICE->getCastKind(), 13012 SubExpr, nullptr, 13013 ICE->getValueKind()); 13014 } 13015 13016 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13017 if (!GSE->isResultDependent()) { 13018 Expr *SubExpr = 13019 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13020 if (SubExpr == GSE->getResultExpr()) 13021 return GSE; 13022 13023 // Replace the resulting type information before rebuilding the generic 13024 // selection expression. 13025 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13026 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13027 unsigned ResultIdx = GSE->getResultIndex(); 13028 AssocExprs[ResultIdx] = SubExpr; 13029 13030 return new (Context) GenericSelectionExpr( 13031 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13032 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13033 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13034 ResultIdx); 13035 } 13036 // Rather than fall through to the unreachable, return the original generic 13037 // selection expression. 13038 return GSE; 13039 } 13040 13041 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13042 assert(UnOp->getOpcode() == UO_AddrOf && 13043 "Can only take the address of an overloaded function"); 13044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13045 if (Method->isStatic()) { 13046 // Do nothing: static member functions aren't any different 13047 // from non-member functions. 13048 } else { 13049 // Fix the subexpression, which really has to be an 13050 // UnresolvedLookupExpr holding an overloaded member function 13051 // or template. 13052 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13053 Found, Fn); 13054 if (SubExpr == UnOp->getSubExpr()) 13055 return UnOp; 13056 13057 assert(isa<DeclRefExpr>(SubExpr) 13058 && "fixed to something other than a decl ref"); 13059 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13060 && "fixed to a member ref with no nested name qualifier"); 13061 13062 // We have taken the address of a pointer to member 13063 // function. Perform the computation here so that we get the 13064 // appropriate pointer to member type. 13065 QualType ClassType 13066 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13067 QualType MemPtrType 13068 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13069 // Under the MS ABI, lock down the inheritance model now. 13070 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13071 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13072 13073 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13074 VK_RValue, OK_Ordinary, 13075 UnOp->getOperatorLoc()); 13076 } 13077 } 13078 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13079 Found, Fn); 13080 if (SubExpr == UnOp->getSubExpr()) 13081 return UnOp; 13082 13083 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13084 Context.getPointerType(SubExpr->getType()), 13085 VK_RValue, OK_Ordinary, 13086 UnOp->getOperatorLoc()); 13087 } 13088 13089 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13090 // FIXME: avoid copy. 13091 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13092 if (ULE->hasExplicitTemplateArgs()) { 13093 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13094 TemplateArgs = &TemplateArgsBuffer; 13095 } 13096 13097 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13098 ULE->getQualifierLoc(), 13099 ULE->getTemplateKeywordLoc(), 13100 Fn, 13101 /*enclosing*/ false, // FIXME? 13102 ULE->getNameLoc(), 13103 Fn->getType(), 13104 VK_LValue, 13105 Found.getDecl(), 13106 TemplateArgs); 13107 MarkDeclRefReferenced(DRE); 13108 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13109 return DRE; 13110 } 13111 13112 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13113 // FIXME: avoid copy. 13114 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13115 if (MemExpr->hasExplicitTemplateArgs()) { 13116 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13117 TemplateArgs = &TemplateArgsBuffer; 13118 } 13119 13120 Expr *Base; 13121 13122 // If we're filling in a static method where we used to have an 13123 // implicit member access, rewrite to a simple decl ref. 13124 if (MemExpr->isImplicitAccess()) { 13125 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13126 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13127 MemExpr->getQualifierLoc(), 13128 MemExpr->getTemplateKeywordLoc(), 13129 Fn, 13130 /*enclosing*/ false, 13131 MemExpr->getMemberLoc(), 13132 Fn->getType(), 13133 VK_LValue, 13134 Found.getDecl(), 13135 TemplateArgs); 13136 MarkDeclRefReferenced(DRE); 13137 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13138 return DRE; 13139 } else { 13140 SourceLocation Loc = MemExpr->getMemberLoc(); 13141 if (MemExpr->getQualifier()) 13142 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13143 CheckCXXThisCapture(Loc); 13144 Base = new (Context) CXXThisExpr(Loc, 13145 MemExpr->getBaseType(), 13146 /*isImplicit=*/true); 13147 } 13148 } else 13149 Base = MemExpr->getBase(); 13150 13151 ExprValueKind valueKind; 13152 QualType type; 13153 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13154 valueKind = VK_LValue; 13155 type = Fn->getType(); 13156 } else { 13157 valueKind = VK_RValue; 13158 type = Context.BoundMemberTy; 13159 } 13160 13161 MemberExpr *ME = MemberExpr::Create( 13162 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13163 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13164 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13165 OK_Ordinary); 13166 ME->setHadMultipleCandidates(true); 13167 MarkMemberReferenced(ME); 13168 return ME; 13169 } 13170 13171 llvm_unreachable("Invalid reference to overloaded function"); 13172 } 13173 13174 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13175 DeclAccessPair Found, 13176 FunctionDecl *Fn) { 13177 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13178 } 13179