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 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 66 VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 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_Conversion, 133 ICR_Conversion, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isObjCObjectPointerType() || 226 getFromType()->isBlockPointerType() || 227 getFromType()->isNullPtrType() || 228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 229 return true; 230 231 return false; 232 } 233 234 /// isPointerConversionToVoidPointer - Determines whether this 235 /// conversion is a conversion of a pointer to a void pointer. This is 236 /// used as part of the ranking of standard conversion sequences (C++ 237 /// 13.3.3.2p4). 238 bool 239 StandardConversionSequence:: 240 isPointerConversionToVoidPointer(ASTContext& Context) const { 241 QualType FromType = getFromType(); 242 QualType ToType = getToType(1); 243 244 // Note that FromType has not necessarily been transformed by the 245 // array-to-pointer implicit conversion, so check for its presence 246 // and redo the conversion to get a pointer. 247 if (First == ICK_Array_To_Pointer) 248 FromType = Context.getArrayDecayedType(FromType); 249 250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 252 return ToPtrType->getPointeeType()->isVoidType(); 253 254 return false; 255 } 256 257 /// Skip any implicit casts which could be either part of a narrowing conversion 258 /// or after one in an implicit conversion. 259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 261 switch (ICE->getCastKind()) { 262 case CK_NoOp: 263 case CK_IntegralCast: 264 case CK_IntegralToBoolean: 265 case CK_IntegralToFloating: 266 case CK_BooleanToSignedIntegral: 267 case CK_FloatingToIntegral: 268 case CK_FloatingToBoolean: 269 case CK_FloatingCast: 270 Converted = ICE->getSubExpr(); 271 continue; 272 273 default: 274 return Converted; 275 } 276 } 277 278 return Converted; 279 } 280 281 /// Check if this standard conversion sequence represents a narrowing 282 /// conversion, according to C++11 [dcl.init.list]p7. 283 /// 284 /// \param Ctx The AST context. 285 /// \param Converted The result of applying this standard conversion sequence. 286 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 287 /// value of the expression prior to the narrowing conversion. 288 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 289 /// type of the expression prior to the narrowing conversion. 290 NarrowingKind 291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 292 const Expr *Converted, 293 APValue &ConstantValue, 294 QualType &ConstantType) const { 295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 296 297 // C++11 [dcl.init.list]p7: 298 // A narrowing conversion is an implicit conversion ... 299 QualType FromType = getToType(0); 300 QualType ToType = getToType(1); 301 302 // A conversion to an enumeration type is narrowing if the conversion to 303 // the underlying type is narrowing. This only arises for expressions of 304 // the form 'Enum{init}'. 305 if (auto *ET = ToType->getAs<EnumType>()) 306 ToType = ET->getDecl()->getIntegerType(); 307 308 switch (Second) { 309 // 'bool' is an integral type; dispatch to the right place to handle it. 310 case ICK_Boolean_Conversion: 311 if (FromType->isRealFloatingType()) 312 goto FloatingIntegralConversion; 313 if (FromType->isIntegralOrUnscopedEnumerationType()) 314 goto IntegralConversion; 315 // Boolean conversions can be from pointers and pointers to members 316 // [conv.bool], and those aren't considered narrowing conversions. 317 return NK_Not_Narrowing; 318 319 // -- from a floating-point type to an integer type, or 320 // 321 // -- from an integer type or unscoped enumeration type to a floating-point 322 // type, except where the source is a constant expression and the actual 323 // value after conversion will fit into the target type and will produce 324 // the original value when converted back to the original type, or 325 case ICK_Floating_Integral: 326 FloatingIntegralConversion: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 if (Initializer && 333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 334 // Convert the integer to the floating type. 335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 337 llvm::APFloat::rmNearestTiesToEven); 338 // And back. 339 llvm::APSInt ConvertedValue = IntConstantValue; 340 bool ignored; 341 Result.convertToInteger(ConvertedValue, 342 llvm::APFloat::rmTowardZero, &ignored); 343 // If the resulting value is different, this was a narrowing conversion. 344 if (IntConstantValue != ConvertedValue) { 345 ConstantValue = APValue(IntConstantValue); 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 // Variables are always narrowings. 351 return NK_Variable_Narrowing; 352 } 353 } 354 return NK_Not_Narrowing; 355 356 // -- from long double to double or float, or from double to float, except 357 // where the source is a constant expression and the actual value after 358 // conversion is within the range of values that can be represented (even 359 // if it cannot be represented exactly), or 360 case ICK_Floating_Conversion: 361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 363 // FromType is larger than ToType. 364 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 366 // Constant! 367 assert(ConstantValue.isFloat()); 368 llvm::APFloat FloatVal = ConstantValue.getFloat(); 369 // Convert the source value into the target type. 370 bool ignored; 371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 372 Ctx.getFloatTypeSemantics(ToType), 373 llvm::APFloat::rmNearestTiesToEven, &ignored); 374 // If there was no overflow, the source value is within the range of 375 // values that can be represented. 376 if (ConvertStatus & llvm::APFloat::opOverflow) { 377 ConstantType = Initializer->getType(); 378 return NK_Constant_Narrowing; 379 } 380 } else { 381 return NK_Variable_Narrowing; 382 } 383 } 384 return NK_Not_Narrowing; 385 386 // -- from an integer type or unscoped enumeration type to an integer type 387 // that cannot represent all the values of the original type, except where 388 // the source is a constant expression and the actual value after 389 // conversion will fit into the target type and will produce the original 390 // value when converted back to the original type. 391 case ICK_Integral_Conversion: 392 IntegralConversion: { 393 assert(FromType->isIntegralOrUnscopedEnumerationType()); 394 assert(ToType->isIntegralOrUnscopedEnumerationType()); 395 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 396 const unsigned FromWidth = Ctx.getIntWidth(FromType); 397 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 398 const unsigned ToWidth = Ctx.getIntWidth(ToType); 399 400 if (FromWidth > ToWidth || 401 (FromWidth == ToWidth && FromSigned != ToSigned) || 402 (FromSigned && !ToSigned)) { 403 // Not all values of FromType can be represented in ToType. 404 llvm::APSInt InitializerValue; 405 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 406 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 407 // Such conversions on variables are always narrowing. 408 return NK_Variable_Narrowing; 409 } 410 bool Narrowing = false; 411 if (FromWidth < ToWidth) { 412 // Negative -> unsigned is narrowing. Otherwise, more bits is never 413 // narrowing. 414 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 415 Narrowing = true; 416 } else { 417 // Add a bit to the InitializerValue so we don't have to worry about 418 // signed vs. unsigned comparisons. 419 InitializerValue = InitializerValue.extend( 420 InitializerValue.getBitWidth() + 1); 421 // Convert the initializer to and from the target width and signed-ness. 422 llvm::APSInt ConvertedValue = InitializerValue; 423 ConvertedValue = ConvertedValue.trunc(ToWidth); 424 ConvertedValue.setIsSigned(ToSigned); 425 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 426 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 427 // If the result is different, this was a narrowing conversion. 428 if (ConvertedValue != InitializerValue) 429 Narrowing = true; 430 } 431 if (Narrowing) { 432 ConstantType = Initializer->getType(); 433 ConstantValue = APValue(InitializerValue); 434 return NK_Constant_Narrowing; 435 } 436 } 437 return NK_Not_Narrowing; 438 } 439 440 default: 441 // Other kinds of conversions are not narrowings. 442 return NK_Not_Narrowing; 443 } 444 } 445 446 /// dump - Print this standard conversion sequence to standard 447 /// error. Useful for debugging overloading issues. 448 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 449 raw_ostream &OS = llvm::errs(); 450 bool PrintedSomething = false; 451 if (First != ICK_Identity) { 452 OS << GetImplicitConversionName(First); 453 PrintedSomething = true; 454 } 455 456 if (Second != ICK_Identity) { 457 if (PrintedSomething) { 458 OS << " -> "; 459 } 460 OS << GetImplicitConversionName(Second); 461 462 if (CopyConstructor) { 463 OS << " (by copy constructor)"; 464 } else if (DirectBinding) { 465 OS << " (direct reference binding)"; 466 } else if (ReferenceBinding) { 467 OS << " (reference binding)"; 468 } 469 PrintedSomething = true; 470 } 471 472 if (Third != ICK_Identity) { 473 if (PrintedSomething) { 474 OS << " -> "; 475 } 476 OS << GetImplicitConversionName(Third); 477 PrintedSomething = true; 478 } 479 480 if (!PrintedSomething) { 481 OS << "No conversions required"; 482 } 483 } 484 485 /// dump - Print this user-defined conversion sequence to standard 486 /// error. Useful for debugging overloading issues. 487 void UserDefinedConversionSequence::dump() const { 488 raw_ostream &OS = llvm::errs(); 489 if (Before.First || Before.Second || Before.Third) { 490 Before.dump(); 491 OS << " -> "; 492 } 493 if (ConversionFunction) 494 OS << '\'' << *ConversionFunction << '\''; 495 else 496 OS << "aggregate initialization"; 497 if (After.First || After.Second || After.Third) { 498 OS << " -> "; 499 After.dump(); 500 } 501 } 502 503 /// dump - Print this implicit conversion sequence to standard 504 /// error. Useful for debugging overloading issues. 505 void ImplicitConversionSequence::dump() const { 506 raw_ostream &OS = llvm::errs(); 507 if (isStdInitializerListElement()) 508 OS << "Worst std::initializer_list element conversion: "; 509 switch (ConversionKind) { 510 case StandardConversion: 511 OS << "Standard conversion: "; 512 Standard.dump(); 513 break; 514 case UserDefinedConversion: 515 OS << "User-defined conversion: "; 516 UserDefined.dump(); 517 break; 518 case EllipsisConversion: 519 OS << "Ellipsis conversion"; 520 break; 521 case AmbiguousConversion: 522 OS << "Ambiguous conversion"; 523 break; 524 case BadConversion: 525 OS << "Bad conversion"; 526 break; 527 } 528 529 OS << "\n"; 530 } 531 532 void AmbiguousConversionSequence::construct() { 533 new (&conversions()) ConversionSet(); 534 } 535 536 void AmbiguousConversionSequence::destruct() { 537 conversions().~ConversionSet(); 538 } 539 540 void 541 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 542 FromTypePtr = O.FromTypePtr; 543 ToTypePtr = O.ToTypePtr; 544 new (&conversions()) ConversionSet(O.conversions()); 545 } 546 547 namespace { 548 // Structure used by DeductionFailureInfo to store 549 // template argument information. 550 struct DFIArguments { 551 TemplateArgument FirstArg; 552 TemplateArgument SecondArg; 553 }; 554 // Structure used by DeductionFailureInfo to store 555 // template parameter and template argument information. 556 struct DFIParamWithArguments : DFIArguments { 557 TemplateParameter Param; 558 }; 559 // Structure used by DeductionFailureInfo to store template argument 560 // information and the index of the problematic call argument. 561 struct DFIDeducedMismatchArgs : DFIArguments { 562 TemplateArgumentList *TemplateArgs; 563 unsigned CallArgIndex; 564 }; 565 } 566 567 /// \brief Convert from Sema's representation of template deduction information 568 /// to the form used in overload-candidate information. 569 DeductionFailureInfo 570 clang::MakeDeductionFailureInfo(ASTContext &Context, 571 Sema::TemplateDeductionResult TDK, 572 TemplateDeductionInfo &Info) { 573 DeductionFailureInfo Result; 574 Result.Result = static_cast<unsigned>(TDK); 575 Result.HasDiagnostic = false; 576 switch (TDK) { 577 case Sema::TDK_Success: 578 case Sema::TDK_Invalid: 579 case Sema::TDK_InstantiationDepth: 580 case Sema::TDK_TooManyArguments: 581 case Sema::TDK_TooFewArguments: 582 case Sema::TDK_MiscellaneousDeductionFailure: 583 Result.Data = nullptr; 584 break; 585 586 case Sema::TDK_Incomplete: 587 case Sema::TDK_InvalidExplicitArguments: 588 Result.Data = Info.Param.getOpaqueValue(); 589 break; 590 591 case Sema::TDK_DeducedMismatch: { 592 // FIXME: Should allocate from normal heap so that we can free this later. 593 auto *Saved = new (Context) DFIDeducedMismatchArgs; 594 Saved->FirstArg = Info.FirstArg; 595 Saved->SecondArg = Info.SecondArg; 596 Saved->TemplateArgs = Info.take(); 597 Saved->CallArgIndex = Info.CallArgIndex; 598 Result.Data = Saved; 599 break; 600 } 601 602 case Sema::TDK_NonDeducedMismatch: { 603 // FIXME: Should allocate from normal heap so that we can free this later. 604 DFIArguments *Saved = new (Context) DFIArguments; 605 Saved->FirstArg = Info.FirstArg; 606 Saved->SecondArg = Info.SecondArg; 607 Result.Data = Saved; 608 break; 609 } 610 611 case Sema::TDK_Inconsistent: 612 case Sema::TDK_Underqualified: { 613 // FIXME: Should allocate from normal heap so that we can free this later. 614 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 615 Saved->Param = Info.Param; 616 Saved->FirstArg = Info.FirstArg; 617 Saved->SecondArg = Info.SecondArg; 618 Result.Data = Saved; 619 break; 620 } 621 622 case Sema::TDK_SubstitutionFailure: 623 Result.Data = Info.take(); 624 if (Info.hasSFINAEDiagnostic()) { 625 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 626 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 627 Info.takeSFINAEDiagnostic(*Diag); 628 Result.HasDiagnostic = true; 629 } 630 break; 631 632 case Sema::TDK_FailedOverloadResolution: 633 Result.Data = Info.Expression; 634 break; 635 } 636 637 return Result; 638 } 639 640 void DeductionFailureInfo::Destroy() { 641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 642 case Sema::TDK_Success: 643 case Sema::TDK_Invalid: 644 case Sema::TDK_InstantiationDepth: 645 case Sema::TDK_Incomplete: 646 case Sema::TDK_TooManyArguments: 647 case Sema::TDK_TooFewArguments: 648 case Sema::TDK_InvalidExplicitArguments: 649 case Sema::TDK_FailedOverloadResolution: 650 break; 651 652 case Sema::TDK_Inconsistent: 653 case Sema::TDK_Underqualified: 654 case Sema::TDK_DeducedMismatch: 655 case Sema::TDK_NonDeducedMismatch: 656 // FIXME: Destroy the data? 657 Data = nullptr; 658 break; 659 660 case Sema::TDK_SubstitutionFailure: 661 // FIXME: Destroy the template argument list? 662 Data = nullptr; 663 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 664 Diag->~PartialDiagnosticAt(); 665 HasDiagnostic = false; 666 } 667 break; 668 669 // Unhandled 670 case Sema::TDK_MiscellaneousDeductionFailure: 671 break; 672 } 673 } 674 675 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 676 if (HasDiagnostic) 677 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 678 return nullptr; 679 } 680 681 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 682 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 683 case Sema::TDK_Success: 684 case Sema::TDK_Invalid: 685 case Sema::TDK_InstantiationDepth: 686 case Sema::TDK_TooManyArguments: 687 case Sema::TDK_TooFewArguments: 688 case Sema::TDK_SubstitutionFailure: 689 case Sema::TDK_DeducedMismatch: 690 case Sema::TDK_NonDeducedMismatch: 691 case Sema::TDK_FailedOverloadResolution: 692 return TemplateParameter(); 693 694 case Sema::TDK_Incomplete: 695 case Sema::TDK_InvalidExplicitArguments: 696 return TemplateParameter::getFromOpaqueValue(Data); 697 698 case Sema::TDK_Inconsistent: 699 case Sema::TDK_Underqualified: 700 return static_cast<DFIParamWithArguments*>(Data)->Param; 701 702 // Unhandled 703 case Sema::TDK_MiscellaneousDeductionFailure: 704 break; 705 } 706 707 return TemplateParameter(); 708 } 709 710 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 711 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 712 case Sema::TDK_Success: 713 case Sema::TDK_Invalid: 714 case Sema::TDK_InstantiationDepth: 715 case Sema::TDK_TooManyArguments: 716 case Sema::TDK_TooFewArguments: 717 case Sema::TDK_Incomplete: 718 case Sema::TDK_InvalidExplicitArguments: 719 case Sema::TDK_Inconsistent: 720 case Sema::TDK_Underqualified: 721 case Sema::TDK_NonDeducedMismatch: 722 case Sema::TDK_FailedOverloadResolution: 723 return nullptr; 724 725 case Sema::TDK_DeducedMismatch: 726 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 727 728 case Sema::TDK_SubstitutionFailure: 729 return static_cast<TemplateArgumentList*>(Data); 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 736 return nullptr; 737 } 738 739 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 741 case Sema::TDK_Success: 742 case Sema::TDK_Invalid: 743 case Sema::TDK_InstantiationDepth: 744 case Sema::TDK_Incomplete: 745 case Sema::TDK_TooManyArguments: 746 case Sema::TDK_TooFewArguments: 747 case Sema::TDK_InvalidExplicitArguments: 748 case Sema::TDK_SubstitutionFailure: 749 case Sema::TDK_FailedOverloadResolution: 750 return nullptr; 751 752 case Sema::TDK_Inconsistent: 753 case Sema::TDK_Underqualified: 754 case Sema::TDK_DeducedMismatch: 755 case Sema::TDK_NonDeducedMismatch: 756 return &static_cast<DFIArguments*>(Data)->FirstArg; 757 758 // Unhandled 759 case Sema::TDK_MiscellaneousDeductionFailure: 760 break; 761 } 762 763 return nullptr; 764 } 765 766 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 767 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 768 case Sema::TDK_Success: 769 case Sema::TDK_Invalid: 770 case Sema::TDK_InstantiationDepth: 771 case Sema::TDK_Incomplete: 772 case Sema::TDK_TooManyArguments: 773 case Sema::TDK_TooFewArguments: 774 case Sema::TDK_InvalidExplicitArguments: 775 case Sema::TDK_SubstitutionFailure: 776 case Sema::TDK_FailedOverloadResolution: 777 return nullptr; 778 779 case Sema::TDK_Inconsistent: 780 case Sema::TDK_Underqualified: 781 case Sema::TDK_DeducedMismatch: 782 case Sema::TDK_NonDeducedMismatch: 783 return &static_cast<DFIArguments*>(Data)->SecondArg; 784 785 // Unhandled 786 case Sema::TDK_MiscellaneousDeductionFailure: 787 break; 788 } 789 790 return nullptr; 791 } 792 793 Expr *DeductionFailureInfo::getExpr() { 794 if (static_cast<Sema::TemplateDeductionResult>(Result) == 795 Sema::TDK_FailedOverloadResolution) 796 return static_cast<Expr*>(Data); 797 798 return nullptr; 799 } 800 801 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 802 if (static_cast<Sema::TemplateDeductionResult>(Result) == 803 Sema::TDK_DeducedMismatch) 804 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 805 806 return llvm::None; 807 } 808 809 void OverloadCandidateSet::destroyCandidates() { 810 for (iterator i = begin(), e = end(); i != e; ++i) { 811 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 812 i->Conversions[ii].~ImplicitConversionSequence(); 813 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 814 i->DeductionFailure.Destroy(); 815 } 816 } 817 818 void OverloadCandidateSet::clear() { 819 destroyCandidates(); 820 NumInlineSequences = 0; 821 Candidates.clear(); 822 Functions.clear(); 823 } 824 825 namespace { 826 class UnbridgedCastsSet { 827 struct Entry { 828 Expr **Addr; 829 Expr *Saved; 830 }; 831 SmallVector<Entry, 2> Entries; 832 833 public: 834 void save(Sema &S, Expr *&E) { 835 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 836 Entry entry = { &E, E }; 837 Entries.push_back(entry); 838 E = S.stripARCUnbridgedCast(E); 839 } 840 841 void restore() { 842 for (SmallVectorImpl<Entry>::iterator 843 i = Entries.begin(), e = Entries.end(); i != e; ++i) 844 *i->Addr = i->Saved; 845 } 846 }; 847 } 848 849 /// checkPlaceholderForOverload - Do any interesting placeholder-like 850 /// preprocessing on the given expression. 851 /// 852 /// \param unbridgedCasts a collection to which to add unbridged casts; 853 /// without this, they will be immediately diagnosed as errors 854 /// 855 /// Return true on unrecoverable error. 856 static bool 857 checkPlaceholderForOverload(Sema &S, Expr *&E, 858 UnbridgedCastsSet *unbridgedCasts = nullptr) { 859 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 860 // We can't handle overloaded expressions here because overload 861 // resolution might reasonably tweak them. 862 if (placeholder->getKind() == BuiltinType::Overload) return false; 863 864 // If the context potentially accepts unbridged ARC casts, strip 865 // the unbridged cast and add it to the collection for later restoration. 866 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 867 unbridgedCasts) { 868 unbridgedCasts->save(S, E); 869 return false; 870 } 871 872 // Go ahead and check everything else. 873 ExprResult result = S.CheckPlaceholderExpr(E); 874 if (result.isInvalid()) 875 return true; 876 877 E = result.get(); 878 return false; 879 } 880 881 // Nothing to do. 882 return false; 883 } 884 885 /// checkArgPlaceholdersForOverload - Check a set of call operands for 886 /// placeholders. 887 static bool checkArgPlaceholdersForOverload(Sema &S, 888 MultiExprArg Args, 889 UnbridgedCastsSet &unbridged) { 890 for (unsigned i = 0, e = Args.size(); i != e; ++i) 891 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 892 return true; 893 894 return false; 895 } 896 897 // IsOverload - Determine whether the given New declaration is an 898 // overload of the declarations in Old. This routine returns false if 899 // New and Old cannot be overloaded, e.g., if New has the same 900 // signature as some function in Old (C++ 1.3.10) or if the Old 901 // declarations aren't functions (or function templates) at all. When 902 // it does return false, MatchedDecl will point to the decl that New 903 // cannot be overloaded with. This decl may be a UsingShadowDecl on 904 // top of the underlying declaration. 905 // 906 // Example: Given the following input: 907 // 908 // void f(int, float); // #1 909 // void f(int, int); // #2 910 // int f(int, int); // #3 911 // 912 // When we process #1, there is no previous declaration of "f", 913 // so IsOverload will not be used. 914 // 915 // When we process #2, Old contains only the FunctionDecl for #1. By 916 // comparing the parameter types, we see that #1 and #2 are overloaded 917 // (since they have different signatures), so this routine returns 918 // false; MatchedDecl is unchanged. 919 // 920 // When we process #3, Old is an overload set containing #1 and #2. We 921 // compare the signatures of #3 to #1 (they're overloaded, so we do 922 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 923 // identical (return types of functions are not part of the 924 // signature), IsOverload returns false and MatchedDecl will be set to 925 // point to the FunctionDecl for #2. 926 // 927 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 928 // into a class by a using declaration. The rules for whether to hide 929 // shadow declarations ignore some properties which otherwise figure 930 // into a function template's signature. 931 Sema::OverloadKind 932 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 933 NamedDecl *&Match, bool NewIsUsingDecl) { 934 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 935 I != E; ++I) { 936 NamedDecl *OldD = *I; 937 938 bool OldIsUsingDecl = false; 939 if (isa<UsingShadowDecl>(OldD)) { 940 OldIsUsingDecl = true; 941 942 // We can always introduce two using declarations into the same 943 // context, even if they have identical signatures. 944 if (NewIsUsingDecl) continue; 945 946 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 947 } 948 949 // A using-declaration does not conflict with another declaration 950 // if one of them is hidden. 951 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 952 continue; 953 954 // If either declaration was introduced by a using declaration, 955 // we'll need to use slightly different rules for matching. 956 // Essentially, these rules are the normal rules, except that 957 // function templates hide function templates with different 958 // return types or template parameter lists. 959 bool UseMemberUsingDeclRules = 960 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 961 !New->getFriendObjectKind(); 962 963 if (FunctionDecl *OldF = OldD->getAsFunction()) { 964 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 965 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 966 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 967 continue; 968 } 969 970 if (!isa<FunctionTemplateDecl>(OldD) && 971 !shouldLinkPossiblyHiddenDecl(*I, New)) 972 continue; 973 974 Match = *I; 975 return Ovl_Match; 976 } 977 } else if (isa<UsingDecl>(OldD)) { 978 // We can overload with these, which can show up when doing 979 // redeclaration checks for UsingDecls. 980 assert(Old.getLookupKind() == LookupUsingDeclName); 981 } else if (isa<TagDecl>(OldD)) { 982 // We can always overload with tags by hiding them. 983 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 984 // Optimistically assume that an unresolved using decl will 985 // overload; if it doesn't, we'll have to diagnose during 986 // template instantiation. 987 } else { 988 // (C++ 13p1): 989 // Only function declarations can be overloaded; object and type 990 // declarations cannot be overloaded. 991 Match = *I; 992 return Ovl_NonFunction; 993 } 994 } 995 996 return Ovl_Overload; 997 } 998 999 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1000 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1001 // C++ [basic.start.main]p2: This function shall not be overloaded. 1002 if (New->isMain()) 1003 return false; 1004 1005 // MSVCRT user defined entry points cannot be overloaded. 1006 if (New->isMSVCRTEntryPoint()) 1007 return false; 1008 1009 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1010 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1011 1012 // C++ [temp.fct]p2: 1013 // A function template can be overloaded with other function templates 1014 // and with normal (non-template) functions. 1015 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1016 return true; 1017 1018 // Is the function New an overload of the function Old? 1019 QualType OldQType = Context.getCanonicalType(Old->getType()); 1020 QualType NewQType = Context.getCanonicalType(New->getType()); 1021 1022 // Compare the signatures (C++ 1.3.10) of the two functions to 1023 // determine whether they are overloads. If we find any mismatch 1024 // in the signature, they are overloads. 1025 1026 // If either of these functions is a K&R-style function (no 1027 // prototype), then we consider them to have matching signatures. 1028 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1029 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1030 return false; 1031 1032 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1033 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1034 1035 // The signature of a function includes the types of its 1036 // parameters (C++ 1.3.10), which includes the presence or absence 1037 // of the ellipsis; see C++ DR 357). 1038 if (OldQType != NewQType && 1039 (OldType->getNumParams() != NewType->getNumParams() || 1040 OldType->isVariadic() != NewType->isVariadic() || 1041 !FunctionParamTypesAreEqual(OldType, NewType))) 1042 return true; 1043 1044 // C++ [temp.over.link]p4: 1045 // The signature of a function template consists of its function 1046 // signature, its return type and its template parameter list. The names 1047 // of the template parameters are significant only for establishing the 1048 // relationship between the template parameters and the rest of the 1049 // signature. 1050 // 1051 // We check the return type and template parameter lists for function 1052 // templates first; the remaining checks follow. 1053 // 1054 // However, we don't consider either of these when deciding whether 1055 // a member introduced by a shadow declaration is hidden. 1056 if (!UseMemberUsingDeclRules && NewTemplate && 1057 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1058 OldTemplate->getTemplateParameters(), 1059 false, TPL_TemplateMatch) || 1060 OldType->getReturnType() != NewType->getReturnType())) 1061 return true; 1062 1063 // If the function is a class member, its signature includes the 1064 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1065 // 1066 // As part of this, also check whether one of the member functions 1067 // is static, in which case they are not overloads (C++ 1068 // 13.1p2). While not part of the definition of the signature, 1069 // this check is important to determine whether these functions 1070 // can be overloaded. 1071 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1072 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1073 if (OldMethod && NewMethod && 1074 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1075 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1076 if (!UseMemberUsingDeclRules && 1077 (OldMethod->getRefQualifier() == RQ_None || 1078 NewMethod->getRefQualifier() == RQ_None)) { 1079 // C++0x [over.load]p2: 1080 // - Member function declarations with the same name and the same 1081 // parameter-type-list as well as member function template 1082 // declarations with the same name, the same parameter-type-list, and 1083 // the same template parameter lists cannot be overloaded if any of 1084 // them, but not all, have a ref-qualifier (8.3.5). 1085 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1086 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1087 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1088 } 1089 return true; 1090 } 1091 1092 // We may not have applied the implicit const for a constexpr member 1093 // function yet (because we haven't yet resolved whether this is a static 1094 // or non-static member function). Add it now, on the assumption that this 1095 // is a redeclaration of OldMethod. 1096 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1097 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1098 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1099 !isa<CXXConstructorDecl>(NewMethod)) 1100 NewQuals |= Qualifiers::Const; 1101 1102 // We do not allow overloading based off of '__restrict'. 1103 OldQuals &= ~Qualifiers::Restrict; 1104 NewQuals &= ~Qualifiers::Restrict; 1105 if (OldQuals != NewQuals) 1106 return true; 1107 } 1108 1109 // Though pass_object_size is placed on parameters and takes an argument, we 1110 // consider it to be a function-level modifier for the sake of function 1111 // identity. Either the function has one or more parameters with 1112 // pass_object_size or it doesn't. 1113 if (functionHasPassObjectSizeParams(New) != 1114 functionHasPassObjectSizeParams(Old)) 1115 return true; 1116 1117 // enable_if attributes are an order-sensitive part of the signature. 1118 for (specific_attr_iterator<EnableIfAttr> 1119 NewI = New->specific_attr_begin<EnableIfAttr>(), 1120 NewE = New->specific_attr_end<EnableIfAttr>(), 1121 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1122 OldE = Old->specific_attr_end<EnableIfAttr>(); 1123 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1124 if (NewI == NewE || OldI == OldE) 1125 return true; 1126 llvm::FoldingSetNodeID NewID, OldID; 1127 NewI->getCond()->Profile(NewID, Context, true); 1128 OldI->getCond()->Profile(OldID, Context, true); 1129 if (NewID != OldID) 1130 return true; 1131 } 1132 1133 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1134 // Don't allow overloading of destructors. (In theory we could, but it 1135 // would be a giant change to clang.) 1136 if (isa<CXXDestructorDecl>(New)) 1137 return false; 1138 1139 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1140 OldTarget = IdentifyCUDATarget(Old); 1141 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1142 return false; 1143 1144 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1145 1146 // Don't allow HD and global functions to overload other functions with the 1147 // same signature. We allow overloading based on CUDA attributes so that 1148 // functions can have different implementations on the host and device, but 1149 // HD/global functions "exist" in some sense on both the host and device, so 1150 // should have the same implementation on both sides. 1151 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1152 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1153 return false; 1154 1155 // Allow overloading of functions with same signature and different CUDA 1156 // target attributes. 1157 return NewTarget != OldTarget; 1158 } 1159 1160 // The signatures match; this is not an overload. 1161 return false; 1162 } 1163 1164 /// \brief Checks availability of the function depending on the current 1165 /// function context. Inside an unavailable function, unavailability is ignored. 1166 /// 1167 /// \returns true if \arg FD is unavailable and current context is inside 1168 /// an available function, false otherwise. 1169 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1170 if (!FD->isUnavailable()) 1171 return false; 1172 1173 // Walk up the context of the caller. 1174 Decl *C = cast<Decl>(CurContext); 1175 do { 1176 if (C->isUnavailable()) 1177 return false; 1178 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1179 return true; 1180 } 1181 1182 /// \brief Tries a user-defined conversion from From to ToType. 1183 /// 1184 /// Produces an implicit conversion sequence for when a standard conversion 1185 /// is not an option. See TryImplicitConversion for more information. 1186 static ImplicitConversionSequence 1187 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1188 bool SuppressUserConversions, 1189 bool AllowExplicit, 1190 bool InOverloadResolution, 1191 bool CStyle, 1192 bool AllowObjCWritebackConversion, 1193 bool AllowObjCConversionOnExplicit) { 1194 ImplicitConversionSequence ICS; 1195 1196 if (SuppressUserConversions) { 1197 // We're not in the case above, so there is no conversion that 1198 // we can perform. 1199 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1200 return ICS; 1201 } 1202 1203 // Attempt user-defined conversion. 1204 OverloadCandidateSet Conversions(From->getExprLoc(), 1205 OverloadCandidateSet::CSK_Normal); 1206 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1207 Conversions, AllowExplicit, 1208 AllowObjCConversionOnExplicit)) { 1209 case OR_Success: 1210 case OR_Deleted: 1211 ICS.setUserDefined(); 1212 // C++ [over.ics.user]p4: 1213 // A conversion of an expression of class type to the same class 1214 // type is given Exact Match rank, and a conversion of an 1215 // expression of class type to a base class of that type is 1216 // given Conversion rank, in spite of the fact that a copy 1217 // constructor (i.e., a user-defined conversion function) is 1218 // called for those cases. 1219 if (CXXConstructorDecl *Constructor 1220 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1221 QualType FromCanon 1222 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1223 QualType ToCanon 1224 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1225 if (Constructor->isCopyConstructor() && 1226 (FromCanon == ToCanon || 1227 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1228 // Turn this into a "standard" conversion sequence, so that it 1229 // gets ranked with standard conversion sequences. 1230 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1231 ICS.setStandard(); 1232 ICS.Standard.setAsIdentityConversion(); 1233 ICS.Standard.setFromType(From->getType()); 1234 ICS.Standard.setAllToTypes(ToType); 1235 ICS.Standard.CopyConstructor = Constructor; 1236 ICS.Standard.FoundCopyConstructor = Found; 1237 if (ToCanon != FromCanon) 1238 ICS.Standard.Second = ICK_Derived_To_Base; 1239 } 1240 } 1241 break; 1242 1243 case OR_Ambiguous: 1244 ICS.setAmbiguous(); 1245 ICS.Ambiguous.setFromType(From->getType()); 1246 ICS.Ambiguous.setToType(ToType); 1247 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1248 Cand != Conversions.end(); ++Cand) 1249 if (Cand->Viable) 1250 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1251 break; 1252 1253 // Fall through. 1254 case OR_No_Viable_Function: 1255 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1256 break; 1257 } 1258 1259 return ICS; 1260 } 1261 1262 /// TryImplicitConversion - Attempt to perform an implicit conversion 1263 /// from the given expression (Expr) to the given type (ToType). This 1264 /// function returns an implicit conversion sequence that can be used 1265 /// to perform the initialization. Given 1266 /// 1267 /// void f(float f); 1268 /// void g(int i) { f(i); } 1269 /// 1270 /// this routine would produce an implicit conversion sequence to 1271 /// describe the initialization of f from i, which will be a standard 1272 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1273 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1274 // 1275 /// Note that this routine only determines how the conversion can be 1276 /// performed; it does not actually perform the conversion. As such, 1277 /// it will not produce any diagnostics if no conversion is available, 1278 /// but will instead return an implicit conversion sequence of kind 1279 /// "BadConversion". 1280 /// 1281 /// If @p SuppressUserConversions, then user-defined conversions are 1282 /// not permitted. 1283 /// If @p AllowExplicit, then explicit user-defined conversions are 1284 /// permitted. 1285 /// 1286 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1287 /// writeback conversion, which allows __autoreleasing id* parameters to 1288 /// be initialized with __strong id* or __weak id* arguments. 1289 static ImplicitConversionSequence 1290 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1291 bool SuppressUserConversions, 1292 bool AllowExplicit, 1293 bool InOverloadResolution, 1294 bool CStyle, 1295 bool AllowObjCWritebackConversion, 1296 bool AllowObjCConversionOnExplicit) { 1297 ImplicitConversionSequence ICS; 1298 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1299 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1300 ICS.setStandard(); 1301 return ICS; 1302 } 1303 1304 if (!S.getLangOpts().CPlusPlus) { 1305 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1306 return ICS; 1307 } 1308 1309 // C++ [over.ics.user]p4: 1310 // A conversion of an expression of class type to the same class 1311 // type is given Exact Match rank, and a conversion of an 1312 // expression of class type to a base class of that type is 1313 // given Conversion rank, in spite of the fact that a copy/move 1314 // constructor (i.e., a user-defined conversion function) is 1315 // called for those cases. 1316 QualType FromType = From->getType(); 1317 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1318 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1319 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1320 ICS.setStandard(); 1321 ICS.Standard.setAsIdentityConversion(); 1322 ICS.Standard.setFromType(FromType); 1323 ICS.Standard.setAllToTypes(ToType); 1324 1325 // We don't actually check at this point whether there is a valid 1326 // copy/move constructor, since overloading just assumes that it 1327 // exists. When we actually perform initialization, we'll find the 1328 // appropriate constructor to copy the returned object, if needed. 1329 ICS.Standard.CopyConstructor = nullptr; 1330 1331 // Determine whether this is considered a derived-to-base conversion. 1332 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1333 ICS.Standard.Second = ICK_Derived_To_Base; 1334 1335 return ICS; 1336 } 1337 1338 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1339 AllowExplicit, InOverloadResolution, CStyle, 1340 AllowObjCWritebackConversion, 1341 AllowObjCConversionOnExplicit); 1342 } 1343 1344 ImplicitConversionSequence 1345 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1346 bool SuppressUserConversions, 1347 bool AllowExplicit, 1348 bool InOverloadResolution, 1349 bool CStyle, 1350 bool AllowObjCWritebackConversion) { 1351 return ::TryImplicitConversion(*this, From, ToType, 1352 SuppressUserConversions, AllowExplicit, 1353 InOverloadResolution, CStyle, 1354 AllowObjCWritebackConversion, 1355 /*AllowObjCConversionOnExplicit=*/false); 1356 } 1357 1358 /// PerformImplicitConversion - Perform an implicit conversion of the 1359 /// expression From to the type ToType. Returns the 1360 /// converted expression. Flavor is the kind of conversion we're 1361 /// performing, used in the error message. If @p AllowExplicit, 1362 /// explicit user-defined conversions are permitted. 1363 ExprResult 1364 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1365 AssignmentAction Action, bool AllowExplicit) { 1366 ImplicitConversionSequence ICS; 1367 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1368 } 1369 1370 ExprResult 1371 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1372 AssignmentAction Action, bool AllowExplicit, 1373 ImplicitConversionSequence& ICS) { 1374 if (checkPlaceholderForOverload(*this, From)) 1375 return ExprError(); 1376 1377 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1378 bool AllowObjCWritebackConversion 1379 = getLangOpts().ObjCAutoRefCount && 1380 (Action == AA_Passing || Action == AA_Sending); 1381 if (getLangOpts().ObjC1) 1382 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1383 ToType, From->getType(), From); 1384 ICS = ::TryImplicitConversion(*this, From, ToType, 1385 /*SuppressUserConversions=*/false, 1386 AllowExplicit, 1387 /*InOverloadResolution=*/false, 1388 /*CStyle=*/false, 1389 AllowObjCWritebackConversion, 1390 /*AllowObjCConversionOnExplicit=*/false); 1391 return PerformImplicitConversion(From, ToType, ICS, Action); 1392 } 1393 1394 /// \brief Determine whether the conversion from FromType to ToType is a valid 1395 /// conversion that strips "noexcept" or "noreturn" off the nested function 1396 /// type. 1397 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1398 QualType &ResultTy) { 1399 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1400 return false; 1401 1402 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1403 // or F(t noexcept) -> F(t) 1404 // where F adds one of the following at most once: 1405 // - a pointer 1406 // - a member pointer 1407 // - a block pointer 1408 // Changes here need matching changes in FindCompositePointerType. 1409 CanQualType CanTo = Context.getCanonicalType(ToType); 1410 CanQualType CanFrom = Context.getCanonicalType(FromType); 1411 Type::TypeClass TyClass = CanTo->getTypeClass(); 1412 if (TyClass != CanFrom->getTypeClass()) return false; 1413 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1414 if (TyClass == Type::Pointer) { 1415 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1416 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1417 } else if (TyClass == Type::BlockPointer) { 1418 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1419 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1420 } else if (TyClass == Type::MemberPointer) { 1421 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1422 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1423 // A function pointer conversion cannot change the class of the function. 1424 if (ToMPT->getClass() != FromMPT->getClass()) 1425 return false; 1426 CanTo = ToMPT->getPointeeType(); 1427 CanFrom = FromMPT->getPointeeType(); 1428 } else { 1429 return false; 1430 } 1431 1432 TyClass = CanTo->getTypeClass(); 1433 if (TyClass != CanFrom->getTypeClass()) return false; 1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1435 return false; 1436 } 1437 1438 const auto *FromFn = cast<FunctionType>(CanFrom); 1439 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1440 1441 const auto *ToFn = cast<FunctionType>(CanTo); 1442 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1443 1444 bool Changed = false; 1445 1446 // Drop 'noreturn' if not present in target type. 1447 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1448 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1449 Changed = true; 1450 } 1451 1452 // Drop 'noexcept' if not present in target type. 1453 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1454 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1455 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1456 FromFn = cast<FunctionType>( 1457 Context.getFunctionType(FromFPT->getReturnType(), 1458 FromFPT->getParamTypes(), 1459 FromFPT->getExtProtoInfo().withExceptionSpec( 1460 FunctionProtoType::ExceptionSpecInfo())) 1461 .getTypePtr()); 1462 Changed = true; 1463 } 1464 } 1465 1466 if (!Changed) 1467 return false; 1468 1469 assert(QualType(FromFn, 0).isCanonical()); 1470 if (QualType(FromFn, 0) != CanTo) return false; 1471 1472 ResultTy = ToType; 1473 return true; 1474 } 1475 1476 /// \brief Determine whether the conversion from FromType to ToType is a valid 1477 /// vector conversion. 1478 /// 1479 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1480 /// conversion. 1481 static bool IsVectorConversion(Sema &S, QualType FromType, 1482 QualType ToType, ImplicitConversionKind &ICK) { 1483 // We need at least one of these types to be a vector type to have a vector 1484 // conversion. 1485 if (!ToType->isVectorType() && !FromType->isVectorType()) 1486 return false; 1487 1488 // Identical types require no conversions. 1489 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1490 return false; 1491 1492 // There are no conversions between extended vector types, only identity. 1493 if (ToType->isExtVectorType()) { 1494 // There are no conversions between extended vector types other than the 1495 // identity conversion. 1496 if (FromType->isExtVectorType()) 1497 return false; 1498 1499 // Vector splat from any arithmetic type to a vector. 1500 if (FromType->isArithmeticType()) { 1501 ICK = ICK_Vector_Splat; 1502 return true; 1503 } 1504 } 1505 1506 // We can perform the conversion between vector types in the following cases: 1507 // 1)vector types are equivalent AltiVec and GCC vector types 1508 // 2)lax vector conversions are permitted and the vector types are of the 1509 // same size 1510 if (ToType->isVectorType() && FromType->isVectorType()) { 1511 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1512 S.isLaxVectorConversion(FromType, ToType)) { 1513 ICK = ICK_Vector_Conversion; 1514 return true; 1515 } 1516 } 1517 1518 return false; 1519 } 1520 1521 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1522 bool InOverloadResolution, 1523 StandardConversionSequence &SCS, 1524 bool CStyle); 1525 1526 /// IsStandardConversion - Determines whether there is a standard 1527 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1528 /// expression From to the type ToType. Standard conversion sequences 1529 /// only consider non-class types; for conversions that involve class 1530 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1531 /// contain the standard conversion sequence required to perform this 1532 /// conversion and this routine will return true. Otherwise, this 1533 /// routine will return false and the value of SCS is unspecified. 1534 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1535 bool InOverloadResolution, 1536 StandardConversionSequence &SCS, 1537 bool CStyle, 1538 bool AllowObjCWritebackConversion) { 1539 QualType FromType = From->getType(); 1540 1541 // Standard conversions (C++ [conv]) 1542 SCS.setAsIdentityConversion(); 1543 SCS.IncompatibleObjC = false; 1544 SCS.setFromType(FromType); 1545 SCS.CopyConstructor = nullptr; 1546 1547 // There are no standard conversions for class types in C++, so 1548 // abort early. When overloading in C, however, we do permit them. 1549 if (S.getLangOpts().CPlusPlus && 1550 (FromType->isRecordType() || ToType->isRecordType())) 1551 return false; 1552 1553 // The first conversion can be an lvalue-to-rvalue conversion, 1554 // array-to-pointer conversion, or function-to-pointer conversion 1555 // (C++ 4p1). 1556 1557 if (FromType == S.Context.OverloadTy) { 1558 DeclAccessPair AccessPair; 1559 if (FunctionDecl *Fn 1560 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1561 AccessPair)) { 1562 // We were able to resolve the address of the overloaded function, 1563 // so we can convert to the type of that function. 1564 FromType = Fn->getType(); 1565 SCS.setFromType(FromType); 1566 1567 // we can sometimes resolve &foo<int> regardless of ToType, so check 1568 // if the type matches (identity) or we are converting to bool 1569 if (!S.Context.hasSameUnqualifiedType( 1570 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1571 QualType resultTy; 1572 // if the function type matches except for [[noreturn]], it's ok 1573 if (!S.IsFunctionConversion(FromType, 1574 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1575 // otherwise, only a boolean conversion is standard 1576 if (!ToType->isBooleanType()) 1577 return false; 1578 } 1579 1580 // Check if the "from" expression is taking the address of an overloaded 1581 // function and recompute the FromType accordingly. Take advantage of the 1582 // fact that non-static member functions *must* have such an address-of 1583 // expression. 1584 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1585 if (Method && !Method->isStatic()) { 1586 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1587 "Non-unary operator on non-static member address"); 1588 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1589 == UO_AddrOf && 1590 "Non-address-of operator on non-static member address"); 1591 const Type *ClassType 1592 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1593 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1594 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1595 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1596 UO_AddrOf && 1597 "Non-address-of operator for overloaded function expression"); 1598 FromType = S.Context.getPointerType(FromType); 1599 } 1600 1601 // Check that we've computed the proper type after overload resolution. 1602 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1603 // be calling it from within an NDEBUG block. 1604 assert(S.Context.hasSameType( 1605 FromType, 1606 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1607 } else { 1608 return false; 1609 } 1610 } 1611 // Lvalue-to-rvalue conversion (C++11 4.1): 1612 // A glvalue (3.10) of a non-function, non-array type T can 1613 // be converted to a prvalue. 1614 bool argIsLValue = From->isGLValue(); 1615 if (argIsLValue && 1616 !FromType->isFunctionType() && !FromType->isArrayType() && 1617 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1618 SCS.First = ICK_Lvalue_To_Rvalue; 1619 1620 // C11 6.3.2.1p2: 1621 // ... if the lvalue has atomic type, the value has the non-atomic version 1622 // of the type of the lvalue ... 1623 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1624 FromType = Atomic->getValueType(); 1625 1626 // If T is a non-class type, the type of the rvalue is the 1627 // cv-unqualified version of T. Otherwise, the type of the rvalue 1628 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1629 // just strip the qualifiers because they don't matter. 1630 FromType = FromType.getUnqualifiedType(); 1631 } else if (FromType->isArrayType()) { 1632 // Array-to-pointer conversion (C++ 4.2) 1633 SCS.First = ICK_Array_To_Pointer; 1634 1635 // An lvalue or rvalue of type "array of N T" or "array of unknown 1636 // bound of T" can be converted to an rvalue of type "pointer to 1637 // T" (C++ 4.2p1). 1638 FromType = S.Context.getArrayDecayedType(FromType); 1639 1640 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1641 // This conversion is deprecated in C++03 (D.4) 1642 SCS.DeprecatedStringLiteralToCharPtr = true; 1643 1644 // For the purpose of ranking in overload resolution 1645 // (13.3.3.1.1), this conversion is considered an 1646 // array-to-pointer conversion followed by a qualification 1647 // conversion (4.4). (C++ 4.2p2) 1648 SCS.Second = ICK_Identity; 1649 SCS.Third = ICK_Qualification; 1650 SCS.QualificationIncludesObjCLifetime = false; 1651 SCS.setAllToTypes(FromType); 1652 return true; 1653 } 1654 } else if (FromType->isFunctionType() && argIsLValue) { 1655 // Function-to-pointer conversion (C++ 4.3). 1656 SCS.First = ICK_Function_To_Pointer; 1657 1658 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1659 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1660 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1661 return false; 1662 1663 // An lvalue of function type T can be converted to an rvalue of 1664 // type "pointer to T." The result is a pointer to the 1665 // function. (C++ 4.3p1). 1666 FromType = S.Context.getPointerType(FromType); 1667 } else { 1668 // We don't require any conversions for the first step. 1669 SCS.First = ICK_Identity; 1670 } 1671 SCS.setToType(0, FromType); 1672 1673 // The second conversion can be an integral promotion, floating 1674 // point promotion, integral conversion, floating point conversion, 1675 // floating-integral conversion, pointer conversion, 1676 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1677 // For overloading in C, this can also be a "compatible-type" 1678 // conversion. 1679 bool IncompatibleObjC = false; 1680 ImplicitConversionKind SecondICK = ICK_Identity; 1681 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1682 // The unqualified versions of the types are the same: there's no 1683 // conversion to do. 1684 SCS.Second = ICK_Identity; 1685 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1686 // Integral promotion (C++ 4.5). 1687 SCS.Second = ICK_Integral_Promotion; 1688 FromType = ToType.getUnqualifiedType(); 1689 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1690 // Floating point promotion (C++ 4.6). 1691 SCS.Second = ICK_Floating_Promotion; 1692 FromType = ToType.getUnqualifiedType(); 1693 } else if (S.IsComplexPromotion(FromType, ToType)) { 1694 // Complex promotion (Clang extension) 1695 SCS.Second = ICK_Complex_Promotion; 1696 FromType = ToType.getUnqualifiedType(); 1697 } else if (ToType->isBooleanType() && 1698 (FromType->isArithmeticType() || 1699 FromType->isAnyPointerType() || 1700 FromType->isBlockPointerType() || 1701 FromType->isMemberPointerType() || 1702 FromType->isNullPtrType())) { 1703 // Boolean conversions (C++ 4.12). 1704 SCS.Second = ICK_Boolean_Conversion; 1705 FromType = S.Context.BoolTy; 1706 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1707 ToType->isIntegralType(S.Context)) { 1708 // Integral conversions (C++ 4.7). 1709 SCS.Second = ICK_Integral_Conversion; 1710 FromType = ToType.getUnqualifiedType(); 1711 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1712 // Complex conversions (C99 6.3.1.6) 1713 SCS.Second = ICK_Complex_Conversion; 1714 FromType = ToType.getUnqualifiedType(); 1715 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1716 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1717 // Complex-real conversions (C99 6.3.1.7) 1718 SCS.Second = ICK_Complex_Real; 1719 FromType = ToType.getUnqualifiedType(); 1720 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1721 // FIXME: disable conversions between long double and __float128 if 1722 // their representation is different until there is back end support 1723 // We of course allow this conversion if long double is really double. 1724 if (&S.Context.getFloatTypeSemantics(FromType) != 1725 &S.Context.getFloatTypeSemantics(ToType)) { 1726 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1727 ToType == S.Context.LongDoubleTy) || 1728 (FromType == S.Context.LongDoubleTy && 1729 ToType == S.Context.Float128Ty)); 1730 if (Float128AndLongDouble && 1731 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1732 &llvm::APFloat::IEEEdouble)) 1733 return false; 1734 } 1735 // Floating point conversions (C++ 4.8). 1736 SCS.Second = ICK_Floating_Conversion; 1737 FromType = ToType.getUnqualifiedType(); 1738 } else if ((FromType->isRealFloatingType() && 1739 ToType->isIntegralType(S.Context)) || 1740 (FromType->isIntegralOrUnscopedEnumerationType() && 1741 ToType->isRealFloatingType())) { 1742 // Floating-integral conversions (C++ 4.9). 1743 SCS.Second = ICK_Floating_Integral; 1744 FromType = ToType.getUnqualifiedType(); 1745 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1746 SCS.Second = ICK_Block_Pointer_Conversion; 1747 } else if (AllowObjCWritebackConversion && 1748 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1749 SCS.Second = ICK_Writeback_Conversion; 1750 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1751 FromType, IncompatibleObjC)) { 1752 // Pointer conversions (C++ 4.10). 1753 SCS.Second = ICK_Pointer_Conversion; 1754 SCS.IncompatibleObjC = IncompatibleObjC; 1755 FromType = FromType.getUnqualifiedType(); 1756 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1757 InOverloadResolution, FromType)) { 1758 // Pointer to member conversions (4.11). 1759 SCS.Second = ICK_Pointer_Member; 1760 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1761 SCS.Second = SecondICK; 1762 FromType = ToType.getUnqualifiedType(); 1763 } else if (!S.getLangOpts().CPlusPlus && 1764 S.Context.typesAreCompatible(ToType, FromType)) { 1765 // Compatible conversions (Clang extension for C function overloading) 1766 SCS.Second = ICK_Compatible_Conversion; 1767 FromType = ToType.getUnqualifiedType(); 1768 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1769 InOverloadResolution, 1770 SCS, CStyle)) { 1771 SCS.Second = ICK_TransparentUnionConversion; 1772 FromType = ToType; 1773 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1774 CStyle)) { 1775 // tryAtomicConversion has updated the standard conversion sequence 1776 // appropriately. 1777 return true; 1778 } else if (ToType->isEventT() && 1779 From->isIntegerConstantExpr(S.getASTContext()) && 1780 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1781 SCS.Second = ICK_Zero_Event_Conversion; 1782 FromType = ToType; 1783 } else { 1784 // No second conversion required. 1785 SCS.Second = ICK_Identity; 1786 } 1787 SCS.setToType(1, FromType); 1788 1789 // The third conversion can be a function pointer conversion or a 1790 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1791 bool ObjCLifetimeConversion; 1792 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1793 // Function pointer conversions (removing 'noexcept') including removal of 1794 // 'noreturn' (Clang extension). 1795 SCS.Third = ICK_Function_Conversion; 1796 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1797 ObjCLifetimeConversion)) { 1798 SCS.Third = ICK_Qualification; 1799 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1800 FromType = ToType; 1801 } else { 1802 // No conversion required 1803 SCS.Third = ICK_Identity; 1804 } 1805 1806 // C++ [over.best.ics]p6: 1807 // [...] Any difference in top-level cv-qualification is 1808 // subsumed by the initialization itself and does not constitute 1809 // a conversion. [...] 1810 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1811 QualType CanonTo = S.Context.getCanonicalType(ToType); 1812 if (CanonFrom.getLocalUnqualifiedType() 1813 == CanonTo.getLocalUnqualifiedType() && 1814 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1815 FromType = ToType; 1816 CanonFrom = CanonTo; 1817 } 1818 1819 SCS.setToType(2, FromType); 1820 1821 if (CanonFrom == CanonTo) 1822 return true; 1823 1824 // If we have not converted the argument type to the parameter type, 1825 // this is a bad conversion sequence, unless we're resolving an overload in C. 1826 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1827 return false; 1828 1829 ExprResult ER = ExprResult{From}; 1830 Sema::AssignConvertType Conv = 1831 S.CheckSingleAssignmentConstraints(ToType, ER, 1832 /*Diagnose=*/false, 1833 /*DiagnoseCFAudited=*/false, 1834 /*ConvertRHS=*/false); 1835 ImplicitConversionKind SecondConv; 1836 switch (Conv) { 1837 case Sema::Compatible: 1838 SecondConv = ICK_C_Only_Conversion; 1839 break; 1840 // For our purposes, discarding qualifiers is just as bad as using an 1841 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1842 // qualifiers, as well. 1843 case Sema::CompatiblePointerDiscardsQualifiers: 1844 case Sema::IncompatiblePointer: 1845 case Sema::IncompatiblePointerSign: 1846 SecondConv = ICK_Incompatible_Pointer_Conversion; 1847 break; 1848 default: 1849 return false; 1850 } 1851 1852 // First can only be an lvalue conversion, so we pretend that this was the 1853 // second conversion. First should already be valid from earlier in the 1854 // function. 1855 SCS.Second = SecondConv; 1856 SCS.setToType(1, ToType); 1857 1858 // Third is Identity, because Second should rank us worse than any other 1859 // conversion. This could also be ICK_Qualification, but it's simpler to just 1860 // lump everything in with the second conversion, and we don't gain anything 1861 // from making this ICK_Qualification. 1862 SCS.Third = ICK_Identity; 1863 SCS.setToType(2, ToType); 1864 return true; 1865 } 1866 1867 static bool 1868 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1869 QualType &ToType, 1870 bool InOverloadResolution, 1871 StandardConversionSequence &SCS, 1872 bool CStyle) { 1873 1874 const RecordType *UT = ToType->getAsUnionType(); 1875 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1876 return false; 1877 // The field to initialize within the transparent union. 1878 RecordDecl *UD = UT->getDecl(); 1879 // It's compatible if the expression matches any of the fields. 1880 for (const auto *it : UD->fields()) { 1881 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1882 CStyle, /*ObjCWritebackConversion=*/false)) { 1883 ToType = it->getType(); 1884 return true; 1885 } 1886 } 1887 return false; 1888 } 1889 1890 /// IsIntegralPromotion - Determines whether the conversion from the 1891 /// expression From (whose potentially-adjusted type is FromType) to 1892 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1893 /// sets PromotedType to the promoted type. 1894 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1895 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1896 // All integers are built-in. 1897 if (!To) { 1898 return false; 1899 } 1900 1901 // An rvalue of type char, signed char, unsigned char, short int, or 1902 // unsigned short int can be converted to an rvalue of type int if 1903 // int can represent all the values of the source type; otherwise, 1904 // the source rvalue can be converted to an rvalue of type unsigned 1905 // int (C++ 4.5p1). 1906 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1907 !FromType->isEnumeralType()) { 1908 if (// We can promote any signed, promotable integer type to an int 1909 (FromType->isSignedIntegerType() || 1910 // We can promote any unsigned integer type whose size is 1911 // less than int to an int. 1912 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1913 return To->getKind() == BuiltinType::Int; 1914 } 1915 1916 return To->getKind() == BuiltinType::UInt; 1917 } 1918 1919 // C++11 [conv.prom]p3: 1920 // A prvalue of an unscoped enumeration type whose underlying type is not 1921 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1922 // following types that can represent all the values of the enumeration 1923 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1924 // unsigned int, long int, unsigned long int, long long int, or unsigned 1925 // long long int. If none of the types in that list can represent all the 1926 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1927 // type can be converted to an rvalue a prvalue of the extended integer type 1928 // with lowest integer conversion rank (4.13) greater than the rank of long 1929 // long in which all the values of the enumeration can be represented. If 1930 // there are two such extended types, the signed one is chosen. 1931 // C++11 [conv.prom]p4: 1932 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1933 // can be converted to a prvalue of its underlying type. Moreover, if 1934 // integral promotion can be applied to its underlying type, a prvalue of an 1935 // unscoped enumeration type whose underlying type is fixed can also be 1936 // converted to a prvalue of the promoted underlying type. 1937 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1938 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1939 // provided for a scoped enumeration. 1940 if (FromEnumType->getDecl()->isScoped()) 1941 return false; 1942 1943 // We can perform an integral promotion to the underlying type of the enum, 1944 // even if that's not the promoted type. Note that the check for promoting 1945 // the underlying type is based on the type alone, and does not consider 1946 // the bitfield-ness of the actual source expression. 1947 if (FromEnumType->getDecl()->isFixed()) { 1948 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1949 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1950 IsIntegralPromotion(nullptr, Underlying, ToType); 1951 } 1952 1953 // We have already pre-calculated the promotion type, so this is trivial. 1954 if (ToType->isIntegerType() && 1955 isCompleteType(From->getLocStart(), FromType)) 1956 return Context.hasSameUnqualifiedType( 1957 ToType, FromEnumType->getDecl()->getPromotionType()); 1958 } 1959 1960 // C++0x [conv.prom]p2: 1961 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1962 // to an rvalue a prvalue of the first of the following types that can 1963 // represent all the values of its underlying type: int, unsigned int, 1964 // long int, unsigned long int, long long int, or unsigned long long int. 1965 // If none of the types in that list can represent all the values of its 1966 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1967 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1968 // type. 1969 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1970 ToType->isIntegerType()) { 1971 // Determine whether the type we're converting from is signed or 1972 // unsigned. 1973 bool FromIsSigned = FromType->isSignedIntegerType(); 1974 uint64_t FromSize = Context.getTypeSize(FromType); 1975 1976 // The types we'll try to promote to, in the appropriate 1977 // order. Try each of these types. 1978 QualType PromoteTypes[6] = { 1979 Context.IntTy, Context.UnsignedIntTy, 1980 Context.LongTy, Context.UnsignedLongTy , 1981 Context.LongLongTy, Context.UnsignedLongLongTy 1982 }; 1983 for (int Idx = 0; Idx < 6; ++Idx) { 1984 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1985 if (FromSize < ToSize || 1986 (FromSize == ToSize && 1987 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1988 // We found the type that we can promote to. If this is the 1989 // type we wanted, we have a promotion. Otherwise, no 1990 // promotion. 1991 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1992 } 1993 } 1994 } 1995 1996 // An rvalue for an integral bit-field (9.6) can be converted to an 1997 // rvalue of type int if int can represent all the values of the 1998 // bit-field; otherwise, it can be converted to unsigned int if 1999 // unsigned int can represent all the values of the bit-field. If 2000 // the bit-field is larger yet, no integral promotion applies to 2001 // it. If the bit-field has an enumerated type, it is treated as any 2002 // other value of that type for promotion purposes (C++ 4.5p3). 2003 // FIXME: We should delay checking of bit-fields until we actually perform the 2004 // conversion. 2005 if (From) { 2006 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2007 llvm::APSInt BitWidth; 2008 if (FromType->isIntegralType(Context) && 2009 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2010 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2011 ToSize = Context.getTypeSize(ToType); 2012 2013 // Are we promoting to an int from a bitfield that fits in an int? 2014 if (BitWidth < ToSize || 2015 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2016 return To->getKind() == BuiltinType::Int; 2017 } 2018 2019 // Are we promoting to an unsigned int from an unsigned bitfield 2020 // that fits into an unsigned int? 2021 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2022 return To->getKind() == BuiltinType::UInt; 2023 } 2024 2025 return false; 2026 } 2027 } 2028 } 2029 2030 // An rvalue of type bool can be converted to an rvalue of type int, 2031 // with false becoming zero and true becoming one (C++ 4.5p4). 2032 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2033 return true; 2034 } 2035 2036 return false; 2037 } 2038 2039 /// IsFloatingPointPromotion - Determines whether the conversion from 2040 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2041 /// returns true and sets PromotedType to the promoted type. 2042 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2043 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2044 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2045 /// An rvalue of type float can be converted to an rvalue of type 2046 /// double. (C++ 4.6p1). 2047 if (FromBuiltin->getKind() == BuiltinType::Float && 2048 ToBuiltin->getKind() == BuiltinType::Double) 2049 return true; 2050 2051 // C99 6.3.1.5p1: 2052 // When a float is promoted to double or long double, or a 2053 // double is promoted to long double [...]. 2054 if (!getLangOpts().CPlusPlus && 2055 (FromBuiltin->getKind() == BuiltinType::Float || 2056 FromBuiltin->getKind() == BuiltinType::Double) && 2057 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2058 ToBuiltin->getKind() == BuiltinType::Float128)) 2059 return true; 2060 2061 // Half can be promoted to float. 2062 if (!getLangOpts().NativeHalfType && 2063 FromBuiltin->getKind() == BuiltinType::Half && 2064 ToBuiltin->getKind() == BuiltinType::Float) 2065 return true; 2066 } 2067 2068 return false; 2069 } 2070 2071 /// \brief Determine if a conversion is a complex promotion. 2072 /// 2073 /// A complex promotion is defined as a complex -> complex conversion 2074 /// where the conversion between the underlying real types is a 2075 /// floating-point or integral promotion. 2076 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2077 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2078 if (!FromComplex) 2079 return false; 2080 2081 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2082 if (!ToComplex) 2083 return false; 2084 2085 return IsFloatingPointPromotion(FromComplex->getElementType(), 2086 ToComplex->getElementType()) || 2087 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2088 ToComplex->getElementType()); 2089 } 2090 2091 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2092 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2093 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2094 /// if non-empty, will be a pointer to ToType that may or may not have 2095 /// the right set of qualifiers on its pointee. 2096 /// 2097 static QualType 2098 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2099 QualType ToPointee, QualType ToType, 2100 ASTContext &Context, 2101 bool StripObjCLifetime = false) { 2102 assert((FromPtr->getTypeClass() == Type::Pointer || 2103 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2104 "Invalid similarly-qualified pointer type"); 2105 2106 /// Conversions to 'id' subsume cv-qualifier conversions. 2107 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2108 return ToType.getUnqualifiedType(); 2109 2110 QualType CanonFromPointee 2111 = Context.getCanonicalType(FromPtr->getPointeeType()); 2112 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2113 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2114 2115 if (StripObjCLifetime) 2116 Quals.removeObjCLifetime(); 2117 2118 // Exact qualifier match -> return the pointer type we're converting to. 2119 if (CanonToPointee.getLocalQualifiers() == Quals) { 2120 // ToType is exactly what we need. Return it. 2121 if (!ToType.isNull()) 2122 return ToType.getUnqualifiedType(); 2123 2124 // Build a pointer to ToPointee. It has the right qualifiers 2125 // already. 2126 if (isa<ObjCObjectPointerType>(ToType)) 2127 return Context.getObjCObjectPointerType(ToPointee); 2128 return Context.getPointerType(ToPointee); 2129 } 2130 2131 // Just build a canonical type that has the right qualifiers. 2132 QualType QualifiedCanonToPointee 2133 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2134 2135 if (isa<ObjCObjectPointerType>(ToType)) 2136 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2137 return Context.getPointerType(QualifiedCanonToPointee); 2138 } 2139 2140 static bool isNullPointerConstantForConversion(Expr *Expr, 2141 bool InOverloadResolution, 2142 ASTContext &Context) { 2143 // Handle value-dependent integral null pointer constants correctly. 2144 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2145 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2146 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2147 return !InOverloadResolution; 2148 2149 return Expr->isNullPointerConstant(Context, 2150 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2151 : Expr::NPC_ValueDependentIsNull); 2152 } 2153 2154 /// IsPointerConversion - Determines whether the conversion of the 2155 /// expression From, which has the (possibly adjusted) type FromType, 2156 /// can be converted to the type ToType via a pointer conversion (C++ 2157 /// 4.10). If so, returns true and places the converted type (that 2158 /// might differ from ToType in its cv-qualifiers at some level) into 2159 /// ConvertedType. 2160 /// 2161 /// This routine also supports conversions to and from block pointers 2162 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2163 /// pointers to interfaces. FIXME: Once we've determined the 2164 /// appropriate overloading rules for Objective-C, we may want to 2165 /// split the Objective-C checks into a different routine; however, 2166 /// GCC seems to consider all of these conversions to be pointer 2167 /// conversions, so for now they live here. IncompatibleObjC will be 2168 /// set if the conversion is an allowed Objective-C conversion that 2169 /// should result in a warning. 2170 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2171 bool InOverloadResolution, 2172 QualType& ConvertedType, 2173 bool &IncompatibleObjC) { 2174 IncompatibleObjC = false; 2175 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2176 IncompatibleObjC)) 2177 return true; 2178 2179 // Conversion from a null pointer constant to any Objective-C pointer type. 2180 if (ToType->isObjCObjectPointerType() && 2181 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2182 ConvertedType = ToType; 2183 return true; 2184 } 2185 2186 // Blocks: Block pointers can be converted to void*. 2187 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2188 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2189 ConvertedType = ToType; 2190 return true; 2191 } 2192 // Blocks: A null pointer constant can be converted to a block 2193 // pointer type. 2194 if (ToType->isBlockPointerType() && 2195 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2196 ConvertedType = ToType; 2197 return true; 2198 } 2199 2200 // If the left-hand-side is nullptr_t, the right side can be a null 2201 // pointer constant. 2202 if (ToType->isNullPtrType() && 2203 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2204 ConvertedType = ToType; 2205 return true; 2206 } 2207 2208 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2209 if (!ToTypePtr) 2210 return false; 2211 2212 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2213 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2214 ConvertedType = ToType; 2215 return true; 2216 } 2217 2218 // Beyond this point, both types need to be pointers 2219 // , including objective-c pointers. 2220 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2221 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2222 !getLangOpts().ObjCAutoRefCount) { 2223 ConvertedType = BuildSimilarlyQualifiedPointerType( 2224 FromType->getAs<ObjCObjectPointerType>(), 2225 ToPointeeType, 2226 ToType, Context); 2227 return true; 2228 } 2229 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2230 if (!FromTypePtr) 2231 return false; 2232 2233 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2234 2235 // If the unqualified pointee types are the same, this can't be a 2236 // pointer conversion, so don't do all of the work below. 2237 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2238 return false; 2239 2240 // An rvalue of type "pointer to cv T," where T is an object type, 2241 // can be converted to an rvalue of type "pointer to cv void" (C++ 2242 // 4.10p2). 2243 if (FromPointeeType->isIncompleteOrObjectType() && 2244 ToPointeeType->isVoidType()) { 2245 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2246 ToPointeeType, 2247 ToType, Context, 2248 /*StripObjCLifetime=*/true); 2249 return true; 2250 } 2251 2252 // MSVC allows implicit function to void* type conversion. 2253 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2254 ToPointeeType->isVoidType()) { 2255 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2256 ToPointeeType, 2257 ToType, Context); 2258 return true; 2259 } 2260 2261 // When we're overloading in C, we allow a special kind of pointer 2262 // conversion for compatible-but-not-identical pointee types. 2263 if (!getLangOpts().CPlusPlus && 2264 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2265 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2266 ToPointeeType, 2267 ToType, Context); 2268 return true; 2269 } 2270 2271 // C++ [conv.ptr]p3: 2272 // 2273 // An rvalue of type "pointer to cv D," where D is a class type, 2274 // can be converted to an rvalue of type "pointer to cv B," where 2275 // B is a base class (clause 10) of D. If B is an inaccessible 2276 // (clause 11) or ambiguous (10.2) base class of D, a program that 2277 // necessitates this conversion is ill-formed. The result of the 2278 // conversion is a pointer to the base class sub-object of the 2279 // derived class object. The null pointer value is converted to 2280 // the null pointer value of the destination type. 2281 // 2282 // Note that we do not check for ambiguity or inaccessibility 2283 // here. That is handled by CheckPointerConversion. 2284 if (getLangOpts().CPlusPlus && 2285 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2286 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2287 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2288 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2289 ToPointeeType, 2290 ToType, Context); 2291 return true; 2292 } 2293 2294 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2295 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2296 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2297 ToPointeeType, 2298 ToType, Context); 2299 return true; 2300 } 2301 2302 return false; 2303 } 2304 2305 /// \brief Adopt the given qualifiers for the given type. 2306 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2307 Qualifiers TQs = T.getQualifiers(); 2308 2309 // Check whether qualifiers already match. 2310 if (TQs == Qs) 2311 return T; 2312 2313 if (Qs.compatiblyIncludes(TQs)) 2314 return Context.getQualifiedType(T, Qs); 2315 2316 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2317 } 2318 2319 /// isObjCPointerConversion - Determines whether this is an 2320 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2321 /// with the same arguments and return values. 2322 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2323 QualType& ConvertedType, 2324 bool &IncompatibleObjC) { 2325 if (!getLangOpts().ObjC1) 2326 return false; 2327 2328 // The set of qualifiers on the type we're converting from. 2329 Qualifiers FromQualifiers = FromType.getQualifiers(); 2330 2331 // First, we handle all conversions on ObjC object pointer types. 2332 const ObjCObjectPointerType* ToObjCPtr = 2333 ToType->getAs<ObjCObjectPointerType>(); 2334 const ObjCObjectPointerType *FromObjCPtr = 2335 FromType->getAs<ObjCObjectPointerType>(); 2336 2337 if (ToObjCPtr && FromObjCPtr) { 2338 // If the pointee types are the same (ignoring qualifications), 2339 // then this is not a pointer conversion. 2340 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2341 FromObjCPtr->getPointeeType())) 2342 return false; 2343 2344 // Conversion between Objective-C pointers. 2345 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2346 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2347 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2348 if (getLangOpts().CPlusPlus && LHS && RHS && 2349 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2350 FromObjCPtr->getPointeeType())) 2351 return false; 2352 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2353 ToObjCPtr->getPointeeType(), 2354 ToType, Context); 2355 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2356 return true; 2357 } 2358 2359 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2360 // Okay: this is some kind of implicit downcast of Objective-C 2361 // interfaces, which is permitted. However, we're going to 2362 // complain about it. 2363 IncompatibleObjC = true; 2364 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2365 ToObjCPtr->getPointeeType(), 2366 ToType, Context); 2367 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2368 return true; 2369 } 2370 } 2371 // Beyond this point, both types need to be C pointers or block pointers. 2372 QualType ToPointeeType; 2373 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2374 ToPointeeType = ToCPtr->getPointeeType(); 2375 else if (const BlockPointerType *ToBlockPtr = 2376 ToType->getAs<BlockPointerType>()) { 2377 // Objective C++: We're able to convert from a pointer to any object 2378 // to a block pointer type. 2379 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2380 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2381 return true; 2382 } 2383 ToPointeeType = ToBlockPtr->getPointeeType(); 2384 } 2385 else if (FromType->getAs<BlockPointerType>() && 2386 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2387 // Objective C++: We're able to convert from a block pointer type to a 2388 // pointer to any object. 2389 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2390 return true; 2391 } 2392 else 2393 return false; 2394 2395 QualType FromPointeeType; 2396 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2397 FromPointeeType = FromCPtr->getPointeeType(); 2398 else if (const BlockPointerType *FromBlockPtr = 2399 FromType->getAs<BlockPointerType>()) 2400 FromPointeeType = FromBlockPtr->getPointeeType(); 2401 else 2402 return false; 2403 2404 // If we have pointers to pointers, recursively check whether this 2405 // is an Objective-C conversion. 2406 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2407 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2408 IncompatibleObjC)) { 2409 // We always complain about this conversion. 2410 IncompatibleObjC = true; 2411 ConvertedType = Context.getPointerType(ConvertedType); 2412 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2413 return true; 2414 } 2415 // Allow conversion of pointee being objective-c pointer to another one; 2416 // as in I* to id. 2417 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2418 ToPointeeType->getAs<ObjCObjectPointerType>() && 2419 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2420 IncompatibleObjC)) { 2421 2422 ConvertedType = Context.getPointerType(ConvertedType); 2423 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2424 return true; 2425 } 2426 2427 // If we have pointers to functions or blocks, check whether the only 2428 // differences in the argument and result types are in Objective-C 2429 // pointer conversions. If so, we permit the conversion (but 2430 // complain about it). 2431 const FunctionProtoType *FromFunctionType 2432 = FromPointeeType->getAs<FunctionProtoType>(); 2433 const FunctionProtoType *ToFunctionType 2434 = ToPointeeType->getAs<FunctionProtoType>(); 2435 if (FromFunctionType && ToFunctionType) { 2436 // If the function types are exactly the same, this isn't an 2437 // Objective-C pointer conversion. 2438 if (Context.getCanonicalType(FromPointeeType) 2439 == Context.getCanonicalType(ToPointeeType)) 2440 return false; 2441 2442 // Perform the quick checks that will tell us whether these 2443 // function types are obviously different. 2444 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2445 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2446 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2447 return false; 2448 2449 bool HasObjCConversion = false; 2450 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2451 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2452 // Okay, the types match exactly. Nothing to do. 2453 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2454 ToFunctionType->getReturnType(), 2455 ConvertedType, IncompatibleObjC)) { 2456 // Okay, we have an Objective-C pointer conversion. 2457 HasObjCConversion = true; 2458 } else { 2459 // Function types are too different. Abort. 2460 return false; 2461 } 2462 2463 // Check argument types. 2464 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2465 ArgIdx != NumArgs; ++ArgIdx) { 2466 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2467 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2468 if (Context.getCanonicalType(FromArgType) 2469 == Context.getCanonicalType(ToArgType)) { 2470 // Okay, the types match exactly. Nothing to do. 2471 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2472 ConvertedType, IncompatibleObjC)) { 2473 // Okay, we have an Objective-C pointer conversion. 2474 HasObjCConversion = true; 2475 } else { 2476 // Argument types are too different. Abort. 2477 return false; 2478 } 2479 } 2480 2481 if (HasObjCConversion) { 2482 // We had an Objective-C conversion. Allow this pointer 2483 // conversion, but complain about it. 2484 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2485 IncompatibleObjC = true; 2486 return true; 2487 } 2488 } 2489 2490 return false; 2491 } 2492 2493 /// \brief Determine whether this is an Objective-C writeback conversion, 2494 /// used for parameter passing when performing automatic reference counting. 2495 /// 2496 /// \param FromType The type we're converting form. 2497 /// 2498 /// \param ToType The type we're converting to. 2499 /// 2500 /// \param ConvertedType The type that will be produced after applying 2501 /// this conversion. 2502 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2503 QualType &ConvertedType) { 2504 if (!getLangOpts().ObjCAutoRefCount || 2505 Context.hasSameUnqualifiedType(FromType, ToType)) 2506 return false; 2507 2508 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2509 QualType ToPointee; 2510 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2511 ToPointee = ToPointer->getPointeeType(); 2512 else 2513 return false; 2514 2515 Qualifiers ToQuals = ToPointee.getQualifiers(); 2516 if (!ToPointee->isObjCLifetimeType() || 2517 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2518 !ToQuals.withoutObjCLifetime().empty()) 2519 return false; 2520 2521 // Argument must be a pointer to __strong to __weak. 2522 QualType FromPointee; 2523 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2524 FromPointee = FromPointer->getPointeeType(); 2525 else 2526 return false; 2527 2528 Qualifiers FromQuals = FromPointee.getQualifiers(); 2529 if (!FromPointee->isObjCLifetimeType() || 2530 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2531 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2532 return false; 2533 2534 // Make sure that we have compatible qualifiers. 2535 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2536 if (!ToQuals.compatiblyIncludes(FromQuals)) 2537 return false; 2538 2539 // Remove qualifiers from the pointee type we're converting from; they 2540 // aren't used in the compatibility check belong, and we'll be adding back 2541 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2542 FromPointee = FromPointee.getUnqualifiedType(); 2543 2544 // The unqualified form of the pointee types must be compatible. 2545 ToPointee = ToPointee.getUnqualifiedType(); 2546 bool IncompatibleObjC; 2547 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2548 FromPointee = ToPointee; 2549 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2550 IncompatibleObjC)) 2551 return false; 2552 2553 /// \brief Construct the type we're converting to, which is a pointer to 2554 /// __autoreleasing pointee. 2555 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2556 ConvertedType = Context.getPointerType(FromPointee); 2557 return true; 2558 } 2559 2560 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2561 QualType& ConvertedType) { 2562 QualType ToPointeeType; 2563 if (const BlockPointerType *ToBlockPtr = 2564 ToType->getAs<BlockPointerType>()) 2565 ToPointeeType = ToBlockPtr->getPointeeType(); 2566 else 2567 return false; 2568 2569 QualType FromPointeeType; 2570 if (const BlockPointerType *FromBlockPtr = 2571 FromType->getAs<BlockPointerType>()) 2572 FromPointeeType = FromBlockPtr->getPointeeType(); 2573 else 2574 return false; 2575 // We have pointer to blocks, check whether the only 2576 // differences in the argument and result types are in Objective-C 2577 // pointer conversions. If so, we permit the conversion. 2578 2579 const FunctionProtoType *FromFunctionType 2580 = FromPointeeType->getAs<FunctionProtoType>(); 2581 const FunctionProtoType *ToFunctionType 2582 = ToPointeeType->getAs<FunctionProtoType>(); 2583 2584 if (!FromFunctionType || !ToFunctionType) 2585 return false; 2586 2587 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2588 return true; 2589 2590 // Perform the quick checks that will tell us whether these 2591 // function types are obviously different. 2592 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2593 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2594 return false; 2595 2596 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2597 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2598 if (FromEInfo != ToEInfo) 2599 return false; 2600 2601 bool IncompatibleObjC = false; 2602 if (Context.hasSameType(FromFunctionType->getReturnType(), 2603 ToFunctionType->getReturnType())) { 2604 // Okay, the types match exactly. Nothing to do. 2605 } else { 2606 QualType RHS = FromFunctionType->getReturnType(); 2607 QualType LHS = ToFunctionType->getReturnType(); 2608 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2609 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2610 LHS = LHS.getUnqualifiedType(); 2611 2612 if (Context.hasSameType(RHS,LHS)) { 2613 // OK exact match. 2614 } else if (isObjCPointerConversion(RHS, LHS, 2615 ConvertedType, IncompatibleObjC)) { 2616 if (IncompatibleObjC) 2617 return false; 2618 // Okay, we have an Objective-C pointer conversion. 2619 } 2620 else 2621 return false; 2622 } 2623 2624 // Check argument types. 2625 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2626 ArgIdx != NumArgs; ++ArgIdx) { 2627 IncompatibleObjC = false; 2628 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2629 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2630 if (Context.hasSameType(FromArgType, ToArgType)) { 2631 // Okay, the types match exactly. Nothing to do. 2632 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2633 ConvertedType, IncompatibleObjC)) { 2634 if (IncompatibleObjC) 2635 return false; 2636 // Okay, we have an Objective-C pointer conversion. 2637 } else 2638 // Argument types are too different. Abort. 2639 return false; 2640 } 2641 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2642 ToFunctionType)) 2643 return false; 2644 2645 ConvertedType = ToType; 2646 return true; 2647 } 2648 2649 enum { 2650 ft_default, 2651 ft_different_class, 2652 ft_parameter_arity, 2653 ft_parameter_mismatch, 2654 ft_return_type, 2655 ft_qualifer_mismatch, 2656 ft_noexcept 2657 }; 2658 2659 /// Attempts to get the FunctionProtoType from a Type. Handles 2660 /// MemberFunctionPointers properly. 2661 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2662 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2663 return FPT; 2664 2665 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2666 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2667 2668 return nullptr; 2669 } 2670 2671 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2672 /// function types. Catches different number of parameter, mismatch in 2673 /// parameter types, and different return types. 2674 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2675 QualType FromType, QualType ToType) { 2676 // If either type is not valid, include no extra info. 2677 if (FromType.isNull() || ToType.isNull()) { 2678 PDiag << ft_default; 2679 return; 2680 } 2681 2682 // Get the function type from the pointers. 2683 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2684 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2685 *ToMember = ToType->getAs<MemberPointerType>(); 2686 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2687 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2688 << QualType(FromMember->getClass(), 0); 2689 return; 2690 } 2691 FromType = FromMember->getPointeeType(); 2692 ToType = ToMember->getPointeeType(); 2693 } 2694 2695 if (FromType->isPointerType()) 2696 FromType = FromType->getPointeeType(); 2697 if (ToType->isPointerType()) 2698 ToType = ToType->getPointeeType(); 2699 2700 // Remove references. 2701 FromType = FromType.getNonReferenceType(); 2702 ToType = ToType.getNonReferenceType(); 2703 2704 // Don't print extra info for non-specialized template functions. 2705 if (FromType->isInstantiationDependentType() && 2706 !FromType->getAs<TemplateSpecializationType>()) { 2707 PDiag << ft_default; 2708 return; 2709 } 2710 2711 // No extra info for same types. 2712 if (Context.hasSameType(FromType, ToType)) { 2713 PDiag << ft_default; 2714 return; 2715 } 2716 2717 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2718 *ToFunction = tryGetFunctionProtoType(ToType); 2719 2720 // Both types need to be function types. 2721 if (!FromFunction || !ToFunction) { 2722 PDiag << ft_default; 2723 return; 2724 } 2725 2726 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2727 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2728 << FromFunction->getNumParams(); 2729 return; 2730 } 2731 2732 // Handle different parameter types. 2733 unsigned ArgPos; 2734 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2735 PDiag << ft_parameter_mismatch << ArgPos + 1 2736 << ToFunction->getParamType(ArgPos) 2737 << FromFunction->getParamType(ArgPos); 2738 return; 2739 } 2740 2741 // Handle different return type. 2742 if (!Context.hasSameType(FromFunction->getReturnType(), 2743 ToFunction->getReturnType())) { 2744 PDiag << ft_return_type << ToFunction->getReturnType() 2745 << FromFunction->getReturnType(); 2746 return; 2747 } 2748 2749 unsigned FromQuals = FromFunction->getTypeQuals(), 2750 ToQuals = ToFunction->getTypeQuals(); 2751 if (FromQuals != ToQuals) { 2752 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2753 return; 2754 } 2755 2756 // Handle exception specification differences on canonical type (in C++17 2757 // onwards). 2758 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2759 ->isNothrow(Context) != 2760 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2761 ->isNothrow(Context)) { 2762 PDiag << ft_noexcept; 2763 return; 2764 } 2765 2766 // Unable to find a difference, so add no extra info. 2767 PDiag << ft_default; 2768 } 2769 2770 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2771 /// for equality of their argument types. Caller has already checked that 2772 /// they have same number of arguments. If the parameters are different, 2773 /// ArgPos will have the parameter index of the first different parameter. 2774 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2775 const FunctionProtoType *NewType, 2776 unsigned *ArgPos) { 2777 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2778 N = NewType->param_type_begin(), 2779 E = OldType->param_type_end(); 2780 O && (O != E); ++O, ++N) { 2781 if (!Context.hasSameType(O->getUnqualifiedType(), 2782 N->getUnqualifiedType())) { 2783 if (ArgPos) 2784 *ArgPos = O - OldType->param_type_begin(); 2785 return false; 2786 } 2787 } 2788 return true; 2789 } 2790 2791 /// CheckPointerConversion - Check the pointer conversion from the 2792 /// expression From to the type ToType. This routine checks for 2793 /// ambiguous or inaccessible derived-to-base pointer 2794 /// conversions for which IsPointerConversion has already returned 2795 /// true. It returns true and produces a diagnostic if there was an 2796 /// error, or returns false otherwise. 2797 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2798 CastKind &Kind, 2799 CXXCastPath& BasePath, 2800 bool IgnoreBaseAccess, 2801 bool Diagnose) { 2802 QualType FromType = From->getType(); 2803 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2804 2805 Kind = CK_BitCast; 2806 2807 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2808 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2809 Expr::NPCK_ZeroExpression) { 2810 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2811 DiagRuntimeBehavior(From->getExprLoc(), From, 2812 PDiag(diag::warn_impcast_bool_to_null_pointer) 2813 << ToType << From->getSourceRange()); 2814 else if (!isUnevaluatedContext()) 2815 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2816 << ToType << From->getSourceRange(); 2817 } 2818 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2819 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2820 QualType FromPointeeType = FromPtrType->getPointeeType(), 2821 ToPointeeType = ToPtrType->getPointeeType(); 2822 2823 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2824 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2825 // We must have a derived-to-base conversion. Check an 2826 // ambiguous or inaccessible conversion. 2827 unsigned InaccessibleID = 0; 2828 unsigned AmbigiousID = 0; 2829 if (Diagnose) { 2830 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2831 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2832 } 2833 if (CheckDerivedToBaseConversion( 2834 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2835 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2836 &BasePath, IgnoreBaseAccess)) 2837 return true; 2838 2839 // The conversion was successful. 2840 Kind = CK_DerivedToBase; 2841 } 2842 2843 if (Diagnose && !IsCStyleOrFunctionalCast && 2844 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2845 assert(getLangOpts().MSVCCompat && 2846 "this should only be possible with MSVCCompat!"); 2847 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2848 << From->getSourceRange(); 2849 } 2850 } 2851 } else if (const ObjCObjectPointerType *ToPtrType = 2852 ToType->getAs<ObjCObjectPointerType>()) { 2853 if (const ObjCObjectPointerType *FromPtrType = 2854 FromType->getAs<ObjCObjectPointerType>()) { 2855 // Objective-C++ conversions are always okay. 2856 // FIXME: We should have a different class of conversions for the 2857 // Objective-C++ implicit conversions. 2858 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2859 return false; 2860 } else if (FromType->isBlockPointerType()) { 2861 Kind = CK_BlockPointerToObjCPointerCast; 2862 } else { 2863 Kind = CK_CPointerToObjCPointerCast; 2864 } 2865 } else if (ToType->isBlockPointerType()) { 2866 if (!FromType->isBlockPointerType()) 2867 Kind = CK_AnyPointerToBlockPointerCast; 2868 } 2869 2870 // We shouldn't fall into this case unless it's valid for other 2871 // reasons. 2872 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2873 Kind = CK_NullToPointer; 2874 2875 return false; 2876 } 2877 2878 /// IsMemberPointerConversion - Determines whether the conversion of the 2879 /// expression From, which has the (possibly adjusted) type FromType, can be 2880 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2881 /// If so, returns true and places the converted type (that might differ from 2882 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2883 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2884 QualType ToType, 2885 bool InOverloadResolution, 2886 QualType &ConvertedType) { 2887 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2888 if (!ToTypePtr) 2889 return false; 2890 2891 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2892 if (From->isNullPointerConstant(Context, 2893 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2894 : Expr::NPC_ValueDependentIsNull)) { 2895 ConvertedType = ToType; 2896 return true; 2897 } 2898 2899 // Otherwise, both types have to be member pointers. 2900 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2901 if (!FromTypePtr) 2902 return false; 2903 2904 // A pointer to member of B can be converted to a pointer to member of D, 2905 // where D is derived from B (C++ 4.11p2). 2906 QualType FromClass(FromTypePtr->getClass(), 0); 2907 QualType ToClass(ToTypePtr->getClass(), 0); 2908 2909 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2910 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2911 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2912 ToClass.getTypePtr()); 2913 return true; 2914 } 2915 2916 return false; 2917 } 2918 2919 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2920 /// expression From to the type ToType. This routine checks for ambiguous or 2921 /// virtual or inaccessible base-to-derived member pointer conversions 2922 /// for which IsMemberPointerConversion has already returned true. It returns 2923 /// true and produces a diagnostic if there was an error, or returns false 2924 /// otherwise. 2925 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2926 CastKind &Kind, 2927 CXXCastPath &BasePath, 2928 bool IgnoreBaseAccess) { 2929 QualType FromType = From->getType(); 2930 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2931 if (!FromPtrType) { 2932 // This must be a null pointer to member pointer conversion 2933 assert(From->isNullPointerConstant(Context, 2934 Expr::NPC_ValueDependentIsNull) && 2935 "Expr must be null pointer constant!"); 2936 Kind = CK_NullToMemberPointer; 2937 return false; 2938 } 2939 2940 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2941 assert(ToPtrType && "No member pointer cast has a target type " 2942 "that is not a member pointer."); 2943 2944 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2945 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2946 2947 // FIXME: What about dependent types? 2948 assert(FromClass->isRecordType() && "Pointer into non-class."); 2949 assert(ToClass->isRecordType() && "Pointer into non-class."); 2950 2951 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2952 /*DetectVirtual=*/true); 2953 bool DerivationOkay = 2954 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2955 assert(DerivationOkay && 2956 "Should not have been called if derivation isn't OK."); 2957 (void)DerivationOkay; 2958 2959 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2960 getUnqualifiedType())) { 2961 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2962 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2963 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2964 return true; 2965 } 2966 2967 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2968 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2969 << FromClass << ToClass << QualType(VBase, 0) 2970 << From->getSourceRange(); 2971 return true; 2972 } 2973 2974 if (!IgnoreBaseAccess) 2975 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2976 Paths.front(), 2977 diag::err_downcast_from_inaccessible_base); 2978 2979 // Must be a base to derived member conversion. 2980 BuildBasePathArray(Paths, BasePath); 2981 Kind = CK_BaseToDerivedMemberPointer; 2982 return false; 2983 } 2984 2985 /// Determine whether the lifetime conversion between the two given 2986 /// qualifiers sets is nontrivial. 2987 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2988 Qualifiers ToQuals) { 2989 // Converting anything to const __unsafe_unretained is trivial. 2990 if (ToQuals.hasConst() && 2991 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2992 return false; 2993 2994 return true; 2995 } 2996 2997 /// IsQualificationConversion - Determines whether the conversion from 2998 /// an rvalue of type FromType to ToType is a qualification conversion 2999 /// (C++ 4.4). 3000 /// 3001 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3002 /// when the qualification conversion involves a change in the Objective-C 3003 /// object lifetime. 3004 bool 3005 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3006 bool CStyle, bool &ObjCLifetimeConversion) { 3007 FromType = Context.getCanonicalType(FromType); 3008 ToType = Context.getCanonicalType(ToType); 3009 ObjCLifetimeConversion = false; 3010 3011 // If FromType and ToType are the same type, this is not a 3012 // qualification conversion. 3013 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3014 return false; 3015 3016 // (C++ 4.4p4): 3017 // A conversion can add cv-qualifiers at levels other than the first 3018 // in multi-level pointers, subject to the following rules: [...] 3019 bool PreviousToQualsIncludeConst = true; 3020 bool UnwrappedAnyPointer = false; 3021 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3022 // Within each iteration of the loop, we check the qualifiers to 3023 // determine if this still looks like a qualification 3024 // conversion. Then, if all is well, we unwrap one more level of 3025 // pointers or pointers-to-members and do it all again 3026 // until there are no more pointers or pointers-to-members left to 3027 // unwrap. 3028 UnwrappedAnyPointer = true; 3029 3030 Qualifiers FromQuals = FromType.getQualifiers(); 3031 Qualifiers ToQuals = ToType.getQualifiers(); 3032 3033 // Ignore __unaligned qualifier if this type is void. 3034 if (ToType.getUnqualifiedType()->isVoidType()) 3035 FromQuals.removeUnaligned(); 3036 3037 // Objective-C ARC: 3038 // Check Objective-C lifetime conversions. 3039 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3040 UnwrappedAnyPointer) { 3041 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3042 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3043 ObjCLifetimeConversion = true; 3044 FromQuals.removeObjCLifetime(); 3045 ToQuals.removeObjCLifetime(); 3046 } else { 3047 // Qualification conversions cannot cast between different 3048 // Objective-C lifetime qualifiers. 3049 return false; 3050 } 3051 } 3052 3053 // Allow addition/removal of GC attributes but not changing GC attributes. 3054 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3055 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3056 FromQuals.removeObjCGCAttr(); 3057 ToQuals.removeObjCGCAttr(); 3058 } 3059 3060 // -- for every j > 0, if const is in cv 1,j then const is in cv 3061 // 2,j, and similarly for volatile. 3062 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3063 return false; 3064 3065 // -- if the cv 1,j and cv 2,j are different, then const is in 3066 // every cv for 0 < k < j. 3067 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3068 && !PreviousToQualsIncludeConst) 3069 return false; 3070 3071 // Keep track of whether all prior cv-qualifiers in the "to" type 3072 // include const. 3073 PreviousToQualsIncludeConst 3074 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3075 } 3076 3077 // We are left with FromType and ToType being the pointee types 3078 // after unwrapping the original FromType and ToType the same number 3079 // of types. If we unwrapped any pointers, and if FromType and 3080 // ToType have the same unqualified type (since we checked 3081 // qualifiers above), then this is a qualification conversion. 3082 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3083 } 3084 3085 /// \brief - Determine whether this is a conversion from a scalar type to an 3086 /// atomic type. 3087 /// 3088 /// If successful, updates \c SCS's second and third steps in the conversion 3089 /// sequence to finish the conversion. 3090 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3091 bool InOverloadResolution, 3092 StandardConversionSequence &SCS, 3093 bool CStyle) { 3094 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3095 if (!ToAtomic) 3096 return false; 3097 3098 StandardConversionSequence InnerSCS; 3099 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3100 InOverloadResolution, InnerSCS, 3101 CStyle, /*AllowObjCWritebackConversion=*/false)) 3102 return false; 3103 3104 SCS.Second = InnerSCS.Second; 3105 SCS.setToType(1, InnerSCS.getToType(1)); 3106 SCS.Third = InnerSCS.Third; 3107 SCS.QualificationIncludesObjCLifetime 3108 = InnerSCS.QualificationIncludesObjCLifetime; 3109 SCS.setToType(2, InnerSCS.getToType(2)); 3110 return true; 3111 } 3112 3113 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3114 CXXConstructorDecl *Constructor, 3115 QualType Type) { 3116 const FunctionProtoType *CtorType = 3117 Constructor->getType()->getAs<FunctionProtoType>(); 3118 if (CtorType->getNumParams() > 0) { 3119 QualType FirstArg = CtorType->getParamType(0); 3120 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3121 return true; 3122 } 3123 return false; 3124 } 3125 3126 static OverloadingResult 3127 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3128 CXXRecordDecl *To, 3129 UserDefinedConversionSequence &User, 3130 OverloadCandidateSet &CandidateSet, 3131 bool AllowExplicit) { 3132 for (auto *D : S.LookupConstructors(To)) { 3133 auto Info = getConstructorInfo(D); 3134 if (!Info) 3135 continue; 3136 3137 bool Usable = !Info.Constructor->isInvalidDecl() && 3138 S.isInitListConstructor(Info.Constructor) && 3139 (AllowExplicit || !Info.Constructor->isExplicit()); 3140 if (Usable) { 3141 // If the first argument is (a reference to) the target type, 3142 // suppress conversions. 3143 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3144 S.Context, Info.Constructor, ToType); 3145 if (Info.ConstructorTmpl) 3146 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3147 /*ExplicitArgs*/ nullptr, From, 3148 CandidateSet, SuppressUserConversions); 3149 else 3150 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3151 CandidateSet, SuppressUserConversions); 3152 } 3153 } 3154 3155 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3156 3157 OverloadCandidateSet::iterator Best; 3158 switch (auto Result = 3159 CandidateSet.BestViableFunction(S, From->getLocStart(), 3160 Best, true)) { 3161 case OR_Deleted: 3162 case OR_Success: { 3163 // Record the standard conversion we used and the conversion function. 3164 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3165 QualType ThisType = Constructor->getThisType(S.Context); 3166 // Initializer lists don't have conversions as such. 3167 User.Before.setAsIdentityConversion(); 3168 User.HadMultipleCandidates = HadMultipleCandidates; 3169 User.ConversionFunction = Constructor; 3170 User.FoundConversionFunction = Best->FoundDecl; 3171 User.After.setAsIdentityConversion(); 3172 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3173 User.After.setAllToTypes(ToType); 3174 return Result; 3175 } 3176 3177 case OR_No_Viable_Function: 3178 return OR_No_Viable_Function; 3179 case OR_Ambiguous: 3180 return OR_Ambiguous; 3181 } 3182 3183 llvm_unreachable("Invalid OverloadResult!"); 3184 } 3185 3186 /// Determines whether there is a user-defined conversion sequence 3187 /// (C++ [over.ics.user]) that converts expression From to the type 3188 /// ToType. If such a conversion exists, User will contain the 3189 /// user-defined conversion sequence that performs such a conversion 3190 /// and this routine will return true. Otherwise, this routine returns 3191 /// false and User is unspecified. 3192 /// 3193 /// \param AllowExplicit true if the conversion should consider C++0x 3194 /// "explicit" conversion functions as well as non-explicit conversion 3195 /// functions (C++0x [class.conv.fct]p2). 3196 /// 3197 /// \param AllowObjCConversionOnExplicit true if the conversion should 3198 /// allow an extra Objective-C pointer conversion on uses of explicit 3199 /// constructors. Requires \c AllowExplicit to also be set. 3200 static OverloadingResult 3201 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3202 UserDefinedConversionSequence &User, 3203 OverloadCandidateSet &CandidateSet, 3204 bool AllowExplicit, 3205 bool AllowObjCConversionOnExplicit) { 3206 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3207 3208 // Whether we will only visit constructors. 3209 bool ConstructorsOnly = false; 3210 3211 // If the type we are conversion to is a class type, enumerate its 3212 // constructors. 3213 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3214 // C++ [over.match.ctor]p1: 3215 // When objects of class type are direct-initialized (8.5), or 3216 // copy-initialized from an expression of the same or a 3217 // derived class type (8.5), overload resolution selects the 3218 // constructor. [...] For copy-initialization, the candidate 3219 // functions are all the converting constructors (12.3.1) of 3220 // that class. The argument list is the expression-list within 3221 // the parentheses of the initializer. 3222 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3223 (From->getType()->getAs<RecordType>() && 3224 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3225 ConstructorsOnly = true; 3226 3227 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3228 // We're not going to find any constructors. 3229 } else if (CXXRecordDecl *ToRecordDecl 3230 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3231 3232 Expr **Args = &From; 3233 unsigned NumArgs = 1; 3234 bool ListInitializing = false; 3235 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3236 // But first, see if there is an init-list-constructor that will work. 3237 OverloadingResult Result = IsInitializerListConstructorConversion( 3238 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3239 if (Result != OR_No_Viable_Function) 3240 return Result; 3241 // Never mind. 3242 CandidateSet.clear(); 3243 3244 // If we're list-initializing, we pass the individual elements as 3245 // arguments, not the entire list. 3246 Args = InitList->getInits(); 3247 NumArgs = InitList->getNumInits(); 3248 ListInitializing = true; 3249 } 3250 3251 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3252 auto Info = getConstructorInfo(D); 3253 if (!Info) 3254 continue; 3255 3256 bool Usable = !Info.Constructor->isInvalidDecl(); 3257 if (ListInitializing) 3258 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3259 else 3260 Usable = Usable && 3261 Info.Constructor->isConvertingConstructor(AllowExplicit); 3262 if (Usable) { 3263 bool SuppressUserConversions = !ConstructorsOnly; 3264 if (SuppressUserConversions && ListInitializing) { 3265 SuppressUserConversions = false; 3266 if (NumArgs == 1) { 3267 // If the first argument is (a reference to) the target type, 3268 // suppress conversions. 3269 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3270 S.Context, Info.Constructor, ToType); 3271 } 3272 } 3273 if (Info.ConstructorTmpl) 3274 S.AddTemplateOverloadCandidate( 3275 Info.ConstructorTmpl, Info.FoundDecl, 3276 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3277 CandidateSet, SuppressUserConversions); 3278 else 3279 // Allow one user-defined conversion when user specifies a 3280 // From->ToType conversion via an static cast (c-style, etc). 3281 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3282 llvm::makeArrayRef(Args, NumArgs), 3283 CandidateSet, SuppressUserConversions); 3284 } 3285 } 3286 } 3287 } 3288 3289 // Enumerate conversion functions, if we're allowed to. 3290 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3291 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3292 // No conversion functions from incomplete types. 3293 } else if (const RecordType *FromRecordType 3294 = From->getType()->getAs<RecordType>()) { 3295 if (CXXRecordDecl *FromRecordDecl 3296 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3297 // Add all of the conversion functions as candidates. 3298 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3299 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3300 DeclAccessPair FoundDecl = I.getPair(); 3301 NamedDecl *D = FoundDecl.getDecl(); 3302 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3303 if (isa<UsingShadowDecl>(D)) 3304 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3305 3306 CXXConversionDecl *Conv; 3307 FunctionTemplateDecl *ConvTemplate; 3308 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3309 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3310 else 3311 Conv = cast<CXXConversionDecl>(D); 3312 3313 if (AllowExplicit || !Conv->isExplicit()) { 3314 if (ConvTemplate) 3315 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3316 ActingContext, From, ToType, 3317 CandidateSet, 3318 AllowObjCConversionOnExplicit); 3319 else 3320 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3321 From, ToType, CandidateSet, 3322 AllowObjCConversionOnExplicit); 3323 } 3324 } 3325 } 3326 } 3327 3328 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3329 3330 OverloadCandidateSet::iterator Best; 3331 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3332 Best, true)) { 3333 case OR_Success: 3334 case OR_Deleted: 3335 // Record the standard conversion we used and the conversion function. 3336 if (CXXConstructorDecl *Constructor 3337 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3338 // C++ [over.ics.user]p1: 3339 // If the user-defined conversion is specified by a 3340 // constructor (12.3.1), the initial standard conversion 3341 // sequence converts the source type to the type required by 3342 // the argument of the constructor. 3343 // 3344 QualType ThisType = Constructor->getThisType(S.Context); 3345 if (isa<InitListExpr>(From)) { 3346 // Initializer lists don't have conversions as such. 3347 User.Before.setAsIdentityConversion(); 3348 } else { 3349 if (Best->Conversions[0].isEllipsis()) 3350 User.EllipsisConversion = true; 3351 else { 3352 User.Before = Best->Conversions[0].Standard; 3353 User.EllipsisConversion = false; 3354 } 3355 } 3356 User.HadMultipleCandidates = HadMultipleCandidates; 3357 User.ConversionFunction = Constructor; 3358 User.FoundConversionFunction = Best->FoundDecl; 3359 User.After.setAsIdentityConversion(); 3360 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3361 User.After.setAllToTypes(ToType); 3362 return Result; 3363 } 3364 if (CXXConversionDecl *Conversion 3365 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3366 // C++ [over.ics.user]p1: 3367 // 3368 // [...] If the user-defined conversion is specified by a 3369 // conversion function (12.3.2), the initial standard 3370 // conversion sequence converts the source type to the 3371 // implicit object parameter of the conversion function. 3372 User.Before = Best->Conversions[0].Standard; 3373 User.HadMultipleCandidates = HadMultipleCandidates; 3374 User.ConversionFunction = Conversion; 3375 User.FoundConversionFunction = Best->FoundDecl; 3376 User.EllipsisConversion = false; 3377 3378 // C++ [over.ics.user]p2: 3379 // The second standard conversion sequence converts the 3380 // result of the user-defined conversion to the target type 3381 // for the sequence. Since an implicit conversion sequence 3382 // is an initialization, the special rules for 3383 // initialization by user-defined conversion apply when 3384 // selecting the best user-defined conversion for a 3385 // user-defined conversion sequence (see 13.3.3 and 3386 // 13.3.3.1). 3387 User.After = Best->FinalConversion; 3388 return Result; 3389 } 3390 llvm_unreachable("Not a constructor or conversion function?"); 3391 3392 case OR_No_Viable_Function: 3393 return OR_No_Viable_Function; 3394 3395 case OR_Ambiguous: 3396 return OR_Ambiguous; 3397 } 3398 3399 llvm_unreachable("Invalid OverloadResult!"); 3400 } 3401 3402 bool 3403 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3404 ImplicitConversionSequence ICS; 3405 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3406 OverloadCandidateSet::CSK_Normal); 3407 OverloadingResult OvResult = 3408 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3409 CandidateSet, false, false); 3410 if (OvResult == OR_Ambiguous) 3411 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3412 << From->getType() << ToType << From->getSourceRange(); 3413 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3414 if (!RequireCompleteType(From->getLocStart(), ToType, 3415 diag::err_typecheck_nonviable_condition_incomplete, 3416 From->getType(), From->getSourceRange())) 3417 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3418 << false << From->getType() << From->getSourceRange() << ToType; 3419 } else 3420 return false; 3421 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3422 return true; 3423 } 3424 3425 /// \brief Compare the user-defined conversion functions or constructors 3426 /// of two user-defined conversion sequences to determine whether any ordering 3427 /// is possible. 3428 static ImplicitConversionSequence::CompareKind 3429 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3430 FunctionDecl *Function2) { 3431 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3432 return ImplicitConversionSequence::Indistinguishable; 3433 3434 // Objective-C++: 3435 // If both conversion functions are implicitly-declared conversions from 3436 // a lambda closure type to a function pointer and a block pointer, 3437 // respectively, always prefer the conversion to a function pointer, 3438 // because the function pointer is more lightweight and is more likely 3439 // to keep code working. 3440 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3441 if (!Conv1) 3442 return ImplicitConversionSequence::Indistinguishable; 3443 3444 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3445 if (!Conv2) 3446 return ImplicitConversionSequence::Indistinguishable; 3447 3448 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3449 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3450 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3451 if (Block1 != Block2) 3452 return Block1 ? ImplicitConversionSequence::Worse 3453 : ImplicitConversionSequence::Better; 3454 } 3455 3456 return ImplicitConversionSequence::Indistinguishable; 3457 } 3458 3459 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3460 const ImplicitConversionSequence &ICS) { 3461 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3462 (ICS.isUserDefined() && 3463 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3464 } 3465 3466 /// CompareImplicitConversionSequences - Compare two implicit 3467 /// conversion sequences to determine whether one is better than the 3468 /// other or if they are indistinguishable (C++ 13.3.3.2). 3469 static ImplicitConversionSequence::CompareKind 3470 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3471 const ImplicitConversionSequence& ICS1, 3472 const ImplicitConversionSequence& ICS2) 3473 { 3474 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3475 // conversion sequences (as defined in 13.3.3.1) 3476 // -- a standard conversion sequence (13.3.3.1.1) is a better 3477 // conversion sequence than a user-defined conversion sequence or 3478 // an ellipsis conversion sequence, and 3479 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3480 // conversion sequence than an ellipsis conversion sequence 3481 // (13.3.3.1.3). 3482 // 3483 // C++0x [over.best.ics]p10: 3484 // For the purpose of ranking implicit conversion sequences as 3485 // described in 13.3.3.2, the ambiguous conversion sequence is 3486 // treated as a user-defined sequence that is indistinguishable 3487 // from any other user-defined conversion sequence. 3488 3489 // String literal to 'char *' conversion has been deprecated in C++03. It has 3490 // been removed from C++11. We still accept this conversion, if it happens at 3491 // the best viable function. Otherwise, this conversion is considered worse 3492 // than ellipsis conversion. Consider this as an extension; this is not in the 3493 // standard. For example: 3494 // 3495 // int &f(...); // #1 3496 // void f(char*); // #2 3497 // void g() { int &r = f("foo"); } 3498 // 3499 // In C++03, we pick #2 as the best viable function. 3500 // In C++11, we pick #1 as the best viable function, because ellipsis 3501 // conversion is better than string-literal to char* conversion (since there 3502 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3503 // convert arguments, #2 would be the best viable function in C++11. 3504 // If the best viable function has this conversion, a warning will be issued 3505 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3506 3507 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3508 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3509 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3510 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3511 ? ImplicitConversionSequence::Worse 3512 : ImplicitConversionSequence::Better; 3513 3514 if (ICS1.getKindRank() < ICS2.getKindRank()) 3515 return ImplicitConversionSequence::Better; 3516 if (ICS2.getKindRank() < ICS1.getKindRank()) 3517 return ImplicitConversionSequence::Worse; 3518 3519 // The following checks require both conversion sequences to be of 3520 // the same kind. 3521 if (ICS1.getKind() != ICS2.getKind()) 3522 return ImplicitConversionSequence::Indistinguishable; 3523 3524 ImplicitConversionSequence::CompareKind Result = 3525 ImplicitConversionSequence::Indistinguishable; 3526 3527 // Two implicit conversion sequences of the same form are 3528 // indistinguishable conversion sequences unless one of the 3529 // following rules apply: (C++ 13.3.3.2p3): 3530 3531 // List-initialization sequence L1 is a better conversion sequence than 3532 // list-initialization sequence L2 if: 3533 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3534 // if not that, 3535 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3536 // and N1 is smaller than N2., 3537 // even if one of the other rules in this paragraph would otherwise apply. 3538 if (!ICS1.isBad()) { 3539 if (ICS1.isStdInitializerListElement() && 3540 !ICS2.isStdInitializerListElement()) 3541 return ImplicitConversionSequence::Better; 3542 if (!ICS1.isStdInitializerListElement() && 3543 ICS2.isStdInitializerListElement()) 3544 return ImplicitConversionSequence::Worse; 3545 } 3546 3547 if (ICS1.isStandard()) 3548 // Standard conversion sequence S1 is a better conversion sequence than 3549 // standard conversion sequence S2 if [...] 3550 Result = CompareStandardConversionSequences(S, Loc, 3551 ICS1.Standard, ICS2.Standard); 3552 else if (ICS1.isUserDefined()) { 3553 // User-defined conversion sequence U1 is a better conversion 3554 // sequence than another user-defined conversion sequence U2 if 3555 // they contain the same user-defined conversion function or 3556 // constructor and if the second standard conversion sequence of 3557 // U1 is better than the second standard conversion sequence of 3558 // U2 (C++ 13.3.3.2p3). 3559 if (ICS1.UserDefined.ConversionFunction == 3560 ICS2.UserDefined.ConversionFunction) 3561 Result = CompareStandardConversionSequences(S, Loc, 3562 ICS1.UserDefined.After, 3563 ICS2.UserDefined.After); 3564 else 3565 Result = compareConversionFunctions(S, 3566 ICS1.UserDefined.ConversionFunction, 3567 ICS2.UserDefined.ConversionFunction); 3568 } 3569 3570 return Result; 3571 } 3572 3573 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3574 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3575 Qualifiers Quals; 3576 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3577 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3578 } 3579 3580 return Context.hasSameUnqualifiedType(T1, T2); 3581 } 3582 3583 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3584 // determine if one is a proper subset of the other. 3585 static ImplicitConversionSequence::CompareKind 3586 compareStandardConversionSubsets(ASTContext &Context, 3587 const StandardConversionSequence& SCS1, 3588 const StandardConversionSequence& SCS2) { 3589 ImplicitConversionSequence::CompareKind Result 3590 = ImplicitConversionSequence::Indistinguishable; 3591 3592 // the identity conversion sequence is considered to be a subsequence of 3593 // any non-identity conversion sequence 3594 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3595 return ImplicitConversionSequence::Better; 3596 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3597 return ImplicitConversionSequence::Worse; 3598 3599 if (SCS1.Second != SCS2.Second) { 3600 if (SCS1.Second == ICK_Identity) 3601 Result = ImplicitConversionSequence::Better; 3602 else if (SCS2.Second == ICK_Identity) 3603 Result = ImplicitConversionSequence::Worse; 3604 else 3605 return ImplicitConversionSequence::Indistinguishable; 3606 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3607 return ImplicitConversionSequence::Indistinguishable; 3608 3609 if (SCS1.Third == SCS2.Third) { 3610 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3611 : ImplicitConversionSequence::Indistinguishable; 3612 } 3613 3614 if (SCS1.Third == ICK_Identity) 3615 return Result == ImplicitConversionSequence::Worse 3616 ? ImplicitConversionSequence::Indistinguishable 3617 : ImplicitConversionSequence::Better; 3618 3619 if (SCS2.Third == ICK_Identity) 3620 return Result == ImplicitConversionSequence::Better 3621 ? ImplicitConversionSequence::Indistinguishable 3622 : ImplicitConversionSequence::Worse; 3623 3624 return ImplicitConversionSequence::Indistinguishable; 3625 } 3626 3627 /// \brief Determine whether one of the given reference bindings is better 3628 /// than the other based on what kind of bindings they are. 3629 static bool 3630 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3631 const StandardConversionSequence &SCS2) { 3632 // C++0x [over.ics.rank]p3b4: 3633 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3634 // implicit object parameter of a non-static member function declared 3635 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3636 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3637 // lvalue reference to a function lvalue and S2 binds an rvalue 3638 // reference*. 3639 // 3640 // FIXME: Rvalue references. We're going rogue with the above edits, 3641 // because the semantics in the current C++0x working paper (N3225 at the 3642 // time of this writing) break the standard definition of std::forward 3643 // and std::reference_wrapper when dealing with references to functions. 3644 // Proposed wording changes submitted to CWG for consideration. 3645 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3646 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3647 return false; 3648 3649 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3650 SCS2.IsLvalueReference) || 3651 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3652 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3653 } 3654 3655 /// CompareStandardConversionSequences - Compare two standard 3656 /// conversion sequences to determine whether one is better than the 3657 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3658 static ImplicitConversionSequence::CompareKind 3659 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3660 const StandardConversionSequence& SCS1, 3661 const StandardConversionSequence& SCS2) 3662 { 3663 // Standard conversion sequence S1 is a better conversion sequence 3664 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3665 3666 // -- S1 is a proper subsequence of S2 (comparing the conversion 3667 // sequences in the canonical form defined by 13.3.3.1.1, 3668 // excluding any Lvalue Transformation; the identity conversion 3669 // sequence is considered to be a subsequence of any 3670 // non-identity conversion sequence) or, if not that, 3671 if (ImplicitConversionSequence::CompareKind CK 3672 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3673 return CK; 3674 3675 // -- the rank of S1 is better than the rank of S2 (by the rules 3676 // defined below), or, if not that, 3677 ImplicitConversionRank Rank1 = SCS1.getRank(); 3678 ImplicitConversionRank Rank2 = SCS2.getRank(); 3679 if (Rank1 < Rank2) 3680 return ImplicitConversionSequence::Better; 3681 else if (Rank2 < Rank1) 3682 return ImplicitConversionSequence::Worse; 3683 3684 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3685 // are indistinguishable unless one of the following rules 3686 // applies: 3687 3688 // A conversion that is not a conversion of a pointer, or 3689 // pointer to member, to bool is better than another conversion 3690 // that is such a conversion. 3691 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3692 return SCS2.isPointerConversionToBool() 3693 ? ImplicitConversionSequence::Better 3694 : ImplicitConversionSequence::Worse; 3695 3696 // C++ [over.ics.rank]p4b2: 3697 // 3698 // If class B is derived directly or indirectly from class A, 3699 // conversion of B* to A* is better than conversion of B* to 3700 // void*, and conversion of A* to void* is better than conversion 3701 // of B* to void*. 3702 bool SCS1ConvertsToVoid 3703 = SCS1.isPointerConversionToVoidPointer(S.Context); 3704 bool SCS2ConvertsToVoid 3705 = SCS2.isPointerConversionToVoidPointer(S.Context); 3706 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3707 // Exactly one of the conversion sequences is a conversion to 3708 // a void pointer; it's the worse conversion. 3709 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3710 : ImplicitConversionSequence::Worse; 3711 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3712 // Neither conversion sequence converts to a void pointer; compare 3713 // their derived-to-base conversions. 3714 if (ImplicitConversionSequence::CompareKind DerivedCK 3715 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3716 return DerivedCK; 3717 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3718 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3719 // Both conversion sequences are conversions to void 3720 // pointers. Compare the source types to determine if there's an 3721 // inheritance relationship in their sources. 3722 QualType FromType1 = SCS1.getFromType(); 3723 QualType FromType2 = SCS2.getFromType(); 3724 3725 // Adjust the types we're converting from via the array-to-pointer 3726 // conversion, if we need to. 3727 if (SCS1.First == ICK_Array_To_Pointer) 3728 FromType1 = S.Context.getArrayDecayedType(FromType1); 3729 if (SCS2.First == ICK_Array_To_Pointer) 3730 FromType2 = S.Context.getArrayDecayedType(FromType2); 3731 3732 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3733 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3734 3735 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3736 return ImplicitConversionSequence::Better; 3737 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3738 return ImplicitConversionSequence::Worse; 3739 3740 // Objective-C++: If one interface is more specific than the 3741 // other, it is the better one. 3742 const ObjCObjectPointerType* FromObjCPtr1 3743 = FromType1->getAs<ObjCObjectPointerType>(); 3744 const ObjCObjectPointerType* FromObjCPtr2 3745 = FromType2->getAs<ObjCObjectPointerType>(); 3746 if (FromObjCPtr1 && FromObjCPtr2) { 3747 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3748 FromObjCPtr2); 3749 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3750 FromObjCPtr1); 3751 if (AssignLeft != AssignRight) { 3752 return AssignLeft? ImplicitConversionSequence::Better 3753 : ImplicitConversionSequence::Worse; 3754 } 3755 } 3756 } 3757 3758 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3759 // bullet 3). 3760 if (ImplicitConversionSequence::CompareKind QualCK 3761 = CompareQualificationConversions(S, SCS1, SCS2)) 3762 return QualCK; 3763 3764 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3765 // Check for a better reference binding based on the kind of bindings. 3766 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3767 return ImplicitConversionSequence::Better; 3768 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3769 return ImplicitConversionSequence::Worse; 3770 3771 // C++ [over.ics.rank]p3b4: 3772 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3773 // which the references refer are the same type except for 3774 // top-level cv-qualifiers, and the type to which the reference 3775 // initialized by S2 refers is more cv-qualified than the type 3776 // to which the reference initialized by S1 refers. 3777 QualType T1 = SCS1.getToType(2); 3778 QualType T2 = SCS2.getToType(2); 3779 T1 = S.Context.getCanonicalType(T1); 3780 T2 = S.Context.getCanonicalType(T2); 3781 Qualifiers T1Quals, T2Quals; 3782 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3783 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3784 if (UnqualT1 == UnqualT2) { 3785 // Objective-C++ ARC: If the references refer to objects with different 3786 // lifetimes, prefer bindings that don't change lifetime. 3787 if (SCS1.ObjCLifetimeConversionBinding != 3788 SCS2.ObjCLifetimeConversionBinding) { 3789 return SCS1.ObjCLifetimeConversionBinding 3790 ? ImplicitConversionSequence::Worse 3791 : ImplicitConversionSequence::Better; 3792 } 3793 3794 // If the type is an array type, promote the element qualifiers to the 3795 // type for comparison. 3796 if (isa<ArrayType>(T1) && T1Quals) 3797 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3798 if (isa<ArrayType>(T2) && T2Quals) 3799 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3800 if (T2.isMoreQualifiedThan(T1)) 3801 return ImplicitConversionSequence::Better; 3802 else if (T1.isMoreQualifiedThan(T2)) 3803 return ImplicitConversionSequence::Worse; 3804 } 3805 } 3806 3807 // In Microsoft mode, prefer an integral conversion to a 3808 // floating-to-integral conversion if the integral conversion 3809 // is between types of the same size. 3810 // For example: 3811 // void f(float); 3812 // void f(int); 3813 // int main { 3814 // long a; 3815 // f(a); 3816 // } 3817 // Here, MSVC will call f(int) instead of generating a compile error 3818 // as clang will do in standard mode. 3819 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3820 SCS2.Second == ICK_Floating_Integral && 3821 S.Context.getTypeSize(SCS1.getFromType()) == 3822 S.Context.getTypeSize(SCS1.getToType(2))) 3823 return ImplicitConversionSequence::Better; 3824 3825 return ImplicitConversionSequence::Indistinguishable; 3826 } 3827 3828 /// CompareQualificationConversions - Compares two standard conversion 3829 /// sequences to determine whether they can be ranked based on their 3830 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3831 static ImplicitConversionSequence::CompareKind 3832 CompareQualificationConversions(Sema &S, 3833 const StandardConversionSequence& SCS1, 3834 const StandardConversionSequence& SCS2) { 3835 // C++ 13.3.3.2p3: 3836 // -- S1 and S2 differ only in their qualification conversion and 3837 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3838 // cv-qualification signature of type T1 is a proper subset of 3839 // the cv-qualification signature of type T2, and S1 is not the 3840 // deprecated string literal array-to-pointer conversion (4.2). 3841 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3842 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3843 return ImplicitConversionSequence::Indistinguishable; 3844 3845 // FIXME: the example in the standard doesn't use a qualification 3846 // conversion (!) 3847 QualType T1 = SCS1.getToType(2); 3848 QualType T2 = SCS2.getToType(2); 3849 T1 = S.Context.getCanonicalType(T1); 3850 T2 = S.Context.getCanonicalType(T2); 3851 Qualifiers T1Quals, T2Quals; 3852 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3853 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3854 3855 // If the types are the same, we won't learn anything by unwrapped 3856 // them. 3857 if (UnqualT1 == UnqualT2) 3858 return ImplicitConversionSequence::Indistinguishable; 3859 3860 // If the type is an array type, promote the element qualifiers to the type 3861 // for comparison. 3862 if (isa<ArrayType>(T1) && T1Quals) 3863 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3864 if (isa<ArrayType>(T2) && T2Quals) 3865 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3866 3867 ImplicitConversionSequence::CompareKind Result 3868 = ImplicitConversionSequence::Indistinguishable; 3869 3870 // Objective-C++ ARC: 3871 // Prefer qualification conversions not involving a change in lifetime 3872 // to qualification conversions that do not change lifetime. 3873 if (SCS1.QualificationIncludesObjCLifetime != 3874 SCS2.QualificationIncludesObjCLifetime) { 3875 Result = SCS1.QualificationIncludesObjCLifetime 3876 ? ImplicitConversionSequence::Worse 3877 : ImplicitConversionSequence::Better; 3878 } 3879 3880 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3881 // Within each iteration of the loop, we check the qualifiers to 3882 // determine if this still looks like a qualification 3883 // conversion. Then, if all is well, we unwrap one more level of 3884 // pointers or pointers-to-members and do it all again 3885 // until there are no more pointers or pointers-to-members left 3886 // to unwrap. This essentially mimics what 3887 // IsQualificationConversion does, but here we're checking for a 3888 // strict subset of qualifiers. 3889 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3890 // The qualifiers are the same, so this doesn't tell us anything 3891 // about how the sequences rank. 3892 ; 3893 else if (T2.isMoreQualifiedThan(T1)) { 3894 // T1 has fewer qualifiers, so it could be the better sequence. 3895 if (Result == ImplicitConversionSequence::Worse) 3896 // Neither has qualifiers that are a subset of the other's 3897 // qualifiers. 3898 return ImplicitConversionSequence::Indistinguishable; 3899 3900 Result = ImplicitConversionSequence::Better; 3901 } else if (T1.isMoreQualifiedThan(T2)) { 3902 // T2 has fewer qualifiers, so it could be the better sequence. 3903 if (Result == ImplicitConversionSequence::Better) 3904 // Neither has qualifiers that are a subset of the other's 3905 // qualifiers. 3906 return ImplicitConversionSequence::Indistinguishable; 3907 3908 Result = ImplicitConversionSequence::Worse; 3909 } else { 3910 // Qualifiers are disjoint. 3911 return ImplicitConversionSequence::Indistinguishable; 3912 } 3913 3914 // If the types after this point are equivalent, we're done. 3915 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3916 break; 3917 } 3918 3919 // Check that the winning standard conversion sequence isn't using 3920 // the deprecated string literal array to pointer conversion. 3921 switch (Result) { 3922 case ImplicitConversionSequence::Better: 3923 if (SCS1.DeprecatedStringLiteralToCharPtr) 3924 Result = ImplicitConversionSequence::Indistinguishable; 3925 break; 3926 3927 case ImplicitConversionSequence::Indistinguishable: 3928 break; 3929 3930 case ImplicitConversionSequence::Worse: 3931 if (SCS2.DeprecatedStringLiteralToCharPtr) 3932 Result = ImplicitConversionSequence::Indistinguishable; 3933 break; 3934 } 3935 3936 return Result; 3937 } 3938 3939 /// CompareDerivedToBaseConversions - Compares two standard conversion 3940 /// sequences to determine whether they can be ranked based on their 3941 /// various kinds of derived-to-base conversions (C++ 3942 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3943 /// conversions between Objective-C interface types. 3944 static ImplicitConversionSequence::CompareKind 3945 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3946 const StandardConversionSequence& SCS1, 3947 const StandardConversionSequence& SCS2) { 3948 QualType FromType1 = SCS1.getFromType(); 3949 QualType ToType1 = SCS1.getToType(1); 3950 QualType FromType2 = SCS2.getFromType(); 3951 QualType ToType2 = SCS2.getToType(1); 3952 3953 // Adjust the types we're converting from via the array-to-pointer 3954 // conversion, if we need to. 3955 if (SCS1.First == ICK_Array_To_Pointer) 3956 FromType1 = S.Context.getArrayDecayedType(FromType1); 3957 if (SCS2.First == ICK_Array_To_Pointer) 3958 FromType2 = S.Context.getArrayDecayedType(FromType2); 3959 3960 // Canonicalize all of the types. 3961 FromType1 = S.Context.getCanonicalType(FromType1); 3962 ToType1 = S.Context.getCanonicalType(ToType1); 3963 FromType2 = S.Context.getCanonicalType(FromType2); 3964 ToType2 = S.Context.getCanonicalType(ToType2); 3965 3966 // C++ [over.ics.rank]p4b3: 3967 // 3968 // If class B is derived directly or indirectly from class A and 3969 // class C is derived directly or indirectly from B, 3970 // 3971 // Compare based on pointer conversions. 3972 if (SCS1.Second == ICK_Pointer_Conversion && 3973 SCS2.Second == ICK_Pointer_Conversion && 3974 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3975 FromType1->isPointerType() && FromType2->isPointerType() && 3976 ToType1->isPointerType() && ToType2->isPointerType()) { 3977 QualType FromPointee1 3978 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3979 QualType ToPointee1 3980 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3981 QualType FromPointee2 3982 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3983 QualType ToPointee2 3984 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3985 3986 // -- conversion of C* to B* is better than conversion of C* to A*, 3987 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3988 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3989 return ImplicitConversionSequence::Better; 3990 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3991 return ImplicitConversionSequence::Worse; 3992 } 3993 3994 // -- conversion of B* to A* is better than conversion of C* to A*, 3995 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3996 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3997 return ImplicitConversionSequence::Better; 3998 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3999 return ImplicitConversionSequence::Worse; 4000 } 4001 } else if (SCS1.Second == ICK_Pointer_Conversion && 4002 SCS2.Second == ICK_Pointer_Conversion) { 4003 const ObjCObjectPointerType *FromPtr1 4004 = FromType1->getAs<ObjCObjectPointerType>(); 4005 const ObjCObjectPointerType *FromPtr2 4006 = FromType2->getAs<ObjCObjectPointerType>(); 4007 const ObjCObjectPointerType *ToPtr1 4008 = ToType1->getAs<ObjCObjectPointerType>(); 4009 const ObjCObjectPointerType *ToPtr2 4010 = ToType2->getAs<ObjCObjectPointerType>(); 4011 4012 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4013 // Apply the same conversion ranking rules for Objective-C pointer types 4014 // that we do for C++ pointers to class types. However, we employ the 4015 // Objective-C pseudo-subtyping relationship used for assignment of 4016 // Objective-C pointer types. 4017 bool FromAssignLeft 4018 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4019 bool FromAssignRight 4020 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4021 bool ToAssignLeft 4022 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4023 bool ToAssignRight 4024 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4025 4026 // A conversion to an a non-id object pointer type or qualified 'id' 4027 // type is better than a conversion to 'id'. 4028 if (ToPtr1->isObjCIdType() && 4029 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4030 return ImplicitConversionSequence::Worse; 4031 if (ToPtr2->isObjCIdType() && 4032 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4033 return ImplicitConversionSequence::Better; 4034 4035 // A conversion to a non-id object pointer type is better than a 4036 // conversion to a qualified 'id' type 4037 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4038 return ImplicitConversionSequence::Worse; 4039 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4040 return ImplicitConversionSequence::Better; 4041 4042 // A conversion to an a non-Class object pointer type or qualified 'Class' 4043 // type is better than a conversion to 'Class'. 4044 if (ToPtr1->isObjCClassType() && 4045 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4046 return ImplicitConversionSequence::Worse; 4047 if (ToPtr2->isObjCClassType() && 4048 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4049 return ImplicitConversionSequence::Better; 4050 4051 // A conversion to a non-Class object pointer type is better than a 4052 // conversion to a qualified 'Class' type. 4053 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4054 return ImplicitConversionSequence::Worse; 4055 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4056 return ImplicitConversionSequence::Better; 4057 4058 // -- "conversion of C* to B* is better than conversion of C* to A*," 4059 if (S.Context.hasSameType(FromType1, FromType2) && 4060 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4061 (ToAssignLeft != ToAssignRight)) 4062 return ToAssignLeft? ImplicitConversionSequence::Worse 4063 : ImplicitConversionSequence::Better; 4064 4065 // -- "conversion of B* to A* is better than conversion of C* to A*," 4066 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4067 (FromAssignLeft != FromAssignRight)) 4068 return FromAssignLeft? ImplicitConversionSequence::Better 4069 : ImplicitConversionSequence::Worse; 4070 } 4071 } 4072 4073 // Ranking of member-pointer types. 4074 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4075 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4076 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4077 const MemberPointerType * FromMemPointer1 = 4078 FromType1->getAs<MemberPointerType>(); 4079 const MemberPointerType * ToMemPointer1 = 4080 ToType1->getAs<MemberPointerType>(); 4081 const MemberPointerType * FromMemPointer2 = 4082 FromType2->getAs<MemberPointerType>(); 4083 const MemberPointerType * ToMemPointer2 = 4084 ToType2->getAs<MemberPointerType>(); 4085 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4086 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4087 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4088 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4089 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4090 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4091 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4092 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4093 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4094 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4095 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4096 return ImplicitConversionSequence::Worse; 4097 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4098 return ImplicitConversionSequence::Better; 4099 } 4100 // conversion of B::* to C::* is better than conversion of A::* to C::* 4101 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4102 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4103 return ImplicitConversionSequence::Better; 4104 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4105 return ImplicitConversionSequence::Worse; 4106 } 4107 } 4108 4109 if (SCS1.Second == ICK_Derived_To_Base) { 4110 // -- conversion of C to B is better than conversion of C to A, 4111 // -- binding of an expression of type C to a reference of type 4112 // B& is better than binding an expression of type C to a 4113 // reference of type A&, 4114 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4115 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4116 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4117 return ImplicitConversionSequence::Better; 4118 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4119 return ImplicitConversionSequence::Worse; 4120 } 4121 4122 // -- conversion of B to A is better than conversion of C to A. 4123 // -- binding of an expression of type B to a reference of type 4124 // A& is better than binding an expression of type C to a 4125 // reference of type A&, 4126 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4127 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4128 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4129 return ImplicitConversionSequence::Better; 4130 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4131 return ImplicitConversionSequence::Worse; 4132 } 4133 } 4134 4135 return ImplicitConversionSequence::Indistinguishable; 4136 } 4137 4138 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4139 /// C++ class. 4140 static bool isTypeValid(QualType T) { 4141 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4142 return !Record->isInvalidDecl(); 4143 4144 return true; 4145 } 4146 4147 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4148 /// determine whether they are reference-related, 4149 /// reference-compatible, reference-compatible with added 4150 /// qualification, or incompatible, for use in C++ initialization by 4151 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4152 /// type, and the first type (T1) is the pointee type of the reference 4153 /// type being initialized. 4154 Sema::ReferenceCompareResult 4155 Sema::CompareReferenceRelationship(SourceLocation Loc, 4156 QualType OrigT1, QualType OrigT2, 4157 bool &DerivedToBase, 4158 bool &ObjCConversion, 4159 bool &ObjCLifetimeConversion) { 4160 assert(!OrigT1->isReferenceType() && 4161 "T1 must be the pointee type of the reference type"); 4162 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4163 4164 QualType T1 = Context.getCanonicalType(OrigT1); 4165 QualType T2 = Context.getCanonicalType(OrigT2); 4166 Qualifiers T1Quals, T2Quals; 4167 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4168 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4169 4170 // C++ [dcl.init.ref]p4: 4171 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4172 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4173 // T1 is a base class of T2. 4174 DerivedToBase = false; 4175 ObjCConversion = false; 4176 ObjCLifetimeConversion = false; 4177 QualType ConvertedT2; 4178 if (UnqualT1 == UnqualT2) { 4179 // Nothing to do. 4180 } else if (isCompleteType(Loc, OrigT2) && 4181 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4182 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4183 DerivedToBase = true; 4184 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4185 UnqualT2->isObjCObjectOrInterfaceType() && 4186 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4187 ObjCConversion = true; 4188 else if (UnqualT2->isFunctionType() && 4189 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4190 // C++1z [dcl.init.ref]p4: 4191 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4192 // function" and T1 is "function" 4193 // 4194 // We extend this to also apply to 'noreturn', so allow any function 4195 // conversion between function types. 4196 return Ref_Compatible; 4197 else 4198 return Ref_Incompatible; 4199 4200 // At this point, we know that T1 and T2 are reference-related (at 4201 // least). 4202 4203 // If the type is an array type, promote the element qualifiers to the type 4204 // for comparison. 4205 if (isa<ArrayType>(T1) && T1Quals) 4206 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4207 if (isa<ArrayType>(T2) && T2Quals) 4208 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4209 4210 // C++ [dcl.init.ref]p4: 4211 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4212 // reference-related to T2 and cv1 is the same cv-qualification 4213 // as, or greater cv-qualification than, cv2. For purposes of 4214 // overload resolution, cases for which cv1 is greater 4215 // cv-qualification than cv2 are identified as 4216 // reference-compatible with added qualification (see 13.3.3.2). 4217 // 4218 // Note that we also require equivalence of Objective-C GC and address-space 4219 // qualifiers when performing these computations, so that e.g., an int in 4220 // address space 1 is not reference-compatible with an int in address 4221 // space 2. 4222 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4223 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4224 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4225 ObjCLifetimeConversion = true; 4226 4227 T1Quals.removeObjCLifetime(); 4228 T2Quals.removeObjCLifetime(); 4229 } 4230 4231 // MS compiler ignores __unaligned qualifier for references; do the same. 4232 T1Quals.removeUnaligned(); 4233 T2Quals.removeUnaligned(); 4234 4235 if (T1Quals.compatiblyIncludes(T2Quals)) 4236 return Ref_Compatible; 4237 else 4238 return Ref_Related; 4239 } 4240 4241 /// \brief Look for a user-defined conversion to an value reference-compatible 4242 /// with DeclType. Return true if something definite is found. 4243 static bool 4244 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4245 QualType DeclType, SourceLocation DeclLoc, 4246 Expr *Init, QualType T2, bool AllowRvalues, 4247 bool AllowExplicit) { 4248 assert(T2->isRecordType() && "Can only find conversions of record types."); 4249 CXXRecordDecl *T2RecordDecl 4250 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4251 4252 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4253 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4254 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4255 NamedDecl *D = *I; 4256 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4257 if (isa<UsingShadowDecl>(D)) 4258 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4259 4260 FunctionTemplateDecl *ConvTemplate 4261 = dyn_cast<FunctionTemplateDecl>(D); 4262 CXXConversionDecl *Conv; 4263 if (ConvTemplate) 4264 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4265 else 4266 Conv = cast<CXXConversionDecl>(D); 4267 4268 // If this is an explicit conversion, and we're not allowed to consider 4269 // explicit conversions, skip it. 4270 if (!AllowExplicit && Conv->isExplicit()) 4271 continue; 4272 4273 if (AllowRvalues) { 4274 bool DerivedToBase = false; 4275 bool ObjCConversion = false; 4276 bool ObjCLifetimeConversion = false; 4277 4278 // If we are initializing an rvalue reference, don't permit conversion 4279 // functions that return lvalues. 4280 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4281 const ReferenceType *RefType 4282 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4283 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4284 continue; 4285 } 4286 4287 if (!ConvTemplate && 4288 S.CompareReferenceRelationship( 4289 DeclLoc, 4290 Conv->getConversionType().getNonReferenceType() 4291 .getUnqualifiedType(), 4292 DeclType.getNonReferenceType().getUnqualifiedType(), 4293 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4294 Sema::Ref_Incompatible) 4295 continue; 4296 } else { 4297 // If the conversion function doesn't return a reference type, 4298 // it can't be considered for this conversion. An rvalue reference 4299 // is only acceptable if its referencee is a function type. 4300 4301 const ReferenceType *RefType = 4302 Conv->getConversionType()->getAs<ReferenceType>(); 4303 if (!RefType || 4304 (!RefType->isLValueReferenceType() && 4305 !RefType->getPointeeType()->isFunctionType())) 4306 continue; 4307 } 4308 4309 if (ConvTemplate) 4310 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4311 Init, DeclType, CandidateSet, 4312 /*AllowObjCConversionOnExplicit=*/false); 4313 else 4314 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4315 DeclType, CandidateSet, 4316 /*AllowObjCConversionOnExplicit=*/false); 4317 } 4318 4319 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4320 4321 OverloadCandidateSet::iterator Best; 4322 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4323 case OR_Success: 4324 // C++ [over.ics.ref]p1: 4325 // 4326 // [...] If the parameter binds directly to the result of 4327 // applying a conversion function to the argument 4328 // expression, the implicit conversion sequence is a 4329 // user-defined conversion sequence (13.3.3.1.2), with the 4330 // second standard conversion sequence either an identity 4331 // conversion or, if the conversion function returns an 4332 // entity of a type that is a derived class of the parameter 4333 // type, a derived-to-base Conversion. 4334 if (!Best->FinalConversion.DirectBinding) 4335 return false; 4336 4337 ICS.setUserDefined(); 4338 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4339 ICS.UserDefined.After = Best->FinalConversion; 4340 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4341 ICS.UserDefined.ConversionFunction = Best->Function; 4342 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4343 ICS.UserDefined.EllipsisConversion = false; 4344 assert(ICS.UserDefined.After.ReferenceBinding && 4345 ICS.UserDefined.After.DirectBinding && 4346 "Expected a direct reference binding!"); 4347 return true; 4348 4349 case OR_Ambiguous: 4350 ICS.setAmbiguous(); 4351 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4352 Cand != CandidateSet.end(); ++Cand) 4353 if (Cand->Viable) 4354 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4355 return true; 4356 4357 case OR_No_Viable_Function: 4358 case OR_Deleted: 4359 // There was no suitable conversion, or we found a deleted 4360 // conversion; continue with other checks. 4361 return false; 4362 } 4363 4364 llvm_unreachable("Invalid OverloadResult!"); 4365 } 4366 4367 /// \brief Compute an implicit conversion sequence for reference 4368 /// initialization. 4369 static ImplicitConversionSequence 4370 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4371 SourceLocation DeclLoc, 4372 bool SuppressUserConversions, 4373 bool AllowExplicit) { 4374 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4375 4376 // Most paths end in a failed conversion. 4377 ImplicitConversionSequence ICS; 4378 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4379 4380 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4381 QualType T2 = Init->getType(); 4382 4383 // If the initializer is the address of an overloaded function, try 4384 // to resolve the overloaded function. If all goes well, T2 is the 4385 // type of the resulting function. 4386 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4387 DeclAccessPair Found; 4388 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4389 false, Found)) 4390 T2 = Fn->getType(); 4391 } 4392 4393 // Compute some basic properties of the types and the initializer. 4394 bool isRValRef = DeclType->isRValueReferenceType(); 4395 bool DerivedToBase = false; 4396 bool ObjCConversion = false; 4397 bool ObjCLifetimeConversion = false; 4398 Expr::Classification InitCategory = Init->Classify(S.Context); 4399 Sema::ReferenceCompareResult RefRelationship 4400 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4401 ObjCConversion, ObjCLifetimeConversion); 4402 4403 4404 // C++0x [dcl.init.ref]p5: 4405 // A reference to type "cv1 T1" is initialized by an expression 4406 // of type "cv2 T2" as follows: 4407 4408 // -- If reference is an lvalue reference and the initializer expression 4409 if (!isRValRef) { 4410 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4411 // reference-compatible with "cv2 T2," or 4412 // 4413 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4414 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4415 // C++ [over.ics.ref]p1: 4416 // When a parameter of reference type binds directly (8.5.3) 4417 // to an argument expression, the implicit conversion sequence 4418 // is the identity conversion, unless the argument expression 4419 // has a type that is a derived class of the parameter type, 4420 // in which case the implicit conversion sequence is a 4421 // derived-to-base Conversion (13.3.3.1). 4422 ICS.setStandard(); 4423 ICS.Standard.First = ICK_Identity; 4424 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4425 : ObjCConversion? ICK_Compatible_Conversion 4426 : ICK_Identity; 4427 ICS.Standard.Third = ICK_Identity; 4428 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4429 ICS.Standard.setToType(0, T2); 4430 ICS.Standard.setToType(1, T1); 4431 ICS.Standard.setToType(2, T1); 4432 ICS.Standard.ReferenceBinding = true; 4433 ICS.Standard.DirectBinding = true; 4434 ICS.Standard.IsLvalueReference = !isRValRef; 4435 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4436 ICS.Standard.BindsToRvalue = false; 4437 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4438 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4439 ICS.Standard.CopyConstructor = nullptr; 4440 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4441 4442 // Nothing more to do: the inaccessibility/ambiguity check for 4443 // derived-to-base conversions is suppressed when we're 4444 // computing the implicit conversion sequence (C++ 4445 // [over.best.ics]p2). 4446 return ICS; 4447 } 4448 4449 // -- has a class type (i.e., T2 is a class type), where T1 is 4450 // not reference-related to T2, and can be implicitly 4451 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4452 // is reference-compatible with "cv3 T3" 92) (this 4453 // conversion is selected by enumerating the applicable 4454 // conversion functions (13.3.1.6) and choosing the best 4455 // one through overload resolution (13.3)), 4456 if (!SuppressUserConversions && T2->isRecordType() && 4457 S.isCompleteType(DeclLoc, T2) && 4458 RefRelationship == Sema::Ref_Incompatible) { 4459 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4460 Init, T2, /*AllowRvalues=*/false, 4461 AllowExplicit)) 4462 return ICS; 4463 } 4464 } 4465 4466 // -- Otherwise, the reference shall be an lvalue reference to a 4467 // non-volatile const type (i.e., cv1 shall be const), or the reference 4468 // shall be an rvalue reference. 4469 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4470 return ICS; 4471 4472 // -- If the initializer expression 4473 // 4474 // -- is an xvalue, class prvalue, array prvalue or function 4475 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4476 if (RefRelationship == Sema::Ref_Compatible && 4477 (InitCategory.isXValue() || 4478 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4479 (InitCategory.isLValue() && T2->isFunctionType()))) { 4480 ICS.setStandard(); 4481 ICS.Standard.First = ICK_Identity; 4482 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4483 : ObjCConversion? ICK_Compatible_Conversion 4484 : ICK_Identity; 4485 ICS.Standard.Third = ICK_Identity; 4486 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4487 ICS.Standard.setToType(0, T2); 4488 ICS.Standard.setToType(1, T1); 4489 ICS.Standard.setToType(2, T1); 4490 ICS.Standard.ReferenceBinding = true; 4491 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4492 // binding unless we're binding to a class prvalue. 4493 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4494 // allow the use of rvalue references in C++98/03 for the benefit of 4495 // standard library implementors; therefore, we need the xvalue check here. 4496 ICS.Standard.DirectBinding = 4497 S.getLangOpts().CPlusPlus11 || 4498 !(InitCategory.isPRValue() || T2->isRecordType()); 4499 ICS.Standard.IsLvalueReference = !isRValRef; 4500 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4501 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4502 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4503 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4504 ICS.Standard.CopyConstructor = nullptr; 4505 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4506 return ICS; 4507 } 4508 4509 // -- has a class type (i.e., T2 is a class type), where T1 is not 4510 // reference-related to T2, and can be implicitly converted to 4511 // an xvalue, class prvalue, or function lvalue of type 4512 // "cv3 T3", where "cv1 T1" is reference-compatible with 4513 // "cv3 T3", 4514 // 4515 // then the reference is bound to the value of the initializer 4516 // expression in the first case and to the result of the conversion 4517 // in the second case (or, in either case, to an appropriate base 4518 // class subobject). 4519 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4520 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4521 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4522 Init, T2, /*AllowRvalues=*/true, 4523 AllowExplicit)) { 4524 // In the second case, if the reference is an rvalue reference 4525 // and the second standard conversion sequence of the 4526 // user-defined conversion sequence includes an lvalue-to-rvalue 4527 // conversion, the program is ill-formed. 4528 if (ICS.isUserDefined() && isRValRef && 4529 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4530 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4531 4532 return ICS; 4533 } 4534 4535 // A temporary of function type cannot be created; don't even try. 4536 if (T1->isFunctionType()) 4537 return ICS; 4538 4539 // -- Otherwise, a temporary of type "cv1 T1" is created and 4540 // initialized from the initializer expression using the 4541 // rules for a non-reference copy initialization (8.5). The 4542 // reference is then bound to the temporary. If T1 is 4543 // reference-related to T2, cv1 must be the same 4544 // cv-qualification as, or greater cv-qualification than, 4545 // cv2; otherwise, the program is ill-formed. 4546 if (RefRelationship == Sema::Ref_Related) { 4547 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4548 // we would be reference-compatible or reference-compatible with 4549 // added qualification. But that wasn't the case, so the reference 4550 // initialization fails. 4551 // 4552 // Note that we only want to check address spaces and cvr-qualifiers here. 4553 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4554 Qualifiers T1Quals = T1.getQualifiers(); 4555 Qualifiers T2Quals = T2.getQualifiers(); 4556 T1Quals.removeObjCGCAttr(); 4557 T1Quals.removeObjCLifetime(); 4558 T2Quals.removeObjCGCAttr(); 4559 T2Quals.removeObjCLifetime(); 4560 // MS compiler ignores __unaligned qualifier for references; do the same. 4561 T1Quals.removeUnaligned(); 4562 T2Quals.removeUnaligned(); 4563 if (!T1Quals.compatiblyIncludes(T2Quals)) 4564 return ICS; 4565 } 4566 4567 // If at least one of the types is a class type, the types are not 4568 // related, and we aren't allowed any user conversions, the 4569 // reference binding fails. This case is important for breaking 4570 // recursion, since TryImplicitConversion below will attempt to 4571 // create a temporary through the use of a copy constructor. 4572 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4573 (T1->isRecordType() || T2->isRecordType())) 4574 return ICS; 4575 4576 // If T1 is reference-related to T2 and the reference is an rvalue 4577 // reference, the initializer expression shall not be an lvalue. 4578 if (RefRelationship >= Sema::Ref_Related && 4579 isRValRef && Init->Classify(S.Context).isLValue()) 4580 return ICS; 4581 4582 // C++ [over.ics.ref]p2: 4583 // When a parameter of reference type is not bound directly to 4584 // an argument expression, the conversion sequence is the one 4585 // required to convert the argument expression to the 4586 // underlying type of the reference according to 4587 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4588 // to copy-initializing a temporary of the underlying type with 4589 // the argument expression. Any difference in top-level 4590 // cv-qualification is subsumed by the initialization itself 4591 // and does not constitute a conversion. 4592 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4593 /*AllowExplicit=*/false, 4594 /*InOverloadResolution=*/false, 4595 /*CStyle=*/false, 4596 /*AllowObjCWritebackConversion=*/false, 4597 /*AllowObjCConversionOnExplicit=*/false); 4598 4599 // Of course, that's still a reference binding. 4600 if (ICS.isStandard()) { 4601 ICS.Standard.ReferenceBinding = true; 4602 ICS.Standard.IsLvalueReference = !isRValRef; 4603 ICS.Standard.BindsToFunctionLvalue = false; 4604 ICS.Standard.BindsToRvalue = true; 4605 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4606 ICS.Standard.ObjCLifetimeConversionBinding = false; 4607 } else if (ICS.isUserDefined()) { 4608 const ReferenceType *LValRefType = 4609 ICS.UserDefined.ConversionFunction->getReturnType() 4610 ->getAs<LValueReferenceType>(); 4611 4612 // C++ [over.ics.ref]p3: 4613 // Except for an implicit object parameter, for which see 13.3.1, a 4614 // standard conversion sequence cannot be formed if it requires [...] 4615 // binding an rvalue reference to an lvalue other than a function 4616 // lvalue. 4617 // Note that the function case is not possible here. 4618 if (DeclType->isRValueReferenceType() && LValRefType) { 4619 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4620 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4621 // reference to an rvalue! 4622 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4623 return ICS; 4624 } 4625 4626 ICS.UserDefined.After.ReferenceBinding = true; 4627 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4628 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4629 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4630 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4631 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4632 } 4633 4634 return ICS; 4635 } 4636 4637 static ImplicitConversionSequence 4638 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4639 bool SuppressUserConversions, 4640 bool InOverloadResolution, 4641 bool AllowObjCWritebackConversion, 4642 bool AllowExplicit = false); 4643 4644 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4645 /// initializer list From. 4646 static ImplicitConversionSequence 4647 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4648 bool SuppressUserConversions, 4649 bool InOverloadResolution, 4650 bool AllowObjCWritebackConversion) { 4651 // C++11 [over.ics.list]p1: 4652 // When an argument is an initializer list, it is not an expression and 4653 // special rules apply for converting it to a parameter type. 4654 4655 ImplicitConversionSequence Result; 4656 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4657 4658 // We need a complete type for what follows. Incomplete types can never be 4659 // initialized from init lists. 4660 if (!S.isCompleteType(From->getLocStart(), ToType)) 4661 return Result; 4662 4663 // Per DR1467: 4664 // If the parameter type is a class X and the initializer list has a single 4665 // element of type cv U, where U is X or a class derived from X, the 4666 // implicit conversion sequence is the one required to convert the element 4667 // to the parameter type. 4668 // 4669 // Otherwise, if the parameter type is a character array [... ] 4670 // and the initializer list has a single element that is an 4671 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4672 // implicit conversion sequence is the identity conversion. 4673 if (From->getNumInits() == 1) { 4674 if (ToType->isRecordType()) { 4675 QualType InitType = From->getInit(0)->getType(); 4676 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4677 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4678 return TryCopyInitialization(S, From->getInit(0), ToType, 4679 SuppressUserConversions, 4680 InOverloadResolution, 4681 AllowObjCWritebackConversion); 4682 } 4683 // FIXME: Check the other conditions here: array of character type, 4684 // initializer is a string literal. 4685 if (ToType->isArrayType()) { 4686 InitializedEntity Entity = 4687 InitializedEntity::InitializeParameter(S.Context, ToType, 4688 /*Consumed=*/false); 4689 if (S.CanPerformCopyInitialization(Entity, From)) { 4690 Result.setStandard(); 4691 Result.Standard.setAsIdentityConversion(); 4692 Result.Standard.setFromType(ToType); 4693 Result.Standard.setAllToTypes(ToType); 4694 return Result; 4695 } 4696 } 4697 } 4698 4699 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4700 // C++11 [over.ics.list]p2: 4701 // If the parameter type is std::initializer_list<X> or "array of X" and 4702 // all the elements can be implicitly converted to X, the implicit 4703 // conversion sequence is the worst conversion necessary to convert an 4704 // element of the list to X. 4705 // 4706 // C++14 [over.ics.list]p3: 4707 // Otherwise, if the parameter type is "array of N X", if the initializer 4708 // list has exactly N elements or if it has fewer than N elements and X is 4709 // default-constructible, and if all the elements of the initializer list 4710 // can be implicitly converted to X, the implicit conversion sequence is 4711 // the worst conversion necessary to convert an element of the list to X. 4712 // 4713 // FIXME: We're missing a lot of these checks. 4714 bool toStdInitializerList = false; 4715 QualType X; 4716 if (ToType->isArrayType()) 4717 X = S.Context.getAsArrayType(ToType)->getElementType(); 4718 else 4719 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4720 if (!X.isNull()) { 4721 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4722 Expr *Init = From->getInit(i); 4723 ImplicitConversionSequence ICS = 4724 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4725 InOverloadResolution, 4726 AllowObjCWritebackConversion); 4727 // If a single element isn't convertible, fail. 4728 if (ICS.isBad()) { 4729 Result = ICS; 4730 break; 4731 } 4732 // Otherwise, look for the worst conversion. 4733 if (Result.isBad() || 4734 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4735 Result) == 4736 ImplicitConversionSequence::Worse) 4737 Result = ICS; 4738 } 4739 4740 // For an empty list, we won't have computed any conversion sequence. 4741 // Introduce the identity conversion sequence. 4742 if (From->getNumInits() == 0) { 4743 Result.setStandard(); 4744 Result.Standard.setAsIdentityConversion(); 4745 Result.Standard.setFromType(ToType); 4746 Result.Standard.setAllToTypes(ToType); 4747 } 4748 4749 Result.setStdInitializerListElement(toStdInitializerList); 4750 return Result; 4751 } 4752 4753 // C++14 [over.ics.list]p4: 4754 // C++11 [over.ics.list]p3: 4755 // Otherwise, if the parameter is a non-aggregate class X and overload 4756 // resolution chooses a single best constructor [...] the implicit 4757 // conversion sequence is a user-defined conversion sequence. If multiple 4758 // constructors are viable but none is better than the others, the 4759 // implicit conversion sequence is a user-defined conversion sequence. 4760 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4761 // This function can deal with initializer lists. 4762 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4763 /*AllowExplicit=*/false, 4764 InOverloadResolution, /*CStyle=*/false, 4765 AllowObjCWritebackConversion, 4766 /*AllowObjCConversionOnExplicit=*/false); 4767 } 4768 4769 // C++14 [over.ics.list]p5: 4770 // C++11 [over.ics.list]p4: 4771 // Otherwise, if the parameter has an aggregate type which can be 4772 // initialized from the initializer list [...] the implicit conversion 4773 // sequence is a user-defined conversion sequence. 4774 if (ToType->isAggregateType()) { 4775 // Type is an aggregate, argument is an init list. At this point it comes 4776 // down to checking whether the initialization works. 4777 // FIXME: Find out whether this parameter is consumed or not. 4778 InitializedEntity Entity = 4779 InitializedEntity::InitializeParameter(S.Context, ToType, 4780 /*Consumed=*/false); 4781 if (S.CanPerformCopyInitialization(Entity, From)) { 4782 Result.setUserDefined(); 4783 Result.UserDefined.Before.setAsIdentityConversion(); 4784 // Initializer lists don't have a type. 4785 Result.UserDefined.Before.setFromType(QualType()); 4786 Result.UserDefined.Before.setAllToTypes(QualType()); 4787 4788 Result.UserDefined.After.setAsIdentityConversion(); 4789 Result.UserDefined.After.setFromType(ToType); 4790 Result.UserDefined.After.setAllToTypes(ToType); 4791 Result.UserDefined.ConversionFunction = nullptr; 4792 } 4793 return Result; 4794 } 4795 4796 // C++14 [over.ics.list]p6: 4797 // C++11 [over.ics.list]p5: 4798 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4799 if (ToType->isReferenceType()) { 4800 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4801 // mention initializer lists in any way. So we go by what list- 4802 // initialization would do and try to extrapolate from that. 4803 4804 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4805 4806 // If the initializer list has a single element that is reference-related 4807 // to the parameter type, we initialize the reference from that. 4808 if (From->getNumInits() == 1) { 4809 Expr *Init = From->getInit(0); 4810 4811 QualType T2 = Init->getType(); 4812 4813 // If the initializer is the address of an overloaded function, try 4814 // to resolve the overloaded function. If all goes well, T2 is the 4815 // type of the resulting function. 4816 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4817 DeclAccessPair Found; 4818 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4819 Init, ToType, false, Found)) 4820 T2 = Fn->getType(); 4821 } 4822 4823 // Compute some basic properties of the types and the initializer. 4824 bool dummy1 = false; 4825 bool dummy2 = false; 4826 bool dummy3 = false; 4827 Sema::ReferenceCompareResult RefRelationship 4828 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4829 dummy2, dummy3); 4830 4831 if (RefRelationship >= Sema::Ref_Related) { 4832 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4833 SuppressUserConversions, 4834 /*AllowExplicit=*/false); 4835 } 4836 } 4837 4838 // Otherwise, we bind the reference to a temporary created from the 4839 // initializer list. 4840 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4841 InOverloadResolution, 4842 AllowObjCWritebackConversion); 4843 if (Result.isFailure()) 4844 return Result; 4845 assert(!Result.isEllipsis() && 4846 "Sub-initialization cannot result in ellipsis conversion."); 4847 4848 // Can we even bind to a temporary? 4849 if (ToType->isRValueReferenceType() || 4850 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4851 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4852 Result.UserDefined.After; 4853 SCS.ReferenceBinding = true; 4854 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4855 SCS.BindsToRvalue = true; 4856 SCS.BindsToFunctionLvalue = false; 4857 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4858 SCS.ObjCLifetimeConversionBinding = false; 4859 } else 4860 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4861 From, ToType); 4862 return Result; 4863 } 4864 4865 // C++14 [over.ics.list]p7: 4866 // C++11 [over.ics.list]p6: 4867 // Otherwise, if the parameter type is not a class: 4868 if (!ToType->isRecordType()) { 4869 // - if the initializer list has one element that is not itself an 4870 // initializer list, the implicit conversion sequence is the one 4871 // required to convert the element to the parameter type. 4872 unsigned NumInits = From->getNumInits(); 4873 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4874 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4875 SuppressUserConversions, 4876 InOverloadResolution, 4877 AllowObjCWritebackConversion); 4878 // - if the initializer list has no elements, the implicit conversion 4879 // sequence is the identity conversion. 4880 else if (NumInits == 0) { 4881 Result.setStandard(); 4882 Result.Standard.setAsIdentityConversion(); 4883 Result.Standard.setFromType(ToType); 4884 Result.Standard.setAllToTypes(ToType); 4885 } 4886 return Result; 4887 } 4888 4889 // C++14 [over.ics.list]p8: 4890 // C++11 [over.ics.list]p7: 4891 // In all cases other than those enumerated above, no conversion is possible 4892 return Result; 4893 } 4894 4895 /// TryCopyInitialization - Try to copy-initialize a value of type 4896 /// ToType from the expression From. Return the implicit conversion 4897 /// sequence required to pass this argument, which may be a bad 4898 /// conversion sequence (meaning that the argument cannot be passed to 4899 /// a parameter of this type). If @p SuppressUserConversions, then we 4900 /// do not permit any user-defined conversion sequences. 4901 static ImplicitConversionSequence 4902 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4903 bool SuppressUserConversions, 4904 bool InOverloadResolution, 4905 bool AllowObjCWritebackConversion, 4906 bool AllowExplicit) { 4907 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4908 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4909 InOverloadResolution,AllowObjCWritebackConversion); 4910 4911 if (ToType->isReferenceType()) 4912 return TryReferenceInit(S, From, ToType, 4913 /*FIXME:*/From->getLocStart(), 4914 SuppressUserConversions, 4915 AllowExplicit); 4916 4917 return TryImplicitConversion(S, From, ToType, 4918 SuppressUserConversions, 4919 /*AllowExplicit=*/false, 4920 InOverloadResolution, 4921 /*CStyle=*/false, 4922 AllowObjCWritebackConversion, 4923 /*AllowObjCConversionOnExplicit=*/false); 4924 } 4925 4926 static bool TryCopyInitialization(const CanQualType FromQTy, 4927 const CanQualType ToQTy, 4928 Sema &S, 4929 SourceLocation Loc, 4930 ExprValueKind FromVK) { 4931 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4932 ImplicitConversionSequence ICS = 4933 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4934 4935 return !ICS.isBad(); 4936 } 4937 4938 /// TryObjectArgumentInitialization - Try to initialize the object 4939 /// parameter of the given member function (@c Method) from the 4940 /// expression @p From. 4941 static ImplicitConversionSequence 4942 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4943 Expr::Classification FromClassification, 4944 CXXMethodDecl *Method, 4945 CXXRecordDecl *ActingContext) { 4946 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4947 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4948 // const volatile object. 4949 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4950 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4951 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4952 4953 // Set up the conversion sequence as a "bad" conversion, to allow us 4954 // to exit early. 4955 ImplicitConversionSequence ICS; 4956 4957 // We need to have an object of class type. 4958 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4959 FromType = PT->getPointeeType(); 4960 4961 // When we had a pointer, it's implicitly dereferenced, so we 4962 // better have an lvalue. 4963 assert(FromClassification.isLValue()); 4964 } 4965 4966 assert(FromType->isRecordType()); 4967 4968 // C++0x [over.match.funcs]p4: 4969 // For non-static member functions, the type of the implicit object 4970 // parameter is 4971 // 4972 // - "lvalue reference to cv X" for functions declared without a 4973 // ref-qualifier or with the & ref-qualifier 4974 // - "rvalue reference to cv X" for functions declared with the && 4975 // ref-qualifier 4976 // 4977 // where X is the class of which the function is a member and cv is the 4978 // cv-qualification on the member function declaration. 4979 // 4980 // However, when finding an implicit conversion sequence for the argument, we 4981 // are not allowed to create temporaries or perform user-defined conversions 4982 // (C++ [over.match.funcs]p5). We perform a simplified version of 4983 // reference binding here, that allows class rvalues to bind to 4984 // non-constant references. 4985 4986 // First check the qualifiers. 4987 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4988 if (ImplicitParamType.getCVRQualifiers() 4989 != FromTypeCanon.getLocalCVRQualifiers() && 4990 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4991 ICS.setBad(BadConversionSequence::bad_qualifiers, 4992 FromType, ImplicitParamType); 4993 return ICS; 4994 } 4995 4996 // Check that we have either the same type or a derived type. It 4997 // affects the conversion rank. 4998 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4999 ImplicitConversionKind SecondKind; 5000 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5001 SecondKind = ICK_Identity; 5002 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5003 SecondKind = ICK_Derived_To_Base; 5004 else { 5005 ICS.setBad(BadConversionSequence::unrelated_class, 5006 FromType, ImplicitParamType); 5007 return ICS; 5008 } 5009 5010 // Check the ref-qualifier. 5011 switch (Method->getRefQualifier()) { 5012 case RQ_None: 5013 // Do nothing; we don't care about lvalueness or rvalueness. 5014 break; 5015 5016 case RQ_LValue: 5017 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5018 // non-const lvalue reference cannot bind to an rvalue 5019 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5020 ImplicitParamType); 5021 return ICS; 5022 } 5023 break; 5024 5025 case RQ_RValue: 5026 if (!FromClassification.isRValue()) { 5027 // rvalue reference cannot bind to an lvalue 5028 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5029 ImplicitParamType); 5030 return ICS; 5031 } 5032 break; 5033 } 5034 5035 // Success. Mark this as a reference binding. 5036 ICS.setStandard(); 5037 ICS.Standard.setAsIdentityConversion(); 5038 ICS.Standard.Second = SecondKind; 5039 ICS.Standard.setFromType(FromType); 5040 ICS.Standard.setAllToTypes(ImplicitParamType); 5041 ICS.Standard.ReferenceBinding = true; 5042 ICS.Standard.DirectBinding = true; 5043 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5044 ICS.Standard.BindsToFunctionLvalue = false; 5045 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5046 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5047 = (Method->getRefQualifier() == RQ_None); 5048 return ICS; 5049 } 5050 5051 /// PerformObjectArgumentInitialization - Perform initialization of 5052 /// the implicit object parameter for the given Method with the given 5053 /// expression. 5054 ExprResult 5055 Sema::PerformObjectArgumentInitialization(Expr *From, 5056 NestedNameSpecifier *Qualifier, 5057 NamedDecl *FoundDecl, 5058 CXXMethodDecl *Method) { 5059 QualType FromRecordType, DestType; 5060 QualType ImplicitParamRecordType = 5061 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5062 5063 Expr::Classification FromClassification; 5064 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5065 FromRecordType = PT->getPointeeType(); 5066 DestType = Method->getThisType(Context); 5067 FromClassification = Expr::Classification::makeSimpleLValue(); 5068 } else { 5069 FromRecordType = From->getType(); 5070 DestType = ImplicitParamRecordType; 5071 FromClassification = From->Classify(Context); 5072 } 5073 5074 // Note that we always use the true parent context when performing 5075 // the actual argument initialization. 5076 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5077 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5078 Method->getParent()); 5079 if (ICS.isBad()) { 5080 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5081 Qualifiers FromQs = FromRecordType.getQualifiers(); 5082 Qualifiers ToQs = DestType.getQualifiers(); 5083 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5084 if (CVR) { 5085 Diag(From->getLocStart(), 5086 diag::err_member_function_call_bad_cvr) 5087 << Method->getDeclName() << FromRecordType << (CVR - 1) 5088 << From->getSourceRange(); 5089 Diag(Method->getLocation(), diag::note_previous_decl) 5090 << Method->getDeclName(); 5091 return ExprError(); 5092 } 5093 } 5094 5095 return Diag(From->getLocStart(), 5096 diag::err_implicit_object_parameter_init) 5097 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5098 } 5099 5100 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5101 ExprResult FromRes = 5102 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5103 if (FromRes.isInvalid()) 5104 return ExprError(); 5105 From = FromRes.get(); 5106 } 5107 5108 if (!Context.hasSameType(From->getType(), DestType)) 5109 From = ImpCastExprToType(From, DestType, CK_NoOp, 5110 From->getValueKind()).get(); 5111 return From; 5112 } 5113 5114 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5115 /// expression From to bool (C++0x [conv]p3). 5116 static ImplicitConversionSequence 5117 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5118 return TryImplicitConversion(S, From, S.Context.BoolTy, 5119 /*SuppressUserConversions=*/false, 5120 /*AllowExplicit=*/true, 5121 /*InOverloadResolution=*/false, 5122 /*CStyle=*/false, 5123 /*AllowObjCWritebackConversion=*/false, 5124 /*AllowObjCConversionOnExplicit=*/false); 5125 } 5126 5127 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5128 /// of the expression From to bool (C++0x [conv]p3). 5129 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5130 if (checkPlaceholderForOverload(*this, From)) 5131 return ExprError(); 5132 5133 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5134 if (!ICS.isBad()) 5135 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5136 5137 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5138 return Diag(From->getLocStart(), 5139 diag::err_typecheck_bool_condition) 5140 << From->getType() << From->getSourceRange(); 5141 return ExprError(); 5142 } 5143 5144 /// Check that the specified conversion is permitted in a converted constant 5145 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5146 /// is acceptable. 5147 static bool CheckConvertedConstantConversions(Sema &S, 5148 StandardConversionSequence &SCS) { 5149 // Since we know that the target type is an integral or unscoped enumeration 5150 // type, most conversion kinds are impossible. All possible First and Third 5151 // conversions are fine. 5152 switch (SCS.Second) { 5153 case ICK_Identity: 5154 case ICK_Function_Conversion: 5155 case ICK_Integral_Promotion: 5156 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5157 return true; 5158 5159 case ICK_Boolean_Conversion: 5160 // Conversion from an integral or unscoped enumeration type to bool is 5161 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5162 // conversion, so we allow it in a converted constant expression. 5163 // 5164 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5165 // a lot of popular code. We should at least add a warning for this 5166 // (non-conforming) extension. 5167 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5168 SCS.getToType(2)->isBooleanType(); 5169 5170 case ICK_Pointer_Conversion: 5171 case ICK_Pointer_Member: 5172 // C++1z: null pointer conversions and null member pointer conversions are 5173 // only permitted if the source type is std::nullptr_t. 5174 return SCS.getFromType()->isNullPtrType(); 5175 5176 case ICK_Floating_Promotion: 5177 case ICK_Complex_Promotion: 5178 case ICK_Floating_Conversion: 5179 case ICK_Complex_Conversion: 5180 case ICK_Floating_Integral: 5181 case ICK_Compatible_Conversion: 5182 case ICK_Derived_To_Base: 5183 case ICK_Vector_Conversion: 5184 case ICK_Vector_Splat: 5185 case ICK_Complex_Real: 5186 case ICK_Block_Pointer_Conversion: 5187 case ICK_TransparentUnionConversion: 5188 case ICK_Writeback_Conversion: 5189 case ICK_Zero_Event_Conversion: 5190 case ICK_C_Only_Conversion: 5191 case ICK_Incompatible_Pointer_Conversion: 5192 return false; 5193 5194 case ICK_Lvalue_To_Rvalue: 5195 case ICK_Array_To_Pointer: 5196 case ICK_Function_To_Pointer: 5197 llvm_unreachable("found a first conversion kind in Second"); 5198 5199 case ICK_Qualification: 5200 llvm_unreachable("found a third conversion kind in Second"); 5201 5202 case ICK_Num_Conversion_Kinds: 5203 break; 5204 } 5205 5206 llvm_unreachable("unknown conversion kind"); 5207 } 5208 5209 /// CheckConvertedConstantExpression - Check that the expression From is a 5210 /// converted constant expression of type T, perform the conversion and produce 5211 /// the converted expression, per C++11 [expr.const]p3. 5212 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5213 QualType T, APValue &Value, 5214 Sema::CCEKind CCE, 5215 bool RequireInt) { 5216 assert(S.getLangOpts().CPlusPlus11 && 5217 "converted constant expression outside C++11"); 5218 5219 if (checkPlaceholderForOverload(S, From)) 5220 return ExprError(); 5221 5222 // C++1z [expr.const]p3: 5223 // A converted constant expression of type T is an expression, 5224 // implicitly converted to type T, where the converted 5225 // expression is a constant expression and the implicit conversion 5226 // sequence contains only [... list of conversions ...]. 5227 // C++1z [stmt.if]p2: 5228 // If the if statement is of the form if constexpr, the value of the 5229 // condition shall be a contextually converted constant expression of type 5230 // bool. 5231 ImplicitConversionSequence ICS = 5232 CCE == Sema::CCEK_ConstexprIf 5233 ? TryContextuallyConvertToBool(S, From) 5234 : TryCopyInitialization(S, From, T, 5235 /*SuppressUserConversions=*/false, 5236 /*InOverloadResolution=*/false, 5237 /*AllowObjcWritebackConversion=*/false, 5238 /*AllowExplicit=*/false); 5239 StandardConversionSequence *SCS = nullptr; 5240 switch (ICS.getKind()) { 5241 case ImplicitConversionSequence::StandardConversion: 5242 SCS = &ICS.Standard; 5243 break; 5244 case ImplicitConversionSequence::UserDefinedConversion: 5245 // We are converting to a non-class type, so the Before sequence 5246 // must be trivial. 5247 SCS = &ICS.UserDefined.After; 5248 break; 5249 case ImplicitConversionSequence::AmbiguousConversion: 5250 case ImplicitConversionSequence::BadConversion: 5251 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5252 return S.Diag(From->getLocStart(), 5253 diag::err_typecheck_converted_constant_expression) 5254 << From->getType() << From->getSourceRange() << T; 5255 return ExprError(); 5256 5257 case ImplicitConversionSequence::EllipsisConversion: 5258 llvm_unreachable("ellipsis conversion in converted constant expression"); 5259 } 5260 5261 // Check that we would only use permitted conversions. 5262 if (!CheckConvertedConstantConversions(S, *SCS)) { 5263 return S.Diag(From->getLocStart(), 5264 diag::err_typecheck_converted_constant_expression_disallowed) 5265 << From->getType() << From->getSourceRange() << T; 5266 } 5267 // [...] and where the reference binding (if any) binds directly. 5268 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5269 return S.Diag(From->getLocStart(), 5270 diag::err_typecheck_converted_constant_expression_indirect) 5271 << From->getType() << From->getSourceRange() << T; 5272 } 5273 5274 ExprResult Result = 5275 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5276 if (Result.isInvalid()) 5277 return Result; 5278 5279 // Check for a narrowing implicit conversion. 5280 APValue PreNarrowingValue; 5281 QualType PreNarrowingType; 5282 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5283 PreNarrowingType)) { 5284 case NK_Variable_Narrowing: 5285 // Implicit conversion to a narrower type, and the value is not a constant 5286 // expression. We'll diagnose this in a moment. 5287 case NK_Not_Narrowing: 5288 break; 5289 5290 case NK_Constant_Narrowing: 5291 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5292 << CCE << /*Constant*/1 5293 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5294 break; 5295 5296 case NK_Type_Narrowing: 5297 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5298 << CCE << /*Constant*/0 << From->getType() << T; 5299 break; 5300 } 5301 5302 // Check the expression is a constant expression. 5303 SmallVector<PartialDiagnosticAt, 8> Notes; 5304 Expr::EvalResult Eval; 5305 Eval.Diag = &Notes; 5306 5307 if ((T->isReferenceType() 5308 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5309 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5310 (RequireInt && !Eval.Val.isInt())) { 5311 // The expression can't be folded, so we can't keep it at this position in 5312 // the AST. 5313 Result = ExprError(); 5314 } else { 5315 Value = Eval.Val; 5316 5317 if (Notes.empty()) { 5318 // It's a constant expression. 5319 return Result; 5320 } 5321 } 5322 5323 // It's not a constant expression. Produce an appropriate diagnostic. 5324 if (Notes.size() == 1 && 5325 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5326 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5327 else { 5328 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5329 << CCE << From->getSourceRange(); 5330 for (unsigned I = 0; I < Notes.size(); ++I) 5331 S.Diag(Notes[I].first, Notes[I].second); 5332 } 5333 return ExprError(); 5334 } 5335 5336 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5337 APValue &Value, CCEKind CCE) { 5338 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5339 } 5340 5341 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5342 llvm::APSInt &Value, 5343 CCEKind CCE) { 5344 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5345 5346 APValue V; 5347 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5348 if (!R.isInvalid()) 5349 Value = V.getInt(); 5350 return R; 5351 } 5352 5353 5354 /// dropPointerConversions - If the given standard conversion sequence 5355 /// involves any pointer conversions, remove them. This may change 5356 /// the result type of the conversion sequence. 5357 static void dropPointerConversion(StandardConversionSequence &SCS) { 5358 if (SCS.Second == ICK_Pointer_Conversion) { 5359 SCS.Second = ICK_Identity; 5360 SCS.Third = ICK_Identity; 5361 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5362 } 5363 } 5364 5365 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5366 /// convert the expression From to an Objective-C pointer type. 5367 static ImplicitConversionSequence 5368 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5369 // Do an implicit conversion to 'id'. 5370 QualType Ty = S.Context.getObjCIdType(); 5371 ImplicitConversionSequence ICS 5372 = TryImplicitConversion(S, From, Ty, 5373 // FIXME: Are these flags correct? 5374 /*SuppressUserConversions=*/false, 5375 /*AllowExplicit=*/true, 5376 /*InOverloadResolution=*/false, 5377 /*CStyle=*/false, 5378 /*AllowObjCWritebackConversion=*/false, 5379 /*AllowObjCConversionOnExplicit=*/true); 5380 5381 // Strip off any final conversions to 'id'. 5382 switch (ICS.getKind()) { 5383 case ImplicitConversionSequence::BadConversion: 5384 case ImplicitConversionSequence::AmbiguousConversion: 5385 case ImplicitConversionSequence::EllipsisConversion: 5386 break; 5387 5388 case ImplicitConversionSequence::UserDefinedConversion: 5389 dropPointerConversion(ICS.UserDefined.After); 5390 break; 5391 5392 case ImplicitConversionSequence::StandardConversion: 5393 dropPointerConversion(ICS.Standard); 5394 break; 5395 } 5396 5397 return ICS; 5398 } 5399 5400 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5401 /// conversion of the expression From to an Objective-C pointer type. 5402 /// Returns a valid but null ExprResult if no conversion sequence exists. 5403 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5404 if (checkPlaceholderForOverload(*this, From)) 5405 return ExprError(); 5406 5407 QualType Ty = Context.getObjCIdType(); 5408 ImplicitConversionSequence ICS = 5409 TryContextuallyConvertToObjCPointer(*this, From); 5410 if (!ICS.isBad()) 5411 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5412 return ExprResult(); 5413 } 5414 5415 /// Determine whether the provided type is an integral type, or an enumeration 5416 /// type of a permitted flavor. 5417 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5418 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5419 : T->isIntegralOrUnscopedEnumerationType(); 5420 } 5421 5422 static ExprResult 5423 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5424 Sema::ContextualImplicitConverter &Converter, 5425 QualType T, UnresolvedSetImpl &ViableConversions) { 5426 5427 if (Converter.Suppress) 5428 return ExprError(); 5429 5430 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5431 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5432 CXXConversionDecl *Conv = 5433 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5434 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5435 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5436 } 5437 return From; 5438 } 5439 5440 static bool 5441 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5442 Sema::ContextualImplicitConverter &Converter, 5443 QualType T, bool HadMultipleCandidates, 5444 UnresolvedSetImpl &ExplicitConversions) { 5445 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5446 DeclAccessPair Found = ExplicitConversions[0]; 5447 CXXConversionDecl *Conversion = 5448 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5449 5450 // The user probably meant to invoke the given explicit 5451 // conversion; use it. 5452 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5453 std::string TypeStr; 5454 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5455 5456 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5457 << FixItHint::CreateInsertion(From->getLocStart(), 5458 "static_cast<" + TypeStr + ">(") 5459 << FixItHint::CreateInsertion( 5460 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5461 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5462 5463 // If we aren't in a SFINAE context, build a call to the 5464 // explicit conversion function. 5465 if (SemaRef.isSFINAEContext()) 5466 return true; 5467 5468 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5469 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5470 HadMultipleCandidates); 5471 if (Result.isInvalid()) 5472 return true; 5473 // Record usage of conversion in an implicit cast. 5474 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5475 CK_UserDefinedConversion, Result.get(), 5476 nullptr, Result.get()->getValueKind()); 5477 } 5478 return false; 5479 } 5480 5481 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5482 Sema::ContextualImplicitConverter &Converter, 5483 QualType T, bool HadMultipleCandidates, 5484 DeclAccessPair &Found) { 5485 CXXConversionDecl *Conversion = 5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5487 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5488 5489 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5490 if (!Converter.SuppressConversion) { 5491 if (SemaRef.isSFINAEContext()) 5492 return true; 5493 5494 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5495 << From->getSourceRange(); 5496 } 5497 5498 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5499 HadMultipleCandidates); 5500 if (Result.isInvalid()) 5501 return true; 5502 // Record usage of conversion in an implicit cast. 5503 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5504 CK_UserDefinedConversion, Result.get(), 5505 nullptr, Result.get()->getValueKind()); 5506 return false; 5507 } 5508 5509 static ExprResult finishContextualImplicitConversion( 5510 Sema &SemaRef, SourceLocation Loc, Expr *From, 5511 Sema::ContextualImplicitConverter &Converter) { 5512 if (!Converter.match(From->getType()) && !Converter.Suppress) 5513 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5514 << From->getSourceRange(); 5515 5516 return SemaRef.DefaultLvalueConversion(From); 5517 } 5518 5519 static void 5520 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5521 UnresolvedSetImpl &ViableConversions, 5522 OverloadCandidateSet &CandidateSet) { 5523 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5524 DeclAccessPair FoundDecl = ViableConversions[I]; 5525 NamedDecl *D = FoundDecl.getDecl(); 5526 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5527 if (isa<UsingShadowDecl>(D)) 5528 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5529 5530 CXXConversionDecl *Conv; 5531 FunctionTemplateDecl *ConvTemplate; 5532 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5533 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5534 else 5535 Conv = cast<CXXConversionDecl>(D); 5536 5537 if (ConvTemplate) 5538 SemaRef.AddTemplateConversionCandidate( 5539 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5540 /*AllowObjCConversionOnExplicit=*/false); 5541 else 5542 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5543 ToType, CandidateSet, 5544 /*AllowObjCConversionOnExplicit=*/false); 5545 } 5546 } 5547 5548 /// \brief Attempt to convert the given expression to a type which is accepted 5549 /// by the given converter. 5550 /// 5551 /// This routine will attempt to convert an expression of class type to a 5552 /// type accepted by the specified converter. In C++11 and before, the class 5553 /// must have a single non-explicit conversion function converting to a matching 5554 /// type. In C++1y, there can be multiple such conversion functions, but only 5555 /// one target type. 5556 /// 5557 /// \param Loc The source location of the construct that requires the 5558 /// conversion. 5559 /// 5560 /// \param From The expression we're converting from. 5561 /// 5562 /// \param Converter Used to control and diagnose the conversion process. 5563 /// 5564 /// \returns The expression, converted to an integral or enumeration type if 5565 /// successful. 5566 ExprResult Sema::PerformContextualImplicitConversion( 5567 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5568 // We can't perform any more checking for type-dependent expressions. 5569 if (From->isTypeDependent()) 5570 return From; 5571 5572 // Process placeholders immediately. 5573 if (From->hasPlaceholderType()) { 5574 ExprResult result = CheckPlaceholderExpr(From); 5575 if (result.isInvalid()) 5576 return result; 5577 From = result.get(); 5578 } 5579 5580 // If the expression already has a matching type, we're golden. 5581 QualType T = From->getType(); 5582 if (Converter.match(T)) 5583 return DefaultLvalueConversion(From); 5584 5585 // FIXME: Check for missing '()' if T is a function type? 5586 5587 // We can only perform contextual implicit conversions on objects of class 5588 // type. 5589 const RecordType *RecordTy = T->getAs<RecordType>(); 5590 if (!RecordTy || !getLangOpts().CPlusPlus) { 5591 if (!Converter.Suppress) 5592 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5593 return From; 5594 } 5595 5596 // We must have a complete class type. 5597 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5598 ContextualImplicitConverter &Converter; 5599 Expr *From; 5600 5601 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5602 : Converter(Converter), From(From) {} 5603 5604 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5605 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5606 } 5607 } IncompleteDiagnoser(Converter, From); 5608 5609 if (Converter.Suppress ? !isCompleteType(Loc, T) 5610 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5611 return From; 5612 5613 // Look for a conversion to an integral or enumeration type. 5614 UnresolvedSet<4> 5615 ViableConversions; // These are *potentially* viable in C++1y. 5616 UnresolvedSet<4> ExplicitConversions; 5617 const auto &Conversions = 5618 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5619 5620 bool HadMultipleCandidates = 5621 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5622 5623 // To check that there is only one target type, in C++1y: 5624 QualType ToType; 5625 bool HasUniqueTargetType = true; 5626 5627 // Collect explicit or viable (potentially in C++1y) conversions. 5628 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5629 NamedDecl *D = (*I)->getUnderlyingDecl(); 5630 CXXConversionDecl *Conversion; 5631 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5632 if (ConvTemplate) { 5633 if (getLangOpts().CPlusPlus14) 5634 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5635 else 5636 continue; // C++11 does not consider conversion operator templates(?). 5637 } else 5638 Conversion = cast<CXXConversionDecl>(D); 5639 5640 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5641 "Conversion operator templates are considered potentially " 5642 "viable in C++1y"); 5643 5644 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5645 if (Converter.match(CurToType) || ConvTemplate) { 5646 5647 if (Conversion->isExplicit()) { 5648 // FIXME: For C++1y, do we need this restriction? 5649 // cf. diagnoseNoViableConversion() 5650 if (!ConvTemplate) 5651 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5652 } else { 5653 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5654 if (ToType.isNull()) 5655 ToType = CurToType.getUnqualifiedType(); 5656 else if (HasUniqueTargetType && 5657 (CurToType.getUnqualifiedType() != ToType)) 5658 HasUniqueTargetType = false; 5659 } 5660 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5661 } 5662 } 5663 } 5664 5665 if (getLangOpts().CPlusPlus14) { 5666 // C++1y [conv]p6: 5667 // ... An expression e of class type E appearing in such a context 5668 // is said to be contextually implicitly converted to a specified 5669 // type T and is well-formed if and only if e can be implicitly 5670 // converted to a type T that is determined as follows: E is searched 5671 // for conversion functions whose return type is cv T or reference to 5672 // cv T such that T is allowed by the context. There shall be 5673 // exactly one such T. 5674 5675 // If no unique T is found: 5676 if (ToType.isNull()) { 5677 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5678 HadMultipleCandidates, 5679 ExplicitConversions)) 5680 return ExprError(); 5681 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5682 } 5683 5684 // If more than one unique Ts are found: 5685 if (!HasUniqueTargetType) 5686 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5687 ViableConversions); 5688 5689 // If one unique T is found: 5690 // First, build a candidate set from the previously recorded 5691 // potentially viable conversions. 5692 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5693 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5694 CandidateSet); 5695 5696 // Then, perform overload resolution over the candidate set. 5697 OverloadCandidateSet::iterator Best; 5698 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5699 case OR_Success: { 5700 // Apply this conversion. 5701 DeclAccessPair Found = 5702 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5703 if (recordConversion(*this, Loc, From, Converter, T, 5704 HadMultipleCandidates, Found)) 5705 return ExprError(); 5706 break; 5707 } 5708 case OR_Ambiguous: 5709 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5710 ViableConversions); 5711 case OR_No_Viable_Function: 5712 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5713 HadMultipleCandidates, 5714 ExplicitConversions)) 5715 return ExprError(); 5716 // fall through 'OR_Deleted' case. 5717 case OR_Deleted: 5718 // We'll complain below about a non-integral condition type. 5719 break; 5720 } 5721 } else { 5722 switch (ViableConversions.size()) { 5723 case 0: { 5724 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5725 HadMultipleCandidates, 5726 ExplicitConversions)) 5727 return ExprError(); 5728 5729 // We'll complain below about a non-integral condition type. 5730 break; 5731 } 5732 case 1: { 5733 // Apply this conversion. 5734 DeclAccessPair Found = ViableConversions[0]; 5735 if (recordConversion(*this, Loc, From, Converter, T, 5736 HadMultipleCandidates, Found)) 5737 return ExprError(); 5738 break; 5739 } 5740 default: 5741 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5742 ViableConversions); 5743 } 5744 } 5745 5746 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5747 } 5748 5749 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5750 /// an acceptable non-member overloaded operator for a call whose 5751 /// arguments have types T1 (and, if non-empty, T2). This routine 5752 /// implements the check in C++ [over.match.oper]p3b2 concerning 5753 /// enumeration types. 5754 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5755 FunctionDecl *Fn, 5756 ArrayRef<Expr *> Args) { 5757 QualType T1 = Args[0]->getType(); 5758 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5759 5760 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5761 return true; 5762 5763 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5764 return true; 5765 5766 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5767 if (Proto->getNumParams() < 1) 5768 return false; 5769 5770 if (T1->isEnumeralType()) { 5771 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5772 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5773 return true; 5774 } 5775 5776 if (Proto->getNumParams() < 2) 5777 return false; 5778 5779 if (!T2.isNull() && T2->isEnumeralType()) { 5780 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5781 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5782 return true; 5783 } 5784 5785 return false; 5786 } 5787 5788 /// AddOverloadCandidate - Adds the given function to the set of 5789 /// candidate functions, using the given function call arguments. If 5790 /// @p SuppressUserConversions, then don't allow user-defined 5791 /// conversions via constructors or conversion operators. 5792 /// 5793 /// \param PartialOverloading true if we are performing "partial" overloading 5794 /// based on an incomplete set of function arguments. This feature is used by 5795 /// code completion. 5796 void 5797 Sema::AddOverloadCandidate(FunctionDecl *Function, 5798 DeclAccessPair FoundDecl, 5799 ArrayRef<Expr *> Args, 5800 OverloadCandidateSet &CandidateSet, 5801 bool SuppressUserConversions, 5802 bool PartialOverloading, 5803 bool AllowExplicit) { 5804 const FunctionProtoType *Proto 5805 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5806 assert(Proto && "Functions without a prototype cannot be overloaded"); 5807 assert(!Function->getDescribedFunctionTemplate() && 5808 "Use AddTemplateOverloadCandidate for function templates"); 5809 5810 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5811 if (!isa<CXXConstructorDecl>(Method)) { 5812 // If we get here, it's because we're calling a member function 5813 // that is named without a member access expression (e.g., 5814 // "this->f") that was either written explicitly or created 5815 // implicitly. This can happen with a qualified call to a member 5816 // function, e.g., X::f(). We use an empty type for the implied 5817 // object argument (C++ [over.call.func]p3), and the acting context 5818 // is irrelevant. 5819 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5820 QualType(), Expr::Classification::makeSimpleLValue(), 5821 Args, CandidateSet, SuppressUserConversions, 5822 PartialOverloading); 5823 return; 5824 } 5825 // We treat a constructor like a non-member function, since its object 5826 // argument doesn't participate in overload resolution. 5827 } 5828 5829 if (!CandidateSet.isNewCandidate(Function)) 5830 return; 5831 5832 // C++ [over.match.oper]p3: 5833 // if no operand has a class type, only those non-member functions in the 5834 // lookup set that have a first parameter of type T1 or "reference to 5835 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5836 // is a right operand) a second parameter of type T2 or "reference to 5837 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5838 // candidate functions. 5839 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5840 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5841 return; 5842 5843 // C++11 [class.copy]p11: [DR1402] 5844 // A defaulted move constructor that is defined as deleted is ignored by 5845 // overload resolution. 5846 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5847 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5848 Constructor->isMoveConstructor()) 5849 return; 5850 5851 // Overload resolution is always an unevaluated context. 5852 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5853 5854 // Add this candidate 5855 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5856 Candidate.FoundDecl = FoundDecl; 5857 Candidate.Function = Function; 5858 Candidate.Viable = true; 5859 Candidate.IsSurrogate = false; 5860 Candidate.IgnoreObjectArgument = false; 5861 Candidate.ExplicitCallArguments = Args.size(); 5862 5863 if (Constructor) { 5864 // C++ [class.copy]p3: 5865 // A member function template is never instantiated to perform the copy 5866 // of a class object to an object of its class type. 5867 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5868 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5869 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5870 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5871 ClassType))) { 5872 Candidate.Viable = false; 5873 Candidate.FailureKind = ovl_fail_illegal_constructor; 5874 return; 5875 } 5876 } 5877 5878 unsigned NumParams = Proto->getNumParams(); 5879 5880 // (C++ 13.3.2p2): A candidate function having fewer than m 5881 // parameters is viable only if it has an ellipsis in its parameter 5882 // list (8.3.5). 5883 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5884 !Proto->isVariadic()) { 5885 Candidate.Viable = false; 5886 Candidate.FailureKind = ovl_fail_too_many_arguments; 5887 return; 5888 } 5889 5890 // (C++ 13.3.2p2): A candidate function having more than m parameters 5891 // is viable only if the (m+1)st parameter has a default argument 5892 // (8.3.6). For the purposes of overload resolution, the 5893 // parameter list is truncated on the right, so that there are 5894 // exactly m parameters. 5895 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5896 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5897 // Not enough arguments. 5898 Candidate.Viable = false; 5899 Candidate.FailureKind = ovl_fail_too_few_arguments; 5900 return; 5901 } 5902 5903 // (CUDA B.1): Check for invalid calls between targets. 5904 if (getLangOpts().CUDA) 5905 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5906 // Skip the check for callers that are implicit members, because in this 5907 // case we may not yet know what the member's target is; the target is 5908 // inferred for the member automatically, based on the bases and fields of 5909 // the class. 5910 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5911 Candidate.Viable = false; 5912 Candidate.FailureKind = ovl_fail_bad_target; 5913 return; 5914 } 5915 5916 // Determine the implicit conversion sequences for each of the 5917 // arguments. 5918 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5919 if (ArgIdx < NumParams) { 5920 // (C++ 13.3.2p3): for F to be a viable function, there shall 5921 // exist for each argument an implicit conversion sequence 5922 // (13.3.3.1) that converts that argument to the corresponding 5923 // parameter of F. 5924 QualType ParamType = Proto->getParamType(ArgIdx); 5925 Candidate.Conversions[ArgIdx] 5926 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5927 SuppressUserConversions, 5928 /*InOverloadResolution=*/true, 5929 /*AllowObjCWritebackConversion=*/ 5930 getLangOpts().ObjCAutoRefCount, 5931 AllowExplicit); 5932 if (Candidate.Conversions[ArgIdx].isBad()) { 5933 Candidate.Viable = false; 5934 Candidate.FailureKind = ovl_fail_bad_conversion; 5935 return; 5936 } 5937 } else { 5938 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5939 // argument for which there is no corresponding parameter is 5940 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5941 Candidate.Conversions[ArgIdx].setEllipsis(); 5942 } 5943 } 5944 5945 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5946 Candidate.Viable = false; 5947 Candidate.FailureKind = ovl_fail_enable_if; 5948 Candidate.DeductionFailure.Data = FailedAttr; 5949 return; 5950 } 5951 } 5952 5953 ObjCMethodDecl * 5954 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5955 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5956 if (Methods.size() <= 1) 5957 return nullptr; 5958 5959 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5960 bool Match = true; 5961 ObjCMethodDecl *Method = Methods[b]; 5962 unsigned NumNamedArgs = Sel.getNumArgs(); 5963 // Method might have more arguments than selector indicates. This is due 5964 // to addition of c-style arguments in method. 5965 if (Method->param_size() > NumNamedArgs) 5966 NumNamedArgs = Method->param_size(); 5967 if (Args.size() < NumNamedArgs) 5968 continue; 5969 5970 for (unsigned i = 0; i < NumNamedArgs; i++) { 5971 // We can't do any type-checking on a type-dependent argument. 5972 if (Args[i]->isTypeDependent()) { 5973 Match = false; 5974 break; 5975 } 5976 5977 ParmVarDecl *param = Method->parameters()[i]; 5978 Expr *argExpr = Args[i]; 5979 assert(argExpr && "SelectBestMethod(): missing expression"); 5980 5981 // Strip the unbridged-cast placeholder expression off unless it's 5982 // a consumed argument. 5983 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5984 !param->hasAttr<CFConsumedAttr>()) 5985 argExpr = stripARCUnbridgedCast(argExpr); 5986 5987 // If the parameter is __unknown_anytype, move on to the next method. 5988 if (param->getType() == Context.UnknownAnyTy) { 5989 Match = false; 5990 break; 5991 } 5992 5993 ImplicitConversionSequence ConversionState 5994 = TryCopyInitialization(*this, argExpr, param->getType(), 5995 /*SuppressUserConversions*/false, 5996 /*InOverloadResolution=*/true, 5997 /*AllowObjCWritebackConversion=*/ 5998 getLangOpts().ObjCAutoRefCount, 5999 /*AllowExplicit*/false); 6000 // This function looks for a reasonably-exact match, so we consider 6001 // incompatible pointer conversions to be a failure here. 6002 if (ConversionState.isBad() || 6003 (ConversionState.isStandard() && 6004 ConversionState.Standard.Second == 6005 ICK_Incompatible_Pointer_Conversion)) { 6006 Match = false; 6007 break; 6008 } 6009 } 6010 // Promote additional arguments to variadic methods. 6011 if (Match && Method->isVariadic()) { 6012 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6013 if (Args[i]->isTypeDependent()) { 6014 Match = false; 6015 break; 6016 } 6017 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6018 nullptr); 6019 if (Arg.isInvalid()) { 6020 Match = false; 6021 break; 6022 } 6023 } 6024 } else { 6025 // Check for extra arguments to non-variadic methods. 6026 if (Args.size() != NumNamedArgs) 6027 Match = false; 6028 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6029 // Special case when selectors have no argument. In this case, select 6030 // one with the most general result type of 'id'. 6031 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6032 QualType ReturnT = Methods[b]->getReturnType(); 6033 if (ReturnT->isObjCIdType()) 6034 return Methods[b]; 6035 } 6036 } 6037 } 6038 6039 if (Match) 6040 return Method; 6041 } 6042 return nullptr; 6043 } 6044 6045 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6046 // enable_if is order-sensitive. As a result, we need to reverse things 6047 // sometimes. Size of 4 elements is arbitrary. 6048 static SmallVector<EnableIfAttr *, 4> 6049 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6050 SmallVector<EnableIfAttr *, 4> Result; 6051 if (!Function->hasAttrs()) 6052 return Result; 6053 6054 const auto &FuncAttrs = Function->getAttrs(); 6055 for (Attr *Attr : FuncAttrs) 6056 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6057 Result.push_back(EnableIf); 6058 6059 std::reverse(Result.begin(), Result.end()); 6060 return Result; 6061 } 6062 6063 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6064 bool MissingImplicitThis) { 6065 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 6066 if (EnableIfAttrs.empty()) 6067 return nullptr; 6068 6069 SFINAETrap Trap(*this); 6070 SmallVector<Expr *, 16> ConvertedArgs; 6071 bool InitializationFailed = false; 6072 6073 // Ignore any variadic arguments. Converting them is pointless, since the 6074 // user can't refer to them in the enable_if condition. 6075 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6076 6077 // Convert the arguments. 6078 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6079 ExprResult R; 6080 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 6081 !cast<CXXMethodDecl>(Function)->isStatic() && 6082 !isa<CXXConstructorDecl>(Function)) { 6083 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6084 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 6085 Method, Method); 6086 } else { 6087 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6088 Context, Function->getParamDecl(I)), 6089 SourceLocation(), Args[I]); 6090 } 6091 6092 if (R.isInvalid()) { 6093 InitializationFailed = true; 6094 break; 6095 } 6096 6097 ConvertedArgs.push_back(R.get()); 6098 } 6099 6100 if (InitializationFailed || Trap.hasErrorOccurred()) 6101 return EnableIfAttrs[0]; 6102 6103 // Push default arguments if needed. 6104 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6105 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6106 ParmVarDecl *P = Function->getParamDecl(i); 6107 ExprResult R = PerformCopyInitialization( 6108 InitializedEntity::InitializeParameter(Context, 6109 Function->getParamDecl(i)), 6110 SourceLocation(), 6111 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6112 : P->getDefaultArg()); 6113 if (R.isInvalid()) { 6114 InitializationFailed = true; 6115 break; 6116 } 6117 ConvertedArgs.push_back(R.get()); 6118 } 6119 6120 if (InitializationFailed || Trap.hasErrorOccurred()) 6121 return EnableIfAttrs[0]; 6122 } 6123 6124 for (auto *EIA : EnableIfAttrs) { 6125 APValue Result; 6126 // FIXME: This doesn't consider value-dependent cases, because doing so is 6127 // very difficult. Ideally, we should handle them more gracefully. 6128 if (!EIA->getCond()->EvaluateWithSubstitution( 6129 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6130 return EIA; 6131 6132 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6133 return EIA; 6134 } 6135 return nullptr; 6136 } 6137 6138 /// \brief Add all of the function declarations in the given function set to 6139 /// the overload candidate set. 6140 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6141 ArrayRef<Expr *> Args, 6142 OverloadCandidateSet& CandidateSet, 6143 TemplateArgumentListInfo *ExplicitTemplateArgs, 6144 bool SuppressUserConversions, 6145 bool PartialOverloading) { 6146 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6147 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6149 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6150 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6151 cast<CXXMethodDecl>(FD)->getParent(), 6152 Args[0]->getType(), Args[0]->Classify(Context), 6153 Args.slice(1), CandidateSet, 6154 SuppressUserConversions, PartialOverloading); 6155 else 6156 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6157 SuppressUserConversions, PartialOverloading); 6158 } else { 6159 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6160 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6161 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6162 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6163 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6164 ExplicitTemplateArgs, 6165 Args[0]->getType(), 6166 Args[0]->Classify(Context), Args.slice(1), 6167 CandidateSet, SuppressUserConversions, 6168 PartialOverloading); 6169 else 6170 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6171 ExplicitTemplateArgs, Args, 6172 CandidateSet, SuppressUserConversions, 6173 PartialOverloading); 6174 } 6175 } 6176 } 6177 6178 /// AddMethodCandidate - Adds a named decl (which is some kind of 6179 /// method) as a method candidate to the given overload set. 6180 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6181 QualType ObjectType, 6182 Expr::Classification ObjectClassification, 6183 ArrayRef<Expr *> Args, 6184 OverloadCandidateSet& CandidateSet, 6185 bool SuppressUserConversions) { 6186 NamedDecl *Decl = FoundDecl.getDecl(); 6187 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6188 6189 if (isa<UsingShadowDecl>(Decl)) 6190 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6191 6192 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6193 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6194 "Expected a member function template"); 6195 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6196 /*ExplicitArgs*/ nullptr, 6197 ObjectType, ObjectClassification, 6198 Args, CandidateSet, 6199 SuppressUserConversions); 6200 } else { 6201 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6202 ObjectType, ObjectClassification, 6203 Args, 6204 CandidateSet, SuppressUserConversions); 6205 } 6206 } 6207 6208 /// AddMethodCandidate - Adds the given C++ member function to the set 6209 /// of candidate functions, using the given function call arguments 6210 /// and the object argument (@c Object). For example, in a call 6211 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6212 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6213 /// allow user-defined conversions via constructors or conversion 6214 /// operators. 6215 void 6216 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6217 CXXRecordDecl *ActingContext, QualType ObjectType, 6218 Expr::Classification ObjectClassification, 6219 ArrayRef<Expr *> Args, 6220 OverloadCandidateSet &CandidateSet, 6221 bool SuppressUserConversions, 6222 bool PartialOverloading) { 6223 const FunctionProtoType *Proto 6224 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6225 assert(Proto && "Methods without a prototype cannot be overloaded"); 6226 assert(!isa<CXXConstructorDecl>(Method) && 6227 "Use AddOverloadCandidate for constructors"); 6228 6229 if (!CandidateSet.isNewCandidate(Method)) 6230 return; 6231 6232 // C++11 [class.copy]p23: [DR1402] 6233 // A defaulted move assignment operator that is defined as deleted is 6234 // ignored by overload resolution. 6235 if (Method->isDefaulted() && Method->isDeleted() && 6236 Method->isMoveAssignmentOperator()) 6237 return; 6238 6239 // Overload resolution is always an unevaluated context. 6240 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6241 6242 // Add this candidate 6243 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6244 Candidate.FoundDecl = FoundDecl; 6245 Candidate.Function = Method; 6246 Candidate.IsSurrogate = false; 6247 Candidate.IgnoreObjectArgument = false; 6248 Candidate.ExplicitCallArguments = Args.size(); 6249 6250 unsigned NumParams = Proto->getNumParams(); 6251 6252 // (C++ 13.3.2p2): A candidate function having fewer than m 6253 // parameters is viable only if it has an ellipsis in its parameter 6254 // list (8.3.5). 6255 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6256 !Proto->isVariadic()) { 6257 Candidate.Viable = false; 6258 Candidate.FailureKind = ovl_fail_too_many_arguments; 6259 return; 6260 } 6261 6262 // (C++ 13.3.2p2): A candidate function having more than m parameters 6263 // is viable only if the (m+1)st parameter has a default argument 6264 // (8.3.6). For the purposes of overload resolution, the 6265 // parameter list is truncated on the right, so that there are 6266 // exactly m parameters. 6267 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6268 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6269 // Not enough arguments. 6270 Candidate.Viable = false; 6271 Candidate.FailureKind = ovl_fail_too_few_arguments; 6272 return; 6273 } 6274 6275 Candidate.Viable = true; 6276 6277 if (Method->isStatic() || ObjectType.isNull()) 6278 // The implicit object argument is ignored. 6279 Candidate.IgnoreObjectArgument = true; 6280 else { 6281 // Determine the implicit conversion sequence for the object 6282 // parameter. 6283 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6284 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6285 Method, ActingContext); 6286 if (Candidate.Conversions[0].isBad()) { 6287 Candidate.Viable = false; 6288 Candidate.FailureKind = ovl_fail_bad_conversion; 6289 return; 6290 } 6291 } 6292 6293 // (CUDA B.1): Check for invalid calls between targets. 6294 if (getLangOpts().CUDA) 6295 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6296 if (!IsAllowedCUDACall(Caller, Method)) { 6297 Candidate.Viable = false; 6298 Candidate.FailureKind = ovl_fail_bad_target; 6299 return; 6300 } 6301 6302 // Determine the implicit conversion sequences for each of the 6303 // arguments. 6304 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6305 if (ArgIdx < NumParams) { 6306 // (C++ 13.3.2p3): for F to be a viable function, there shall 6307 // exist for each argument an implicit conversion sequence 6308 // (13.3.3.1) that converts that argument to the corresponding 6309 // parameter of F. 6310 QualType ParamType = Proto->getParamType(ArgIdx); 6311 Candidate.Conversions[ArgIdx + 1] 6312 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6313 SuppressUserConversions, 6314 /*InOverloadResolution=*/true, 6315 /*AllowObjCWritebackConversion=*/ 6316 getLangOpts().ObjCAutoRefCount); 6317 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6318 Candidate.Viable = false; 6319 Candidate.FailureKind = ovl_fail_bad_conversion; 6320 return; 6321 } 6322 } else { 6323 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6324 // argument for which there is no corresponding parameter is 6325 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6326 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6327 } 6328 } 6329 6330 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6331 Candidate.Viable = false; 6332 Candidate.FailureKind = ovl_fail_enable_if; 6333 Candidate.DeductionFailure.Data = FailedAttr; 6334 return; 6335 } 6336 } 6337 6338 /// \brief Add a C++ member function template as a candidate to the candidate 6339 /// set, using template argument deduction to produce an appropriate member 6340 /// function template specialization. 6341 void 6342 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6343 DeclAccessPair FoundDecl, 6344 CXXRecordDecl *ActingContext, 6345 TemplateArgumentListInfo *ExplicitTemplateArgs, 6346 QualType ObjectType, 6347 Expr::Classification ObjectClassification, 6348 ArrayRef<Expr *> Args, 6349 OverloadCandidateSet& CandidateSet, 6350 bool SuppressUserConversions, 6351 bool PartialOverloading) { 6352 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6353 return; 6354 6355 // C++ [over.match.funcs]p7: 6356 // In each case where a candidate is a function template, candidate 6357 // function template specializations are generated using template argument 6358 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6359 // candidate functions in the usual way.113) A given name can refer to one 6360 // or more function templates and also to a set of overloaded non-template 6361 // functions. In such a case, the candidate functions generated from each 6362 // function template are combined with the set of non-template candidate 6363 // functions. 6364 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6365 FunctionDecl *Specialization = nullptr; 6366 if (TemplateDeductionResult Result 6367 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6368 Specialization, Info, PartialOverloading)) { 6369 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6370 Candidate.FoundDecl = FoundDecl; 6371 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6372 Candidate.Viable = false; 6373 Candidate.FailureKind = ovl_fail_bad_deduction; 6374 Candidate.IsSurrogate = false; 6375 Candidate.IgnoreObjectArgument = false; 6376 Candidate.ExplicitCallArguments = Args.size(); 6377 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6378 Info); 6379 return; 6380 } 6381 6382 // Add the function template specialization produced by template argument 6383 // deduction as a candidate. 6384 assert(Specialization && "Missing member function template specialization?"); 6385 assert(isa<CXXMethodDecl>(Specialization) && 6386 "Specialization is not a member function?"); 6387 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6388 ActingContext, ObjectType, ObjectClassification, Args, 6389 CandidateSet, SuppressUserConversions, PartialOverloading); 6390 } 6391 6392 /// \brief Add a C++ function template specialization as a candidate 6393 /// in the candidate set, using template argument deduction to produce 6394 /// an appropriate function template specialization. 6395 void 6396 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6397 DeclAccessPair FoundDecl, 6398 TemplateArgumentListInfo *ExplicitTemplateArgs, 6399 ArrayRef<Expr *> Args, 6400 OverloadCandidateSet& CandidateSet, 6401 bool SuppressUserConversions, 6402 bool PartialOverloading) { 6403 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6404 return; 6405 6406 // C++ [over.match.funcs]p7: 6407 // In each case where a candidate is a function template, candidate 6408 // function template specializations are generated using template argument 6409 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6410 // candidate functions in the usual way.113) A given name can refer to one 6411 // or more function templates and also to a set of overloaded non-template 6412 // functions. In such a case, the candidate functions generated from each 6413 // function template are combined with the set of non-template candidate 6414 // functions. 6415 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6416 FunctionDecl *Specialization = nullptr; 6417 if (TemplateDeductionResult Result 6418 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6419 Specialization, Info, PartialOverloading)) { 6420 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6421 Candidate.FoundDecl = FoundDecl; 6422 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6423 Candidate.Viable = false; 6424 Candidate.FailureKind = ovl_fail_bad_deduction; 6425 Candidate.IsSurrogate = false; 6426 Candidate.IgnoreObjectArgument = false; 6427 Candidate.ExplicitCallArguments = Args.size(); 6428 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6429 Info); 6430 return; 6431 } 6432 6433 // Add the function template specialization produced by template argument 6434 // deduction as a candidate. 6435 assert(Specialization && "Missing function template specialization?"); 6436 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6437 SuppressUserConversions, PartialOverloading); 6438 } 6439 6440 /// Determine whether this is an allowable conversion from the result 6441 /// of an explicit conversion operator to the expected type, per C++ 6442 /// [over.match.conv]p1 and [over.match.ref]p1. 6443 /// 6444 /// \param ConvType The return type of the conversion function. 6445 /// 6446 /// \param ToType The type we are converting to. 6447 /// 6448 /// \param AllowObjCPointerConversion Allow a conversion from one 6449 /// Objective-C pointer to another. 6450 /// 6451 /// \returns true if the conversion is allowable, false otherwise. 6452 static bool isAllowableExplicitConversion(Sema &S, 6453 QualType ConvType, QualType ToType, 6454 bool AllowObjCPointerConversion) { 6455 QualType ToNonRefType = ToType.getNonReferenceType(); 6456 6457 // Easy case: the types are the same. 6458 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6459 return true; 6460 6461 // Allow qualification conversions. 6462 bool ObjCLifetimeConversion; 6463 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6464 ObjCLifetimeConversion)) 6465 return true; 6466 6467 // If we're not allowed to consider Objective-C pointer conversions, 6468 // we're done. 6469 if (!AllowObjCPointerConversion) 6470 return false; 6471 6472 // Is this an Objective-C pointer conversion? 6473 bool IncompatibleObjC = false; 6474 QualType ConvertedType; 6475 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6476 IncompatibleObjC); 6477 } 6478 6479 /// AddConversionCandidate - Add a C++ conversion function as a 6480 /// candidate in the candidate set (C++ [over.match.conv], 6481 /// C++ [over.match.copy]). From is the expression we're converting from, 6482 /// and ToType is the type that we're eventually trying to convert to 6483 /// (which may or may not be the same type as the type that the 6484 /// conversion function produces). 6485 void 6486 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6487 DeclAccessPair FoundDecl, 6488 CXXRecordDecl *ActingContext, 6489 Expr *From, QualType ToType, 6490 OverloadCandidateSet& CandidateSet, 6491 bool AllowObjCConversionOnExplicit) { 6492 assert(!Conversion->getDescribedFunctionTemplate() && 6493 "Conversion function templates use AddTemplateConversionCandidate"); 6494 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6495 if (!CandidateSet.isNewCandidate(Conversion)) 6496 return; 6497 6498 // If the conversion function has an undeduced return type, trigger its 6499 // deduction now. 6500 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6501 if (DeduceReturnType(Conversion, From->getExprLoc())) 6502 return; 6503 ConvType = Conversion->getConversionType().getNonReferenceType(); 6504 } 6505 6506 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6507 // operator is only a candidate if its return type is the target type or 6508 // can be converted to the target type with a qualification conversion. 6509 if (Conversion->isExplicit() && 6510 !isAllowableExplicitConversion(*this, ConvType, ToType, 6511 AllowObjCConversionOnExplicit)) 6512 return; 6513 6514 // Overload resolution is always an unevaluated context. 6515 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6516 6517 // Add this candidate 6518 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6519 Candidate.FoundDecl = FoundDecl; 6520 Candidate.Function = Conversion; 6521 Candidate.IsSurrogate = false; 6522 Candidate.IgnoreObjectArgument = false; 6523 Candidate.FinalConversion.setAsIdentityConversion(); 6524 Candidate.FinalConversion.setFromType(ConvType); 6525 Candidate.FinalConversion.setAllToTypes(ToType); 6526 Candidate.Viable = true; 6527 Candidate.ExplicitCallArguments = 1; 6528 6529 // C++ [over.match.funcs]p4: 6530 // For conversion functions, the function is considered to be a member of 6531 // the class of the implicit implied object argument for the purpose of 6532 // defining the type of the implicit object parameter. 6533 // 6534 // Determine the implicit conversion sequence for the implicit 6535 // object parameter. 6536 QualType ImplicitParamType = From->getType(); 6537 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6538 ImplicitParamType = FromPtrType->getPointeeType(); 6539 CXXRecordDecl *ConversionContext 6540 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6541 6542 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6543 *this, CandidateSet.getLocation(), From->getType(), 6544 From->Classify(Context), Conversion, ConversionContext); 6545 6546 if (Candidate.Conversions[0].isBad()) { 6547 Candidate.Viable = false; 6548 Candidate.FailureKind = ovl_fail_bad_conversion; 6549 return; 6550 } 6551 6552 // We won't go through a user-defined type conversion function to convert a 6553 // derived to base as such conversions are given Conversion Rank. They only 6554 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6555 QualType FromCanon 6556 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6557 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6558 if (FromCanon == ToCanon || 6559 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6560 Candidate.Viable = false; 6561 Candidate.FailureKind = ovl_fail_trivial_conversion; 6562 return; 6563 } 6564 6565 // To determine what the conversion from the result of calling the 6566 // conversion function to the type we're eventually trying to 6567 // convert to (ToType), we need to synthesize a call to the 6568 // conversion function and attempt copy initialization from it. This 6569 // makes sure that we get the right semantics with respect to 6570 // lvalues/rvalues and the type. Fortunately, we can allocate this 6571 // call on the stack and we don't need its arguments to be 6572 // well-formed. 6573 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6574 VK_LValue, From->getLocStart()); 6575 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6576 Context.getPointerType(Conversion->getType()), 6577 CK_FunctionToPointerDecay, 6578 &ConversionRef, VK_RValue); 6579 6580 QualType ConversionType = Conversion->getConversionType(); 6581 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6582 Candidate.Viable = false; 6583 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6584 return; 6585 } 6586 6587 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6588 6589 // Note that it is safe to allocate CallExpr on the stack here because 6590 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6591 // allocator). 6592 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6593 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6594 From->getLocStart()); 6595 ImplicitConversionSequence ICS = 6596 TryCopyInitialization(*this, &Call, ToType, 6597 /*SuppressUserConversions=*/true, 6598 /*InOverloadResolution=*/false, 6599 /*AllowObjCWritebackConversion=*/false); 6600 6601 switch (ICS.getKind()) { 6602 case ImplicitConversionSequence::StandardConversion: 6603 Candidate.FinalConversion = ICS.Standard; 6604 6605 // C++ [over.ics.user]p3: 6606 // If the user-defined conversion is specified by a specialization of a 6607 // conversion function template, the second standard conversion sequence 6608 // shall have exact match rank. 6609 if (Conversion->getPrimaryTemplate() && 6610 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6611 Candidate.Viable = false; 6612 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6613 return; 6614 } 6615 6616 // C++0x [dcl.init.ref]p5: 6617 // In the second case, if the reference is an rvalue reference and 6618 // the second standard conversion sequence of the user-defined 6619 // conversion sequence includes an lvalue-to-rvalue conversion, the 6620 // program is ill-formed. 6621 if (ToType->isRValueReferenceType() && 6622 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6623 Candidate.Viable = false; 6624 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6625 return; 6626 } 6627 break; 6628 6629 case ImplicitConversionSequence::BadConversion: 6630 Candidate.Viable = false; 6631 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6632 return; 6633 6634 default: 6635 llvm_unreachable( 6636 "Can only end up with a standard conversion sequence or failure"); 6637 } 6638 6639 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6640 Candidate.Viable = false; 6641 Candidate.FailureKind = ovl_fail_enable_if; 6642 Candidate.DeductionFailure.Data = FailedAttr; 6643 return; 6644 } 6645 } 6646 6647 /// \brief Adds a conversion function template specialization 6648 /// candidate to the overload set, using template argument deduction 6649 /// to deduce the template arguments of the conversion function 6650 /// template from the type that we are converting to (C++ 6651 /// [temp.deduct.conv]). 6652 void 6653 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6654 DeclAccessPair FoundDecl, 6655 CXXRecordDecl *ActingDC, 6656 Expr *From, QualType ToType, 6657 OverloadCandidateSet &CandidateSet, 6658 bool AllowObjCConversionOnExplicit) { 6659 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6660 "Only conversion function templates permitted here"); 6661 6662 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6663 return; 6664 6665 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6666 CXXConversionDecl *Specialization = nullptr; 6667 if (TemplateDeductionResult Result 6668 = DeduceTemplateArguments(FunctionTemplate, ToType, 6669 Specialization, Info)) { 6670 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6671 Candidate.FoundDecl = FoundDecl; 6672 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6673 Candidate.Viable = false; 6674 Candidate.FailureKind = ovl_fail_bad_deduction; 6675 Candidate.IsSurrogate = false; 6676 Candidate.IgnoreObjectArgument = false; 6677 Candidate.ExplicitCallArguments = 1; 6678 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6679 Info); 6680 return; 6681 } 6682 6683 // Add the conversion function template specialization produced by 6684 // template argument deduction as a candidate. 6685 assert(Specialization && "Missing function template specialization?"); 6686 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6687 CandidateSet, AllowObjCConversionOnExplicit); 6688 } 6689 6690 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6691 /// converts the given @c Object to a function pointer via the 6692 /// conversion function @c Conversion, and then attempts to call it 6693 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6694 /// the type of function that we'll eventually be calling. 6695 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6696 DeclAccessPair FoundDecl, 6697 CXXRecordDecl *ActingContext, 6698 const FunctionProtoType *Proto, 6699 Expr *Object, 6700 ArrayRef<Expr *> Args, 6701 OverloadCandidateSet& CandidateSet) { 6702 if (!CandidateSet.isNewCandidate(Conversion)) 6703 return; 6704 6705 // Overload resolution is always an unevaluated context. 6706 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6707 6708 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6709 Candidate.FoundDecl = FoundDecl; 6710 Candidate.Function = nullptr; 6711 Candidate.Surrogate = Conversion; 6712 Candidate.Viable = true; 6713 Candidate.IsSurrogate = true; 6714 Candidate.IgnoreObjectArgument = false; 6715 Candidate.ExplicitCallArguments = Args.size(); 6716 6717 // Determine the implicit conversion sequence for the implicit 6718 // object parameter. 6719 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6720 *this, CandidateSet.getLocation(), Object->getType(), 6721 Object->Classify(Context), Conversion, ActingContext); 6722 if (ObjectInit.isBad()) { 6723 Candidate.Viable = false; 6724 Candidate.FailureKind = ovl_fail_bad_conversion; 6725 Candidate.Conversions[0] = ObjectInit; 6726 return; 6727 } 6728 6729 // The first conversion is actually a user-defined conversion whose 6730 // first conversion is ObjectInit's standard conversion (which is 6731 // effectively a reference binding). Record it as such. 6732 Candidate.Conversions[0].setUserDefined(); 6733 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6734 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6735 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6736 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6737 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6738 Candidate.Conversions[0].UserDefined.After 6739 = Candidate.Conversions[0].UserDefined.Before; 6740 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6741 6742 // Find the 6743 unsigned NumParams = Proto->getNumParams(); 6744 6745 // (C++ 13.3.2p2): A candidate function having fewer than m 6746 // parameters is viable only if it has an ellipsis in its parameter 6747 // list (8.3.5). 6748 if (Args.size() > NumParams && !Proto->isVariadic()) { 6749 Candidate.Viable = false; 6750 Candidate.FailureKind = ovl_fail_too_many_arguments; 6751 return; 6752 } 6753 6754 // Function types don't have any default arguments, so just check if 6755 // we have enough arguments. 6756 if (Args.size() < NumParams) { 6757 // Not enough arguments. 6758 Candidate.Viable = false; 6759 Candidate.FailureKind = ovl_fail_too_few_arguments; 6760 return; 6761 } 6762 6763 // Determine the implicit conversion sequences for each of the 6764 // arguments. 6765 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6766 if (ArgIdx < NumParams) { 6767 // (C++ 13.3.2p3): for F to be a viable function, there shall 6768 // exist for each argument an implicit conversion sequence 6769 // (13.3.3.1) that converts that argument to the corresponding 6770 // parameter of F. 6771 QualType ParamType = Proto->getParamType(ArgIdx); 6772 Candidate.Conversions[ArgIdx + 1] 6773 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6774 /*SuppressUserConversions=*/false, 6775 /*InOverloadResolution=*/false, 6776 /*AllowObjCWritebackConversion=*/ 6777 getLangOpts().ObjCAutoRefCount); 6778 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6779 Candidate.Viable = false; 6780 Candidate.FailureKind = ovl_fail_bad_conversion; 6781 return; 6782 } 6783 } else { 6784 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6785 // argument for which there is no corresponding parameter is 6786 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6787 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6788 } 6789 } 6790 6791 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6792 Candidate.Viable = false; 6793 Candidate.FailureKind = ovl_fail_enable_if; 6794 Candidate.DeductionFailure.Data = FailedAttr; 6795 return; 6796 } 6797 } 6798 6799 /// \brief Add overload candidates for overloaded operators that are 6800 /// member functions. 6801 /// 6802 /// Add the overloaded operator candidates that are member functions 6803 /// for the operator Op that was used in an operator expression such 6804 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6805 /// CandidateSet will store the added overload candidates. (C++ 6806 /// [over.match.oper]). 6807 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6808 SourceLocation OpLoc, 6809 ArrayRef<Expr *> Args, 6810 OverloadCandidateSet& CandidateSet, 6811 SourceRange OpRange) { 6812 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6813 6814 // C++ [over.match.oper]p3: 6815 // For a unary operator @ with an operand of a type whose 6816 // cv-unqualified version is T1, and for a binary operator @ with 6817 // a left operand of a type whose cv-unqualified version is T1 and 6818 // a right operand of a type whose cv-unqualified version is T2, 6819 // three sets of candidate functions, designated member 6820 // candidates, non-member candidates and built-in candidates, are 6821 // constructed as follows: 6822 QualType T1 = Args[0]->getType(); 6823 6824 // -- If T1 is a complete class type or a class currently being 6825 // defined, the set of member candidates is the result of the 6826 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6827 // the set of member candidates is empty. 6828 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6829 // Complete the type if it can be completed. 6830 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6831 return; 6832 // If the type is neither complete nor being defined, bail out now. 6833 if (!T1Rec->getDecl()->getDefinition()) 6834 return; 6835 6836 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6837 LookupQualifiedName(Operators, T1Rec->getDecl()); 6838 Operators.suppressDiagnostics(); 6839 6840 for (LookupResult::iterator Oper = Operators.begin(), 6841 OperEnd = Operators.end(); 6842 Oper != OperEnd; 6843 ++Oper) 6844 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6845 Args[0]->Classify(Context), 6846 Args.slice(1), 6847 CandidateSet, 6848 /* SuppressUserConversions = */ false); 6849 } 6850 } 6851 6852 /// AddBuiltinCandidate - Add a candidate for a built-in 6853 /// operator. ResultTy and ParamTys are the result and parameter types 6854 /// of the built-in candidate, respectively. Args and NumArgs are the 6855 /// arguments being passed to the candidate. IsAssignmentOperator 6856 /// should be true when this built-in candidate is an assignment 6857 /// operator. NumContextualBoolArguments is the number of arguments 6858 /// (at the beginning of the argument list) that will be contextually 6859 /// converted to bool. 6860 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6861 ArrayRef<Expr *> Args, 6862 OverloadCandidateSet& CandidateSet, 6863 bool IsAssignmentOperator, 6864 unsigned NumContextualBoolArguments) { 6865 // Overload resolution is always an unevaluated context. 6866 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6867 6868 // Add this candidate 6869 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6870 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6871 Candidate.Function = nullptr; 6872 Candidate.IsSurrogate = false; 6873 Candidate.IgnoreObjectArgument = false; 6874 Candidate.BuiltinTypes.ResultTy = ResultTy; 6875 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6876 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6877 6878 // Determine the implicit conversion sequences for each of the 6879 // arguments. 6880 Candidate.Viable = true; 6881 Candidate.ExplicitCallArguments = Args.size(); 6882 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6883 // C++ [over.match.oper]p4: 6884 // For the built-in assignment operators, conversions of the 6885 // left operand are restricted as follows: 6886 // -- no temporaries are introduced to hold the left operand, and 6887 // -- no user-defined conversions are applied to the left 6888 // operand to achieve a type match with the left-most 6889 // parameter of a built-in candidate. 6890 // 6891 // We block these conversions by turning off user-defined 6892 // conversions, since that is the only way that initialization of 6893 // a reference to a non-class type can occur from something that 6894 // is not of the same type. 6895 if (ArgIdx < NumContextualBoolArguments) { 6896 assert(ParamTys[ArgIdx] == Context.BoolTy && 6897 "Contextual conversion to bool requires bool type"); 6898 Candidate.Conversions[ArgIdx] 6899 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6900 } else { 6901 Candidate.Conversions[ArgIdx] 6902 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6903 ArgIdx == 0 && IsAssignmentOperator, 6904 /*InOverloadResolution=*/false, 6905 /*AllowObjCWritebackConversion=*/ 6906 getLangOpts().ObjCAutoRefCount); 6907 } 6908 if (Candidate.Conversions[ArgIdx].isBad()) { 6909 Candidate.Viable = false; 6910 Candidate.FailureKind = ovl_fail_bad_conversion; 6911 break; 6912 } 6913 } 6914 } 6915 6916 namespace { 6917 6918 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6919 /// candidate operator functions for built-in operators (C++ 6920 /// [over.built]). The types are separated into pointer types and 6921 /// enumeration types. 6922 class BuiltinCandidateTypeSet { 6923 /// TypeSet - A set of types. 6924 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6925 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6926 6927 /// PointerTypes - The set of pointer types that will be used in the 6928 /// built-in candidates. 6929 TypeSet PointerTypes; 6930 6931 /// MemberPointerTypes - The set of member pointer types that will be 6932 /// used in the built-in candidates. 6933 TypeSet MemberPointerTypes; 6934 6935 /// EnumerationTypes - The set of enumeration types that will be 6936 /// used in the built-in candidates. 6937 TypeSet EnumerationTypes; 6938 6939 /// \brief The set of vector types that will be used in the built-in 6940 /// candidates. 6941 TypeSet VectorTypes; 6942 6943 /// \brief A flag indicating non-record types are viable candidates 6944 bool HasNonRecordTypes; 6945 6946 /// \brief A flag indicating whether either arithmetic or enumeration types 6947 /// were present in the candidate set. 6948 bool HasArithmeticOrEnumeralTypes; 6949 6950 /// \brief A flag indicating whether the nullptr type was present in the 6951 /// candidate set. 6952 bool HasNullPtrType; 6953 6954 /// Sema - The semantic analysis instance where we are building the 6955 /// candidate type set. 6956 Sema &SemaRef; 6957 6958 /// Context - The AST context in which we will build the type sets. 6959 ASTContext &Context; 6960 6961 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6962 const Qualifiers &VisibleQuals); 6963 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6964 6965 public: 6966 /// iterator - Iterates through the types that are part of the set. 6967 typedef TypeSet::iterator iterator; 6968 6969 BuiltinCandidateTypeSet(Sema &SemaRef) 6970 : HasNonRecordTypes(false), 6971 HasArithmeticOrEnumeralTypes(false), 6972 HasNullPtrType(false), 6973 SemaRef(SemaRef), 6974 Context(SemaRef.Context) { } 6975 6976 void AddTypesConvertedFrom(QualType Ty, 6977 SourceLocation Loc, 6978 bool AllowUserConversions, 6979 bool AllowExplicitConversions, 6980 const Qualifiers &VisibleTypeConversionsQuals); 6981 6982 /// pointer_begin - First pointer type found; 6983 iterator pointer_begin() { return PointerTypes.begin(); } 6984 6985 /// pointer_end - Past the last pointer type found; 6986 iterator pointer_end() { return PointerTypes.end(); } 6987 6988 /// member_pointer_begin - First member pointer type found; 6989 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6990 6991 /// member_pointer_end - Past the last member pointer type found; 6992 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6993 6994 /// enumeration_begin - First enumeration type found; 6995 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6996 6997 /// enumeration_end - Past the last enumeration type found; 6998 iterator enumeration_end() { return EnumerationTypes.end(); } 6999 7000 iterator vector_begin() { return VectorTypes.begin(); } 7001 iterator vector_end() { return VectorTypes.end(); } 7002 7003 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7004 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7005 bool hasNullPtrType() const { return HasNullPtrType; } 7006 }; 7007 7008 } // end anonymous namespace 7009 7010 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7011 /// the set of pointer types along with any more-qualified variants of 7012 /// that type. For example, if @p Ty is "int const *", this routine 7013 /// will add "int const *", "int const volatile *", "int const 7014 /// restrict *", and "int const volatile restrict *" to the set of 7015 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7016 /// false otherwise. 7017 /// 7018 /// FIXME: what to do about extended qualifiers? 7019 bool 7020 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7021 const Qualifiers &VisibleQuals) { 7022 7023 // Insert this type. 7024 if (!PointerTypes.insert(Ty)) 7025 return false; 7026 7027 QualType PointeeTy; 7028 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7029 bool buildObjCPtr = false; 7030 if (!PointerTy) { 7031 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7032 PointeeTy = PTy->getPointeeType(); 7033 buildObjCPtr = true; 7034 } else { 7035 PointeeTy = PointerTy->getPointeeType(); 7036 } 7037 7038 // Don't add qualified variants of arrays. For one, they're not allowed 7039 // (the qualifier would sink to the element type), and for another, the 7040 // only overload situation where it matters is subscript or pointer +- int, 7041 // and those shouldn't have qualifier variants anyway. 7042 if (PointeeTy->isArrayType()) 7043 return true; 7044 7045 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7046 bool hasVolatile = VisibleQuals.hasVolatile(); 7047 bool hasRestrict = VisibleQuals.hasRestrict(); 7048 7049 // Iterate through all strict supersets of BaseCVR. 7050 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7051 if ((CVR | BaseCVR) != CVR) continue; 7052 // Skip over volatile if no volatile found anywhere in the types. 7053 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7054 7055 // Skip over restrict if no restrict found anywhere in the types, or if 7056 // the type cannot be restrict-qualified. 7057 if ((CVR & Qualifiers::Restrict) && 7058 (!hasRestrict || 7059 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7060 continue; 7061 7062 // Build qualified pointee type. 7063 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7064 7065 // Build qualified pointer type. 7066 QualType QPointerTy; 7067 if (!buildObjCPtr) 7068 QPointerTy = Context.getPointerType(QPointeeTy); 7069 else 7070 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7071 7072 // Insert qualified pointer type. 7073 PointerTypes.insert(QPointerTy); 7074 } 7075 7076 return true; 7077 } 7078 7079 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7080 /// to the set of pointer types along with any more-qualified variants of 7081 /// that type. For example, if @p Ty is "int const *", this routine 7082 /// will add "int const *", "int const volatile *", "int const 7083 /// restrict *", and "int const volatile restrict *" to the set of 7084 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7085 /// false otherwise. 7086 /// 7087 /// FIXME: what to do about extended qualifiers? 7088 bool 7089 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7090 QualType Ty) { 7091 // Insert this type. 7092 if (!MemberPointerTypes.insert(Ty)) 7093 return false; 7094 7095 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7096 assert(PointerTy && "type was not a member pointer type!"); 7097 7098 QualType PointeeTy = PointerTy->getPointeeType(); 7099 // Don't add qualified variants of arrays. For one, they're not allowed 7100 // (the qualifier would sink to the element type), and for another, the 7101 // only overload situation where it matters is subscript or pointer +- int, 7102 // and those shouldn't have qualifier variants anyway. 7103 if (PointeeTy->isArrayType()) 7104 return true; 7105 const Type *ClassTy = PointerTy->getClass(); 7106 7107 // Iterate through all strict supersets of the pointee type's CVR 7108 // qualifiers. 7109 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7110 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7111 if ((CVR | BaseCVR) != CVR) continue; 7112 7113 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7114 MemberPointerTypes.insert( 7115 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7116 } 7117 7118 return true; 7119 } 7120 7121 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7122 /// Ty can be implicit converted to the given set of @p Types. We're 7123 /// primarily interested in pointer types and enumeration types. We also 7124 /// take member pointer types, for the conditional operator. 7125 /// AllowUserConversions is true if we should look at the conversion 7126 /// functions of a class type, and AllowExplicitConversions if we 7127 /// should also include the explicit conversion functions of a class 7128 /// type. 7129 void 7130 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7131 SourceLocation Loc, 7132 bool AllowUserConversions, 7133 bool AllowExplicitConversions, 7134 const Qualifiers &VisibleQuals) { 7135 // Only deal with canonical types. 7136 Ty = Context.getCanonicalType(Ty); 7137 7138 // Look through reference types; they aren't part of the type of an 7139 // expression for the purposes of conversions. 7140 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7141 Ty = RefTy->getPointeeType(); 7142 7143 // If we're dealing with an array type, decay to the pointer. 7144 if (Ty->isArrayType()) 7145 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7146 7147 // Otherwise, we don't care about qualifiers on the type. 7148 Ty = Ty.getLocalUnqualifiedType(); 7149 7150 // Flag if we ever add a non-record type. 7151 const RecordType *TyRec = Ty->getAs<RecordType>(); 7152 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7153 7154 // Flag if we encounter an arithmetic type. 7155 HasArithmeticOrEnumeralTypes = 7156 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7157 7158 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7159 PointerTypes.insert(Ty); 7160 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7161 // Insert our type, and its more-qualified variants, into the set 7162 // of types. 7163 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7164 return; 7165 } else if (Ty->isMemberPointerType()) { 7166 // Member pointers are far easier, since the pointee can't be converted. 7167 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7168 return; 7169 } else if (Ty->isEnumeralType()) { 7170 HasArithmeticOrEnumeralTypes = true; 7171 EnumerationTypes.insert(Ty); 7172 } else if (Ty->isVectorType()) { 7173 // We treat vector types as arithmetic types in many contexts as an 7174 // extension. 7175 HasArithmeticOrEnumeralTypes = true; 7176 VectorTypes.insert(Ty); 7177 } else if (Ty->isNullPtrType()) { 7178 HasNullPtrType = true; 7179 } else if (AllowUserConversions && TyRec) { 7180 // No conversion functions in incomplete types. 7181 if (!SemaRef.isCompleteType(Loc, Ty)) 7182 return; 7183 7184 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7185 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7186 if (isa<UsingShadowDecl>(D)) 7187 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7188 7189 // Skip conversion function templates; they don't tell us anything 7190 // about which builtin types we can convert to. 7191 if (isa<FunctionTemplateDecl>(D)) 7192 continue; 7193 7194 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7195 if (AllowExplicitConversions || !Conv->isExplicit()) { 7196 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7197 VisibleQuals); 7198 } 7199 } 7200 } 7201 } 7202 7203 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7204 /// the volatile- and non-volatile-qualified assignment operators for the 7205 /// given type to the candidate set. 7206 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7207 QualType T, 7208 ArrayRef<Expr *> Args, 7209 OverloadCandidateSet &CandidateSet) { 7210 QualType ParamTypes[2]; 7211 7212 // T& operator=(T&, T) 7213 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7214 ParamTypes[1] = T; 7215 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7216 /*IsAssignmentOperator=*/true); 7217 7218 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7219 // volatile T& operator=(volatile T&, T) 7220 ParamTypes[0] 7221 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7222 ParamTypes[1] = T; 7223 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7224 /*IsAssignmentOperator=*/true); 7225 } 7226 } 7227 7228 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7229 /// if any, found in visible type conversion functions found in ArgExpr's type. 7230 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7231 Qualifiers VRQuals; 7232 const RecordType *TyRec; 7233 if (const MemberPointerType *RHSMPType = 7234 ArgExpr->getType()->getAs<MemberPointerType>()) 7235 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7236 else 7237 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7238 if (!TyRec) { 7239 // Just to be safe, assume the worst case. 7240 VRQuals.addVolatile(); 7241 VRQuals.addRestrict(); 7242 return VRQuals; 7243 } 7244 7245 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7246 if (!ClassDecl->hasDefinition()) 7247 return VRQuals; 7248 7249 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7250 if (isa<UsingShadowDecl>(D)) 7251 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7252 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7253 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7254 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7255 CanTy = ResTypeRef->getPointeeType(); 7256 // Need to go down the pointer/mempointer chain and add qualifiers 7257 // as see them. 7258 bool done = false; 7259 while (!done) { 7260 if (CanTy.isRestrictQualified()) 7261 VRQuals.addRestrict(); 7262 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7263 CanTy = ResTypePtr->getPointeeType(); 7264 else if (const MemberPointerType *ResTypeMPtr = 7265 CanTy->getAs<MemberPointerType>()) 7266 CanTy = ResTypeMPtr->getPointeeType(); 7267 else 7268 done = true; 7269 if (CanTy.isVolatileQualified()) 7270 VRQuals.addVolatile(); 7271 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7272 return VRQuals; 7273 } 7274 } 7275 } 7276 return VRQuals; 7277 } 7278 7279 namespace { 7280 7281 /// \brief Helper class to manage the addition of builtin operator overload 7282 /// candidates. It provides shared state and utility methods used throughout 7283 /// the process, as well as a helper method to add each group of builtin 7284 /// operator overloads from the standard to a candidate set. 7285 class BuiltinOperatorOverloadBuilder { 7286 // Common instance state available to all overload candidate addition methods. 7287 Sema &S; 7288 ArrayRef<Expr *> Args; 7289 Qualifiers VisibleTypeConversionsQuals; 7290 bool HasArithmeticOrEnumeralCandidateType; 7291 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7292 OverloadCandidateSet &CandidateSet; 7293 7294 // Define some constants used to index and iterate over the arithemetic types 7295 // provided via the getArithmeticType() method below. 7296 // The "promoted arithmetic types" are the arithmetic 7297 // types are that preserved by promotion (C++ [over.built]p2). 7298 static const unsigned FirstIntegralType = 4; 7299 static const unsigned LastIntegralType = 21; 7300 static const unsigned FirstPromotedIntegralType = 4, 7301 LastPromotedIntegralType = 12; 7302 static const unsigned FirstPromotedArithmeticType = 0, 7303 LastPromotedArithmeticType = 12; 7304 static const unsigned NumArithmeticTypes = 21; 7305 7306 /// \brief Get the canonical type for a given arithmetic type index. 7307 CanQualType getArithmeticType(unsigned index) { 7308 assert(index < NumArithmeticTypes); 7309 static CanQualType ASTContext::* const 7310 ArithmeticTypes[NumArithmeticTypes] = { 7311 // Start of promoted types. 7312 &ASTContext::FloatTy, 7313 &ASTContext::DoubleTy, 7314 &ASTContext::LongDoubleTy, 7315 &ASTContext::Float128Ty, 7316 7317 // Start of integral types. 7318 &ASTContext::IntTy, 7319 &ASTContext::LongTy, 7320 &ASTContext::LongLongTy, 7321 &ASTContext::Int128Ty, 7322 &ASTContext::UnsignedIntTy, 7323 &ASTContext::UnsignedLongTy, 7324 &ASTContext::UnsignedLongLongTy, 7325 &ASTContext::UnsignedInt128Ty, 7326 // End of promoted types. 7327 7328 &ASTContext::BoolTy, 7329 &ASTContext::CharTy, 7330 &ASTContext::WCharTy, 7331 &ASTContext::Char16Ty, 7332 &ASTContext::Char32Ty, 7333 &ASTContext::SignedCharTy, 7334 &ASTContext::ShortTy, 7335 &ASTContext::UnsignedCharTy, 7336 &ASTContext::UnsignedShortTy, 7337 // End of integral types. 7338 // FIXME: What about complex? What about half? 7339 }; 7340 return S.Context.*ArithmeticTypes[index]; 7341 } 7342 7343 /// \brief Gets the canonical type resulting from the usual arithemetic 7344 /// converions for the given arithmetic types. 7345 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7346 // Accelerator table for performing the usual arithmetic conversions. 7347 // The rules are basically: 7348 // - if either is floating-point, use the wider floating-point 7349 // - if same signedness, use the higher rank 7350 // - if same size, use unsigned of the higher rank 7351 // - use the larger type 7352 // These rules, together with the axiom that higher ranks are 7353 // never smaller, are sufficient to precompute all of these results 7354 // *except* when dealing with signed types of higher rank. 7355 // (we could precompute SLL x UI for all known platforms, but it's 7356 // better not to make any assumptions). 7357 // We assume that int128 has a higher rank than long long on all platforms. 7358 enum PromotedType : int8_t { 7359 Dep=-1, 7360 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7361 }; 7362 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7363 [LastPromotedArithmeticType] = { 7364 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7365 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7366 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7367 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7368 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7369 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7370 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7371 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7372 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7373 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7374 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7375 }; 7376 7377 assert(L < LastPromotedArithmeticType); 7378 assert(R < LastPromotedArithmeticType); 7379 int Idx = ConversionsTable[L][R]; 7380 7381 // Fast path: the table gives us a concrete answer. 7382 if (Idx != Dep) return getArithmeticType(Idx); 7383 7384 // Slow path: we need to compare widths. 7385 // An invariant is that the signed type has higher rank. 7386 CanQualType LT = getArithmeticType(L), 7387 RT = getArithmeticType(R); 7388 unsigned LW = S.Context.getIntWidth(LT), 7389 RW = S.Context.getIntWidth(RT); 7390 7391 // If they're different widths, use the signed type. 7392 if (LW > RW) return LT; 7393 else if (LW < RW) return RT; 7394 7395 // Otherwise, use the unsigned type of the signed type's rank. 7396 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7397 assert(L == SLL || R == SLL); 7398 return S.Context.UnsignedLongLongTy; 7399 } 7400 7401 /// \brief Helper method to factor out the common pattern of adding overloads 7402 /// for '++' and '--' builtin operators. 7403 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7404 bool HasVolatile, 7405 bool HasRestrict) { 7406 QualType ParamTypes[2] = { 7407 S.Context.getLValueReferenceType(CandidateTy), 7408 S.Context.IntTy 7409 }; 7410 7411 // Non-volatile version. 7412 if (Args.size() == 1) 7413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7414 else 7415 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7416 7417 // Use a heuristic to reduce number of builtin candidates in the set: 7418 // add volatile version only if there are conversions to a volatile type. 7419 if (HasVolatile) { 7420 ParamTypes[0] = 7421 S.Context.getLValueReferenceType( 7422 S.Context.getVolatileType(CandidateTy)); 7423 if (Args.size() == 1) 7424 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7425 else 7426 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7427 } 7428 7429 // Add restrict version only if there are conversions to a restrict type 7430 // and our candidate type is a non-restrict-qualified pointer. 7431 if (HasRestrict && CandidateTy->isAnyPointerType() && 7432 !CandidateTy.isRestrictQualified()) { 7433 ParamTypes[0] 7434 = S.Context.getLValueReferenceType( 7435 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7436 if (Args.size() == 1) 7437 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7438 else 7439 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7440 7441 if (HasVolatile) { 7442 ParamTypes[0] 7443 = S.Context.getLValueReferenceType( 7444 S.Context.getCVRQualifiedType(CandidateTy, 7445 (Qualifiers::Volatile | 7446 Qualifiers::Restrict))); 7447 if (Args.size() == 1) 7448 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7449 else 7450 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7451 } 7452 } 7453 7454 } 7455 7456 public: 7457 BuiltinOperatorOverloadBuilder( 7458 Sema &S, ArrayRef<Expr *> Args, 7459 Qualifiers VisibleTypeConversionsQuals, 7460 bool HasArithmeticOrEnumeralCandidateType, 7461 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7462 OverloadCandidateSet &CandidateSet) 7463 : S(S), Args(Args), 7464 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7465 HasArithmeticOrEnumeralCandidateType( 7466 HasArithmeticOrEnumeralCandidateType), 7467 CandidateTypes(CandidateTypes), 7468 CandidateSet(CandidateSet) { 7469 // Validate some of our static helper constants in debug builds. 7470 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7471 "Invalid first promoted integral type"); 7472 assert(getArithmeticType(LastPromotedIntegralType - 1) 7473 == S.Context.UnsignedInt128Ty && 7474 "Invalid last promoted integral type"); 7475 assert(getArithmeticType(FirstPromotedArithmeticType) 7476 == S.Context.FloatTy && 7477 "Invalid first promoted arithmetic type"); 7478 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7479 == S.Context.UnsignedInt128Ty && 7480 "Invalid last promoted arithmetic type"); 7481 } 7482 7483 // C++ [over.built]p3: 7484 // 7485 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7486 // is either volatile or empty, there exist candidate operator 7487 // functions of the form 7488 // 7489 // VQ T& operator++(VQ T&); 7490 // T operator++(VQ T&, int); 7491 // 7492 // C++ [over.built]p4: 7493 // 7494 // For every pair (T, VQ), where T is an arithmetic type other 7495 // than bool, and VQ is either volatile or empty, there exist 7496 // candidate operator functions of the form 7497 // 7498 // VQ T& operator--(VQ T&); 7499 // T operator--(VQ T&, int); 7500 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7501 if (!HasArithmeticOrEnumeralCandidateType) 7502 return; 7503 7504 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7505 Arith < NumArithmeticTypes; ++Arith) { 7506 addPlusPlusMinusMinusStyleOverloads( 7507 getArithmeticType(Arith), 7508 VisibleTypeConversionsQuals.hasVolatile(), 7509 VisibleTypeConversionsQuals.hasRestrict()); 7510 } 7511 } 7512 7513 // C++ [over.built]p5: 7514 // 7515 // For every pair (T, VQ), where T is a cv-qualified or 7516 // cv-unqualified object type, and VQ is either volatile or 7517 // empty, there exist candidate operator functions of the form 7518 // 7519 // T*VQ& operator++(T*VQ&); 7520 // T*VQ& operator--(T*VQ&); 7521 // T* operator++(T*VQ&, int); 7522 // T* operator--(T*VQ&, int); 7523 void addPlusPlusMinusMinusPointerOverloads() { 7524 for (BuiltinCandidateTypeSet::iterator 7525 Ptr = CandidateTypes[0].pointer_begin(), 7526 PtrEnd = CandidateTypes[0].pointer_end(); 7527 Ptr != PtrEnd; ++Ptr) { 7528 // Skip pointer types that aren't pointers to object types. 7529 if (!(*Ptr)->getPointeeType()->isObjectType()) 7530 continue; 7531 7532 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7533 (!(*Ptr).isVolatileQualified() && 7534 VisibleTypeConversionsQuals.hasVolatile()), 7535 (!(*Ptr).isRestrictQualified() && 7536 VisibleTypeConversionsQuals.hasRestrict())); 7537 } 7538 } 7539 7540 // C++ [over.built]p6: 7541 // For every cv-qualified or cv-unqualified object type T, there 7542 // exist candidate operator functions of the form 7543 // 7544 // T& operator*(T*); 7545 // 7546 // C++ [over.built]p7: 7547 // For every function type T that does not have cv-qualifiers or a 7548 // ref-qualifier, there exist candidate operator functions of the form 7549 // T& operator*(T*); 7550 void addUnaryStarPointerOverloads() { 7551 for (BuiltinCandidateTypeSet::iterator 7552 Ptr = CandidateTypes[0].pointer_begin(), 7553 PtrEnd = CandidateTypes[0].pointer_end(); 7554 Ptr != PtrEnd; ++Ptr) { 7555 QualType ParamTy = *Ptr; 7556 QualType PointeeTy = ParamTy->getPointeeType(); 7557 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7558 continue; 7559 7560 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7561 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7562 continue; 7563 7564 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7565 &ParamTy, Args, CandidateSet); 7566 } 7567 } 7568 7569 // C++ [over.built]p9: 7570 // For every promoted arithmetic type T, there exist candidate 7571 // operator functions of the form 7572 // 7573 // T operator+(T); 7574 // T operator-(T); 7575 void addUnaryPlusOrMinusArithmeticOverloads() { 7576 if (!HasArithmeticOrEnumeralCandidateType) 7577 return; 7578 7579 for (unsigned Arith = FirstPromotedArithmeticType; 7580 Arith < LastPromotedArithmeticType; ++Arith) { 7581 QualType ArithTy = getArithmeticType(Arith); 7582 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7583 } 7584 7585 // Extension: We also add these operators for vector types. 7586 for (BuiltinCandidateTypeSet::iterator 7587 Vec = CandidateTypes[0].vector_begin(), 7588 VecEnd = CandidateTypes[0].vector_end(); 7589 Vec != VecEnd; ++Vec) { 7590 QualType VecTy = *Vec; 7591 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7592 } 7593 } 7594 7595 // C++ [over.built]p8: 7596 // For every type T, there exist candidate operator functions of 7597 // the form 7598 // 7599 // T* operator+(T*); 7600 void addUnaryPlusPointerOverloads() { 7601 for (BuiltinCandidateTypeSet::iterator 7602 Ptr = CandidateTypes[0].pointer_begin(), 7603 PtrEnd = CandidateTypes[0].pointer_end(); 7604 Ptr != PtrEnd; ++Ptr) { 7605 QualType ParamTy = *Ptr; 7606 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7607 } 7608 } 7609 7610 // C++ [over.built]p10: 7611 // For every promoted integral type T, there exist candidate 7612 // operator functions of the form 7613 // 7614 // T operator~(T); 7615 void addUnaryTildePromotedIntegralOverloads() { 7616 if (!HasArithmeticOrEnumeralCandidateType) 7617 return; 7618 7619 for (unsigned Int = FirstPromotedIntegralType; 7620 Int < LastPromotedIntegralType; ++Int) { 7621 QualType IntTy = getArithmeticType(Int); 7622 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7623 } 7624 7625 // Extension: We also add this operator for vector types. 7626 for (BuiltinCandidateTypeSet::iterator 7627 Vec = CandidateTypes[0].vector_begin(), 7628 VecEnd = CandidateTypes[0].vector_end(); 7629 Vec != VecEnd; ++Vec) { 7630 QualType VecTy = *Vec; 7631 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7632 } 7633 } 7634 7635 // C++ [over.match.oper]p16: 7636 // For every pointer to member type T or type std::nullptr_t, there 7637 // exist candidate operator functions of the form 7638 // 7639 // bool operator==(T,T); 7640 // bool operator!=(T,T); 7641 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7642 /// Set of (canonical) types that we've already handled. 7643 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7644 7645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7646 for (BuiltinCandidateTypeSet::iterator 7647 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7648 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7649 MemPtr != MemPtrEnd; 7650 ++MemPtr) { 7651 // Don't add the same builtin candidate twice. 7652 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7653 continue; 7654 7655 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7656 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7657 } 7658 7659 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7660 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7661 if (AddedTypes.insert(NullPtrTy).second) { 7662 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7663 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7664 CandidateSet); 7665 } 7666 } 7667 } 7668 } 7669 7670 // C++ [over.built]p15: 7671 // 7672 // For every T, where T is an enumeration type or a pointer type, 7673 // there exist candidate operator functions of the form 7674 // 7675 // bool operator<(T, T); 7676 // bool operator>(T, T); 7677 // bool operator<=(T, T); 7678 // bool operator>=(T, T); 7679 // bool operator==(T, T); 7680 // bool operator!=(T, T); 7681 void addRelationalPointerOrEnumeralOverloads() { 7682 // C++ [over.match.oper]p3: 7683 // [...]the built-in candidates include all of the candidate operator 7684 // functions defined in 13.6 that, compared to the given operator, [...] 7685 // do not have the same parameter-type-list as any non-template non-member 7686 // candidate. 7687 // 7688 // Note that in practice, this only affects enumeration types because there 7689 // aren't any built-in candidates of record type, and a user-defined operator 7690 // must have an operand of record or enumeration type. Also, the only other 7691 // overloaded operator with enumeration arguments, operator=, 7692 // cannot be overloaded for enumeration types, so this is the only place 7693 // where we must suppress candidates like this. 7694 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7695 UserDefinedBinaryOperators; 7696 7697 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7698 if (CandidateTypes[ArgIdx].enumeration_begin() != 7699 CandidateTypes[ArgIdx].enumeration_end()) { 7700 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7701 CEnd = CandidateSet.end(); 7702 C != CEnd; ++C) { 7703 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7704 continue; 7705 7706 if (C->Function->isFunctionTemplateSpecialization()) 7707 continue; 7708 7709 QualType FirstParamType = 7710 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7711 QualType SecondParamType = 7712 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7713 7714 // Skip if either parameter isn't of enumeral type. 7715 if (!FirstParamType->isEnumeralType() || 7716 !SecondParamType->isEnumeralType()) 7717 continue; 7718 7719 // Add this operator to the set of known user-defined operators. 7720 UserDefinedBinaryOperators.insert( 7721 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7722 S.Context.getCanonicalType(SecondParamType))); 7723 } 7724 } 7725 } 7726 7727 /// Set of (canonical) types that we've already handled. 7728 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7729 7730 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7731 for (BuiltinCandidateTypeSet::iterator 7732 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7733 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7734 Ptr != PtrEnd; ++Ptr) { 7735 // Don't add the same builtin candidate twice. 7736 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7737 continue; 7738 7739 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7740 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7741 } 7742 for (BuiltinCandidateTypeSet::iterator 7743 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7744 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7745 Enum != EnumEnd; ++Enum) { 7746 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7747 7748 // Don't add the same builtin candidate twice, or if a user defined 7749 // candidate exists. 7750 if (!AddedTypes.insert(CanonType).second || 7751 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7752 CanonType))) 7753 continue; 7754 7755 QualType ParamTypes[2] = { *Enum, *Enum }; 7756 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7757 } 7758 } 7759 } 7760 7761 // C++ [over.built]p13: 7762 // 7763 // For every cv-qualified or cv-unqualified object type T 7764 // there exist candidate operator functions of the form 7765 // 7766 // T* operator+(T*, ptrdiff_t); 7767 // T& operator[](T*, ptrdiff_t); [BELOW] 7768 // T* operator-(T*, ptrdiff_t); 7769 // T* operator+(ptrdiff_t, T*); 7770 // T& operator[](ptrdiff_t, T*); [BELOW] 7771 // 7772 // C++ [over.built]p14: 7773 // 7774 // For every T, where T is a pointer to object type, there 7775 // exist candidate operator functions of the form 7776 // 7777 // ptrdiff_t operator-(T, T); 7778 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7779 /// Set of (canonical) types that we've already handled. 7780 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7781 7782 for (int Arg = 0; Arg < 2; ++Arg) { 7783 QualType AsymmetricParamTypes[2] = { 7784 S.Context.getPointerDiffType(), 7785 S.Context.getPointerDiffType(), 7786 }; 7787 for (BuiltinCandidateTypeSet::iterator 7788 Ptr = CandidateTypes[Arg].pointer_begin(), 7789 PtrEnd = CandidateTypes[Arg].pointer_end(); 7790 Ptr != PtrEnd; ++Ptr) { 7791 QualType PointeeTy = (*Ptr)->getPointeeType(); 7792 if (!PointeeTy->isObjectType()) 7793 continue; 7794 7795 AsymmetricParamTypes[Arg] = *Ptr; 7796 if (Arg == 0 || Op == OO_Plus) { 7797 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7798 // T* operator+(ptrdiff_t, T*); 7799 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7800 } 7801 if (Op == OO_Minus) { 7802 // ptrdiff_t operator-(T, T); 7803 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7804 continue; 7805 7806 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7807 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7808 Args, CandidateSet); 7809 } 7810 } 7811 } 7812 } 7813 7814 // C++ [over.built]p12: 7815 // 7816 // For every pair of promoted arithmetic types L and R, there 7817 // exist candidate operator functions of the form 7818 // 7819 // LR operator*(L, R); 7820 // LR operator/(L, R); 7821 // LR operator+(L, R); 7822 // LR operator-(L, R); 7823 // bool operator<(L, R); 7824 // bool operator>(L, R); 7825 // bool operator<=(L, R); 7826 // bool operator>=(L, R); 7827 // bool operator==(L, R); 7828 // bool operator!=(L, R); 7829 // 7830 // where LR is the result of the usual arithmetic conversions 7831 // between types L and R. 7832 // 7833 // C++ [over.built]p24: 7834 // 7835 // For every pair of promoted arithmetic types L and R, there exist 7836 // candidate operator functions of the form 7837 // 7838 // LR operator?(bool, L, R); 7839 // 7840 // where LR is the result of the usual arithmetic conversions 7841 // between types L and R. 7842 // Our candidates ignore the first parameter. 7843 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7844 if (!HasArithmeticOrEnumeralCandidateType) 7845 return; 7846 7847 for (unsigned Left = FirstPromotedArithmeticType; 7848 Left < LastPromotedArithmeticType; ++Left) { 7849 for (unsigned Right = FirstPromotedArithmeticType; 7850 Right < LastPromotedArithmeticType; ++Right) { 7851 QualType LandR[2] = { getArithmeticType(Left), 7852 getArithmeticType(Right) }; 7853 QualType Result = 7854 isComparison ? S.Context.BoolTy 7855 : getUsualArithmeticConversions(Left, Right); 7856 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7857 } 7858 } 7859 7860 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7861 // conditional operator for vector types. 7862 for (BuiltinCandidateTypeSet::iterator 7863 Vec1 = CandidateTypes[0].vector_begin(), 7864 Vec1End = CandidateTypes[0].vector_end(); 7865 Vec1 != Vec1End; ++Vec1) { 7866 for (BuiltinCandidateTypeSet::iterator 7867 Vec2 = CandidateTypes[1].vector_begin(), 7868 Vec2End = CandidateTypes[1].vector_end(); 7869 Vec2 != Vec2End; ++Vec2) { 7870 QualType LandR[2] = { *Vec1, *Vec2 }; 7871 QualType Result = S.Context.BoolTy; 7872 if (!isComparison) { 7873 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7874 Result = *Vec1; 7875 else 7876 Result = *Vec2; 7877 } 7878 7879 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7880 } 7881 } 7882 } 7883 7884 // C++ [over.built]p17: 7885 // 7886 // For every pair of promoted integral types L and R, there 7887 // exist candidate operator functions of the form 7888 // 7889 // LR operator%(L, R); 7890 // LR operator&(L, R); 7891 // LR operator^(L, R); 7892 // LR operator|(L, R); 7893 // L operator<<(L, R); 7894 // L operator>>(L, R); 7895 // 7896 // where LR is the result of the usual arithmetic conversions 7897 // between types L and R. 7898 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7899 if (!HasArithmeticOrEnumeralCandidateType) 7900 return; 7901 7902 for (unsigned Left = FirstPromotedIntegralType; 7903 Left < LastPromotedIntegralType; ++Left) { 7904 for (unsigned Right = FirstPromotedIntegralType; 7905 Right < LastPromotedIntegralType; ++Right) { 7906 QualType LandR[2] = { getArithmeticType(Left), 7907 getArithmeticType(Right) }; 7908 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7909 ? LandR[0] 7910 : getUsualArithmeticConversions(Left, Right); 7911 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7912 } 7913 } 7914 } 7915 7916 // C++ [over.built]p20: 7917 // 7918 // For every pair (T, VQ), where T is an enumeration or 7919 // pointer to member type and VQ is either volatile or 7920 // empty, there exist candidate operator functions of the form 7921 // 7922 // VQ T& operator=(VQ T&, T); 7923 void addAssignmentMemberPointerOrEnumeralOverloads() { 7924 /// Set of (canonical) types that we've already handled. 7925 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7926 7927 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7928 for (BuiltinCandidateTypeSet::iterator 7929 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7930 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7931 Enum != EnumEnd; ++Enum) { 7932 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7933 continue; 7934 7935 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7936 } 7937 7938 for (BuiltinCandidateTypeSet::iterator 7939 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7940 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7941 MemPtr != MemPtrEnd; ++MemPtr) { 7942 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7943 continue; 7944 7945 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7946 } 7947 } 7948 } 7949 7950 // C++ [over.built]p19: 7951 // 7952 // For every pair (T, VQ), where T is any type and VQ is either 7953 // volatile or empty, there exist candidate operator functions 7954 // of the form 7955 // 7956 // T*VQ& operator=(T*VQ&, T*); 7957 // 7958 // C++ [over.built]p21: 7959 // 7960 // For every pair (T, VQ), where T is a cv-qualified or 7961 // cv-unqualified object type and VQ is either volatile or 7962 // empty, there exist candidate operator functions of the form 7963 // 7964 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7965 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7966 void addAssignmentPointerOverloads(bool isEqualOp) { 7967 /// Set of (canonical) types that we've already handled. 7968 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7969 7970 for (BuiltinCandidateTypeSet::iterator 7971 Ptr = CandidateTypes[0].pointer_begin(), 7972 PtrEnd = CandidateTypes[0].pointer_end(); 7973 Ptr != PtrEnd; ++Ptr) { 7974 // If this is operator=, keep track of the builtin candidates we added. 7975 if (isEqualOp) 7976 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7977 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7978 continue; 7979 7980 // non-volatile version 7981 QualType ParamTypes[2] = { 7982 S.Context.getLValueReferenceType(*Ptr), 7983 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7984 }; 7985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7986 /*IsAssigmentOperator=*/ isEqualOp); 7987 7988 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7989 VisibleTypeConversionsQuals.hasVolatile(); 7990 if (NeedVolatile) { 7991 // volatile version 7992 ParamTypes[0] = 7993 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7994 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7995 /*IsAssigmentOperator=*/isEqualOp); 7996 } 7997 7998 if (!(*Ptr).isRestrictQualified() && 7999 VisibleTypeConversionsQuals.hasRestrict()) { 8000 // restrict version 8001 ParamTypes[0] 8002 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8003 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8004 /*IsAssigmentOperator=*/isEqualOp); 8005 8006 if (NeedVolatile) { 8007 // volatile restrict version 8008 ParamTypes[0] 8009 = S.Context.getLValueReferenceType( 8010 S.Context.getCVRQualifiedType(*Ptr, 8011 (Qualifiers::Volatile | 8012 Qualifiers::Restrict))); 8013 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8014 /*IsAssigmentOperator=*/isEqualOp); 8015 } 8016 } 8017 } 8018 8019 if (isEqualOp) { 8020 for (BuiltinCandidateTypeSet::iterator 8021 Ptr = CandidateTypes[1].pointer_begin(), 8022 PtrEnd = CandidateTypes[1].pointer_end(); 8023 Ptr != PtrEnd; ++Ptr) { 8024 // Make sure we don't add the same candidate twice. 8025 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8026 continue; 8027 8028 QualType ParamTypes[2] = { 8029 S.Context.getLValueReferenceType(*Ptr), 8030 *Ptr, 8031 }; 8032 8033 // non-volatile version 8034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8035 /*IsAssigmentOperator=*/true); 8036 8037 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8038 VisibleTypeConversionsQuals.hasVolatile(); 8039 if (NeedVolatile) { 8040 // volatile version 8041 ParamTypes[0] = 8042 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8043 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8044 /*IsAssigmentOperator=*/true); 8045 } 8046 8047 if (!(*Ptr).isRestrictQualified() && 8048 VisibleTypeConversionsQuals.hasRestrict()) { 8049 // restrict version 8050 ParamTypes[0] 8051 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8052 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8053 /*IsAssigmentOperator=*/true); 8054 8055 if (NeedVolatile) { 8056 // volatile restrict version 8057 ParamTypes[0] 8058 = S.Context.getLValueReferenceType( 8059 S.Context.getCVRQualifiedType(*Ptr, 8060 (Qualifiers::Volatile | 8061 Qualifiers::Restrict))); 8062 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8063 /*IsAssigmentOperator=*/true); 8064 } 8065 } 8066 } 8067 } 8068 } 8069 8070 // C++ [over.built]p18: 8071 // 8072 // For every triple (L, VQ, R), where L is an arithmetic type, 8073 // VQ is either volatile or empty, and R is a promoted 8074 // arithmetic type, there exist candidate operator functions of 8075 // 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 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8083 if (!HasArithmeticOrEnumeralCandidateType) 8084 return; 8085 8086 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8087 for (unsigned Right = FirstPromotedArithmeticType; 8088 Right < LastPromotedArithmeticType; ++Right) { 8089 QualType ParamTypes[2]; 8090 ParamTypes[1] = getArithmeticType(Right); 8091 8092 // Add this built-in operator as a candidate (VQ is empty). 8093 ParamTypes[0] = 8094 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8096 /*IsAssigmentOperator=*/isEqualOp); 8097 8098 // Add this built-in operator as a candidate (VQ is 'volatile'). 8099 if (VisibleTypeConversionsQuals.hasVolatile()) { 8100 ParamTypes[0] = 8101 S.Context.getVolatileType(getArithmeticType(Left)); 8102 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8104 /*IsAssigmentOperator=*/isEqualOp); 8105 } 8106 } 8107 } 8108 8109 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8110 for (BuiltinCandidateTypeSet::iterator 8111 Vec1 = CandidateTypes[0].vector_begin(), 8112 Vec1End = CandidateTypes[0].vector_end(); 8113 Vec1 != Vec1End; ++Vec1) { 8114 for (BuiltinCandidateTypeSet::iterator 8115 Vec2 = CandidateTypes[1].vector_begin(), 8116 Vec2End = CandidateTypes[1].vector_end(); 8117 Vec2 != Vec2End; ++Vec2) { 8118 QualType ParamTypes[2]; 8119 ParamTypes[1] = *Vec2; 8120 // Add this built-in operator as a candidate (VQ is empty). 8121 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8123 /*IsAssigmentOperator=*/isEqualOp); 8124 8125 // Add this built-in operator as a candidate (VQ is 'volatile'). 8126 if (VisibleTypeConversionsQuals.hasVolatile()) { 8127 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8128 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8129 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8130 /*IsAssigmentOperator=*/isEqualOp); 8131 } 8132 } 8133 } 8134 } 8135 8136 // C++ [over.built]p22: 8137 // 8138 // For every triple (L, VQ, R), where L is an integral type, VQ 8139 // is either volatile or empty, and R is a promoted integral 8140 // type, there exist candidate operator functions of the form 8141 // 8142 // VQ L& operator%=(VQ L&, R); 8143 // VQ L& operator<<=(VQ L&, R); 8144 // VQ L& operator>>=(VQ L&, R); 8145 // VQ L& operator&=(VQ L&, R); 8146 // VQ L& operator^=(VQ L&, R); 8147 // VQ L& operator|=(VQ L&, R); 8148 void addAssignmentIntegralOverloads() { 8149 if (!HasArithmeticOrEnumeralCandidateType) 8150 return; 8151 8152 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8153 for (unsigned Right = FirstPromotedIntegralType; 8154 Right < LastPromotedIntegralType; ++Right) { 8155 QualType ParamTypes[2]; 8156 ParamTypes[1] = getArithmeticType(Right); 8157 8158 // Add this built-in operator as a candidate (VQ is empty). 8159 ParamTypes[0] = 8160 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8161 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8162 if (VisibleTypeConversionsQuals.hasVolatile()) { 8163 // Add this built-in operator as a candidate (VQ is 'volatile'). 8164 ParamTypes[0] = getArithmeticType(Left); 8165 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8166 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8167 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8168 } 8169 } 8170 } 8171 } 8172 8173 // C++ [over.operator]p23: 8174 // 8175 // There also exist candidate operator functions of the form 8176 // 8177 // bool operator!(bool); 8178 // bool operator&&(bool, bool); 8179 // bool operator||(bool, bool); 8180 void addExclaimOverload() { 8181 QualType ParamTy = S.Context.BoolTy; 8182 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8183 /*IsAssignmentOperator=*/false, 8184 /*NumContextualBoolArguments=*/1); 8185 } 8186 void addAmpAmpOrPipePipeOverload() { 8187 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8188 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8189 /*IsAssignmentOperator=*/false, 8190 /*NumContextualBoolArguments=*/2); 8191 } 8192 8193 // C++ [over.built]p13: 8194 // 8195 // For every cv-qualified or cv-unqualified object type T there 8196 // exist candidate operator functions of the form 8197 // 8198 // T* operator+(T*, ptrdiff_t); [ABOVE] 8199 // T& operator[](T*, ptrdiff_t); 8200 // T* operator-(T*, ptrdiff_t); [ABOVE] 8201 // T* operator+(ptrdiff_t, T*); [ABOVE] 8202 // T& operator[](ptrdiff_t, T*); 8203 void addSubscriptOverloads() { 8204 for (BuiltinCandidateTypeSet::iterator 8205 Ptr = CandidateTypes[0].pointer_begin(), 8206 PtrEnd = CandidateTypes[0].pointer_end(); 8207 Ptr != PtrEnd; ++Ptr) { 8208 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8209 QualType PointeeType = (*Ptr)->getPointeeType(); 8210 if (!PointeeType->isObjectType()) 8211 continue; 8212 8213 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8214 8215 // T& operator[](T*, ptrdiff_t) 8216 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8217 } 8218 8219 for (BuiltinCandidateTypeSet::iterator 8220 Ptr = CandidateTypes[1].pointer_begin(), 8221 PtrEnd = CandidateTypes[1].pointer_end(); 8222 Ptr != PtrEnd; ++Ptr) { 8223 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8224 QualType PointeeType = (*Ptr)->getPointeeType(); 8225 if (!PointeeType->isObjectType()) 8226 continue; 8227 8228 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8229 8230 // T& operator[](ptrdiff_t, T*) 8231 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8232 } 8233 } 8234 8235 // C++ [over.built]p11: 8236 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8237 // C1 is the same type as C2 or is a derived class of C2, T is an object 8238 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8239 // there exist candidate operator functions of the form 8240 // 8241 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8242 // 8243 // where CV12 is the union of CV1 and CV2. 8244 void addArrowStarOverloads() { 8245 for (BuiltinCandidateTypeSet::iterator 8246 Ptr = CandidateTypes[0].pointer_begin(), 8247 PtrEnd = CandidateTypes[0].pointer_end(); 8248 Ptr != PtrEnd; ++Ptr) { 8249 QualType C1Ty = (*Ptr); 8250 QualType C1; 8251 QualifierCollector Q1; 8252 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8253 if (!isa<RecordType>(C1)) 8254 continue; 8255 // heuristic to reduce number of builtin candidates in the set. 8256 // Add volatile/restrict version only if there are conversions to a 8257 // volatile/restrict type. 8258 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8259 continue; 8260 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8261 continue; 8262 for (BuiltinCandidateTypeSet::iterator 8263 MemPtr = CandidateTypes[1].member_pointer_begin(), 8264 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8265 MemPtr != MemPtrEnd; ++MemPtr) { 8266 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8267 QualType C2 = QualType(mptr->getClass(), 0); 8268 C2 = C2.getUnqualifiedType(); 8269 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8270 break; 8271 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8272 // build CV12 T& 8273 QualType T = mptr->getPointeeType(); 8274 if (!VisibleTypeConversionsQuals.hasVolatile() && 8275 T.isVolatileQualified()) 8276 continue; 8277 if (!VisibleTypeConversionsQuals.hasRestrict() && 8278 T.isRestrictQualified()) 8279 continue; 8280 T = Q1.apply(S.Context, T); 8281 QualType ResultTy = S.Context.getLValueReferenceType(T); 8282 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8283 } 8284 } 8285 } 8286 8287 // Note that we don't consider the first argument, since it has been 8288 // contextually converted to bool long ago. The candidates below are 8289 // therefore added as binary. 8290 // 8291 // C++ [over.built]p25: 8292 // For every type T, where T is a pointer, pointer-to-member, or scoped 8293 // enumeration type, there exist candidate operator functions of the form 8294 // 8295 // T operator?(bool, T, T); 8296 // 8297 void addConditionalOperatorOverloads() { 8298 /// Set of (canonical) types that we've already handled. 8299 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8300 8301 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8302 for (BuiltinCandidateTypeSet::iterator 8303 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8304 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8305 Ptr != PtrEnd; ++Ptr) { 8306 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8307 continue; 8308 8309 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8310 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8311 } 8312 8313 for (BuiltinCandidateTypeSet::iterator 8314 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8315 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8316 MemPtr != MemPtrEnd; ++MemPtr) { 8317 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8318 continue; 8319 8320 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8321 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8322 } 8323 8324 if (S.getLangOpts().CPlusPlus11) { 8325 for (BuiltinCandidateTypeSet::iterator 8326 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8327 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8328 Enum != EnumEnd; ++Enum) { 8329 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8330 continue; 8331 8332 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8333 continue; 8334 8335 QualType ParamTypes[2] = { *Enum, *Enum }; 8336 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8337 } 8338 } 8339 } 8340 } 8341 }; 8342 8343 } // end anonymous namespace 8344 8345 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8346 /// operator overloads to the candidate set (C++ [over.built]), based 8347 /// on the operator @p Op and the arguments given. For example, if the 8348 /// operator is a binary '+', this routine might add "int 8349 /// operator+(int, int)" to cover integer addition. 8350 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8351 SourceLocation OpLoc, 8352 ArrayRef<Expr *> Args, 8353 OverloadCandidateSet &CandidateSet) { 8354 // Find all of the types that the arguments can convert to, but only 8355 // if the operator we're looking at has built-in operator candidates 8356 // that make use of these types. Also record whether we encounter non-record 8357 // candidate types or either arithmetic or enumeral candidate types. 8358 Qualifiers VisibleTypeConversionsQuals; 8359 VisibleTypeConversionsQuals.addConst(); 8360 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8361 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8362 8363 bool HasNonRecordCandidateType = false; 8364 bool HasArithmeticOrEnumeralCandidateType = false; 8365 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8366 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8367 CandidateTypes.emplace_back(*this); 8368 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8369 OpLoc, 8370 true, 8371 (Op == OO_Exclaim || 8372 Op == OO_AmpAmp || 8373 Op == OO_PipePipe), 8374 VisibleTypeConversionsQuals); 8375 HasNonRecordCandidateType = HasNonRecordCandidateType || 8376 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8377 HasArithmeticOrEnumeralCandidateType = 8378 HasArithmeticOrEnumeralCandidateType || 8379 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8380 } 8381 8382 // Exit early when no non-record types have been added to the candidate set 8383 // for any of the arguments to the operator. 8384 // 8385 // We can't exit early for !, ||, or &&, since there we have always have 8386 // 'bool' overloads. 8387 if (!HasNonRecordCandidateType && 8388 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8389 return; 8390 8391 // Setup an object to manage the common state for building overloads. 8392 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8393 VisibleTypeConversionsQuals, 8394 HasArithmeticOrEnumeralCandidateType, 8395 CandidateTypes, CandidateSet); 8396 8397 // Dispatch over the operation to add in only those overloads which apply. 8398 switch (Op) { 8399 case OO_None: 8400 case NUM_OVERLOADED_OPERATORS: 8401 llvm_unreachable("Expected an overloaded operator"); 8402 8403 case OO_New: 8404 case OO_Delete: 8405 case OO_Array_New: 8406 case OO_Array_Delete: 8407 case OO_Call: 8408 llvm_unreachable( 8409 "Special operators don't use AddBuiltinOperatorCandidates"); 8410 8411 case OO_Comma: 8412 case OO_Arrow: 8413 case OO_Coawait: 8414 // C++ [over.match.oper]p3: 8415 // -- For the operator ',', the unary operator '&', the 8416 // operator '->', or the operator 'co_await', the 8417 // built-in candidates set is empty. 8418 break; 8419 8420 case OO_Plus: // '+' is either unary or binary 8421 if (Args.size() == 1) 8422 OpBuilder.addUnaryPlusPointerOverloads(); 8423 // Fall through. 8424 8425 case OO_Minus: // '-' is either unary or binary 8426 if (Args.size() == 1) { 8427 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8428 } else { 8429 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8430 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8431 } 8432 break; 8433 8434 case OO_Star: // '*' is either unary or binary 8435 if (Args.size() == 1) 8436 OpBuilder.addUnaryStarPointerOverloads(); 8437 else 8438 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8439 break; 8440 8441 case OO_Slash: 8442 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8443 break; 8444 8445 case OO_PlusPlus: 8446 case OO_MinusMinus: 8447 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8448 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8449 break; 8450 8451 case OO_EqualEqual: 8452 case OO_ExclaimEqual: 8453 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8454 // Fall through. 8455 8456 case OO_Less: 8457 case OO_Greater: 8458 case OO_LessEqual: 8459 case OO_GreaterEqual: 8460 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8461 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8462 break; 8463 8464 case OO_Percent: 8465 case OO_Caret: 8466 case OO_Pipe: 8467 case OO_LessLess: 8468 case OO_GreaterGreater: 8469 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8470 break; 8471 8472 case OO_Amp: // '&' is either unary or binary 8473 if (Args.size() == 1) 8474 // C++ [over.match.oper]p3: 8475 // -- For the operator ',', the unary operator '&', or the 8476 // operator '->', the built-in candidates set is empty. 8477 break; 8478 8479 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8480 break; 8481 8482 case OO_Tilde: 8483 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8484 break; 8485 8486 case OO_Equal: 8487 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8488 // Fall through. 8489 8490 case OO_PlusEqual: 8491 case OO_MinusEqual: 8492 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8493 // Fall through. 8494 8495 case OO_StarEqual: 8496 case OO_SlashEqual: 8497 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8498 break; 8499 8500 case OO_PercentEqual: 8501 case OO_LessLessEqual: 8502 case OO_GreaterGreaterEqual: 8503 case OO_AmpEqual: 8504 case OO_CaretEqual: 8505 case OO_PipeEqual: 8506 OpBuilder.addAssignmentIntegralOverloads(); 8507 break; 8508 8509 case OO_Exclaim: 8510 OpBuilder.addExclaimOverload(); 8511 break; 8512 8513 case OO_AmpAmp: 8514 case OO_PipePipe: 8515 OpBuilder.addAmpAmpOrPipePipeOverload(); 8516 break; 8517 8518 case OO_Subscript: 8519 OpBuilder.addSubscriptOverloads(); 8520 break; 8521 8522 case OO_ArrowStar: 8523 OpBuilder.addArrowStarOverloads(); 8524 break; 8525 8526 case OO_Conditional: 8527 OpBuilder.addConditionalOperatorOverloads(); 8528 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8529 break; 8530 } 8531 } 8532 8533 /// \brief Add function candidates found via argument-dependent lookup 8534 /// to the set of overloading candidates. 8535 /// 8536 /// This routine performs argument-dependent name lookup based on the 8537 /// given function name (which may also be an operator name) and adds 8538 /// all of the overload candidates found by ADL to the overload 8539 /// candidate set (C++ [basic.lookup.argdep]). 8540 void 8541 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8542 SourceLocation Loc, 8543 ArrayRef<Expr *> Args, 8544 TemplateArgumentListInfo *ExplicitTemplateArgs, 8545 OverloadCandidateSet& CandidateSet, 8546 bool PartialOverloading) { 8547 ADLResult Fns; 8548 8549 // FIXME: This approach for uniquing ADL results (and removing 8550 // redundant candidates from the set) relies on pointer-equality, 8551 // which means we need to key off the canonical decl. However, 8552 // always going back to the canonical decl might not get us the 8553 // right set of default arguments. What default arguments are 8554 // we supposed to consider on ADL candidates, anyway? 8555 8556 // FIXME: Pass in the explicit template arguments? 8557 ArgumentDependentLookup(Name, Loc, Args, Fns); 8558 8559 // Erase all of the candidates we already knew about. 8560 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8561 CandEnd = CandidateSet.end(); 8562 Cand != CandEnd; ++Cand) 8563 if (Cand->Function) { 8564 Fns.erase(Cand->Function); 8565 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8566 Fns.erase(FunTmpl); 8567 } 8568 8569 // For each of the ADL candidates we found, add it to the overload 8570 // set. 8571 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8572 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8574 if (ExplicitTemplateArgs) 8575 continue; 8576 8577 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8578 PartialOverloading); 8579 } else 8580 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8581 FoundDecl, ExplicitTemplateArgs, 8582 Args, CandidateSet, PartialOverloading); 8583 } 8584 } 8585 8586 namespace { 8587 enum class Comparison { Equal, Better, Worse }; 8588 } 8589 8590 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8591 /// overload resolution. 8592 /// 8593 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8594 /// Cand1's first N enable_if attributes have precisely the same conditions as 8595 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8596 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8597 /// 8598 /// Note that you can have a pair of candidates such that Cand1's enable_if 8599 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8600 /// worse than Cand1's. 8601 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8602 const FunctionDecl *Cand2) { 8603 // Common case: One (or both) decls don't have enable_if attrs. 8604 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8605 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8606 if (!Cand1Attr || !Cand2Attr) { 8607 if (Cand1Attr == Cand2Attr) 8608 return Comparison::Equal; 8609 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8610 } 8611 8612 // FIXME: The next several lines are just 8613 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8614 // instead of reverse order which is how they're stored in the AST. 8615 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8616 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8617 8618 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8619 // has fewer enable_if attributes than Cand2. 8620 if (Cand1Attrs.size() < Cand2Attrs.size()) 8621 return Comparison::Worse; 8622 8623 auto Cand1I = Cand1Attrs.begin(); 8624 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8625 for (auto &Cand2A : Cand2Attrs) { 8626 Cand1ID.clear(); 8627 Cand2ID.clear(); 8628 8629 auto &Cand1A = *Cand1I++; 8630 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8631 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8632 if (Cand1ID != Cand2ID) 8633 return Comparison::Worse; 8634 } 8635 8636 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8637 } 8638 8639 /// isBetterOverloadCandidate - Determines whether the first overload 8640 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8641 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8642 const OverloadCandidate &Cand2, 8643 SourceLocation Loc, 8644 bool UserDefinedConversion) { 8645 // Define viable functions to be better candidates than non-viable 8646 // functions. 8647 if (!Cand2.Viable) 8648 return Cand1.Viable; 8649 else if (!Cand1.Viable) 8650 return false; 8651 8652 // C++ [over.match.best]p1: 8653 // 8654 // -- if F is a static member function, ICS1(F) is defined such 8655 // that ICS1(F) is neither better nor worse than ICS1(G) for 8656 // any function G, and, symmetrically, ICS1(G) is neither 8657 // better nor worse than ICS1(F). 8658 unsigned StartArg = 0; 8659 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8660 StartArg = 1; 8661 8662 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8663 // We don't allow incompatible pointer conversions in C++. 8664 if (!S.getLangOpts().CPlusPlus) 8665 return ICS.isStandard() && 8666 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8667 8668 // The only ill-formed conversion we allow in C++ is the string literal to 8669 // char* conversion, which is only considered ill-formed after C++11. 8670 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8671 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8672 }; 8673 8674 // Define functions that don't require ill-formed conversions for a given 8675 // argument to be better candidates than functions that do. 8676 unsigned NumArgs = Cand1.NumConversions; 8677 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8678 bool HasBetterConversion = false; 8679 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8680 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8681 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8682 if (Cand1Bad != Cand2Bad) { 8683 if (Cand1Bad) 8684 return false; 8685 HasBetterConversion = true; 8686 } 8687 } 8688 8689 if (HasBetterConversion) 8690 return true; 8691 8692 // C++ [over.match.best]p1: 8693 // A viable function F1 is defined to be a better function than another 8694 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8695 // conversion sequence than ICSi(F2), and then... 8696 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8697 switch (CompareImplicitConversionSequences(S, Loc, 8698 Cand1.Conversions[ArgIdx], 8699 Cand2.Conversions[ArgIdx])) { 8700 case ImplicitConversionSequence::Better: 8701 // Cand1 has a better conversion sequence. 8702 HasBetterConversion = true; 8703 break; 8704 8705 case ImplicitConversionSequence::Worse: 8706 // Cand1 can't be better than Cand2. 8707 return false; 8708 8709 case ImplicitConversionSequence::Indistinguishable: 8710 // Do nothing. 8711 break; 8712 } 8713 } 8714 8715 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8716 // ICSj(F2), or, if not that, 8717 if (HasBetterConversion) 8718 return true; 8719 8720 // -- the context is an initialization by user-defined conversion 8721 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8722 // from the return type of F1 to the destination type (i.e., 8723 // the type of the entity being initialized) is a better 8724 // conversion sequence than the standard conversion sequence 8725 // from the return type of F2 to the destination type. 8726 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8727 isa<CXXConversionDecl>(Cand1.Function) && 8728 isa<CXXConversionDecl>(Cand2.Function)) { 8729 // First check whether we prefer one of the conversion functions over the 8730 // other. This only distinguishes the results in non-standard, extension 8731 // cases such as the conversion from a lambda closure type to a function 8732 // pointer or block. 8733 ImplicitConversionSequence::CompareKind Result = 8734 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8735 if (Result == ImplicitConversionSequence::Indistinguishable) 8736 Result = CompareStandardConversionSequences(S, Loc, 8737 Cand1.FinalConversion, 8738 Cand2.FinalConversion); 8739 8740 if (Result != ImplicitConversionSequence::Indistinguishable) 8741 return Result == ImplicitConversionSequence::Better; 8742 8743 // FIXME: Compare kind of reference binding if conversion functions 8744 // convert to a reference type used in direct reference binding, per 8745 // C++14 [over.match.best]p1 section 2 bullet 3. 8746 } 8747 8748 // -- F1 is a non-template function and F2 is a function template 8749 // specialization, or, if not that, 8750 bool Cand1IsSpecialization = Cand1.Function && 8751 Cand1.Function->getPrimaryTemplate(); 8752 bool Cand2IsSpecialization = Cand2.Function && 8753 Cand2.Function->getPrimaryTemplate(); 8754 if (Cand1IsSpecialization != Cand2IsSpecialization) 8755 return Cand2IsSpecialization; 8756 8757 // -- F1 and F2 are function template specializations, and the function 8758 // template for F1 is more specialized than the template for F2 8759 // according to the partial ordering rules described in 14.5.5.2, or, 8760 // if not that, 8761 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8762 if (FunctionTemplateDecl *BetterTemplate 8763 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8764 Cand2.Function->getPrimaryTemplate(), 8765 Loc, 8766 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8767 : TPOC_Call, 8768 Cand1.ExplicitCallArguments, 8769 Cand2.ExplicitCallArguments)) 8770 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8771 } 8772 8773 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8774 // A derived-class constructor beats an (inherited) base class constructor. 8775 bool Cand1IsInherited = 8776 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8777 bool Cand2IsInherited = 8778 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8779 if (Cand1IsInherited != Cand2IsInherited) 8780 return Cand2IsInherited; 8781 else if (Cand1IsInherited) { 8782 assert(Cand2IsInherited); 8783 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8784 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8785 if (Cand1Class->isDerivedFrom(Cand2Class)) 8786 return true; 8787 if (Cand2Class->isDerivedFrom(Cand1Class)) 8788 return false; 8789 // Inherited from sibling base classes: still ambiguous. 8790 } 8791 8792 // Check for enable_if value-based overload resolution. 8793 if (Cand1.Function && Cand2.Function) { 8794 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8795 if (Cmp != Comparison::Equal) 8796 return Cmp == Comparison::Better; 8797 } 8798 8799 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8800 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8801 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8802 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8803 } 8804 8805 bool HasPS1 = Cand1.Function != nullptr && 8806 functionHasPassObjectSizeParams(Cand1.Function); 8807 bool HasPS2 = Cand2.Function != nullptr && 8808 functionHasPassObjectSizeParams(Cand2.Function); 8809 return HasPS1 != HasPS2 && HasPS1; 8810 } 8811 8812 /// Determine whether two declarations are "equivalent" for the purposes of 8813 /// name lookup and overload resolution. This applies when the same internal/no 8814 /// linkage entity is defined by two modules (probably by textually including 8815 /// the same header). In such a case, we don't consider the declarations to 8816 /// declare the same entity, but we also don't want lookups with both 8817 /// declarations visible to be ambiguous in some cases (this happens when using 8818 /// a modularized libstdc++). 8819 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8820 const NamedDecl *B) { 8821 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8822 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8823 if (!VA || !VB) 8824 return false; 8825 8826 // The declarations must be declaring the same name as an internal linkage 8827 // entity in different modules. 8828 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8829 VB->getDeclContext()->getRedeclContext()) || 8830 getOwningModule(const_cast<ValueDecl *>(VA)) == 8831 getOwningModule(const_cast<ValueDecl *>(VB)) || 8832 VA->isExternallyVisible() || VB->isExternallyVisible()) 8833 return false; 8834 8835 // Check that the declarations appear to be equivalent. 8836 // 8837 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8838 // For constants and functions, we should check the initializer or body is 8839 // the same. For non-constant variables, we shouldn't allow it at all. 8840 if (Context.hasSameType(VA->getType(), VB->getType())) 8841 return true; 8842 8843 // Enum constants within unnamed enumerations will have different types, but 8844 // may still be similar enough to be interchangeable for our purposes. 8845 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8846 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8847 // Only handle anonymous enums. If the enumerations were named and 8848 // equivalent, they would have been merged to the same type. 8849 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8850 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8851 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8852 !Context.hasSameType(EnumA->getIntegerType(), 8853 EnumB->getIntegerType())) 8854 return false; 8855 // Allow this only if the value is the same for both enumerators. 8856 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8857 } 8858 } 8859 8860 // Nothing else is sufficiently similar. 8861 return false; 8862 } 8863 8864 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8865 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8866 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8867 8868 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8869 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8870 << !M << (M ? M->getFullModuleName() : ""); 8871 8872 for (auto *E : Equiv) { 8873 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8874 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8875 << !M << (M ? M->getFullModuleName() : ""); 8876 } 8877 } 8878 8879 /// \brief Computes the best viable function (C++ 13.3.3) 8880 /// within an overload candidate set. 8881 /// 8882 /// \param Loc The location of the function name (or operator symbol) for 8883 /// which overload resolution occurs. 8884 /// 8885 /// \param Best If overload resolution was successful or found a deleted 8886 /// function, \p Best points to the candidate function found. 8887 /// 8888 /// \returns The result of overload resolution. 8889 OverloadingResult 8890 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8891 iterator &Best, 8892 bool UserDefinedConversion) { 8893 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8894 std::transform(begin(), end(), std::back_inserter(Candidates), 8895 [](OverloadCandidate &Cand) { return &Cand; }); 8896 8897 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8898 // are accepted by both clang and NVCC. However, during a particular 8899 // compilation mode only one call variant is viable. We need to 8900 // exclude non-viable overload candidates from consideration based 8901 // only on their host/device attributes. Specifically, if one 8902 // candidate call is WrongSide and the other is SameSide, we ignore 8903 // the WrongSide candidate. 8904 if (S.getLangOpts().CUDA) { 8905 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8906 bool ContainsSameSideCandidate = 8907 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8908 return Cand->Function && 8909 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8910 Sema::CFP_SameSide; 8911 }); 8912 if (ContainsSameSideCandidate) { 8913 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8914 return Cand->Function && 8915 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8916 Sema::CFP_WrongSide; 8917 }; 8918 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8919 IsWrongSideCandidate), 8920 Candidates.end()); 8921 } 8922 } 8923 8924 // Find the best viable function. 8925 Best = end(); 8926 for (auto *Cand : Candidates) 8927 if (Cand->Viable) 8928 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8929 UserDefinedConversion)) 8930 Best = Cand; 8931 8932 // If we didn't find any viable functions, abort. 8933 if (Best == end()) 8934 return OR_No_Viable_Function; 8935 8936 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8937 8938 // Make sure that this function is better than every other viable 8939 // function. If not, we have an ambiguity. 8940 for (auto *Cand : Candidates) { 8941 if (Cand->Viable && 8942 Cand != Best && 8943 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8944 UserDefinedConversion)) { 8945 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8946 Cand->Function)) { 8947 EquivalentCands.push_back(Cand->Function); 8948 continue; 8949 } 8950 8951 Best = end(); 8952 return OR_Ambiguous; 8953 } 8954 } 8955 8956 // Best is the best viable function. 8957 if (Best->Function && 8958 (Best->Function->isDeleted() || 8959 S.isFunctionConsideredUnavailable(Best->Function))) 8960 return OR_Deleted; 8961 8962 if (!EquivalentCands.empty()) 8963 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8964 EquivalentCands); 8965 8966 return OR_Success; 8967 } 8968 8969 namespace { 8970 8971 enum OverloadCandidateKind { 8972 oc_function, 8973 oc_method, 8974 oc_constructor, 8975 oc_function_template, 8976 oc_method_template, 8977 oc_constructor_template, 8978 oc_implicit_default_constructor, 8979 oc_implicit_copy_constructor, 8980 oc_implicit_move_constructor, 8981 oc_implicit_copy_assignment, 8982 oc_implicit_move_assignment, 8983 oc_inherited_constructor, 8984 oc_inherited_constructor_template 8985 }; 8986 8987 static OverloadCandidateKind 8988 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 8989 std::string &Description) { 8990 bool isTemplate = false; 8991 8992 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8993 isTemplate = true; 8994 Description = S.getTemplateArgumentBindingsText( 8995 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8996 } 8997 8998 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8999 if (!Ctor->isImplicit()) { 9000 if (isa<ConstructorUsingShadowDecl>(Found)) 9001 return isTemplate ? oc_inherited_constructor_template 9002 : oc_inherited_constructor; 9003 else 9004 return isTemplate ? oc_constructor_template : oc_constructor; 9005 } 9006 9007 if (Ctor->isDefaultConstructor()) 9008 return oc_implicit_default_constructor; 9009 9010 if (Ctor->isMoveConstructor()) 9011 return oc_implicit_move_constructor; 9012 9013 assert(Ctor->isCopyConstructor() && 9014 "unexpected sort of implicit constructor"); 9015 return oc_implicit_copy_constructor; 9016 } 9017 9018 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9019 // This actually gets spelled 'candidate function' for now, but 9020 // it doesn't hurt to split it out. 9021 if (!Meth->isImplicit()) 9022 return isTemplate ? oc_method_template : oc_method; 9023 9024 if (Meth->isMoveAssignmentOperator()) 9025 return oc_implicit_move_assignment; 9026 9027 if (Meth->isCopyAssignmentOperator()) 9028 return oc_implicit_copy_assignment; 9029 9030 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9031 return oc_method; 9032 } 9033 9034 return isTemplate ? oc_function_template : oc_function; 9035 } 9036 9037 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9038 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9039 // set. 9040 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9041 S.Diag(FoundDecl->getLocation(), 9042 diag::note_ovl_candidate_inherited_constructor) 9043 << Shadow->getNominatedBaseClass(); 9044 } 9045 9046 } // end anonymous namespace 9047 9048 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9049 const FunctionDecl *FD) { 9050 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9051 bool AlwaysTrue; 9052 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9053 return false; 9054 if (!AlwaysTrue) 9055 return false; 9056 } 9057 return true; 9058 } 9059 9060 /// \brief Returns true if we can take the address of the function. 9061 /// 9062 /// \param Complain - If true, we'll emit a diagnostic 9063 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9064 /// we in overload resolution? 9065 /// \param Loc - The location of the statement we're complaining about. Ignored 9066 /// if we're not complaining, or if we're in overload resolution. 9067 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9068 bool Complain, 9069 bool InOverloadResolution, 9070 SourceLocation Loc) { 9071 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9072 if (Complain) { 9073 if (InOverloadResolution) 9074 S.Diag(FD->getLocStart(), 9075 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9076 else 9077 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9078 } 9079 return false; 9080 } 9081 9082 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9083 return P->hasAttr<PassObjectSizeAttr>(); 9084 }); 9085 if (I == FD->param_end()) 9086 return true; 9087 9088 if (Complain) { 9089 // Add one to ParamNo because it's user-facing 9090 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9091 if (InOverloadResolution) 9092 S.Diag(FD->getLocation(), 9093 diag::note_ovl_candidate_has_pass_object_size_params) 9094 << ParamNo; 9095 else 9096 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9097 << FD << ParamNo; 9098 } 9099 return false; 9100 } 9101 9102 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9103 const FunctionDecl *FD) { 9104 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9105 /*InOverloadResolution=*/true, 9106 /*Loc=*/SourceLocation()); 9107 } 9108 9109 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9110 bool Complain, 9111 SourceLocation Loc) { 9112 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9113 /*InOverloadResolution=*/false, 9114 Loc); 9115 } 9116 9117 // Notes the location of an overload candidate. 9118 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9119 QualType DestType, bool TakingAddress) { 9120 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9121 return; 9122 9123 std::string FnDesc; 9124 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9125 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9126 << (unsigned) K << FnDesc; 9127 9128 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9129 Diag(Fn->getLocation(), PD); 9130 MaybeEmitInheritedConstructorNote(*this, Found); 9131 } 9132 9133 // Notes the location of all overload candidates designated through 9134 // OverloadedExpr 9135 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9136 bool TakingAddress) { 9137 assert(OverloadedExpr->getType() == Context.OverloadTy); 9138 9139 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9140 OverloadExpr *OvlExpr = Ovl.Expression; 9141 9142 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9143 IEnd = OvlExpr->decls_end(); 9144 I != IEnd; ++I) { 9145 if (FunctionTemplateDecl *FunTmpl = 9146 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9147 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9148 TakingAddress); 9149 } else if (FunctionDecl *Fun 9150 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9151 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9152 } 9153 } 9154 } 9155 9156 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9157 /// "lead" diagnostic; it will be given two arguments, the source and 9158 /// target types of the conversion. 9159 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9160 Sema &S, 9161 SourceLocation CaretLoc, 9162 const PartialDiagnostic &PDiag) const { 9163 S.Diag(CaretLoc, PDiag) 9164 << Ambiguous.getFromType() << Ambiguous.getToType(); 9165 // FIXME: The note limiting machinery is borrowed from 9166 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9167 // refactoring here. 9168 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9169 unsigned CandsShown = 0; 9170 AmbiguousConversionSequence::const_iterator I, E; 9171 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9172 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9173 break; 9174 ++CandsShown; 9175 S.NoteOverloadCandidate(I->first, I->second); 9176 } 9177 if (I != E) 9178 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9179 } 9180 9181 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9182 unsigned I, bool TakingCandidateAddress) { 9183 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9184 assert(Conv.isBad()); 9185 assert(Cand->Function && "for now, candidate must be a function"); 9186 FunctionDecl *Fn = Cand->Function; 9187 9188 // There's a conversion slot for the object argument if this is a 9189 // non-constructor method. Note that 'I' corresponds the 9190 // conversion-slot index. 9191 bool isObjectArgument = false; 9192 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9193 if (I == 0) 9194 isObjectArgument = true; 9195 else 9196 I--; 9197 } 9198 9199 std::string FnDesc; 9200 OverloadCandidateKind FnKind = 9201 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9202 9203 Expr *FromExpr = Conv.Bad.FromExpr; 9204 QualType FromTy = Conv.Bad.getFromType(); 9205 QualType ToTy = Conv.Bad.getToType(); 9206 9207 if (FromTy == S.Context.OverloadTy) { 9208 assert(FromExpr && "overload set argument came from implicit argument?"); 9209 Expr *E = FromExpr->IgnoreParens(); 9210 if (isa<UnaryOperator>(E)) 9211 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9212 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9213 9214 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9215 << (unsigned) FnKind << FnDesc 9216 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9217 << ToTy << Name << I+1; 9218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9219 return; 9220 } 9221 9222 // Do some hand-waving analysis to see if the non-viability is due 9223 // to a qualifier mismatch. 9224 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9225 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9226 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9227 CToTy = RT->getPointeeType(); 9228 else { 9229 // TODO: detect and diagnose the full richness of const mismatches. 9230 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9231 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9232 CFromTy = FromPT->getPointeeType(); 9233 CToTy = ToPT->getPointeeType(); 9234 } 9235 } 9236 9237 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9238 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9239 Qualifiers FromQs = CFromTy.getQualifiers(); 9240 Qualifiers ToQs = CToTy.getQualifiers(); 9241 9242 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9244 << (unsigned) FnKind << FnDesc 9245 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9246 << FromTy 9247 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9248 << (unsigned) isObjectArgument << I+1; 9249 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9250 return; 9251 } 9252 9253 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9254 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9255 << (unsigned) FnKind << FnDesc 9256 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9257 << FromTy 9258 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9259 << (unsigned) isObjectArgument << I+1; 9260 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9261 return; 9262 } 9263 9264 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9265 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9266 << (unsigned) FnKind << FnDesc 9267 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9268 << FromTy 9269 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9270 << (unsigned) isObjectArgument << I+1; 9271 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9272 return; 9273 } 9274 9275 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9277 << (unsigned) FnKind << FnDesc 9278 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9279 << FromTy << FromQs.hasUnaligned() << I+1; 9280 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9281 return; 9282 } 9283 9284 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9285 assert(CVR && "unexpected qualifiers mismatch"); 9286 9287 if (isObjectArgument) { 9288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9289 << (unsigned) FnKind << FnDesc 9290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9291 << FromTy << (CVR - 1); 9292 } else { 9293 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9294 << (unsigned) FnKind << FnDesc 9295 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9296 << FromTy << (CVR - 1) << I+1; 9297 } 9298 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9299 return; 9300 } 9301 9302 // Special diagnostic for failure to convert an initializer list, since 9303 // telling the user that it has type void is not useful. 9304 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9306 << (unsigned) FnKind << FnDesc 9307 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9308 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9309 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9310 return; 9311 } 9312 9313 // Diagnose references or pointers to incomplete types differently, 9314 // since it's far from impossible that the incompleteness triggered 9315 // the failure. 9316 QualType TempFromTy = FromTy.getNonReferenceType(); 9317 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9318 TempFromTy = PTy->getPointeeType(); 9319 if (TempFromTy->isIncompleteType()) { 9320 // Emit the generic diagnostic and, optionally, add the hints to it. 9321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9322 << (unsigned) FnKind << FnDesc 9323 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9324 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9325 << (unsigned) (Cand->Fix.Kind); 9326 9327 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9328 return; 9329 } 9330 9331 // Diagnose base -> derived pointer conversions. 9332 unsigned BaseToDerivedConversion = 0; 9333 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9334 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9335 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9336 FromPtrTy->getPointeeType()) && 9337 !FromPtrTy->getPointeeType()->isIncompleteType() && 9338 !ToPtrTy->getPointeeType()->isIncompleteType() && 9339 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9340 FromPtrTy->getPointeeType())) 9341 BaseToDerivedConversion = 1; 9342 } 9343 } else if (const ObjCObjectPointerType *FromPtrTy 9344 = FromTy->getAs<ObjCObjectPointerType>()) { 9345 if (const ObjCObjectPointerType *ToPtrTy 9346 = ToTy->getAs<ObjCObjectPointerType>()) 9347 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9348 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9349 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9350 FromPtrTy->getPointeeType()) && 9351 FromIface->isSuperClassOf(ToIface)) 9352 BaseToDerivedConversion = 2; 9353 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9354 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9355 !FromTy->isIncompleteType() && 9356 !ToRefTy->getPointeeType()->isIncompleteType() && 9357 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9358 BaseToDerivedConversion = 3; 9359 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9360 ToTy.getNonReferenceType().getCanonicalType() == 9361 FromTy.getNonReferenceType().getCanonicalType()) { 9362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9363 << (unsigned) FnKind << FnDesc 9364 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9365 << (unsigned) isObjectArgument << I + 1; 9366 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9367 return; 9368 } 9369 } 9370 9371 if (BaseToDerivedConversion) { 9372 S.Diag(Fn->getLocation(), 9373 diag::note_ovl_candidate_bad_base_to_derived_conv) 9374 << (unsigned) FnKind << FnDesc 9375 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9376 << (BaseToDerivedConversion - 1) 9377 << FromTy << ToTy << I+1; 9378 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9379 return; 9380 } 9381 9382 if (isa<ObjCObjectPointerType>(CFromTy) && 9383 isa<PointerType>(CToTy)) { 9384 Qualifiers FromQs = CFromTy.getQualifiers(); 9385 Qualifiers ToQs = CToTy.getQualifiers(); 9386 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9388 << (unsigned) FnKind << FnDesc 9389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9390 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9391 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9392 return; 9393 } 9394 } 9395 9396 if (TakingCandidateAddress && 9397 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9398 return; 9399 9400 // Emit the generic diagnostic and, optionally, add the hints to it. 9401 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9402 FDiag << (unsigned) FnKind << FnDesc 9403 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9404 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9405 << (unsigned) (Cand->Fix.Kind); 9406 9407 // If we can fix the conversion, suggest the FixIts. 9408 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9409 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9410 FDiag << *HI; 9411 S.Diag(Fn->getLocation(), FDiag); 9412 9413 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9414 } 9415 9416 /// Additional arity mismatch diagnosis specific to a function overload 9417 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9418 /// over a candidate in any candidate set. 9419 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9420 unsigned NumArgs) { 9421 FunctionDecl *Fn = Cand->Function; 9422 unsigned MinParams = Fn->getMinRequiredArguments(); 9423 9424 // With invalid overloaded operators, it's possible that we think we 9425 // have an arity mismatch when in fact it looks like we have the 9426 // right number of arguments, because only overloaded operators have 9427 // the weird behavior of overloading member and non-member functions. 9428 // Just don't report anything. 9429 if (Fn->isInvalidDecl() && 9430 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9431 return true; 9432 9433 if (NumArgs < MinParams) { 9434 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9435 (Cand->FailureKind == ovl_fail_bad_deduction && 9436 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9437 } else { 9438 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9439 (Cand->FailureKind == ovl_fail_bad_deduction && 9440 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9441 } 9442 9443 return false; 9444 } 9445 9446 /// General arity mismatch diagnosis over a candidate in a candidate set. 9447 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9448 unsigned NumFormalArgs) { 9449 assert(isa<FunctionDecl>(D) && 9450 "The templated declaration should at least be a function" 9451 " when diagnosing bad template argument deduction due to too many" 9452 " or too few arguments"); 9453 9454 FunctionDecl *Fn = cast<FunctionDecl>(D); 9455 9456 // TODO: treat calls to a missing default constructor as a special case 9457 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9458 unsigned MinParams = Fn->getMinRequiredArguments(); 9459 9460 // at least / at most / exactly 9461 unsigned mode, modeCount; 9462 if (NumFormalArgs < MinParams) { 9463 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9464 FnTy->isTemplateVariadic()) 9465 mode = 0; // "at least" 9466 else 9467 mode = 2; // "exactly" 9468 modeCount = MinParams; 9469 } else { 9470 if (MinParams != FnTy->getNumParams()) 9471 mode = 1; // "at most" 9472 else 9473 mode = 2; // "exactly" 9474 modeCount = FnTy->getNumParams(); 9475 } 9476 9477 std::string Description; 9478 OverloadCandidateKind FnKind = 9479 ClassifyOverloadCandidate(S, Found, Fn, Description); 9480 9481 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9482 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9483 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9484 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9485 else 9486 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9487 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9488 << mode << modeCount << NumFormalArgs; 9489 MaybeEmitInheritedConstructorNote(S, Found); 9490 } 9491 9492 /// Arity mismatch diagnosis specific to a function overload candidate. 9493 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9494 unsigned NumFormalArgs) { 9495 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9496 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9497 } 9498 9499 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9500 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9501 return TD; 9502 llvm_unreachable("Unsupported: Getting the described template declaration" 9503 " for bad deduction diagnosis"); 9504 } 9505 9506 /// Diagnose a failed template-argument deduction. 9507 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9508 DeductionFailureInfo &DeductionFailure, 9509 unsigned NumArgs, 9510 bool TakingCandidateAddress) { 9511 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9512 NamedDecl *ParamD; 9513 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9514 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9515 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9516 switch (DeductionFailure.Result) { 9517 case Sema::TDK_Success: 9518 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9519 9520 case Sema::TDK_Incomplete: { 9521 assert(ParamD && "no parameter found for incomplete deduction result"); 9522 S.Diag(Templated->getLocation(), 9523 diag::note_ovl_candidate_incomplete_deduction) 9524 << ParamD->getDeclName(); 9525 MaybeEmitInheritedConstructorNote(S, Found); 9526 return; 9527 } 9528 9529 case Sema::TDK_Underqualified: { 9530 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9531 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9532 9533 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9534 9535 // Param will have been canonicalized, but it should just be a 9536 // qualified version of ParamD, so move the qualifiers to that. 9537 QualifierCollector Qs; 9538 Qs.strip(Param); 9539 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9540 assert(S.Context.hasSameType(Param, NonCanonParam)); 9541 9542 // Arg has also been canonicalized, but there's nothing we can do 9543 // about that. It also doesn't matter as much, because it won't 9544 // have any template parameters in it (because deduction isn't 9545 // done on dependent types). 9546 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9547 9548 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9549 << ParamD->getDeclName() << Arg << NonCanonParam; 9550 MaybeEmitInheritedConstructorNote(S, Found); 9551 return; 9552 } 9553 9554 case Sema::TDK_Inconsistent: { 9555 assert(ParamD && "no parameter found for inconsistent deduction result"); 9556 int which = 0; 9557 if (isa<TemplateTypeParmDecl>(ParamD)) 9558 which = 0; 9559 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9560 which = 1; 9561 else { 9562 which = 2; 9563 } 9564 9565 S.Diag(Templated->getLocation(), 9566 diag::note_ovl_candidate_inconsistent_deduction) 9567 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9568 << *DeductionFailure.getSecondArg(); 9569 MaybeEmitInheritedConstructorNote(S, Found); 9570 return; 9571 } 9572 9573 case Sema::TDK_InvalidExplicitArguments: 9574 assert(ParamD && "no parameter found for invalid explicit arguments"); 9575 if (ParamD->getDeclName()) 9576 S.Diag(Templated->getLocation(), 9577 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9578 << ParamD->getDeclName(); 9579 else { 9580 int index = 0; 9581 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9582 index = TTP->getIndex(); 9583 else if (NonTypeTemplateParmDecl *NTTP 9584 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9585 index = NTTP->getIndex(); 9586 else 9587 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9588 S.Diag(Templated->getLocation(), 9589 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9590 << (index + 1); 9591 } 9592 MaybeEmitInheritedConstructorNote(S, Found); 9593 return; 9594 9595 case Sema::TDK_TooManyArguments: 9596 case Sema::TDK_TooFewArguments: 9597 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9598 return; 9599 9600 case Sema::TDK_InstantiationDepth: 9601 S.Diag(Templated->getLocation(), 9602 diag::note_ovl_candidate_instantiation_depth); 9603 MaybeEmitInheritedConstructorNote(S, Found); 9604 return; 9605 9606 case Sema::TDK_SubstitutionFailure: { 9607 // Format the template argument list into the argument string. 9608 SmallString<128> TemplateArgString; 9609 if (TemplateArgumentList *Args = 9610 DeductionFailure.getTemplateArgumentList()) { 9611 TemplateArgString = " "; 9612 TemplateArgString += S.getTemplateArgumentBindingsText( 9613 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9614 } 9615 9616 // If this candidate was disabled by enable_if, say so. 9617 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9618 if (PDiag && PDiag->second.getDiagID() == 9619 diag::err_typename_nested_not_found_enable_if) { 9620 // FIXME: Use the source range of the condition, and the fully-qualified 9621 // name of the enable_if template. These are both present in PDiag. 9622 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9623 << "'enable_if'" << TemplateArgString; 9624 return; 9625 } 9626 9627 // Format the SFINAE diagnostic into the argument string. 9628 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9629 // formatted message in another diagnostic. 9630 SmallString<128> SFINAEArgString; 9631 SourceRange R; 9632 if (PDiag) { 9633 SFINAEArgString = ": "; 9634 R = SourceRange(PDiag->first, PDiag->first); 9635 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9636 } 9637 9638 S.Diag(Templated->getLocation(), 9639 diag::note_ovl_candidate_substitution_failure) 9640 << TemplateArgString << SFINAEArgString << R; 9641 MaybeEmitInheritedConstructorNote(S, Found); 9642 return; 9643 } 9644 9645 case Sema::TDK_FailedOverloadResolution: { 9646 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9647 S.Diag(Templated->getLocation(), 9648 diag::note_ovl_candidate_failed_overload_resolution) 9649 << R.Expression->getName(); 9650 return; 9651 } 9652 9653 case Sema::TDK_DeducedMismatch: { 9654 // Format the template argument list into the argument string. 9655 SmallString<128> TemplateArgString; 9656 if (TemplateArgumentList *Args = 9657 DeductionFailure.getTemplateArgumentList()) { 9658 TemplateArgString = " "; 9659 TemplateArgString += S.getTemplateArgumentBindingsText( 9660 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9661 } 9662 9663 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9664 << (*DeductionFailure.getCallArgIndex() + 1) 9665 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9666 << TemplateArgString; 9667 break; 9668 } 9669 9670 case Sema::TDK_NonDeducedMismatch: { 9671 // FIXME: Provide a source location to indicate what we couldn't match. 9672 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9673 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9674 if (FirstTA.getKind() == TemplateArgument::Template && 9675 SecondTA.getKind() == TemplateArgument::Template) { 9676 TemplateName FirstTN = FirstTA.getAsTemplate(); 9677 TemplateName SecondTN = SecondTA.getAsTemplate(); 9678 if (FirstTN.getKind() == TemplateName::Template && 9679 SecondTN.getKind() == TemplateName::Template) { 9680 if (FirstTN.getAsTemplateDecl()->getName() == 9681 SecondTN.getAsTemplateDecl()->getName()) { 9682 // FIXME: This fixes a bad diagnostic where both templates are named 9683 // the same. This particular case is a bit difficult since: 9684 // 1) It is passed as a string to the diagnostic printer. 9685 // 2) The diagnostic printer only attempts to find a better 9686 // name for types, not decls. 9687 // Ideally, this should folded into the diagnostic printer. 9688 S.Diag(Templated->getLocation(), 9689 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9690 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9691 return; 9692 } 9693 } 9694 } 9695 9696 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9697 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9698 return; 9699 9700 // FIXME: For generic lambda parameters, check if the function is a lambda 9701 // call operator, and if so, emit a prettier and more informative 9702 // diagnostic that mentions 'auto' and lambda in addition to 9703 // (or instead of?) the canonical template type parameters. 9704 S.Diag(Templated->getLocation(), 9705 diag::note_ovl_candidate_non_deduced_mismatch) 9706 << FirstTA << SecondTA; 9707 return; 9708 } 9709 // TODO: diagnose these individually, then kill off 9710 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9711 case Sema::TDK_MiscellaneousDeductionFailure: 9712 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9713 MaybeEmitInheritedConstructorNote(S, Found); 9714 return; 9715 } 9716 } 9717 9718 /// Diagnose a failed template-argument deduction, for function calls. 9719 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9720 unsigned NumArgs, 9721 bool TakingCandidateAddress) { 9722 unsigned TDK = Cand->DeductionFailure.Result; 9723 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9724 if (CheckArityMismatch(S, Cand, NumArgs)) 9725 return; 9726 } 9727 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9728 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9729 } 9730 9731 /// CUDA: diagnose an invalid call across targets. 9732 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9733 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9734 FunctionDecl *Callee = Cand->Function; 9735 9736 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9737 CalleeTarget = S.IdentifyCUDATarget(Callee); 9738 9739 std::string FnDesc; 9740 OverloadCandidateKind FnKind = 9741 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9742 9743 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9744 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9745 9746 // This could be an implicit constructor for which we could not infer the 9747 // target due to a collsion. Diagnose that case. 9748 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9749 if (Meth != nullptr && Meth->isImplicit()) { 9750 CXXRecordDecl *ParentClass = Meth->getParent(); 9751 Sema::CXXSpecialMember CSM; 9752 9753 switch (FnKind) { 9754 default: 9755 return; 9756 case oc_implicit_default_constructor: 9757 CSM = Sema::CXXDefaultConstructor; 9758 break; 9759 case oc_implicit_copy_constructor: 9760 CSM = Sema::CXXCopyConstructor; 9761 break; 9762 case oc_implicit_move_constructor: 9763 CSM = Sema::CXXMoveConstructor; 9764 break; 9765 case oc_implicit_copy_assignment: 9766 CSM = Sema::CXXCopyAssignment; 9767 break; 9768 case oc_implicit_move_assignment: 9769 CSM = Sema::CXXMoveAssignment; 9770 break; 9771 }; 9772 9773 bool ConstRHS = false; 9774 if (Meth->getNumParams()) { 9775 if (const ReferenceType *RT = 9776 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9777 ConstRHS = RT->getPointeeType().isConstQualified(); 9778 } 9779 } 9780 9781 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9782 /* ConstRHS */ ConstRHS, 9783 /* Diagnose */ true); 9784 } 9785 } 9786 9787 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9788 FunctionDecl *Callee = Cand->Function; 9789 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9790 9791 S.Diag(Callee->getLocation(), 9792 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9793 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9794 } 9795 9796 /// Generates a 'note' diagnostic for an overload candidate. We've 9797 /// already generated a primary error at the call site. 9798 /// 9799 /// It really does need to be a single diagnostic with its caret 9800 /// pointed at the candidate declaration. Yes, this creates some 9801 /// major challenges of technical writing. Yes, this makes pointing 9802 /// out problems with specific arguments quite awkward. It's still 9803 /// better than generating twenty screens of text for every failed 9804 /// overload. 9805 /// 9806 /// It would be great to be able to express per-candidate problems 9807 /// more richly for those diagnostic clients that cared, but we'd 9808 /// still have to be just as careful with the default diagnostics. 9809 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9810 unsigned NumArgs, 9811 bool TakingCandidateAddress) { 9812 FunctionDecl *Fn = Cand->Function; 9813 9814 // Note deleted candidates, but only if they're viable. 9815 if (Cand->Viable && (Fn->isDeleted() || 9816 S.isFunctionConsideredUnavailable(Fn))) { 9817 std::string FnDesc; 9818 OverloadCandidateKind FnKind = 9819 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9820 9821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9822 << FnKind << FnDesc 9823 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9825 return; 9826 } 9827 9828 // We don't really have anything else to say about viable candidates. 9829 if (Cand->Viable) { 9830 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9831 return; 9832 } 9833 9834 switch (Cand->FailureKind) { 9835 case ovl_fail_too_many_arguments: 9836 case ovl_fail_too_few_arguments: 9837 return DiagnoseArityMismatch(S, Cand, NumArgs); 9838 9839 case ovl_fail_bad_deduction: 9840 return DiagnoseBadDeduction(S, Cand, NumArgs, 9841 TakingCandidateAddress); 9842 9843 case ovl_fail_illegal_constructor: { 9844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9845 << (Fn->getPrimaryTemplate() ? 1 : 0); 9846 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9847 return; 9848 } 9849 9850 case ovl_fail_trivial_conversion: 9851 case ovl_fail_bad_final_conversion: 9852 case ovl_fail_final_conversion_not_exact: 9853 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9854 9855 case ovl_fail_bad_conversion: { 9856 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9857 for (unsigned N = Cand->NumConversions; I != N; ++I) 9858 if (Cand->Conversions[I].isBad()) 9859 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9860 9861 // FIXME: this currently happens when we're called from SemaInit 9862 // when user-conversion overload fails. Figure out how to handle 9863 // those conditions and diagnose them well. 9864 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9865 } 9866 9867 case ovl_fail_bad_target: 9868 return DiagnoseBadTarget(S, Cand); 9869 9870 case ovl_fail_enable_if: 9871 return DiagnoseFailedEnableIfAttr(S, Cand); 9872 9873 case ovl_fail_addr_not_available: { 9874 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9875 (void)Available; 9876 assert(!Available); 9877 break; 9878 } 9879 } 9880 } 9881 9882 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9883 // Desugar the type of the surrogate down to a function type, 9884 // retaining as many typedefs as possible while still showing 9885 // the function type (and, therefore, its parameter types). 9886 QualType FnType = Cand->Surrogate->getConversionType(); 9887 bool isLValueReference = false; 9888 bool isRValueReference = false; 9889 bool isPointer = false; 9890 if (const LValueReferenceType *FnTypeRef = 9891 FnType->getAs<LValueReferenceType>()) { 9892 FnType = FnTypeRef->getPointeeType(); 9893 isLValueReference = true; 9894 } else if (const RValueReferenceType *FnTypeRef = 9895 FnType->getAs<RValueReferenceType>()) { 9896 FnType = FnTypeRef->getPointeeType(); 9897 isRValueReference = true; 9898 } 9899 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9900 FnType = FnTypePtr->getPointeeType(); 9901 isPointer = true; 9902 } 9903 // Desugar down to a function type. 9904 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9905 // Reconstruct the pointer/reference as appropriate. 9906 if (isPointer) FnType = S.Context.getPointerType(FnType); 9907 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9908 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9909 9910 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9911 << FnType; 9912 } 9913 9914 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9915 SourceLocation OpLoc, 9916 OverloadCandidate *Cand) { 9917 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9918 std::string TypeStr("operator"); 9919 TypeStr += Opc; 9920 TypeStr += "("; 9921 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9922 if (Cand->NumConversions == 1) { 9923 TypeStr += ")"; 9924 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9925 } else { 9926 TypeStr += ", "; 9927 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9928 TypeStr += ")"; 9929 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9930 } 9931 } 9932 9933 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9934 OverloadCandidate *Cand) { 9935 unsigned NoOperands = Cand->NumConversions; 9936 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9937 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9938 if (ICS.isBad()) break; // all meaningless after first invalid 9939 if (!ICS.isAmbiguous()) continue; 9940 9941 ICS.DiagnoseAmbiguousConversion( 9942 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9943 } 9944 } 9945 9946 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9947 if (Cand->Function) 9948 return Cand->Function->getLocation(); 9949 if (Cand->IsSurrogate) 9950 return Cand->Surrogate->getLocation(); 9951 return SourceLocation(); 9952 } 9953 9954 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9955 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9956 case Sema::TDK_Success: 9957 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9958 9959 case Sema::TDK_Invalid: 9960 case Sema::TDK_Incomplete: 9961 return 1; 9962 9963 case Sema::TDK_Underqualified: 9964 case Sema::TDK_Inconsistent: 9965 return 2; 9966 9967 case Sema::TDK_SubstitutionFailure: 9968 case Sema::TDK_DeducedMismatch: 9969 case Sema::TDK_NonDeducedMismatch: 9970 case Sema::TDK_MiscellaneousDeductionFailure: 9971 return 3; 9972 9973 case Sema::TDK_InstantiationDepth: 9974 case Sema::TDK_FailedOverloadResolution: 9975 return 4; 9976 9977 case Sema::TDK_InvalidExplicitArguments: 9978 return 5; 9979 9980 case Sema::TDK_TooManyArguments: 9981 case Sema::TDK_TooFewArguments: 9982 return 6; 9983 } 9984 llvm_unreachable("Unhandled deduction result"); 9985 } 9986 9987 namespace { 9988 struct CompareOverloadCandidatesForDisplay { 9989 Sema &S; 9990 SourceLocation Loc; 9991 size_t NumArgs; 9992 9993 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9994 : S(S), NumArgs(nArgs) {} 9995 9996 bool operator()(const OverloadCandidate *L, 9997 const OverloadCandidate *R) { 9998 // Fast-path this check. 9999 if (L == R) return false; 10000 10001 // Order first by viability. 10002 if (L->Viable) { 10003 if (!R->Viable) return true; 10004 10005 // TODO: introduce a tri-valued comparison for overload 10006 // candidates. Would be more worthwhile if we had a sort 10007 // that could exploit it. 10008 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10009 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10010 } else if (R->Viable) 10011 return false; 10012 10013 assert(L->Viable == R->Viable); 10014 10015 // Criteria by which we can sort non-viable candidates: 10016 if (!L->Viable) { 10017 // 1. Arity mismatches come after other candidates. 10018 if (L->FailureKind == ovl_fail_too_many_arguments || 10019 L->FailureKind == ovl_fail_too_few_arguments) { 10020 if (R->FailureKind == ovl_fail_too_many_arguments || 10021 R->FailureKind == ovl_fail_too_few_arguments) { 10022 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10023 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10024 if (LDist == RDist) { 10025 if (L->FailureKind == R->FailureKind) 10026 // Sort non-surrogates before surrogates. 10027 return !L->IsSurrogate && R->IsSurrogate; 10028 // Sort candidates requiring fewer parameters than there were 10029 // arguments given after candidates requiring more parameters 10030 // than there were arguments given. 10031 return L->FailureKind == ovl_fail_too_many_arguments; 10032 } 10033 return LDist < RDist; 10034 } 10035 return false; 10036 } 10037 if (R->FailureKind == ovl_fail_too_many_arguments || 10038 R->FailureKind == ovl_fail_too_few_arguments) 10039 return true; 10040 10041 // 2. Bad conversions come first and are ordered by the number 10042 // of bad conversions and quality of good conversions. 10043 if (L->FailureKind == ovl_fail_bad_conversion) { 10044 if (R->FailureKind != ovl_fail_bad_conversion) 10045 return true; 10046 10047 // The conversion that can be fixed with a smaller number of changes, 10048 // comes first. 10049 unsigned numLFixes = L->Fix.NumConversionsFixed; 10050 unsigned numRFixes = R->Fix.NumConversionsFixed; 10051 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10052 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10053 if (numLFixes != numRFixes) { 10054 return numLFixes < numRFixes; 10055 } 10056 10057 // If there's any ordering between the defined conversions... 10058 // FIXME: this might not be transitive. 10059 assert(L->NumConversions == R->NumConversions); 10060 10061 int leftBetter = 0; 10062 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10063 for (unsigned E = L->NumConversions; I != E; ++I) { 10064 switch (CompareImplicitConversionSequences(S, Loc, 10065 L->Conversions[I], 10066 R->Conversions[I])) { 10067 case ImplicitConversionSequence::Better: 10068 leftBetter++; 10069 break; 10070 10071 case ImplicitConversionSequence::Worse: 10072 leftBetter--; 10073 break; 10074 10075 case ImplicitConversionSequence::Indistinguishable: 10076 break; 10077 } 10078 } 10079 if (leftBetter > 0) return true; 10080 if (leftBetter < 0) return false; 10081 10082 } else if (R->FailureKind == ovl_fail_bad_conversion) 10083 return false; 10084 10085 if (L->FailureKind == ovl_fail_bad_deduction) { 10086 if (R->FailureKind != ovl_fail_bad_deduction) 10087 return true; 10088 10089 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10090 return RankDeductionFailure(L->DeductionFailure) 10091 < RankDeductionFailure(R->DeductionFailure); 10092 } else if (R->FailureKind == ovl_fail_bad_deduction) 10093 return false; 10094 10095 // TODO: others? 10096 } 10097 10098 // Sort everything else by location. 10099 SourceLocation LLoc = GetLocationForCandidate(L); 10100 SourceLocation RLoc = GetLocationForCandidate(R); 10101 10102 // Put candidates without locations (e.g. builtins) at the end. 10103 if (LLoc.isInvalid()) return false; 10104 if (RLoc.isInvalid()) return true; 10105 10106 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10107 } 10108 }; 10109 } 10110 10111 /// CompleteNonViableCandidate - Normally, overload resolution only 10112 /// computes up to the first. Produces the FixIt set if possible. 10113 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10114 ArrayRef<Expr *> Args) { 10115 assert(!Cand->Viable); 10116 10117 // Don't do anything on failures other than bad conversion. 10118 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10119 10120 // We only want the FixIts if all the arguments can be corrected. 10121 bool Unfixable = false; 10122 // Use a implicit copy initialization to check conversion fixes. 10123 Cand->Fix.setConversionChecker(TryCopyInitialization); 10124 10125 // Skip forward to the first bad conversion. 10126 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10127 unsigned ConvCount = Cand->NumConversions; 10128 while (true) { 10129 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10130 ConvIdx++; 10131 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10132 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10133 break; 10134 } 10135 } 10136 10137 if (ConvIdx == ConvCount) 10138 return; 10139 10140 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10141 "remaining conversion is initialized?"); 10142 10143 // FIXME: this should probably be preserved from the overload 10144 // operation somehow. 10145 bool SuppressUserConversions = false; 10146 10147 const FunctionProtoType* Proto; 10148 unsigned ArgIdx = ConvIdx; 10149 10150 if (Cand->IsSurrogate) { 10151 QualType ConvType 10152 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10153 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10154 ConvType = ConvPtrType->getPointeeType(); 10155 Proto = ConvType->getAs<FunctionProtoType>(); 10156 ArgIdx--; 10157 } else if (Cand->Function) { 10158 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10159 if (isa<CXXMethodDecl>(Cand->Function) && 10160 !isa<CXXConstructorDecl>(Cand->Function)) 10161 ArgIdx--; 10162 } else { 10163 // Builtin binary operator with a bad first conversion. 10164 assert(ConvCount <= 3); 10165 for (; ConvIdx != ConvCount; ++ConvIdx) 10166 Cand->Conversions[ConvIdx] 10167 = TryCopyInitialization(S, Args[ConvIdx], 10168 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10169 SuppressUserConversions, 10170 /*InOverloadResolution*/ true, 10171 /*AllowObjCWritebackConversion=*/ 10172 S.getLangOpts().ObjCAutoRefCount); 10173 return; 10174 } 10175 10176 // Fill in the rest of the conversions. 10177 unsigned NumParams = Proto->getNumParams(); 10178 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10179 if (ArgIdx < NumParams) { 10180 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10181 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10182 /*InOverloadResolution=*/true, 10183 /*AllowObjCWritebackConversion=*/ 10184 S.getLangOpts().ObjCAutoRefCount); 10185 // Store the FixIt in the candidate if it exists. 10186 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10187 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10188 } 10189 else 10190 Cand->Conversions[ConvIdx].setEllipsis(); 10191 } 10192 } 10193 10194 /// PrintOverloadCandidates - When overload resolution fails, prints 10195 /// diagnostic messages containing the candidates in the candidate 10196 /// set. 10197 void OverloadCandidateSet::NoteCandidates( 10198 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10199 StringRef Opc, SourceLocation OpLoc, 10200 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10201 // Sort the candidates by viability and position. Sorting directly would 10202 // be prohibitive, so we make a set of pointers and sort those. 10203 SmallVector<OverloadCandidate*, 32> Cands; 10204 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10205 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10206 if (!Filter(*Cand)) 10207 continue; 10208 if (Cand->Viable) 10209 Cands.push_back(Cand); 10210 else if (OCD == OCD_AllCandidates) { 10211 CompleteNonViableCandidate(S, Cand, Args); 10212 if (Cand->Function || Cand->IsSurrogate) 10213 Cands.push_back(Cand); 10214 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10215 // want to list every possible builtin candidate. 10216 } 10217 } 10218 10219 std::sort(Cands.begin(), Cands.end(), 10220 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10221 10222 bool ReportedAmbiguousConversions = false; 10223 10224 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10225 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10226 unsigned CandsShown = 0; 10227 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10228 OverloadCandidate *Cand = *I; 10229 10230 // Set an arbitrary limit on the number of candidate functions we'll spam 10231 // the user with. FIXME: This limit should depend on details of the 10232 // candidate list. 10233 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10234 break; 10235 } 10236 ++CandsShown; 10237 10238 if (Cand->Function) 10239 NoteFunctionCandidate(S, Cand, Args.size(), 10240 /*TakingCandidateAddress=*/false); 10241 else if (Cand->IsSurrogate) 10242 NoteSurrogateCandidate(S, Cand); 10243 else { 10244 assert(Cand->Viable && 10245 "Non-viable built-in candidates are not added to Cands."); 10246 // Generally we only see ambiguities including viable builtin 10247 // operators if overload resolution got screwed up by an 10248 // ambiguous user-defined conversion. 10249 // 10250 // FIXME: It's quite possible for different conversions to see 10251 // different ambiguities, though. 10252 if (!ReportedAmbiguousConversions) { 10253 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10254 ReportedAmbiguousConversions = true; 10255 } 10256 10257 // If this is a viable builtin, print it. 10258 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10259 } 10260 } 10261 10262 if (I != E) 10263 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10264 } 10265 10266 static SourceLocation 10267 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10268 return Cand->Specialization ? Cand->Specialization->getLocation() 10269 : SourceLocation(); 10270 } 10271 10272 namespace { 10273 struct CompareTemplateSpecCandidatesForDisplay { 10274 Sema &S; 10275 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10276 10277 bool operator()(const TemplateSpecCandidate *L, 10278 const TemplateSpecCandidate *R) { 10279 // Fast-path this check. 10280 if (L == R) 10281 return false; 10282 10283 // Assuming that both candidates are not matches... 10284 10285 // Sort by the ranking of deduction failures. 10286 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10287 return RankDeductionFailure(L->DeductionFailure) < 10288 RankDeductionFailure(R->DeductionFailure); 10289 10290 // Sort everything else by location. 10291 SourceLocation LLoc = GetLocationForCandidate(L); 10292 SourceLocation RLoc = GetLocationForCandidate(R); 10293 10294 // Put candidates without locations (e.g. builtins) at the end. 10295 if (LLoc.isInvalid()) 10296 return false; 10297 if (RLoc.isInvalid()) 10298 return true; 10299 10300 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10301 } 10302 }; 10303 } 10304 10305 /// Diagnose a template argument deduction failure. 10306 /// We are treating these failures as overload failures due to bad 10307 /// deductions. 10308 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10309 bool ForTakingAddress) { 10310 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10311 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10312 } 10313 10314 void TemplateSpecCandidateSet::destroyCandidates() { 10315 for (iterator i = begin(), e = end(); i != e; ++i) { 10316 i->DeductionFailure.Destroy(); 10317 } 10318 } 10319 10320 void TemplateSpecCandidateSet::clear() { 10321 destroyCandidates(); 10322 Candidates.clear(); 10323 } 10324 10325 /// NoteCandidates - When no template specialization match is found, prints 10326 /// diagnostic messages containing the non-matching specializations that form 10327 /// the candidate set. 10328 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10329 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10330 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10331 // Sort the candidates by position (assuming no candidate is a match). 10332 // Sorting directly would be prohibitive, so we make a set of pointers 10333 // and sort those. 10334 SmallVector<TemplateSpecCandidate *, 32> Cands; 10335 Cands.reserve(size()); 10336 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10337 if (Cand->Specialization) 10338 Cands.push_back(Cand); 10339 // Otherwise, this is a non-matching builtin candidate. We do not, 10340 // in general, want to list every possible builtin candidate. 10341 } 10342 10343 std::sort(Cands.begin(), Cands.end(), 10344 CompareTemplateSpecCandidatesForDisplay(S)); 10345 10346 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10347 // for generalization purposes (?). 10348 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10349 10350 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10351 unsigned CandsShown = 0; 10352 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10353 TemplateSpecCandidate *Cand = *I; 10354 10355 // Set an arbitrary limit on the number of candidates we'll spam 10356 // the user with. FIXME: This limit should depend on details of the 10357 // candidate list. 10358 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10359 break; 10360 ++CandsShown; 10361 10362 assert(Cand->Specialization && 10363 "Non-matching built-in candidates are not added to Cands."); 10364 Cand->NoteDeductionFailure(S, ForTakingAddress); 10365 } 10366 10367 if (I != E) 10368 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10369 } 10370 10371 // [PossiblyAFunctionType] --> [Return] 10372 // NonFunctionType --> NonFunctionType 10373 // R (A) --> R(A) 10374 // R (*)(A) --> R (A) 10375 // R (&)(A) --> R (A) 10376 // R (S::*)(A) --> R (A) 10377 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10378 QualType Ret = PossiblyAFunctionType; 10379 if (const PointerType *ToTypePtr = 10380 PossiblyAFunctionType->getAs<PointerType>()) 10381 Ret = ToTypePtr->getPointeeType(); 10382 else if (const ReferenceType *ToTypeRef = 10383 PossiblyAFunctionType->getAs<ReferenceType>()) 10384 Ret = ToTypeRef->getPointeeType(); 10385 else if (const MemberPointerType *MemTypePtr = 10386 PossiblyAFunctionType->getAs<MemberPointerType>()) 10387 Ret = MemTypePtr->getPointeeType(); 10388 Ret = 10389 Context.getCanonicalType(Ret).getUnqualifiedType(); 10390 return Ret; 10391 } 10392 10393 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10394 bool Complain = true) { 10395 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10396 S.DeduceReturnType(FD, Loc, Complain)) 10397 return true; 10398 10399 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10400 if (S.getLangOpts().CPlusPlus1z && 10401 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10402 !S.ResolveExceptionSpec(Loc, FPT)) 10403 return true; 10404 10405 return false; 10406 } 10407 10408 namespace { 10409 // A helper class to help with address of function resolution 10410 // - allows us to avoid passing around all those ugly parameters 10411 class AddressOfFunctionResolver { 10412 Sema& S; 10413 Expr* SourceExpr; 10414 const QualType& TargetType; 10415 QualType TargetFunctionType; // Extracted function type from target type 10416 10417 bool Complain; 10418 //DeclAccessPair& ResultFunctionAccessPair; 10419 ASTContext& Context; 10420 10421 bool TargetTypeIsNonStaticMemberFunction; 10422 bool FoundNonTemplateFunction; 10423 bool StaticMemberFunctionFromBoundPointer; 10424 bool HasComplained; 10425 10426 OverloadExpr::FindResult OvlExprInfo; 10427 OverloadExpr *OvlExpr; 10428 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10429 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10430 TemplateSpecCandidateSet FailedCandidates; 10431 10432 public: 10433 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10434 const QualType &TargetType, bool Complain) 10435 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10436 Complain(Complain), Context(S.getASTContext()), 10437 TargetTypeIsNonStaticMemberFunction( 10438 !!TargetType->getAs<MemberPointerType>()), 10439 FoundNonTemplateFunction(false), 10440 StaticMemberFunctionFromBoundPointer(false), 10441 HasComplained(false), 10442 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10443 OvlExpr(OvlExprInfo.Expression), 10444 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10445 ExtractUnqualifiedFunctionTypeFromTargetType(); 10446 10447 if (TargetFunctionType->isFunctionType()) { 10448 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10449 if (!UME->isImplicitAccess() && 10450 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10451 StaticMemberFunctionFromBoundPointer = true; 10452 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10453 DeclAccessPair dap; 10454 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10455 OvlExpr, false, &dap)) { 10456 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10457 if (!Method->isStatic()) { 10458 // If the target type is a non-function type and the function found 10459 // is a non-static member function, pretend as if that was the 10460 // target, it's the only possible type to end up with. 10461 TargetTypeIsNonStaticMemberFunction = true; 10462 10463 // And skip adding the function if its not in the proper form. 10464 // We'll diagnose this due to an empty set of functions. 10465 if (!OvlExprInfo.HasFormOfMemberPointer) 10466 return; 10467 } 10468 10469 Matches.push_back(std::make_pair(dap, Fn)); 10470 } 10471 return; 10472 } 10473 10474 if (OvlExpr->hasExplicitTemplateArgs()) 10475 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10476 10477 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10478 // C++ [over.over]p4: 10479 // If more than one function is selected, [...] 10480 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10481 if (FoundNonTemplateFunction) 10482 EliminateAllTemplateMatches(); 10483 else 10484 EliminateAllExceptMostSpecializedTemplate(); 10485 } 10486 } 10487 10488 if (S.getLangOpts().CUDA && Matches.size() > 1) 10489 EliminateSuboptimalCudaMatches(); 10490 } 10491 10492 bool hasComplained() const { return HasComplained; } 10493 10494 private: 10495 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10496 QualType Discard; 10497 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10498 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10499 } 10500 10501 /// \return true if A is considered a better overload candidate for the 10502 /// desired type than B. 10503 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10504 // If A doesn't have exactly the correct type, we don't want to classify it 10505 // as "better" than anything else. This way, the user is required to 10506 // disambiguate for us if there are multiple candidates and no exact match. 10507 return candidateHasExactlyCorrectType(A) && 10508 (!candidateHasExactlyCorrectType(B) || 10509 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10510 } 10511 10512 /// \return true if we were able to eliminate all but one overload candidate, 10513 /// false otherwise. 10514 bool eliminiateSuboptimalOverloadCandidates() { 10515 // Same algorithm as overload resolution -- one pass to pick the "best", 10516 // another pass to be sure that nothing is better than the best. 10517 auto Best = Matches.begin(); 10518 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10519 if (isBetterCandidate(I->second, Best->second)) 10520 Best = I; 10521 10522 const FunctionDecl *BestFn = Best->second; 10523 auto IsBestOrInferiorToBest = [this, BestFn]( 10524 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10525 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10526 }; 10527 10528 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10529 // option, so we can potentially give the user a better error 10530 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10531 return false; 10532 Matches[0] = *Best; 10533 Matches.resize(1); 10534 return true; 10535 } 10536 10537 bool isTargetTypeAFunction() const { 10538 return TargetFunctionType->isFunctionType(); 10539 } 10540 10541 // [ToType] [Return] 10542 10543 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10544 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10545 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10546 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10547 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10548 } 10549 10550 // return true if any matching specializations were found 10551 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10552 const DeclAccessPair& CurAccessFunPair) { 10553 if (CXXMethodDecl *Method 10554 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10555 // Skip non-static function templates when converting to pointer, and 10556 // static when converting to member pointer. 10557 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10558 return false; 10559 } 10560 else if (TargetTypeIsNonStaticMemberFunction) 10561 return false; 10562 10563 // C++ [over.over]p2: 10564 // If the name is a function template, template argument deduction is 10565 // done (14.8.2.2), and if the argument deduction succeeds, the 10566 // resulting template argument list is used to generate a single 10567 // function template specialization, which is added to the set of 10568 // overloaded functions considered. 10569 FunctionDecl *Specialization = nullptr; 10570 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10571 if (Sema::TemplateDeductionResult Result 10572 = S.DeduceTemplateArguments(FunctionTemplate, 10573 &OvlExplicitTemplateArgs, 10574 TargetFunctionType, Specialization, 10575 Info, /*InOverloadResolution=*/true)) { 10576 // Make a note of the failed deduction for diagnostics. 10577 FailedCandidates.addCandidate() 10578 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10579 MakeDeductionFailureInfo(Context, Result, Info)); 10580 return false; 10581 } 10582 10583 // Template argument deduction ensures that we have an exact match or 10584 // compatible pointer-to-function arguments that would be adjusted by ICS. 10585 // This function template specicalization works. 10586 assert(S.isSameOrCompatibleFunctionType( 10587 Context.getCanonicalType(Specialization->getType()), 10588 Context.getCanonicalType(TargetFunctionType))); 10589 10590 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10591 return false; 10592 10593 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10594 return true; 10595 } 10596 10597 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10598 const DeclAccessPair& CurAccessFunPair) { 10599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10600 // Skip non-static functions when converting to pointer, and static 10601 // when converting to member pointer. 10602 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10603 return false; 10604 } 10605 else if (TargetTypeIsNonStaticMemberFunction) 10606 return false; 10607 10608 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10609 if (S.getLangOpts().CUDA) 10610 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10611 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10612 return false; 10613 10614 // If any candidate has a placeholder return type, trigger its deduction 10615 // now. 10616 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10617 Complain)) { 10618 HasComplained |= Complain; 10619 return false; 10620 } 10621 10622 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10623 return false; 10624 10625 // If we're in C, we need to support types that aren't exactly identical. 10626 if (!S.getLangOpts().CPlusPlus || 10627 candidateHasExactlyCorrectType(FunDecl)) { 10628 Matches.push_back(std::make_pair( 10629 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10630 FoundNonTemplateFunction = true; 10631 return true; 10632 } 10633 } 10634 10635 return false; 10636 } 10637 10638 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10639 bool Ret = false; 10640 10641 // If the overload expression doesn't have the form of a pointer to 10642 // member, don't try to convert it to a pointer-to-member type. 10643 if (IsInvalidFormOfPointerToMemberFunction()) 10644 return false; 10645 10646 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10647 E = OvlExpr->decls_end(); 10648 I != E; ++I) { 10649 // Look through any using declarations to find the underlying function. 10650 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10651 10652 // C++ [over.over]p3: 10653 // Non-member functions and static member functions match 10654 // targets of type "pointer-to-function" or "reference-to-function." 10655 // Nonstatic member functions match targets of 10656 // type "pointer-to-member-function." 10657 // Note that according to DR 247, the containing class does not matter. 10658 if (FunctionTemplateDecl *FunctionTemplate 10659 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10660 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10661 Ret = true; 10662 } 10663 // If we have explicit template arguments supplied, skip non-templates. 10664 else if (!OvlExpr->hasExplicitTemplateArgs() && 10665 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10666 Ret = true; 10667 } 10668 assert(Ret || Matches.empty()); 10669 return Ret; 10670 } 10671 10672 void EliminateAllExceptMostSpecializedTemplate() { 10673 // [...] and any given function template specialization F1 is 10674 // eliminated if the set contains a second function template 10675 // specialization whose function template is more specialized 10676 // than the function template of F1 according to the partial 10677 // ordering rules of 14.5.5.2. 10678 10679 // The algorithm specified above is quadratic. We instead use a 10680 // two-pass algorithm (similar to the one used to identify the 10681 // best viable function in an overload set) that identifies the 10682 // best function template (if it exists). 10683 10684 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10685 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10686 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10687 10688 // TODO: It looks like FailedCandidates does not serve much purpose 10689 // here, since the no_viable diagnostic has index 0. 10690 UnresolvedSetIterator Result = S.getMostSpecialized( 10691 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10692 SourceExpr->getLocStart(), S.PDiag(), 10693 S.PDiag(diag::err_addr_ovl_ambiguous) 10694 << Matches[0].second->getDeclName(), 10695 S.PDiag(diag::note_ovl_candidate) 10696 << (unsigned)oc_function_template, 10697 Complain, TargetFunctionType); 10698 10699 if (Result != MatchesCopy.end()) { 10700 // Make it the first and only element 10701 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10702 Matches[0].second = cast<FunctionDecl>(*Result); 10703 Matches.resize(1); 10704 } else 10705 HasComplained |= Complain; 10706 } 10707 10708 void EliminateAllTemplateMatches() { 10709 // [...] any function template specializations in the set are 10710 // eliminated if the set also contains a non-template function, [...] 10711 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10712 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10713 ++I; 10714 else { 10715 Matches[I] = Matches[--N]; 10716 Matches.resize(N); 10717 } 10718 } 10719 } 10720 10721 void EliminateSuboptimalCudaMatches() { 10722 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10723 } 10724 10725 public: 10726 void ComplainNoMatchesFound() const { 10727 assert(Matches.empty()); 10728 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10729 << OvlExpr->getName() << TargetFunctionType 10730 << OvlExpr->getSourceRange(); 10731 if (FailedCandidates.empty()) 10732 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10733 /*TakingAddress=*/true); 10734 else { 10735 // We have some deduction failure messages. Use them to diagnose 10736 // the function templates, and diagnose the non-template candidates 10737 // normally. 10738 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10739 IEnd = OvlExpr->decls_end(); 10740 I != IEnd; ++I) 10741 if (FunctionDecl *Fun = 10742 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10743 if (!functionHasPassObjectSizeParams(Fun)) 10744 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10745 /*TakingAddress=*/true); 10746 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10747 } 10748 } 10749 10750 bool IsInvalidFormOfPointerToMemberFunction() const { 10751 return TargetTypeIsNonStaticMemberFunction && 10752 !OvlExprInfo.HasFormOfMemberPointer; 10753 } 10754 10755 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10756 // TODO: Should we condition this on whether any functions might 10757 // have matched, or is it more appropriate to do that in callers? 10758 // TODO: a fixit wouldn't hurt. 10759 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10760 << TargetType << OvlExpr->getSourceRange(); 10761 } 10762 10763 bool IsStaticMemberFunctionFromBoundPointer() const { 10764 return StaticMemberFunctionFromBoundPointer; 10765 } 10766 10767 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10768 S.Diag(OvlExpr->getLocStart(), 10769 diag::err_invalid_form_pointer_member_function) 10770 << OvlExpr->getSourceRange(); 10771 } 10772 10773 void ComplainOfInvalidConversion() const { 10774 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10775 << OvlExpr->getName() << TargetType; 10776 } 10777 10778 void ComplainMultipleMatchesFound() const { 10779 assert(Matches.size() > 1); 10780 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10781 << OvlExpr->getName() 10782 << OvlExpr->getSourceRange(); 10783 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10784 /*TakingAddress=*/true); 10785 } 10786 10787 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10788 10789 int getNumMatches() const { return Matches.size(); } 10790 10791 FunctionDecl* getMatchingFunctionDecl() const { 10792 if (Matches.size() != 1) return nullptr; 10793 return Matches[0].second; 10794 } 10795 10796 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10797 if (Matches.size() != 1) return nullptr; 10798 return &Matches[0].first; 10799 } 10800 }; 10801 } 10802 10803 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10804 /// an overloaded function (C++ [over.over]), where @p From is an 10805 /// expression with overloaded function type and @p ToType is the type 10806 /// we're trying to resolve to. For example: 10807 /// 10808 /// @code 10809 /// int f(double); 10810 /// int f(int); 10811 /// 10812 /// int (*pfd)(double) = f; // selects f(double) 10813 /// @endcode 10814 /// 10815 /// This routine returns the resulting FunctionDecl if it could be 10816 /// resolved, and NULL otherwise. When @p Complain is true, this 10817 /// routine will emit diagnostics if there is an error. 10818 FunctionDecl * 10819 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10820 QualType TargetType, 10821 bool Complain, 10822 DeclAccessPair &FoundResult, 10823 bool *pHadMultipleCandidates) { 10824 assert(AddressOfExpr->getType() == Context.OverloadTy); 10825 10826 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10827 Complain); 10828 int NumMatches = Resolver.getNumMatches(); 10829 FunctionDecl *Fn = nullptr; 10830 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10831 if (NumMatches == 0 && ShouldComplain) { 10832 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10833 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10834 else 10835 Resolver.ComplainNoMatchesFound(); 10836 } 10837 else if (NumMatches > 1 && ShouldComplain) 10838 Resolver.ComplainMultipleMatchesFound(); 10839 else if (NumMatches == 1) { 10840 Fn = Resolver.getMatchingFunctionDecl(); 10841 assert(Fn); 10842 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 10843 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 10844 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10845 if (Complain) { 10846 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10847 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10848 else 10849 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10850 } 10851 } 10852 10853 if (pHadMultipleCandidates) 10854 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10855 return Fn; 10856 } 10857 10858 /// \brief Given an expression that refers to an overloaded function, try to 10859 /// resolve that function to a single function that can have its address taken. 10860 /// This will modify `Pair` iff it returns non-null. 10861 /// 10862 /// This routine can only realistically succeed if all but one candidates in the 10863 /// overload set for SrcExpr cannot have their addresses taken. 10864 FunctionDecl * 10865 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10866 DeclAccessPair &Pair) { 10867 OverloadExpr::FindResult R = OverloadExpr::find(E); 10868 OverloadExpr *Ovl = R.Expression; 10869 FunctionDecl *Result = nullptr; 10870 DeclAccessPair DAP; 10871 // Don't use the AddressOfResolver because we're specifically looking for 10872 // cases where we have one overload candidate that lacks 10873 // enable_if/pass_object_size/... 10874 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10875 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10876 if (!FD) 10877 return nullptr; 10878 10879 if (!checkAddressOfFunctionIsAvailable(FD)) 10880 continue; 10881 10882 // We have more than one result; quit. 10883 if (Result) 10884 return nullptr; 10885 DAP = I.getPair(); 10886 Result = FD; 10887 } 10888 10889 if (Result) 10890 Pair = DAP; 10891 return Result; 10892 } 10893 10894 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10895 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10896 /// will perform access checks, diagnose the use of the resultant decl, and, if 10897 /// necessary, perform a function-to-pointer decay. 10898 /// 10899 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10900 /// Otherwise, returns true. This may emit diagnostics and return true. 10901 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10902 ExprResult &SrcExpr) { 10903 Expr *E = SrcExpr.get(); 10904 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10905 10906 DeclAccessPair DAP; 10907 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10908 if (!Found) 10909 return false; 10910 10911 // Emitting multiple diagnostics for a function that is both inaccessible and 10912 // unavailable is consistent with our behavior elsewhere. So, always check 10913 // for both. 10914 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10915 CheckAddressOfMemberAccess(E, DAP); 10916 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10917 if (Fixed->getType()->isFunctionType()) 10918 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10919 else 10920 SrcExpr = Fixed; 10921 return true; 10922 } 10923 10924 /// \brief Given an expression that refers to an overloaded function, try to 10925 /// resolve that overloaded function expression down to a single function. 10926 /// 10927 /// This routine can only resolve template-ids that refer to a single function 10928 /// template, where that template-id refers to a single template whose template 10929 /// arguments are either provided by the template-id or have defaults, 10930 /// as described in C++0x [temp.arg.explicit]p3. 10931 /// 10932 /// If no template-ids are found, no diagnostics are emitted and NULL is 10933 /// returned. 10934 FunctionDecl * 10935 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10936 bool Complain, 10937 DeclAccessPair *FoundResult) { 10938 // C++ [over.over]p1: 10939 // [...] [Note: any redundant set of parentheses surrounding the 10940 // overloaded function name is ignored (5.1). ] 10941 // C++ [over.over]p1: 10942 // [...] The overloaded function name can be preceded by the & 10943 // operator. 10944 10945 // If we didn't actually find any template-ids, we're done. 10946 if (!ovl->hasExplicitTemplateArgs()) 10947 return nullptr; 10948 10949 TemplateArgumentListInfo ExplicitTemplateArgs; 10950 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10951 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10952 10953 // Look through all of the overloaded functions, searching for one 10954 // whose type matches exactly. 10955 FunctionDecl *Matched = nullptr; 10956 for (UnresolvedSetIterator I = ovl->decls_begin(), 10957 E = ovl->decls_end(); I != E; ++I) { 10958 // C++0x [temp.arg.explicit]p3: 10959 // [...] In contexts where deduction is done and fails, or in contexts 10960 // where deduction is not done, if a template argument list is 10961 // specified and it, along with any default template arguments, 10962 // identifies a single function template specialization, then the 10963 // template-id is an lvalue for the function template specialization. 10964 FunctionTemplateDecl *FunctionTemplate 10965 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10966 10967 // C++ [over.over]p2: 10968 // If the name is a function template, template argument deduction is 10969 // done (14.8.2.2), and if the argument deduction succeeds, the 10970 // resulting template argument list is used to generate a single 10971 // function template specialization, which is added to the set of 10972 // overloaded functions considered. 10973 FunctionDecl *Specialization = nullptr; 10974 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10975 if (TemplateDeductionResult Result 10976 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10977 Specialization, Info, 10978 /*InOverloadResolution=*/true)) { 10979 // Make a note of the failed deduction for diagnostics. 10980 // TODO: Actually use the failed-deduction info? 10981 FailedCandidates.addCandidate() 10982 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 10983 MakeDeductionFailureInfo(Context, Result, Info)); 10984 continue; 10985 } 10986 10987 assert(Specialization && "no specialization and no error?"); 10988 10989 // Multiple matches; we can't resolve to a single declaration. 10990 if (Matched) { 10991 if (Complain) { 10992 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10993 << ovl->getName(); 10994 NoteAllOverloadCandidates(ovl); 10995 } 10996 return nullptr; 10997 } 10998 10999 Matched = Specialization; 11000 if (FoundResult) *FoundResult = I.getPair(); 11001 } 11002 11003 if (Matched && 11004 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11005 return nullptr; 11006 11007 return Matched; 11008 } 11009 11010 11011 11012 11013 // Resolve and fix an overloaded expression that can be resolved 11014 // because it identifies a single function template specialization. 11015 // 11016 // Last three arguments should only be supplied if Complain = true 11017 // 11018 // Return true if it was logically possible to so resolve the 11019 // expression, regardless of whether or not it succeeded. Always 11020 // returns true if 'complain' is set. 11021 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11022 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11023 bool complain, SourceRange OpRangeForComplaining, 11024 QualType DestTypeForComplaining, 11025 unsigned DiagIDForComplaining) { 11026 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11027 11028 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11029 11030 DeclAccessPair found; 11031 ExprResult SingleFunctionExpression; 11032 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11033 ovl.Expression, /*complain*/ false, &found)) { 11034 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11035 SrcExpr = ExprError(); 11036 return true; 11037 } 11038 11039 // It is only correct to resolve to an instance method if we're 11040 // resolving a form that's permitted to be a pointer to member. 11041 // Otherwise we'll end up making a bound member expression, which 11042 // is illegal in all the contexts we resolve like this. 11043 if (!ovl.HasFormOfMemberPointer && 11044 isa<CXXMethodDecl>(fn) && 11045 cast<CXXMethodDecl>(fn)->isInstance()) { 11046 if (!complain) return false; 11047 11048 Diag(ovl.Expression->getExprLoc(), 11049 diag::err_bound_member_function) 11050 << 0 << ovl.Expression->getSourceRange(); 11051 11052 // TODO: I believe we only end up here if there's a mix of 11053 // static and non-static candidates (otherwise the expression 11054 // would have 'bound member' type, not 'overload' type). 11055 // Ideally we would note which candidate was chosen and why 11056 // the static candidates were rejected. 11057 SrcExpr = ExprError(); 11058 return true; 11059 } 11060 11061 // Fix the expression to refer to 'fn'. 11062 SingleFunctionExpression = 11063 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11064 11065 // If desired, do function-to-pointer decay. 11066 if (doFunctionPointerConverion) { 11067 SingleFunctionExpression = 11068 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11069 if (SingleFunctionExpression.isInvalid()) { 11070 SrcExpr = ExprError(); 11071 return true; 11072 } 11073 } 11074 } 11075 11076 if (!SingleFunctionExpression.isUsable()) { 11077 if (complain) { 11078 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11079 << ovl.Expression->getName() 11080 << DestTypeForComplaining 11081 << OpRangeForComplaining 11082 << ovl.Expression->getQualifierLoc().getSourceRange(); 11083 NoteAllOverloadCandidates(SrcExpr.get()); 11084 11085 SrcExpr = ExprError(); 11086 return true; 11087 } 11088 11089 return false; 11090 } 11091 11092 SrcExpr = SingleFunctionExpression; 11093 return true; 11094 } 11095 11096 /// \brief Add a single candidate to the overload set. 11097 static void AddOverloadedCallCandidate(Sema &S, 11098 DeclAccessPair FoundDecl, 11099 TemplateArgumentListInfo *ExplicitTemplateArgs, 11100 ArrayRef<Expr *> Args, 11101 OverloadCandidateSet &CandidateSet, 11102 bool PartialOverloading, 11103 bool KnownValid) { 11104 NamedDecl *Callee = FoundDecl.getDecl(); 11105 if (isa<UsingShadowDecl>(Callee)) 11106 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11107 11108 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11109 if (ExplicitTemplateArgs) { 11110 assert(!KnownValid && "Explicit template arguments?"); 11111 return; 11112 } 11113 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11114 /*SuppressUsedConversions=*/false, 11115 PartialOverloading); 11116 return; 11117 } 11118 11119 if (FunctionTemplateDecl *FuncTemplate 11120 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11121 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11122 ExplicitTemplateArgs, Args, CandidateSet, 11123 /*SuppressUsedConversions=*/false, 11124 PartialOverloading); 11125 return; 11126 } 11127 11128 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11129 } 11130 11131 /// \brief Add the overload candidates named by callee and/or found by argument 11132 /// dependent lookup to the given overload set. 11133 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11134 ArrayRef<Expr *> Args, 11135 OverloadCandidateSet &CandidateSet, 11136 bool PartialOverloading) { 11137 11138 #ifndef NDEBUG 11139 // Verify that ArgumentDependentLookup is consistent with the rules 11140 // in C++0x [basic.lookup.argdep]p3: 11141 // 11142 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11143 // and let Y be the lookup set produced by argument dependent 11144 // lookup (defined as follows). If X contains 11145 // 11146 // -- a declaration of a class member, or 11147 // 11148 // -- a block-scope function declaration that is not a 11149 // using-declaration, or 11150 // 11151 // -- a declaration that is neither a function or a function 11152 // template 11153 // 11154 // then Y is empty. 11155 11156 if (ULE->requiresADL()) { 11157 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11158 E = ULE->decls_end(); I != E; ++I) { 11159 assert(!(*I)->getDeclContext()->isRecord()); 11160 assert(isa<UsingShadowDecl>(*I) || 11161 !(*I)->getDeclContext()->isFunctionOrMethod()); 11162 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11163 } 11164 } 11165 #endif 11166 11167 // It would be nice to avoid this copy. 11168 TemplateArgumentListInfo TABuffer; 11169 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11170 if (ULE->hasExplicitTemplateArgs()) { 11171 ULE->copyTemplateArgumentsInto(TABuffer); 11172 ExplicitTemplateArgs = &TABuffer; 11173 } 11174 11175 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11176 E = ULE->decls_end(); I != E; ++I) 11177 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11178 CandidateSet, PartialOverloading, 11179 /*KnownValid*/ true); 11180 11181 if (ULE->requiresADL()) 11182 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11183 Args, ExplicitTemplateArgs, 11184 CandidateSet, PartialOverloading); 11185 } 11186 11187 /// Determine whether a declaration with the specified name could be moved into 11188 /// a different namespace. 11189 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11190 switch (Name.getCXXOverloadedOperator()) { 11191 case OO_New: case OO_Array_New: 11192 case OO_Delete: case OO_Array_Delete: 11193 return false; 11194 11195 default: 11196 return true; 11197 } 11198 } 11199 11200 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11201 /// template, where the non-dependent name was declared after the template 11202 /// was defined. This is common in code written for a compilers which do not 11203 /// correctly implement two-stage name lookup. 11204 /// 11205 /// Returns true if a viable candidate was found and a diagnostic was issued. 11206 static bool 11207 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11208 const CXXScopeSpec &SS, LookupResult &R, 11209 OverloadCandidateSet::CandidateSetKind CSK, 11210 TemplateArgumentListInfo *ExplicitTemplateArgs, 11211 ArrayRef<Expr *> Args, 11212 bool *DoDiagnoseEmptyLookup = nullptr) { 11213 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11214 return false; 11215 11216 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11217 if (DC->isTransparentContext()) 11218 continue; 11219 11220 SemaRef.LookupQualifiedName(R, DC); 11221 11222 if (!R.empty()) { 11223 R.suppressDiagnostics(); 11224 11225 if (isa<CXXRecordDecl>(DC)) { 11226 // Don't diagnose names we find in classes; we get much better 11227 // diagnostics for these from DiagnoseEmptyLookup. 11228 R.clear(); 11229 if (DoDiagnoseEmptyLookup) 11230 *DoDiagnoseEmptyLookup = true; 11231 return false; 11232 } 11233 11234 OverloadCandidateSet Candidates(FnLoc, CSK); 11235 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11236 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11237 ExplicitTemplateArgs, Args, 11238 Candidates, false, /*KnownValid*/ false); 11239 11240 OverloadCandidateSet::iterator Best; 11241 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11242 // No viable functions. Don't bother the user with notes for functions 11243 // which don't work and shouldn't be found anyway. 11244 R.clear(); 11245 return false; 11246 } 11247 11248 // Find the namespaces where ADL would have looked, and suggest 11249 // declaring the function there instead. 11250 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11251 Sema::AssociatedClassSet AssociatedClasses; 11252 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11253 AssociatedNamespaces, 11254 AssociatedClasses); 11255 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11256 if (canBeDeclaredInNamespace(R.getLookupName())) { 11257 DeclContext *Std = SemaRef.getStdNamespace(); 11258 for (Sema::AssociatedNamespaceSet::iterator 11259 it = AssociatedNamespaces.begin(), 11260 end = AssociatedNamespaces.end(); it != end; ++it) { 11261 // Never suggest declaring a function within namespace 'std'. 11262 if (Std && Std->Encloses(*it)) 11263 continue; 11264 11265 // Never suggest declaring a function within a namespace with a 11266 // reserved name, like __gnu_cxx. 11267 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11268 if (NS && 11269 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11270 continue; 11271 11272 SuggestedNamespaces.insert(*it); 11273 } 11274 } 11275 11276 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11277 << R.getLookupName(); 11278 if (SuggestedNamespaces.empty()) { 11279 SemaRef.Diag(Best->Function->getLocation(), 11280 diag::note_not_found_by_two_phase_lookup) 11281 << R.getLookupName() << 0; 11282 } else if (SuggestedNamespaces.size() == 1) { 11283 SemaRef.Diag(Best->Function->getLocation(), 11284 diag::note_not_found_by_two_phase_lookup) 11285 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11286 } else { 11287 // FIXME: It would be useful to list the associated namespaces here, 11288 // but the diagnostics infrastructure doesn't provide a way to produce 11289 // a localized representation of a list of items. 11290 SemaRef.Diag(Best->Function->getLocation(), 11291 diag::note_not_found_by_two_phase_lookup) 11292 << R.getLookupName() << 2; 11293 } 11294 11295 // Try to recover by calling this function. 11296 return true; 11297 } 11298 11299 R.clear(); 11300 } 11301 11302 return false; 11303 } 11304 11305 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11306 /// template, where the non-dependent operator was declared after the template 11307 /// was defined. 11308 /// 11309 /// Returns true if a viable candidate was found and a diagnostic was issued. 11310 static bool 11311 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11312 SourceLocation OpLoc, 11313 ArrayRef<Expr *> Args) { 11314 DeclarationName OpName = 11315 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11316 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11317 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11318 OverloadCandidateSet::CSK_Operator, 11319 /*ExplicitTemplateArgs=*/nullptr, Args); 11320 } 11321 11322 namespace { 11323 class BuildRecoveryCallExprRAII { 11324 Sema &SemaRef; 11325 public: 11326 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11327 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11328 SemaRef.IsBuildingRecoveryCallExpr = true; 11329 } 11330 11331 ~BuildRecoveryCallExprRAII() { 11332 SemaRef.IsBuildingRecoveryCallExpr = false; 11333 } 11334 }; 11335 11336 } 11337 11338 static std::unique_ptr<CorrectionCandidateCallback> 11339 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11340 bool HasTemplateArgs, bool AllowTypoCorrection) { 11341 if (!AllowTypoCorrection) 11342 return llvm::make_unique<NoTypoCorrectionCCC>(); 11343 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11344 HasTemplateArgs, ME); 11345 } 11346 11347 /// Attempts to recover from a call where no functions were found. 11348 /// 11349 /// Returns true if new candidates were found. 11350 static ExprResult 11351 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11352 UnresolvedLookupExpr *ULE, 11353 SourceLocation LParenLoc, 11354 MutableArrayRef<Expr *> Args, 11355 SourceLocation RParenLoc, 11356 bool EmptyLookup, bool AllowTypoCorrection) { 11357 // Do not try to recover if it is already building a recovery call. 11358 // This stops infinite loops for template instantiations like 11359 // 11360 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11361 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11362 // 11363 if (SemaRef.IsBuildingRecoveryCallExpr) 11364 return ExprError(); 11365 BuildRecoveryCallExprRAII RCE(SemaRef); 11366 11367 CXXScopeSpec SS; 11368 SS.Adopt(ULE->getQualifierLoc()); 11369 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11370 11371 TemplateArgumentListInfo TABuffer; 11372 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11373 if (ULE->hasExplicitTemplateArgs()) { 11374 ULE->copyTemplateArgumentsInto(TABuffer); 11375 ExplicitTemplateArgs = &TABuffer; 11376 } 11377 11378 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11379 Sema::LookupOrdinaryName); 11380 bool DoDiagnoseEmptyLookup = EmptyLookup; 11381 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11382 OverloadCandidateSet::CSK_Normal, 11383 ExplicitTemplateArgs, Args, 11384 &DoDiagnoseEmptyLookup) && 11385 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11386 S, SS, R, 11387 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11388 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11389 ExplicitTemplateArgs, Args))) 11390 return ExprError(); 11391 11392 assert(!R.empty() && "lookup results empty despite recovery"); 11393 11394 // Build an implicit member call if appropriate. Just drop the 11395 // casts and such from the call, we don't really care. 11396 ExprResult NewFn = ExprError(); 11397 if ((*R.begin())->isCXXClassMember()) 11398 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11399 ExplicitTemplateArgs, S); 11400 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11401 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11402 ExplicitTemplateArgs); 11403 else 11404 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11405 11406 if (NewFn.isInvalid()) 11407 return ExprError(); 11408 11409 // This shouldn't cause an infinite loop because we're giving it 11410 // an expression with viable lookup results, which should never 11411 // end up here. 11412 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11413 MultiExprArg(Args.data(), Args.size()), 11414 RParenLoc); 11415 } 11416 11417 /// \brief Constructs and populates an OverloadedCandidateSet from 11418 /// the given function. 11419 /// \returns true when an the ExprResult output parameter has been set. 11420 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11421 UnresolvedLookupExpr *ULE, 11422 MultiExprArg Args, 11423 SourceLocation RParenLoc, 11424 OverloadCandidateSet *CandidateSet, 11425 ExprResult *Result) { 11426 #ifndef NDEBUG 11427 if (ULE->requiresADL()) { 11428 // To do ADL, we must have found an unqualified name. 11429 assert(!ULE->getQualifier() && "qualified name with ADL"); 11430 11431 // We don't perform ADL for implicit declarations of builtins. 11432 // Verify that this was correctly set up. 11433 FunctionDecl *F; 11434 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11435 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11436 F->getBuiltinID() && F->isImplicit()) 11437 llvm_unreachable("performing ADL for builtin"); 11438 11439 // We don't perform ADL in C. 11440 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11441 } 11442 #endif 11443 11444 UnbridgedCastsSet UnbridgedCasts; 11445 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11446 *Result = ExprError(); 11447 return true; 11448 } 11449 11450 // Add the functions denoted by the callee to the set of candidate 11451 // functions, including those from argument-dependent lookup. 11452 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11453 11454 if (getLangOpts().MSVCCompat && 11455 CurContext->isDependentContext() && !isSFINAEContext() && 11456 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11457 11458 OverloadCandidateSet::iterator Best; 11459 if (CandidateSet->empty() || 11460 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11461 OR_No_Viable_Function) { 11462 // In Microsoft mode, if we are inside a template class member function then 11463 // create a type dependent CallExpr. The goal is to postpone name lookup 11464 // to instantiation time to be able to search into type dependent base 11465 // classes. 11466 CallExpr *CE = new (Context) CallExpr( 11467 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11468 CE->setTypeDependent(true); 11469 CE->setValueDependent(true); 11470 CE->setInstantiationDependent(true); 11471 *Result = CE; 11472 return true; 11473 } 11474 } 11475 11476 if (CandidateSet->empty()) 11477 return false; 11478 11479 UnbridgedCasts.restore(); 11480 return false; 11481 } 11482 11483 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11484 /// the completed call expression. If overload resolution fails, emits 11485 /// diagnostics and returns ExprError() 11486 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11487 UnresolvedLookupExpr *ULE, 11488 SourceLocation LParenLoc, 11489 MultiExprArg Args, 11490 SourceLocation RParenLoc, 11491 Expr *ExecConfig, 11492 OverloadCandidateSet *CandidateSet, 11493 OverloadCandidateSet::iterator *Best, 11494 OverloadingResult OverloadResult, 11495 bool AllowTypoCorrection) { 11496 if (CandidateSet->empty()) 11497 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11498 RParenLoc, /*EmptyLookup=*/true, 11499 AllowTypoCorrection); 11500 11501 switch (OverloadResult) { 11502 case OR_Success: { 11503 FunctionDecl *FDecl = (*Best)->Function; 11504 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11505 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11506 return ExprError(); 11507 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11508 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11509 ExecConfig); 11510 } 11511 11512 case OR_No_Viable_Function: { 11513 // Try to recover by looking for viable functions which the user might 11514 // have meant to call. 11515 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11516 Args, RParenLoc, 11517 /*EmptyLookup=*/false, 11518 AllowTypoCorrection); 11519 if (!Recovery.isInvalid()) 11520 return Recovery; 11521 11522 // If the user passes in a function that we can't take the address of, we 11523 // generally end up emitting really bad error messages. Here, we attempt to 11524 // emit better ones. 11525 for (const Expr *Arg : Args) { 11526 if (!Arg->getType()->isFunctionType()) 11527 continue; 11528 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11529 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11530 if (FD && 11531 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11532 Arg->getExprLoc())) 11533 return ExprError(); 11534 } 11535 } 11536 11537 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11538 << ULE->getName() << Fn->getSourceRange(); 11539 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11540 break; 11541 } 11542 11543 case OR_Ambiguous: 11544 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11545 << ULE->getName() << Fn->getSourceRange(); 11546 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11547 break; 11548 11549 case OR_Deleted: { 11550 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11551 << (*Best)->Function->isDeleted() 11552 << ULE->getName() 11553 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11554 << Fn->getSourceRange(); 11555 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11556 11557 // We emitted an error for the unvailable/deleted function call but keep 11558 // the call in the AST. 11559 FunctionDecl *FDecl = (*Best)->Function; 11560 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11561 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11562 ExecConfig); 11563 } 11564 } 11565 11566 // Overload resolution failed. 11567 return ExprError(); 11568 } 11569 11570 static void markUnaddressableCandidatesUnviable(Sema &S, 11571 OverloadCandidateSet &CS) { 11572 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11573 if (I->Viable && 11574 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11575 I->Viable = false; 11576 I->FailureKind = ovl_fail_addr_not_available; 11577 } 11578 } 11579 } 11580 11581 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11582 /// (which eventually refers to the declaration Func) and the call 11583 /// arguments Args/NumArgs, attempt to resolve the function call down 11584 /// to a specific function. If overload resolution succeeds, returns 11585 /// the call expression produced by overload resolution. 11586 /// Otherwise, emits diagnostics and returns ExprError. 11587 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11588 UnresolvedLookupExpr *ULE, 11589 SourceLocation LParenLoc, 11590 MultiExprArg Args, 11591 SourceLocation RParenLoc, 11592 Expr *ExecConfig, 11593 bool AllowTypoCorrection, 11594 bool CalleesAddressIsTaken) { 11595 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11596 OverloadCandidateSet::CSK_Normal); 11597 ExprResult result; 11598 11599 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11600 &result)) 11601 return result; 11602 11603 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11604 // functions that aren't addressible are considered unviable. 11605 if (CalleesAddressIsTaken) 11606 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11607 11608 OverloadCandidateSet::iterator Best; 11609 OverloadingResult OverloadResult = 11610 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11611 11612 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11613 RParenLoc, ExecConfig, &CandidateSet, 11614 &Best, OverloadResult, 11615 AllowTypoCorrection); 11616 } 11617 11618 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11619 return Functions.size() > 1 || 11620 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11621 } 11622 11623 /// \brief Create a unary operation that may resolve to an overloaded 11624 /// operator. 11625 /// 11626 /// \param OpLoc The location of the operator itself (e.g., '*'). 11627 /// 11628 /// \param Opc The UnaryOperatorKind that describes this operator. 11629 /// 11630 /// \param Fns The set of non-member functions that will be 11631 /// considered by overload resolution. The caller needs to build this 11632 /// set based on the context using, e.g., 11633 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11634 /// set should not contain any member functions; those will be added 11635 /// by CreateOverloadedUnaryOp(). 11636 /// 11637 /// \param Input The input argument. 11638 ExprResult 11639 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11640 const UnresolvedSetImpl &Fns, 11641 Expr *Input) { 11642 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11643 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11644 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11645 // TODO: provide better source location info. 11646 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11647 11648 if (checkPlaceholderForOverload(*this, Input)) 11649 return ExprError(); 11650 11651 Expr *Args[2] = { Input, nullptr }; 11652 unsigned NumArgs = 1; 11653 11654 // For post-increment and post-decrement, add the implicit '0' as 11655 // the second argument, so that we know this is a post-increment or 11656 // post-decrement. 11657 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11658 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11659 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11660 SourceLocation()); 11661 NumArgs = 2; 11662 } 11663 11664 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11665 11666 if (Input->isTypeDependent()) { 11667 if (Fns.empty()) 11668 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11669 VK_RValue, OK_Ordinary, OpLoc); 11670 11671 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11672 UnresolvedLookupExpr *Fn 11673 = UnresolvedLookupExpr::Create(Context, NamingClass, 11674 NestedNameSpecifierLoc(), OpNameInfo, 11675 /*ADL*/ true, IsOverloaded(Fns), 11676 Fns.begin(), Fns.end()); 11677 return new (Context) 11678 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11679 VK_RValue, OpLoc, false); 11680 } 11681 11682 // Build an empty overload set. 11683 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11684 11685 // Add the candidates from the given function set. 11686 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11687 11688 // Add operator candidates that are member functions. 11689 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11690 11691 // Add candidates from ADL. 11692 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11693 /*ExplicitTemplateArgs*/nullptr, 11694 CandidateSet); 11695 11696 // Add builtin operator candidates. 11697 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11698 11699 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11700 11701 // Perform overload resolution. 11702 OverloadCandidateSet::iterator Best; 11703 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11704 case OR_Success: { 11705 // We found a built-in operator or an overloaded operator. 11706 FunctionDecl *FnDecl = Best->Function; 11707 11708 if (FnDecl) { 11709 // We matched an overloaded operator. Build a call to that 11710 // operator. 11711 11712 // Convert the arguments. 11713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11714 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11715 11716 ExprResult InputRes = 11717 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11718 Best->FoundDecl, Method); 11719 if (InputRes.isInvalid()) 11720 return ExprError(); 11721 Input = InputRes.get(); 11722 } else { 11723 // Convert the arguments. 11724 ExprResult InputInit 11725 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11726 Context, 11727 FnDecl->getParamDecl(0)), 11728 SourceLocation(), 11729 Input); 11730 if (InputInit.isInvalid()) 11731 return ExprError(); 11732 Input = InputInit.get(); 11733 } 11734 11735 // Build the actual expression node. 11736 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11737 HadMultipleCandidates, OpLoc); 11738 if (FnExpr.isInvalid()) 11739 return ExprError(); 11740 11741 // Determine the result type. 11742 QualType ResultTy = FnDecl->getReturnType(); 11743 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11744 ResultTy = ResultTy.getNonLValueExprType(Context); 11745 11746 Args[0] = Input; 11747 CallExpr *TheCall = 11748 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11749 ResultTy, VK, OpLoc, false); 11750 11751 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11752 return ExprError(); 11753 11754 return MaybeBindToTemporary(TheCall); 11755 } else { 11756 // We matched a built-in operator. Convert the arguments, then 11757 // break out so that we will build the appropriate built-in 11758 // operator node. 11759 ExprResult InputRes = 11760 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11761 Best->Conversions[0], AA_Passing); 11762 if (InputRes.isInvalid()) 11763 return ExprError(); 11764 Input = InputRes.get(); 11765 break; 11766 } 11767 } 11768 11769 case OR_No_Viable_Function: 11770 // This is an erroneous use of an operator which can be overloaded by 11771 // a non-member function. Check for non-member operators which were 11772 // defined too late to be candidates. 11773 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11774 // FIXME: Recover by calling the found function. 11775 return ExprError(); 11776 11777 // No viable function; fall through to handling this as a 11778 // built-in operator, which will produce an error message for us. 11779 break; 11780 11781 case OR_Ambiguous: 11782 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11783 << UnaryOperator::getOpcodeStr(Opc) 11784 << Input->getType() 11785 << Input->getSourceRange(); 11786 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11787 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11788 return ExprError(); 11789 11790 case OR_Deleted: 11791 Diag(OpLoc, diag::err_ovl_deleted_oper) 11792 << Best->Function->isDeleted() 11793 << UnaryOperator::getOpcodeStr(Opc) 11794 << getDeletedOrUnavailableSuffix(Best->Function) 11795 << Input->getSourceRange(); 11796 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11797 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11798 return ExprError(); 11799 } 11800 11801 // Either we found no viable overloaded operator or we matched a 11802 // built-in operator. In either case, fall through to trying to 11803 // build a built-in operation. 11804 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11805 } 11806 11807 /// \brief Create a binary operation that may resolve to an overloaded 11808 /// operator. 11809 /// 11810 /// \param OpLoc The location of the operator itself (e.g., '+'). 11811 /// 11812 /// \param Opc The BinaryOperatorKind that describes this operator. 11813 /// 11814 /// \param Fns The set of non-member functions that will be 11815 /// considered by overload resolution. The caller needs to build this 11816 /// set based on the context using, e.g., 11817 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11818 /// set should not contain any member functions; those will be added 11819 /// by CreateOverloadedBinOp(). 11820 /// 11821 /// \param LHS Left-hand argument. 11822 /// \param RHS Right-hand argument. 11823 ExprResult 11824 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11825 BinaryOperatorKind Opc, 11826 const UnresolvedSetImpl &Fns, 11827 Expr *LHS, Expr *RHS) { 11828 Expr *Args[2] = { LHS, RHS }; 11829 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11830 11831 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11832 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11833 11834 // If either side is type-dependent, create an appropriate dependent 11835 // expression. 11836 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11837 if (Fns.empty()) { 11838 // If there are no functions to store, just build a dependent 11839 // BinaryOperator or CompoundAssignment. 11840 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11841 return new (Context) BinaryOperator( 11842 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11843 OpLoc, FPFeatures.fp_contract); 11844 11845 return new (Context) CompoundAssignOperator( 11846 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11847 Context.DependentTy, Context.DependentTy, OpLoc, 11848 FPFeatures.fp_contract); 11849 } 11850 11851 // FIXME: save results of ADL from here? 11852 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11853 // TODO: provide better source location info in DNLoc component. 11854 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11855 UnresolvedLookupExpr *Fn 11856 = UnresolvedLookupExpr::Create(Context, NamingClass, 11857 NestedNameSpecifierLoc(), OpNameInfo, 11858 /*ADL*/ true, IsOverloaded(Fns), 11859 Fns.begin(), Fns.end()); 11860 return new (Context) 11861 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11862 VK_RValue, OpLoc, FPFeatures.fp_contract); 11863 } 11864 11865 // Always do placeholder-like conversions on the RHS. 11866 if (checkPlaceholderForOverload(*this, Args[1])) 11867 return ExprError(); 11868 11869 // Do placeholder-like conversion on the LHS; note that we should 11870 // not get here with a PseudoObject LHS. 11871 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11872 if (checkPlaceholderForOverload(*this, Args[0])) 11873 return ExprError(); 11874 11875 // If this is the assignment operator, we only perform overload resolution 11876 // if the left-hand side is a class or enumeration type. This is actually 11877 // a hack. The standard requires that we do overload resolution between the 11878 // various built-in candidates, but as DR507 points out, this can lead to 11879 // problems. So we do it this way, which pretty much follows what GCC does. 11880 // Note that we go the traditional code path for compound assignment forms. 11881 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11882 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11883 11884 // If this is the .* operator, which is not overloadable, just 11885 // create a built-in binary operator. 11886 if (Opc == BO_PtrMemD) 11887 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11888 11889 // Build an empty overload set. 11890 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11891 11892 // Add the candidates from the given function set. 11893 AddFunctionCandidates(Fns, Args, CandidateSet); 11894 11895 // Add operator candidates that are member functions. 11896 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11897 11898 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11899 // performed for an assignment operator (nor for operator[] nor operator->, 11900 // which don't get here). 11901 if (Opc != BO_Assign) 11902 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11903 /*ExplicitTemplateArgs*/ nullptr, 11904 CandidateSet); 11905 11906 // Add builtin operator candidates. 11907 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11908 11909 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11910 11911 // Perform overload resolution. 11912 OverloadCandidateSet::iterator Best; 11913 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11914 case OR_Success: { 11915 // We found a built-in operator or an overloaded operator. 11916 FunctionDecl *FnDecl = Best->Function; 11917 11918 if (FnDecl) { 11919 // We matched an overloaded operator. Build a call to that 11920 // operator. 11921 11922 // Convert the arguments. 11923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11924 // Best->Access is only meaningful for class members. 11925 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11926 11927 ExprResult Arg1 = 11928 PerformCopyInitialization( 11929 InitializedEntity::InitializeParameter(Context, 11930 FnDecl->getParamDecl(0)), 11931 SourceLocation(), Args[1]); 11932 if (Arg1.isInvalid()) 11933 return ExprError(); 11934 11935 ExprResult Arg0 = 11936 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11937 Best->FoundDecl, Method); 11938 if (Arg0.isInvalid()) 11939 return ExprError(); 11940 Args[0] = Arg0.getAs<Expr>(); 11941 Args[1] = RHS = Arg1.getAs<Expr>(); 11942 } else { 11943 // Convert the arguments. 11944 ExprResult Arg0 = PerformCopyInitialization( 11945 InitializedEntity::InitializeParameter(Context, 11946 FnDecl->getParamDecl(0)), 11947 SourceLocation(), Args[0]); 11948 if (Arg0.isInvalid()) 11949 return ExprError(); 11950 11951 ExprResult Arg1 = 11952 PerformCopyInitialization( 11953 InitializedEntity::InitializeParameter(Context, 11954 FnDecl->getParamDecl(1)), 11955 SourceLocation(), Args[1]); 11956 if (Arg1.isInvalid()) 11957 return ExprError(); 11958 Args[0] = LHS = Arg0.getAs<Expr>(); 11959 Args[1] = RHS = Arg1.getAs<Expr>(); 11960 } 11961 11962 // Build the actual expression node. 11963 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11964 Best->FoundDecl, 11965 HadMultipleCandidates, OpLoc); 11966 if (FnExpr.isInvalid()) 11967 return ExprError(); 11968 11969 // Determine the result type. 11970 QualType ResultTy = FnDecl->getReturnType(); 11971 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11972 ResultTy = ResultTy.getNonLValueExprType(Context); 11973 11974 CXXOperatorCallExpr *TheCall = 11975 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11976 Args, ResultTy, VK, OpLoc, 11977 FPFeatures.fp_contract); 11978 11979 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11980 FnDecl)) 11981 return ExprError(); 11982 11983 ArrayRef<const Expr *> ArgsArray(Args, 2); 11984 // Cut off the implicit 'this'. 11985 if (isa<CXXMethodDecl>(FnDecl)) 11986 ArgsArray = ArgsArray.slice(1); 11987 11988 // Check for a self move. 11989 if (Op == OO_Equal) 11990 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11991 11992 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11993 TheCall->getSourceRange(), VariadicDoesNotApply); 11994 11995 return MaybeBindToTemporary(TheCall); 11996 } else { 11997 // We matched a built-in operator. Convert the arguments, then 11998 // break out so that we will build the appropriate built-in 11999 // operator node. 12000 ExprResult ArgsRes0 = 12001 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12002 Best->Conversions[0], AA_Passing); 12003 if (ArgsRes0.isInvalid()) 12004 return ExprError(); 12005 Args[0] = ArgsRes0.get(); 12006 12007 ExprResult ArgsRes1 = 12008 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12009 Best->Conversions[1], AA_Passing); 12010 if (ArgsRes1.isInvalid()) 12011 return ExprError(); 12012 Args[1] = ArgsRes1.get(); 12013 break; 12014 } 12015 } 12016 12017 case OR_No_Viable_Function: { 12018 // C++ [over.match.oper]p9: 12019 // If the operator is the operator , [...] and there are no 12020 // viable functions, then the operator is assumed to be the 12021 // built-in operator and interpreted according to clause 5. 12022 if (Opc == BO_Comma) 12023 break; 12024 12025 // For class as left operand for assignment or compound assigment 12026 // operator do not fall through to handling in built-in, but report that 12027 // no overloaded assignment operator found 12028 ExprResult Result = ExprError(); 12029 if (Args[0]->getType()->isRecordType() && 12030 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12031 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12032 << BinaryOperator::getOpcodeStr(Opc) 12033 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12034 if (Args[0]->getType()->isIncompleteType()) { 12035 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12036 << Args[0]->getType() 12037 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12038 } 12039 } else { 12040 // This is an erroneous use of an operator which can be overloaded by 12041 // a non-member function. Check for non-member operators which were 12042 // defined too late to be candidates. 12043 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12044 // FIXME: Recover by calling the found function. 12045 return ExprError(); 12046 12047 // No viable function; try to create a built-in operation, which will 12048 // produce an error. Then, show the non-viable candidates. 12049 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12050 } 12051 assert(Result.isInvalid() && 12052 "C++ binary operator overloading is missing candidates!"); 12053 if (Result.isInvalid()) 12054 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12055 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12056 return Result; 12057 } 12058 12059 case OR_Ambiguous: 12060 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12061 << BinaryOperator::getOpcodeStr(Opc) 12062 << Args[0]->getType() << Args[1]->getType() 12063 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12064 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12065 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12066 return ExprError(); 12067 12068 case OR_Deleted: 12069 if (isImplicitlyDeleted(Best->Function)) { 12070 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12071 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12072 << Context.getRecordType(Method->getParent()) 12073 << getSpecialMember(Method); 12074 12075 // The user probably meant to call this special member. Just 12076 // explain why it's deleted. 12077 NoteDeletedFunction(Method); 12078 return ExprError(); 12079 } else { 12080 Diag(OpLoc, diag::err_ovl_deleted_oper) 12081 << Best->Function->isDeleted() 12082 << BinaryOperator::getOpcodeStr(Opc) 12083 << getDeletedOrUnavailableSuffix(Best->Function) 12084 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12085 } 12086 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12087 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12088 return ExprError(); 12089 } 12090 12091 // We matched a built-in operator; build it. 12092 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12093 } 12094 12095 ExprResult 12096 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12097 SourceLocation RLoc, 12098 Expr *Base, Expr *Idx) { 12099 Expr *Args[2] = { Base, Idx }; 12100 DeclarationName OpName = 12101 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12102 12103 // If either side is type-dependent, create an appropriate dependent 12104 // expression. 12105 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12106 12107 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12108 // CHECKME: no 'operator' keyword? 12109 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12110 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12111 UnresolvedLookupExpr *Fn 12112 = UnresolvedLookupExpr::Create(Context, NamingClass, 12113 NestedNameSpecifierLoc(), OpNameInfo, 12114 /*ADL*/ true, /*Overloaded*/ false, 12115 UnresolvedSetIterator(), 12116 UnresolvedSetIterator()); 12117 // Can't add any actual overloads yet 12118 12119 return new (Context) 12120 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12121 Context.DependentTy, VK_RValue, RLoc, false); 12122 } 12123 12124 // Handle placeholders on both operands. 12125 if (checkPlaceholderForOverload(*this, Args[0])) 12126 return ExprError(); 12127 if (checkPlaceholderForOverload(*this, Args[1])) 12128 return ExprError(); 12129 12130 // Build an empty overload set. 12131 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12132 12133 // Subscript can only be overloaded as a member function. 12134 12135 // Add operator candidates that are member functions. 12136 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12137 12138 // Add builtin operator candidates. 12139 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12140 12141 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12142 12143 // Perform overload resolution. 12144 OverloadCandidateSet::iterator Best; 12145 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12146 case OR_Success: { 12147 // We found a built-in operator or an overloaded operator. 12148 FunctionDecl *FnDecl = Best->Function; 12149 12150 if (FnDecl) { 12151 // We matched an overloaded operator. Build a call to that 12152 // operator. 12153 12154 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12155 12156 // Convert the arguments. 12157 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12158 ExprResult Arg0 = 12159 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12160 Best->FoundDecl, Method); 12161 if (Arg0.isInvalid()) 12162 return ExprError(); 12163 Args[0] = Arg0.get(); 12164 12165 // Convert the arguments. 12166 ExprResult InputInit 12167 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12168 Context, 12169 FnDecl->getParamDecl(0)), 12170 SourceLocation(), 12171 Args[1]); 12172 if (InputInit.isInvalid()) 12173 return ExprError(); 12174 12175 Args[1] = InputInit.getAs<Expr>(); 12176 12177 // Build the actual expression node. 12178 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12179 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12180 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12181 Best->FoundDecl, 12182 HadMultipleCandidates, 12183 OpLocInfo.getLoc(), 12184 OpLocInfo.getInfo()); 12185 if (FnExpr.isInvalid()) 12186 return ExprError(); 12187 12188 // Determine the result type 12189 QualType ResultTy = FnDecl->getReturnType(); 12190 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12191 ResultTy = ResultTy.getNonLValueExprType(Context); 12192 12193 CXXOperatorCallExpr *TheCall = 12194 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12195 FnExpr.get(), Args, 12196 ResultTy, VK, RLoc, 12197 false); 12198 12199 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12200 return ExprError(); 12201 12202 return MaybeBindToTemporary(TheCall); 12203 } else { 12204 // We matched a built-in operator. Convert the arguments, then 12205 // break out so that we will build the appropriate built-in 12206 // operator node. 12207 ExprResult ArgsRes0 = 12208 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12209 Best->Conversions[0], AA_Passing); 12210 if (ArgsRes0.isInvalid()) 12211 return ExprError(); 12212 Args[0] = ArgsRes0.get(); 12213 12214 ExprResult ArgsRes1 = 12215 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12216 Best->Conversions[1], AA_Passing); 12217 if (ArgsRes1.isInvalid()) 12218 return ExprError(); 12219 Args[1] = ArgsRes1.get(); 12220 12221 break; 12222 } 12223 } 12224 12225 case OR_No_Viable_Function: { 12226 if (CandidateSet.empty()) 12227 Diag(LLoc, diag::err_ovl_no_oper) 12228 << Args[0]->getType() << /*subscript*/ 0 12229 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12230 else 12231 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12232 << Args[0]->getType() 12233 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12235 "[]", LLoc); 12236 return ExprError(); 12237 } 12238 12239 case OR_Ambiguous: 12240 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12241 << "[]" 12242 << Args[0]->getType() << Args[1]->getType() 12243 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12244 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12245 "[]", LLoc); 12246 return ExprError(); 12247 12248 case OR_Deleted: 12249 Diag(LLoc, diag::err_ovl_deleted_oper) 12250 << Best->Function->isDeleted() << "[]" 12251 << getDeletedOrUnavailableSuffix(Best->Function) 12252 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12253 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12254 "[]", LLoc); 12255 return ExprError(); 12256 } 12257 12258 // We matched a built-in operator; build it. 12259 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12260 } 12261 12262 /// BuildCallToMemberFunction - Build a call to a member 12263 /// function. MemExpr is the expression that refers to the member 12264 /// function (and includes the object parameter), Args/NumArgs are the 12265 /// arguments to the function call (not including the object 12266 /// parameter). The caller needs to validate that the member 12267 /// expression refers to a non-static member function or an overloaded 12268 /// member function. 12269 ExprResult 12270 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12271 SourceLocation LParenLoc, 12272 MultiExprArg Args, 12273 SourceLocation RParenLoc) { 12274 assert(MemExprE->getType() == Context.BoundMemberTy || 12275 MemExprE->getType() == Context.OverloadTy); 12276 12277 // Dig out the member expression. This holds both the object 12278 // argument and the member function we're referring to. 12279 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12280 12281 // Determine whether this is a call to a pointer-to-member function. 12282 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12283 assert(op->getType() == Context.BoundMemberTy); 12284 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12285 12286 QualType fnType = 12287 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12288 12289 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12290 QualType resultType = proto->getCallResultType(Context); 12291 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12292 12293 // Check that the object type isn't more qualified than the 12294 // member function we're calling. 12295 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12296 12297 QualType objectType = op->getLHS()->getType(); 12298 if (op->getOpcode() == BO_PtrMemI) 12299 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12300 Qualifiers objectQuals = objectType.getQualifiers(); 12301 12302 Qualifiers difference = objectQuals - funcQuals; 12303 difference.removeObjCGCAttr(); 12304 difference.removeAddressSpace(); 12305 if (difference) { 12306 std::string qualsString = difference.getAsString(); 12307 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12308 << fnType.getUnqualifiedType() 12309 << qualsString 12310 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12311 } 12312 12313 CXXMemberCallExpr *call 12314 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12315 resultType, valueKind, RParenLoc); 12316 12317 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12318 call, nullptr)) 12319 return ExprError(); 12320 12321 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12322 return ExprError(); 12323 12324 if (CheckOtherCall(call, proto)) 12325 return ExprError(); 12326 12327 return MaybeBindToTemporary(call); 12328 } 12329 12330 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12331 return new (Context) 12332 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12333 12334 UnbridgedCastsSet UnbridgedCasts; 12335 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12336 return ExprError(); 12337 12338 MemberExpr *MemExpr; 12339 CXXMethodDecl *Method = nullptr; 12340 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12341 NestedNameSpecifier *Qualifier = nullptr; 12342 if (isa<MemberExpr>(NakedMemExpr)) { 12343 MemExpr = cast<MemberExpr>(NakedMemExpr); 12344 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12345 FoundDecl = MemExpr->getFoundDecl(); 12346 Qualifier = MemExpr->getQualifier(); 12347 UnbridgedCasts.restore(); 12348 } else { 12349 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12350 Qualifier = UnresExpr->getQualifier(); 12351 12352 QualType ObjectType = UnresExpr->getBaseType(); 12353 Expr::Classification ObjectClassification 12354 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12355 : UnresExpr->getBase()->Classify(Context); 12356 12357 // Add overload candidates 12358 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12359 OverloadCandidateSet::CSK_Normal); 12360 12361 // FIXME: avoid copy. 12362 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12363 if (UnresExpr->hasExplicitTemplateArgs()) { 12364 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12365 TemplateArgs = &TemplateArgsBuffer; 12366 } 12367 12368 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12369 E = UnresExpr->decls_end(); I != E; ++I) { 12370 12371 NamedDecl *Func = *I; 12372 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12373 if (isa<UsingShadowDecl>(Func)) 12374 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12375 12376 12377 // Microsoft supports direct constructor calls. 12378 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12379 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12380 Args, CandidateSet); 12381 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12382 // If explicit template arguments were provided, we can't call a 12383 // non-template member function. 12384 if (TemplateArgs) 12385 continue; 12386 12387 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12388 ObjectClassification, Args, CandidateSet, 12389 /*SuppressUserConversions=*/false); 12390 } else { 12391 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12392 I.getPair(), ActingDC, TemplateArgs, 12393 ObjectType, ObjectClassification, 12394 Args, CandidateSet, 12395 /*SuppressUsedConversions=*/false); 12396 } 12397 } 12398 12399 DeclarationName DeclName = UnresExpr->getMemberName(); 12400 12401 UnbridgedCasts.restore(); 12402 12403 OverloadCandidateSet::iterator Best; 12404 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12405 Best)) { 12406 case OR_Success: 12407 Method = cast<CXXMethodDecl>(Best->Function); 12408 FoundDecl = Best->FoundDecl; 12409 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12410 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12411 return ExprError(); 12412 // If FoundDecl is different from Method (such as if one is a template 12413 // and the other a specialization), make sure DiagnoseUseOfDecl is 12414 // called on both. 12415 // FIXME: This would be more comprehensively addressed by modifying 12416 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12417 // being used. 12418 if (Method != FoundDecl.getDecl() && 12419 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12420 return ExprError(); 12421 break; 12422 12423 case OR_No_Viable_Function: 12424 Diag(UnresExpr->getMemberLoc(), 12425 diag::err_ovl_no_viable_member_function_in_call) 12426 << DeclName << MemExprE->getSourceRange(); 12427 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12428 // FIXME: Leaking incoming expressions! 12429 return ExprError(); 12430 12431 case OR_Ambiguous: 12432 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12433 << DeclName << MemExprE->getSourceRange(); 12434 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12435 // FIXME: Leaking incoming expressions! 12436 return ExprError(); 12437 12438 case OR_Deleted: 12439 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12440 << Best->Function->isDeleted() 12441 << DeclName 12442 << getDeletedOrUnavailableSuffix(Best->Function) 12443 << MemExprE->getSourceRange(); 12444 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12445 // FIXME: Leaking incoming expressions! 12446 return ExprError(); 12447 } 12448 12449 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12450 12451 // If overload resolution picked a static member, build a 12452 // non-member call based on that function. 12453 if (Method->isStatic()) { 12454 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12455 RParenLoc); 12456 } 12457 12458 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12459 } 12460 12461 QualType ResultType = Method->getReturnType(); 12462 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12463 ResultType = ResultType.getNonLValueExprType(Context); 12464 12465 assert(Method && "Member call to something that isn't a method?"); 12466 CXXMemberCallExpr *TheCall = 12467 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12468 ResultType, VK, RParenLoc); 12469 12470 // Check for a valid return type. 12471 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12472 TheCall, Method)) 12473 return ExprError(); 12474 12475 // Convert the object argument (for a non-static member function call). 12476 // We only need to do this if there was actually an overload; otherwise 12477 // it was done at lookup. 12478 if (!Method->isStatic()) { 12479 ExprResult ObjectArg = 12480 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12481 FoundDecl, Method); 12482 if (ObjectArg.isInvalid()) 12483 return ExprError(); 12484 MemExpr->setBase(ObjectArg.get()); 12485 } 12486 12487 // Convert the rest of the arguments 12488 const FunctionProtoType *Proto = 12489 Method->getType()->getAs<FunctionProtoType>(); 12490 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12491 RParenLoc)) 12492 return ExprError(); 12493 12494 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12495 12496 if (CheckFunctionCall(Method, TheCall, Proto)) 12497 return ExprError(); 12498 12499 // In the case the method to call was not selected by the overloading 12500 // resolution process, we still need to handle the enable_if attribute. Do 12501 // that here, so it will not hide previous -- and more relevant -- errors. 12502 if (isa<MemberExpr>(NakedMemExpr)) { 12503 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12504 Diag(MemExprE->getLocStart(), 12505 diag::err_ovl_no_viable_member_function_in_call) 12506 << Method << Method->getSourceRange(); 12507 Diag(Method->getLocation(), 12508 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12509 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12510 return ExprError(); 12511 } 12512 } 12513 12514 if ((isa<CXXConstructorDecl>(CurContext) || 12515 isa<CXXDestructorDecl>(CurContext)) && 12516 TheCall->getMethodDecl()->isPure()) { 12517 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12518 12519 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12520 MemExpr->performsVirtualDispatch(getLangOpts())) { 12521 Diag(MemExpr->getLocStart(), 12522 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12523 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12524 << MD->getParent()->getDeclName(); 12525 12526 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12527 if (getLangOpts().AppleKext) 12528 Diag(MemExpr->getLocStart(), 12529 diag::note_pure_qualified_call_kext) 12530 << MD->getParent()->getDeclName() 12531 << MD->getDeclName(); 12532 } 12533 } 12534 12535 if (CXXDestructorDecl *DD = 12536 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12537 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12538 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12539 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12540 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12541 MemExpr->getMemberLoc()); 12542 } 12543 12544 return MaybeBindToTemporary(TheCall); 12545 } 12546 12547 /// BuildCallToObjectOfClassType - Build a call to an object of class 12548 /// type (C++ [over.call.object]), which can end up invoking an 12549 /// overloaded function call operator (@c operator()) or performing a 12550 /// user-defined conversion on the object argument. 12551 ExprResult 12552 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12553 SourceLocation LParenLoc, 12554 MultiExprArg Args, 12555 SourceLocation RParenLoc) { 12556 if (checkPlaceholderForOverload(*this, Obj)) 12557 return ExprError(); 12558 ExprResult Object = Obj; 12559 12560 UnbridgedCastsSet UnbridgedCasts; 12561 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12562 return ExprError(); 12563 12564 assert(Object.get()->getType()->isRecordType() && 12565 "Requires object type argument"); 12566 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12567 12568 // C++ [over.call.object]p1: 12569 // If the primary-expression E in the function call syntax 12570 // evaluates to a class object of type "cv T", then the set of 12571 // candidate functions includes at least the function call 12572 // operators of T. The function call operators of T are obtained by 12573 // ordinary lookup of the name operator() in the context of 12574 // (E).operator(). 12575 OverloadCandidateSet CandidateSet(LParenLoc, 12576 OverloadCandidateSet::CSK_Operator); 12577 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12578 12579 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12580 diag::err_incomplete_object_call, Object.get())) 12581 return true; 12582 12583 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12584 LookupQualifiedName(R, Record->getDecl()); 12585 R.suppressDiagnostics(); 12586 12587 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12588 Oper != OperEnd; ++Oper) { 12589 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12590 Object.get()->Classify(Context), 12591 Args, CandidateSet, 12592 /*SuppressUserConversions=*/ false); 12593 } 12594 12595 // C++ [over.call.object]p2: 12596 // In addition, for each (non-explicit in C++0x) conversion function 12597 // declared in T of the form 12598 // 12599 // operator conversion-type-id () cv-qualifier; 12600 // 12601 // where cv-qualifier is the same cv-qualification as, or a 12602 // greater cv-qualification than, cv, and where conversion-type-id 12603 // denotes the type "pointer to function of (P1,...,Pn) returning 12604 // R", or the type "reference to pointer to function of 12605 // (P1,...,Pn) returning R", or the type "reference to function 12606 // of (P1,...,Pn) returning R", a surrogate call function [...] 12607 // is also considered as a candidate function. Similarly, 12608 // surrogate call functions are added to the set of candidate 12609 // functions for each conversion function declared in an 12610 // accessible base class provided the function is not hidden 12611 // within T by another intervening declaration. 12612 const auto &Conversions = 12613 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12614 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12615 NamedDecl *D = *I; 12616 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12617 if (isa<UsingShadowDecl>(D)) 12618 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12619 12620 // Skip over templated conversion functions; they aren't 12621 // surrogates. 12622 if (isa<FunctionTemplateDecl>(D)) 12623 continue; 12624 12625 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12626 if (!Conv->isExplicit()) { 12627 // Strip the reference type (if any) and then the pointer type (if 12628 // any) to get down to what might be a function type. 12629 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12630 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12631 ConvType = ConvPtrType->getPointeeType(); 12632 12633 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12634 { 12635 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12636 Object.get(), Args, CandidateSet); 12637 } 12638 } 12639 } 12640 12641 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12642 12643 // Perform overload resolution. 12644 OverloadCandidateSet::iterator Best; 12645 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12646 Best)) { 12647 case OR_Success: 12648 // Overload resolution succeeded; we'll build the appropriate call 12649 // below. 12650 break; 12651 12652 case OR_No_Viable_Function: 12653 if (CandidateSet.empty()) 12654 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12655 << Object.get()->getType() << /*call*/ 1 12656 << Object.get()->getSourceRange(); 12657 else 12658 Diag(Object.get()->getLocStart(), 12659 diag::err_ovl_no_viable_object_call) 12660 << Object.get()->getType() << Object.get()->getSourceRange(); 12661 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12662 break; 12663 12664 case OR_Ambiguous: 12665 Diag(Object.get()->getLocStart(), 12666 diag::err_ovl_ambiguous_object_call) 12667 << Object.get()->getType() << Object.get()->getSourceRange(); 12668 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12669 break; 12670 12671 case OR_Deleted: 12672 Diag(Object.get()->getLocStart(), 12673 diag::err_ovl_deleted_object_call) 12674 << Best->Function->isDeleted() 12675 << Object.get()->getType() 12676 << getDeletedOrUnavailableSuffix(Best->Function) 12677 << Object.get()->getSourceRange(); 12678 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12679 break; 12680 } 12681 12682 if (Best == CandidateSet.end()) 12683 return true; 12684 12685 UnbridgedCasts.restore(); 12686 12687 if (Best->Function == nullptr) { 12688 // Since there is no function declaration, this is one of the 12689 // surrogate candidates. Dig out the conversion function. 12690 CXXConversionDecl *Conv 12691 = cast<CXXConversionDecl>( 12692 Best->Conversions[0].UserDefined.ConversionFunction); 12693 12694 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12695 Best->FoundDecl); 12696 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12697 return ExprError(); 12698 assert(Conv == Best->FoundDecl.getDecl() && 12699 "Found Decl & conversion-to-functionptr should be same, right?!"); 12700 // We selected one of the surrogate functions that converts the 12701 // object parameter to a function pointer. Perform the conversion 12702 // on the object argument, then let ActOnCallExpr finish the job. 12703 12704 // Create an implicit member expr to refer to the conversion operator. 12705 // and then call it. 12706 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12707 Conv, HadMultipleCandidates); 12708 if (Call.isInvalid()) 12709 return ExprError(); 12710 // Record usage of conversion in an implicit cast. 12711 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12712 CK_UserDefinedConversion, Call.get(), 12713 nullptr, VK_RValue); 12714 12715 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12716 } 12717 12718 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12719 12720 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12721 // that calls this method, using Object for the implicit object 12722 // parameter and passing along the remaining arguments. 12723 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12724 12725 // An error diagnostic has already been printed when parsing the declaration. 12726 if (Method->isInvalidDecl()) 12727 return ExprError(); 12728 12729 const FunctionProtoType *Proto = 12730 Method->getType()->getAs<FunctionProtoType>(); 12731 12732 unsigned NumParams = Proto->getNumParams(); 12733 12734 DeclarationNameInfo OpLocInfo( 12735 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12736 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12737 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12738 HadMultipleCandidates, 12739 OpLocInfo.getLoc(), 12740 OpLocInfo.getInfo()); 12741 if (NewFn.isInvalid()) 12742 return true; 12743 12744 // Build the full argument list for the method call (the implicit object 12745 // parameter is placed at the beginning of the list). 12746 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12747 MethodArgs[0] = Object.get(); 12748 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12749 12750 // Once we've built TheCall, all of the expressions are properly 12751 // owned. 12752 QualType ResultTy = Method->getReturnType(); 12753 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12754 ResultTy = ResultTy.getNonLValueExprType(Context); 12755 12756 CXXOperatorCallExpr *TheCall = new (Context) 12757 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12758 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12759 ResultTy, VK, RParenLoc, false); 12760 MethodArgs.reset(); 12761 12762 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12763 return true; 12764 12765 // We may have default arguments. If so, we need to allocate more 12766 // slots in the call for them. 12767 if (Args.size() < NumParams) 12768 TheCall->setNumArgs(Context, NumParams + 1); 12769 12770 bool IsError = false; 12771 12772 // Initialize the implicit object parameter. 12773 ExprResult ObjRes = 12774 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12775 Best->FoundDecl, Method); 12776 if (ObjRes.isInvalid()) 12777 IsError = true; 12778 else 12779 Object = ObjRes; 12780 TheCall->setArg(0, Object.get()); 12781 12782 // Check the argument types. 12783 for (unsigned i = 0; i != NumParams; i++) { 12784 Expr *Arg; 12785 if (i < Args.size()) { 12786 Arg = Args[i]; 12787 12788 // Pass the argument. 12789 12790 ExprResult InputInit 12791 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12792 Context, 12793 Method->getParamDecl(i)), 12794 SourceLocation(), Arg); 12795 12796 IsError |= InputInit.isInvalid(); 12797 Arg = InputInit.getAs<Expr>(); 12798 } else { 12799 ExprResult DefArg 12800 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12801 if (DefArg.isInvalid()) { 12802 IsError = true; 12803 break; 12804 } 12805 12806 Arg = DefArg.getAs<Expr>(); 12807 } 12808 12809 TheCall->setArg(i + 1, Arg); 12810 } 12811 12812 // If this is a variadic call, handle args passed through "...". 12813 if (Proto->isVariadic()) { 12814 // Promote the arguments (C99 6.5.2.2p7). 12815 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12816 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12817 nullptr); 12818 IsError |= Arg.isInvalid(); 12819 TheCall->setArg(i + 1, Arg.get()); 12820 } 12821 } 12822 12823 if (IsError) return true; 12824 12825 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12826 12827 if (CheckFunctionCall(Method, TheCall, Proto)) 12828 return true; 12829 12830 return MaybeBindToTemporary(TheCall); 12831 } 12832 12833 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12834 /// (if one exists), where @c Base is an expression of class type and 12835 /// @c Member is the name of the member we're trying to find. 12836 ExprResult 12837 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12838 bool *NoArrowOperatorFound) { 12839 assert(Base->getType()->isRecordType() && 12840 "left-hand side must have class type"); 12841 12842 if (checkPlaceholderForOverload(*this, Base)) 12843 return ExprError(); 12844 12845 SourceLocation Loc = Base->getExprLoc(); 12846 12847 // C++ [over.ref]p1: 12848 // 12849 // [...] An expression x->m is interpreted as (x.operator->())->m 12850 // for a class object x of type T if T::operator->() exists and if 12851 // the operator is selected as the best match function by the 12852 // overload resolution mechanism (13.3). 12853 DeclarationName OpName = 12854 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12855 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12856 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12857 12858 if (RequireCompleteType(Loc, Base->getType(), 12859 diag::err_typecheck_incomplete_tag, Base)) 12860 return ExprError(); 12861 12862 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12863 LookupQualifiedName(R, BaseRecord->getDecl()); 12864 R.suppressDiagnostics(); 12865 12866 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12867 Oper != OperEnd; ++Oper) { 12868 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12869 None, CandidateSet, /*SuppressUserConversions=*/false); 12870 } 12871 12872 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12873 12874 // Perform overload resolution. 12875 OverloadCandidateSet::iterator Best; 12876 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12877 case OR_Success: 12878 // Overload resolution succeeded; we'll build the call below. 12879 break; 12880 12881 case OR_No_Viable_Function: 12882 if (CandidateSet.empty()) { 12883 QualType BaseType = Base->getType(); 12884 if (NoArrowOperatorFound) { 12885 // Report this specific error to the caller instead of emitting a 12886 // diagnostic, as requested. 12887 *NoArrowOperatorFound = true; 12888 return ExprError(); 12889 } 12890 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12891 << BaseType << Base->getSourceRange(); 12892 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12893 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12894 << FixItHint::CreateReplacement(OpLoc, "."); 12895 } 12896 } else 12897 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12898 << "operator->" << Base->getSourceRange(); 12899 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12900 return ExprError(); 12901 12902 case OR_Ambiguous: 12903 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12904 << "->" << Base->getType() << Base->getSourceRange(); 12905 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12906 return ExprError(); 12907 12908 case OR_Deleted: 12909 Diag(OpLoc, diag::err_ovl_deleted_oper) 12910 << Best->Function->isDeleted() 12911 << "->" 12912 << getDeletedOrUnavailableSuffix(Best->Function) 12913 << Base->getSourceRange(); 12914 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12915 return ExprError(); 12916 } 12917 12918 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12919 12920 // Convert the object parameter. 12921 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12922 ExprResult BaseResult = 12923 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12924 Best->FoundDecl, Method); 12925 if (BaseResult.isInvalid()) 12926 return ExprError(); 12927 Base = BaseResult.get(); 12928 12929 // Build the operator call. 12930 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12931 HadMultipleCandidates, OpLoc); 12932 if (FnExpr.isInvalid()) 12933 return ExprError(); 12934 12935 QualType ResultTy = Method->getReturnType(); 12936 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12937 ResultTy = ResultTy.getNonLValueExprType(Context); 12938 CXXOperatorCallExpr *TheCall = 12939 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12940 Base, ResultTy, VK, OpLoc, false); 12941 12942 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12943 return ExprError(); 12944 12945 return MaybeBindToTemporary(TheCall); 12946 } 12947 12948 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12949 /// a literal operator described by the provided lookup results. 12950 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12951 DeclarationNameInfo &SuffixInfo, 12952 ArrayRef<Expr*> Args, 12953 SourceLocation LitEndLoc, 12954 TemplateArgumentListInfo *TemplateArgs) { 12955 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12956 12957 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12958 OverloadCandidateSet::CSK_Normal); 12959 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12960 /*SuppressUserConversions=*/true); 12961 12962 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12963 12964 // Perform overload resolution. This will usually be trivial, but might need 12965 // to perform substitutions for a literal operator template. 12966 OverloadCandidateSet::iterator Best; 12967 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12968 case OR_Success: 12969 case OR_Deleted: 12970 break; 12971 12972 case OR_No_Viable_Function: 12973 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12974 << R.getLookupName(); 12975 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12976 return ExprError(); 12977 12978 case OR_Ambiguous: 12979 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12980 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12981 return ExprError(); 12982 } 12983 12984 FunctionDecl *FD = Best->Function; 12985 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12986 HadMultipleCandidates, 12987 SuffixInfo.getLoc(), 12988 SuffixInfo.getInfo()); 12989 if (Fn.isInvalid()) 12990 return true; 12991 12992 // Check the argument types. This should almost always be a no-op, except 12993 // that array-to-pointer decay is applied to string literals. 12994 Expr *ConvArgs[2]; 12995 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12996 ExprResult InputInit = PerformCopyInitialization( 12997 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12998 SourceLocation(), Args[ArgIdx]); 12999 if (InputInit.isInvalid()) 13000 return true; 13001 ConvArgs[ArgIdx] = InputInit.get(); 13002 } 13003 13004 QualType ResultTy = FD->getReturnType(); 13005 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13006 ResultTy = ResultTy.getNonLValueExprType(Context); 13007 13008 UserDefinedLiteral *UDL = 13009 new (Context) UserDefinedLiteral(Context, Fn.get(), 13010 llvm::makeArrayRef(ConvArgs, Args.size()), 13011 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13012 13013 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13014 return ExprError(); 13015 13016 if (CheckFunctionCall(FD, UDL, nullptr)) 13017 return ExprError(); 13018 13019 return MaybeBindToTemporary(UDL); 13020 } 13021 13022 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13023 /// given LookupResult is non-empty, it is assumed to describe a member which 13024 /// will be invoked. Otherwise, the function will be found via argument 13025 /// dependent lookup. 13026 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13027 /// otherwise CallExpr is set to ExprError() and some non-success value 13028 /// is returned. 13029 Sema::ForRangeStatus 13030 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13031 SourceLocation RangeLoc, 13032 const DeclarationNameInfo &NameInfo, 13033 LookupResult &MemberLookup, 13034 OverloadCandidateSet *CandidateSet, 13035 Expr *Range, ExprResult *CallExpr) { 13036 Scope *S = nullptr; 13037 13038 CandidateSet->clear(); 13039 if (!MemberLookup.empty()) { 13040 ExprResult MemberRef = 13041 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13042 /*IsPtr=*/false, CXXScopeSpec(), 13043 /*TemplateKWLoc=*/SourceLocation(), 13044 /*FirstQualifierInScope=*/nullptr, 13045 MemberLookup, 13046 /*TemplateArgs=*/nullptr, S); 13047 if (MemberRef.isInvalid()) { 13048 *CallExpr = ExprError(); 13049 return FRS_DiagnosticIssued; 13050 } 13051 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13052 if (CallExpr->isInvalid()) { 13053 *CallExpr = ExprError(); 13054 return FRS_DiagnosticIssued; 13055 } 13056 } else { 13057 UnresolvedSet<0> FoundNames; 13058 UnresolvedLookupExpr *Fn = 13059 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13060 NestedNameSpecifierLoc(), NameInfo, 13061 /*NeedsADL=*/true, /*Overloaded=*/false, 13062 FoundNames.begin(), FoundNames.end()); 13063 13064 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13065 CandidateSet, CallExpr); 13066 if (CandidateSet->empty() || CandidateSetError) { 13067 *CallExpr = ExprError(); 13068 return FRS_NoViableFunction; 13069 } 13070 OverloadCandidateSet::iterator Best; 13071 OverloadingResult OverloadResult = 13072 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13073 13074 if (OverloadResult == OR_No_Viable_Function) { 13075 *CallExpr = ExprError(); 13076 return FRS_NoViableFunction; 13077 } 13078 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13079 Loc, nullptr, CandidateSet, &Best, 13080 OverloadResult, 13081 /*AllowTypoCorrection=*/false); 13082 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13083 *CallExpr = ExprError(); 13084 return FRS_DiagnosticIssued; 13085 } 13086 } 13087 return FRS_Success; 13088 } 13089 13090 13091 /// FixOverloadedFunctionReference - E is an expression that refers to 13092 /// a C++ overloaded function (possibly with some parentheses and 13093 /// perhaps a '&' around it). We have resolved the overloaded function 13094 /// to the function declaration Fn, so patch up the expression E to 13095 /// refer (possibly indirectly) to Fn. Returns the new expr. 13096 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13097 FunctionDecl *Fn) { 13098 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13099 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13100 Found, Fn); 13101 if (SubExpr == PE->getSubExpr()) 13102 return PE; 13103 13104 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13105 } 13106 13107 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13108 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13109 Found, Fn); 13110 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13111 SubExpr->getType()) && 13112 "Implicit cast type cannot be determined from overload"); 13113 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13114 if (SubExpr == ICE->getSubExpr()) 13115 return ICE; 13116 13117 return ImplicitCastExpr::Create(Context, ICE->getType(), 13118 ICE->getCastKind(), 13119 SubExpr, nullptr, 13120 ICE->getValueKind()); 13121 } 13122 13123 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13124 if (!GSE->isResultDependent()) { 13125 Expr *SubExpr = 13126 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13127 if (SubExpr == GSE->getResultExpr()) 13128 return GSE; 13129 13130 // Replace the resulting type information before rebuilding the generic 13131 // selection expression. 13132 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13133 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13134 unsigned ResultIdx = GSE->getResultIndex(); 13135 AssocExprs[ResultIdx] = SubExpr; 13136 13137 return new (Context) GenericSelectionExpr( 13138 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13139 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13140 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13141 ResultIdx); 13142 } 13143 // Rather than fall through to the unreachable, return the original generic 13144 // selection expression. 13145 return GSE; 13146 } 13147 13148 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13149 assert(UnOp->getOpcode() == UO_AddrOf && 13150 "Can only take the address of an overloaded function"); 13151 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13152 if (Method->isStatic()) { 13153 // Do nothing: static member functions aren't any different 13154 // from non-member functions. 13155 } else { 13156 // Fix the subexpression, which really has to be an 13157 // UnresolvedLookupExpr holding an overloaded member function 13158 // or template. 13159 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13160 Found, Fn); 13161 if (SubExpr == UnOp->getSubExpr()) 13162 return UnOp; 13163 13164 assert(isa<DeclRefExpr>(SubExpr) 13165 && "fixed to something other than a decl ref"); 13166 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13167 && "fixed to a member ref with no nested name qualifier"); 13168 13169 // We have taken the address of a pointer to member 13170 // function. Perform the computation here so that we get the 13171 // appropriate pointer to member type. 13172 QualType ClassType 13173 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13174 QualType MemPtrType 13175 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13176 // Under the MS ABI, lock down the inheritance model now. 13177 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13178 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13179 13180 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13181 VK_RValue, OK_Ordinary, 13182 UnOp->getOperatorLoc()); 13183 } 13184 } 13185 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13186 Found, Fn); 13187 if (SubExpr == UnOp->getSubExpr()) 13188 return UnOp; 13189 13190 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13191 Context.getPointerType(SubExpr->getType()), 13192 VK_RValue, OK_Ordinary, 13193 UnOp->getOperatorLoc()); 13194 } 13195 13196 // C++ [except.spec]p17: 13197 // An exception-specification is considered to be needed when: 13198 // - in an expression the function is the unique lookup result or the 13199 // selected member of a set of overloaded functions 13200 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13201 ResolveExceptionSpec(E->getExprLoc(), FPT); 13202 13203 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13204 // FIXME: avoid copy. 13205 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13206 if (ULE->hasExplicitTemplateArgs()) { 13207 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13208 TemplateArgs = &TemplateArgsBuffer; 13209 } 13210 13211 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13212 ULE->getQualifierLoc(), 13213 ULE->getTemplateKeywordLoc(), 13214 Fn, 13215 /*enclosing*/ false, // FIXME? 13216 ULE->getNameLoc(), 13217 Fn->getType(), 13218 VK_LValue, 13219 Found.getDecl(), 13220 TemplateArgs); 13221 MarkDeclRefReferenced(DRE); 13222 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13223 return DRE; 13224 } 13225 13226 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13227 // FIXME: avoid copy. 13228 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13229 if (MemExpr->hasExplicitTemplateArgs()) { 13230 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13231 TemplateArgs = &TemplateArgsBuffer; 13232 } 13233 13234 Expr *Base; 13235 13236 // If we're filling in a static method where we used to have an 13237 // implicit member access, rewrite to a simple decl ref. 13238 if (MemExpr->isImplicitAccess()) { 13239 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13240 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13241 MemExpr->getQualifierLoc(), 13242 MemExpr->getTemplateKeywordLoc(), 13243 Fn, 13244 /*enclosing*/ false, 13245 MemExpr->getMemberLoc(), 13246 Fn->getType(), 13247 VK_LValue, 13248 Found.getDecl(), 13249 TemplateArgs); 13250 MarkDeclRefReferenced(DRE); 13251 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13252 return DRE; 13253 } else { 13254 SourceLocation Loc = MemExpr->getMemberLoc(); 13255 if (MemExpr->getQualifier()) 13256 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13257 CheckCXXThisCapture(Loc); 13258 Base = new (Context) CXXThisExpr(Loc, 13259 MemExpr->getBaseType(), 13260 /*isImplicit=*/true); 13261 } 13262 } else 13263 Base = MemExpr->getBase(); 13264 13265 ExprValueKind valueKind; 13266 QualType type; 13267 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13268 valueKind = VK_LValue; 13269 type = Fn->getType(); 13270 } else { 13271 valueKind = VK_RValue; 13272 type = Context.BoundMemberTy; 13273 } 13274 13275 MemberExpr *ME = MemberExpr::Create( 13276 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13277 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13278 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13279 OK_Ordinary); 13280 ME->setHadMultipleCandidates(true); 13281 MarkMemberReferenced(ME); 13282 return ME; 13283 } 13284 13285 llvm_unreachable("Invalid reference to overloaded function"); 13286 } 13287 13288 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13289 DeclAccessPair Found, 13290 FunctionDecl *Fn) { 13291 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13292 } 13293