1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 64 VK_LValue, Loc, LocInfo); 65 if (HadMultipleCandidates) 66 DRE->setHadMultipleCandidates(true); 67 68 S.MarkDeclRefReferenced(DRE); 69 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 70 CK_FunctionToPointerDecay); 71 } 72 73 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 74 bool InOverloadResolution, 75 StandardConversionSequence &SCS, 76 bool CStyle, 77 bool AllowObjCWritebackConversion); 78 79 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 80 QualType &ToType, 81 bool InOverloadResolution, 82 StandardConversionSequence &SCS, 83 bool CStyle); 84 static OverloadingResult 85 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 86 UserDefinedConversionSequence& User, 87 OverloadCandidateSet& Conversions, 88 bool AllowExplicit, 89 bool AllowObjCConversionOnExplicit); 90 91 92 static ImplicitConversionSequence::CompareKind 93 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97 static ImplicitConversionSequence::CompareKind 98 CompareQualificationConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 static ImplicitConversionSequence::CompareKind 103 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 104 const StandardConversionSequence& SCS1, 105 const StandardConversionSequence& SCS2); 106 107 /// GetConversionRank - Retrieve the implicit conversion rank 108 /// corresponding to the given implicit conversion kind. 109 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 110 static const ImplicitConversionRank 111 Rank[(int)ICK_Num_Conversion_Kinds] = { 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Promotion, 119 ICR_Promotion, 120 ICR_Promotion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Complex_Real_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Writeback_Conversion, 136 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 137 // it was omitted by the patch that added 138 // ICK_Zero_Event_Conversion 139 ICR_C_Conversion, 140 ICR_C_Conversion_Extension 141 }; 142 return Rank[(int)Kind]; 143 } 144 145 /// GetImplicitConversionName - Return the name of this kind of 146 /// implicit conversion. 147 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 148 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 149 "No conversion", 150 "Lvalue-to-rvalue", 151 "Array-to-pointer", 152 "Function-to-pointer", 153 "Function pointer conversion", 154 "Qualification", 155 "Integral promotion", 156 "Floating point promotion", 157 "Complex promotion", 158 "Integral conversion", 159 "Floating conversion", 160 "Complex conversion", 161 "Floating-integral conversion", 162 "Pointer conversion", 163 "Pointer-to-member conversion", 164 "Boolean conversion", 165 "Compatible-types conversion", 166 "Derived-to-base conversion", 167 "Vector conversion", 168 "Vector splat", 169 "Complex-real conversion", 170 "Block Pointer conversion", 171 "Transparent Union Conversion", 172 "Writeback conversion", 173 "OpenCL Zero Event Conversion", 174 "C specific type conversion", 175 "Incompatible pointer conversion" 176 }; 177 return Name[Kind]; 178 } 179 180 /// StandardConversionSequence - Set the standard conversion 181 /// sequence to the identity conversion. 182 void StandardConversionSequence::setAsIdentityConversion() { 183 First = ICK_Identity; 184 Second = ICK_Identity; 185 Third = ICK_Identity; 186 DeprecatedStringLiteralToCharPtr = false; 187 QualificationIncludesObjCLifetime = false; 188 ReferenceBinding = false; 189 DirectBinding = false; 190 IsLvalueReference = true; 191 BindsToFunctionLvalue = false; 192 BindsToRvalue = false; 193 BindsImplicitObjectArgumentWithoutRefQualifier = false; 194 ObjCLifetimeConversionBinding = false; 195 CopyConstructor = nullptr; 196 } 197 198 /// getRank - Retrieve the rank of this standard conversion sequence 199 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 200 /// implicit conversions. 201 ImplicitConversionRank StandardConversionSequence::getRank() const { 202 ImplicitConversionRank Rank = ICR_Exact_Match; 203 if (GetConversionRank(First) > Rank) 204 Rank = GetConversionRank(First); 205 if (GetConversionRank(Second) > Rank) 206 Rank = GetConversionRank(Second); 207 if (GetConversionRank(Third) > Rank) 208 Rank = GetConversionRank(Third); 209 return Rank; 210 } 211 212 /// isPointerConversionToBool - Determines whether this conversion is 213 /// a conversion of a pointer or pointer-to-member to bool. This is 214 /// used as part of the ranking of standard conversion sequences 215 /// (C++ 13.3.3.2p4). 216 bool StandardConversionSequence::isPointerConversionToBool() const { 217 // Note that FromType has not necessarily been transformed by the 218 // array-to-pointer or function-to-pointer implicit conversions, so 219 // check for their presence as well as checking whether FromType is 220 // a pointer. 221 if (getToType(1)->isBooleanType() && 222 (getFromType()->isPointerType() || 223 getFromType()->isObjCObjectPointerType() || 224 getFromType()->isBlockPointerType() || 225 getFromType()->isNullPtrType() || 226 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 227 return true; 228 229 return false; 230 } 231 232 /// isPointerConversionToVoidPointer - Determines whether this 233 /// conversion is a conversion of a pointer to a void pointer. This is 234 /// used as part of the ranking of standard conversion sequences (C++ 235 /// 13.3.3.2p4). 236 bool 237 StandardConversionSequence:: 238 isPointerConversionToVoidPointer(ASTContext& Context) const { 239 QualType FromType = getFromType(); 240 QualType ToType = getToType(1); 241 242 // Note that FromType has not necessarily been transformed by the 243 // array-to-pointer implicit conversion, so check for its presence 244 // and redo the conversion to get a pointer. 245 if (First == ICK_Array_To_Pointer) 246 FromType = Context.getArrayDecayedType(FromType); 247 248 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 249 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 250 return ToPtrType->getPointeeType()->isVoidType(); 251 252 return false; 253 } 254 255 /// Skip any implicit casts which could be either part of a narrowing conversion 256 /// or after one in an implicit conversion. 257 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 258 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 259 switch (ICE->getCastKind()) { 260 case CK_NoOp: 261 case CK_IntegralCast: 262 case CK_IntegralToBoolean: 263 case CK_IntegralToFloating: 264 case CK_BooleanToSignedIntegral: 265 case CK_FloatingToIntegral: 266 case CK_FloatingToBoolean: 267 case CK_FloatingCast: 268 Converted = ICE->getSubExpr(); 269 continue; 270 271 default: 272 return Converted; 273 } 274 } 275 276 return Converted; 277 } 278 279 /// Check if this standard conversion sequence represents a narrowing 280 /// conversion, according to C++11 [dcl.init.list]p7. 281 /// 282 /// \param Ctx The AST context. 283 /// \param Converted The result of applying this standard conversion sequence. 284 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 285 /// value of the expression prior to the narrowing conversion. 286 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 287 /// type of the expression prior to the narrowing conversion. 288 NarrowingKind 289 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 290 const Expr *Converted, 291 APValue &ConstantValue, 292 QualType &ConstantType) const { 293 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 294 295 // C++11 [dcl.init.list]p7: 296 // A narrowing conversion is an implicit conversion ... 297 QualType FromType = getToType(0); 298 QualType ToType = getToType(1); 299 300 // A conversion to an enumeration type is narrowing if the conversion to 301 // the underlying type is narrowing. This only arises for expressions of 302 // the form 'Enum{init}'. 303 if (auto *ET = ToType->getAs<EnumType>()) 304 ToType = ET->getDecl()->getIntegerType(); 305 306 switch (Second) { 307 // 'bool' is an integral type; dispatch to the right place to handle it. 308 case ICK_Boolean_Conversion: 309 if (FromType->isRealFloatingType()) 310 goto FloatingIntegralConversion; 311 if (FromType->isIntegralOrUnscopedEnumerationType()) 312 goto IntegralConversion; 313 // Boolean conversions can be from pointers and pointers to members 314 // [conv.bool], and those aren't considered narrowing conversions. 315 return NK_Not_Narrowing; 316 317 // -- from a floating-point type to an integer type, or 318 // 319 // -- from an integer type or unscoped enumeration type to a floating-point 320 // type, except where the source is a constant expression and the actual 321 // value after conversion will fit into the target type and will produce 322 // the original value when converted back to the original type, or 323 case ICK_Floating_Integral: 324 FloatingIntegralConversion: 325 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 326 return NK_Type_Narrowing; 327 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 328 llvm::APSInt IntConstantValue; 329 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 330 if (Initializer && 331 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 332 // Convert the integer to the floating type. 333 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 334 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 335 llvm::APFloat::rmNearestTiesToEven); 336 // And back. 337 llvm::APSInt ConvertedValue = IntConstantValue; 338 bool ignored; 339 Result.convertToInteger(ConvertedValue, 340 llvm::APFloat::rmTowardZero, &ignored); 341 // If the resulting value is different, this was a narrowing conversion. 342 if (IntConstantValue != ConvertedValue) { 343 ConstantValue = APValue(IntConstantValue); 344 ConstantType = Initializer->getType(); 345 return NK_Constant_Narrowing; 346 } 347 } else { 348 // Variables are always narrowings. 349 return NK_Variable_Narrowing; 350 } 351 } 352 return NK_Not_Narrowing; 353 354 // -- from long double to double or float, or from double to float, except 355 // where the source is a constant expression and the actual value after 356 // conversion is within the range of values that can be represented (even 357 // if it cannot be represented exactly), or 358 case ICK_Floating_Conversion: 359 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 360 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 361 // FromType is larger than ToType. 362 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 363 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 364 // Constant! 365 assert(ConstantValue.isFloat()); 366 llvm::APFloat FloatVal = ConstantValue.getFloat(); 367 // Convert the source value into the target type. 368 bool ignored; 369 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 370 Ctx.getFloatTypeSemantics(ToType), 371 llvm::APFloat::rmNearestTiesToEven, &ignored); 372 // If there was no overflow, the source value is within the range of 373 // values that can be represented. 374 if (ConvertStatus & llvm::APFloat::opOverflow) { 375 ConstantType = Initializer->getType(); 376 return NK_Constant_Narrowing; 377 } 378 } else { 379 return NK_Variable_Narrowing; 380 } 381 } 382 return NK_Not_Narrowing; 383 384 // -- from an integer type or unscoped enumeration type to an integer type 385 // that cannot represent all the values of the original type, except where 386 // the source is a constant expression and the actual value after 387 // conversion will fit into the target type and will produce the original 388 // value when converted back to the original type. 389 case ICK_Integral_Conversion: 390 IntegralConversion: { 391 assert(FromType->isIntegralOrUnscopedEnumerationType()); 392 assert(ToType->isIntegralOrUnscopedEnumerationType()); 393 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 394 const unsigned FromWidth = Ctx.getIntWidth(FromType); 395 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 396 const unsigned ToWidth = Ctx.getIntWidth(ToType); 397 398 if (FromWidth > ToWidth || 399 (FromWidth == ToWidth && FromSigned != ToSigned) || 400 (FromSigned && !ToSigned)) { 401 // Not all values of FromType can be represented in ToType. 402 llvm::APSInt InitializerValue; 403 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 404 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 405 // Such conversions on variables are always narrowing. 406 return NK_Variable_Narrowing; 407 } 408 bool Narrowing = false; 409 if (FromWidth < ToWidth) { 410 // Negative -> unsigned is narrowing. Otherwise, more bits is never 411 // narrowing. 412 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 413 Narrowing = true; 414 } else { 415 // Add a bit to the InitializerValue so we don't have to worry about 416 // signed vs. unsigned comparisons. 417 InitializerValue = InitializerValue.extend( 418 InitializerValue.getBitWidth() + 1); 419 // Convert the initializer to and from the target width and signed-ness. 420 llvm::APSInt ConvertedValue = InitializerValue; 421 ConvertedValue = ConvertedValue.trunc(ToWidth); 422 ConvertedValue.setIsSigned(ToSigned); 423 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 424 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 425 // If the result is different, this was a narrowing conversion. 426 if (ConvertedValue != InitializerValue) 427 Narrowing = true; 428 } 429 if (Narrowing) { 430 ConstantType = Initializer->getType(); 431 ConstantValue = APValue(InitializerValue); 432 return NK_Constant_Narrowing; 433 } 434 } 435 return NK_Not_Narrowing; 436 } 437 438 default: 439 // Other kinds of conversions are not narrowings. 440 return NK_Not_Narrowing; 441 } 442 } 443 444 /// dump - Print this standard conversion sequence to standard 445 /// error. Useful for debugging overloading issues. 446 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 447 raw_ostream &OS = llvm::errs(); 448 bool PrintedSomething = false; 449 if (First != ICK_Identity) { 450 OS << GetImplicitConversionName(First); 451 PrintedSomething = true; 452 } 453 454 if (Second != ICK_Identity) { 455 if (PrintedSomething) { 456 OS << " -> "; 457 } 458 OS << GetImplicitConversionName(Second); 459 460 if (CopyConstructor) { 461 OS << " (by copy constructor)"; 462 } else if (DirectBinding) { 463 OS << " (direct reference binding)"; 464 } else if (ReferenceBinding) { 465 OS << " (reference binding)"; 466 } 467 PrintedSomething = true; 468 } 469 470 if (Third != ICK_Identity) { 471 if (PrintedSomething) { 472 OS << " -> "; 473 } 474 OS << GetImplicitConversionName(Third); 475 PrintedSomething = true; 476 } 477 478 if (!PrintedSomething) { 479 OS << "No conversions required"; 480 } 481 } 482 483 /// dump - Print this user-defined conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 void UserDefinedConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 if (Before.First || Before.Second || Before.Third) { 488 Before.dump(); 489 OS << " -> "; 490 } 491 if (ConversionFunction) 492 OS << '\'' << *ConversionFunction << '\''; 493 else 494 OS << "aggregate initialization"; 495 if (After.First || After.Second || After.Third) { 496 OS << " -> "; 497 After.dump(); 498 } 499 } 500 501 /// dump - Print this implicit conversion sequence to standard 502 /// error. Useful for debugging overloading issues. 503 void ImplicitConversionSequence::dump() const { 504 raw_ostream &OS = llvm::errs(); 505 if (isStdInitializerListElement()) 506 OS << "Worst std::initializer_list element conversion: "; 507 switch (ConversionKind) { 508 case StandardConversion: 509 OS << "Standard conversion: "; 510 Standard.dump(); 511 break; 512 case UserDefinedConversion: 513 OS << "User-defined conversion: "; 514 UserDefined.dump(); 515 break; 516 case EllipsisConversion: 517 OS << "Ellipsis conversion"; 518 break; 519 case AmbiguousConversion: 520 OS << "Ambiguous conversion"; 521 break; 522 case BadConversion: 523 OS << "Bad conversion"; 524 break; 525 } 526 527 OS << "\n"; 528 } 529 530 void AmbiguousConversionSequence::construct() { 531 new (&conversions()) ConversionSet(); 532 } 533 534 void AmbiguousConversionSequence::destruct() { 535 conversions().~ConversionSet(); 536 } 537 538 void 539 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 540 FromTypePtr = O.FromTypePtr; 541 ToTypePtr = O.ToTypePtr; 542 new (&conversions()) ConversionSet(O.conversions()); 543 } 544 545 namespace { 546 // Structure used by DeductionFailureInfo to store 547 // template argument information. 548 struct DFIArguments { 549 TemplateArgument FirstArg; 550 TemplateArgument SecondArg; 551 }; 552 // Structure used by DeductionFailureInfo to store 553 // template parameter and template argument information. 554 struct DFIParamWithArguments : DFIArguments { 555 TemplateParameter Param; 556 }; 557 // Structure used by DeductionFailureInfo to store template argument 558 // information and the index of the problematic call argument. 559 struct DFIDeducedMismatchArgs : DFIArguments { 560 TemplateArgumentList *TemplateArgs; 561 unsigned CallArgIndex; 562 }; 563 } 564 565 /// \brief Convert from Sema's representation of template deduction information 566 /// to the form used in overload-candidate information. 567 DeductionFailureInfo 568 clang::MakeDeductionFailureInfo(ASTContext &Context, 569 Sema::TemplateDeductionResult TDK, 570 TemplateDeductionInfo &Info) { 571 DeductionFailureInfo Result; 572 Result.Result = static_cast<unsigned>(TDK); 573 Result.HasDiagnostic = false; 574 switch (TDK) { 575 case Sema::TDK_Success: 576 case Sema::TDK_Invalid: 577 case Sema::TDK_InstantiationDepth: 578 case Sema::TDK_TooManyArguments: 579 case Sema::TDK_TooFewArguments: 580 case Sema::TDK_MiscellaneousDeductionFailure: 581 Result.Data = nullptr; 582 break; 583 584 case Sema::TDK_Incomplete: 585 case Sema::TDK_InvalidExplicitArguments: 586 Result.Data = Info.Param.getOpaqueValue(); 587 break; 588 589 case Sema::TDK_DeducedMismatch: { 590 // FIXME: Should allocate from normal heap so that we can free this later. 591 auto *Saved = new (Context) DFIDeducedMismatchArgs; 592 Saved->FirstArg = Info.FirstArg; 593 Saved->SecondArg = Info.SecondArg; 594 Saved->TemplateArgs = Info.take(); 595 Saved->CallArgIndex = Info.CallArgIndex; 596 Result.Data = Saved; 597 break; 598 } 599 600 case Sema::TDK_NonDeducedMismatch: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIArguments *Saved = new (Context) DFIArguments; 603 Saved->FirstArg = Info.FirstArg; 604 Saved->SecondArg = Info.SecondArg; 605 Result.Data = Saved; 606 break; 607 } 608 609 case Sema::TDK_Inconsistent: 610 case Sema::TDK_Underqualified: { 611 // FIXME: Should allocate from normal heap so that we can free this later. 612 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 613 Saved->Param = Info.Param; 614 Saved->FirstArg = Info.FirstArg; 615 Saved->SecondArg = Info.SecondArg; 616 Result.Data = Saved; 617 break; 618 } 619 620 case Sema::TDK_SubstitutionFailure: 621 Result.Data = Info.take(); 622 if (Info.hasSFINAEDiagnostic()) { 623 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 624 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 625 Info.takeSFINAEDiagnostic(*Diag); 626 Result.HasDiagnostic = true; 627 } 628 break; 629 630 case Sema::TDK_FailedOverloadResolution: 631 Result.Data = Info.Expression; 632 break; 633 } 634 635 return Result; 636 } 637 638 void DeductionFailureInfo::Destroy() { 639 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 640 case Sema::TDK_Success: 641 case Sema::TDK_Invalid: 642 case Sema::TDK_InstantiationDepth: 643 case Sema::TDK_Incomplete: 644 case Sema::TDK_TooManyArguments: 645 case Sema::TDK_TooFewArguments: 646 case Sema::TDK_InvalidExplicitArguments: 647 case Sema::TDK_FailedOverloadResolution: 648 break; 649 650 case Sema::TDK_Inconsistent: 651 case Sema::TDK_Underqualified: 652 case Sema::TDK_DeducedMismatch: 653 case Sema::TDK_NonDeducedMismatch: 654 // FIXME: Destroy the data? 655 Data = nullptr; 656 break; 657 658 case Sema::TDK_SubstitutionFailure: 659 // FIXME: Destroy the template argument list? 660 Data = nullptr; 661 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 662 Diag->~PartialDiagnosticAt(); 663 HasDiagnostic = false; 664 } 665 break; 666 667 // Unhandled 668 case Sema::TDK_MiscellaneousDeductionFailure: 669 break; 670 } 671 } 672 673 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 674 if (HasDiagnostic) 675 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 676 return nullptr; 677 } 678 679 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 681 case Sema::TDK_Success: 682 case Sema::TDK_Invalid: 683 case Sema::TDK_InstantiationDepth: 684 case Sema::TDK_TooManyArguments: 685 case Sema::TDK_TooFewArguments: 686 case Sema::TDK_SubstitutionFailure: 687 case Sema::TDK_DeducedMismatch: 688 case Sema::TDK_NonDeducedMismatch: 689 case Sema::TDK_FailedOverloadResolution: 690 return TemplateParameter(); 691 692 case Sema::TDK_Incomplete: 693 case Sema::TDK_InvalidExplicitArguments: 694 return TemplateParameter::getFromOpaqueValue(Data); 695 696 case Sema::TDK_Inconsistent: 697 case Sema::TDK_Underqualified: 698 return static_cast<DFIParamWithArguments*>(Data)->Param; 699 700 // Unhandled 701 case Sema::TDK_MiscellaneousDeductionFailure: 702 break; 703 } 704 705 return TemplateParameter(); 706 } 707 708 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 709 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 710 case Sema::TDK_Success: 711 case Sema::TDK_Invalid: 712 case Sema::TDK_InstantiationDepth: 713 case Sema::TDK_TooManyArguments: 714 case Sema::TDK_TooFewArguments: 715 case Sema::TDK_Incomplete: 716 case Sema::TDK_InvalidExplicitArguments: 717 case Sema::TDK_Inconsistent: 718 case Sema::TDK_Underqualified: 719 case Sema::TDK_NonDeducedMismatch: 720 case Sema::TDK_FailedOverloadResolution: 721 return nullptr; 722 723 case Sema::TDK_DeducedMismatch: 724 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 725 726 case Sema::TDK_SubstitutionFailure: 727 return static_cast<TemplateArgumentList*>(Data); 728 729 // Unhandled 730 case Sema::TDK_MiscellaneousDeductionFailure: 731 break; 732 } 733 734 return nullptr; 735 } 736 737 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 738 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 739 case Sema::TDK_Success: 740 case Sema::TDK_Invalid: 741 case Sema::TDK_InstantiationDepth: 742 case Sema::TDK_Incomplete: 743 case Sema::TDK_TooManyArguments: 744 case Sema::TDK_TooFewArguments: 745 case Sema::TDK_InvalidExplicitArguments: 746 case Sema::TDK_SubstitutionFailure: 747 case Sema::TDK_FailedOverloadResolution: 748 return nullptr; 749 750 case Sema::TDK_Inconsistent: 751 case Sema::TDK_Underqualified: 752 case Sema::TDK_DeducedMismatch: 753 case Sema::TDK_NonDeducedMismatch: 754 return &static_cast<DFIArguments*>(Data)->FirstArg; 755 756 // Unhandled 757 case Sema::TDK_MiscellaneousDeductionFailure: 758 break; 759 } 760 761 return nullptr; 762 } 763 764 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 765 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 766 case Sema::TDK_Success: 767 case Sema::TDK_Invalid: 768 case Sema::TDK_InstantiationDepth: 769 case Sema::TDK_Incomplete: 770 case Sema::TDK_TooManyArguments: 771 case Sema::TDK_TooFewArguments: 772 case Sema::TDK_InvalidExplicitArguments: 773 case Sema::TDK_SubstitutionFailure: 774 case Sema::TDK_FailedOverloadResolution: 775 return nullptr; 776 777 case Sema::TDK_Inconsistent: 778 case Sema::TDK_Underqualified: 779 case Sema::TDK_DeducedMismatch: 780 case Sema::TDK_NonDeducedMismatch: 781 return &static_cast<DFIArguments*>(Data)->SecondArg; 782 783 // Unhandled 784 case Sema::TDK_MiscellaneousDeductionFailure: 785 break; 786 } 787 788 return nullptr; 789 } 790 791 Expr *DeductionFailureInfo::getExpr() { 792 if (static_cast<Sema::TemplateDeductionResult>(Result) == 793 Sema::TDK_FailedOverloadResolution) 794 return static_cast<Expr*>(Data); 795 796 return nullptr; 797 } 798 799 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 800 if (static_cast<Sema::TemplateDeductionResult>(Result) == 801 Sema::TDK_DeducedMismatch) 802 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 803 804 return llvm::None; 805 } 806 807 void OverloadCandidateSet::destroyCandidates() { 808 for (iterator i = begin(), e = end(); i != e; ++i) { 809 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 810 i->Conversions[ii].~ImplicitConversionSequence(); 811 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 812 i->DeductionFailure.Destroy(); 813 } 814 } 815 816 void OverloadCandidateSet::clear() { 817 destroyCandidates(); 818 NumInlineSequences = 0; 819 Candidates.clear(); 820 Functions.clear(); 821 } 822 823 namespace { 824 class UnbridgedCastsSet { 825 struct Entry { 826 Expr **Addr; 827 Expr *Saved; 828 }; 829 SmallVector<Entry, 2> Entries; 830 831 public: 832 void save(Sema &S, Expr *&E) { 833 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 834 Entry entry = { &E, E }; 835 Entries.push_back(entry); 836 E = S.stripARCUnbridgedCast(E); 837 } 838 839 void restore() { 840 for (SmallVectorImpl<Entry>::iterator 841 i = Entries.begin(), e = Entries.end(); i != e; ++i) 842 *i->Addr = i->Saved; 843 } 844 }; 845 } 846 847 /// checkPlaceholderForOverload - Do any interesting placeholder-like 848 /// preprocessing on the given expression. 849 /// 850 /// \param unbridgedCasts a collection to which to add unbridged casts; 851 /// without this, they will be immediately diagnosed as errors 852 /// 853 /// Return true on unrecoverable error. 854 static bool 855 checkPlaceholderForOverload(Sema &S, Expr *&E, 856 UnbridgedCastsSet *unbridgedCasts = nullptr) { 857 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 858 // We can't handle overloaded expressions here because overload 859 // resolution might reasonably tweak them. 860 if (placeholder->getKind() == BuiltinType::Overload) return false; 861 862 // If the context potentially accepts unbridged ARC casts, strip 863 // the unbridged cast and add it to the collection for later restoration. 864 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 865 unbridgedCasts) { 866 unbridgedCasts->save(S, E); 867 return false; 868 } 869 870 // Go ahead and check everything else. 871 ExprResult result = S.CheckPlaceholderExpr(E); 872 if (result.isInvalid()) 873 return true; 874 875 E = result.get(); 876 return false; 877 } 878 879 // Nothing to do. 880 return false; 881 } 882 883 /// checkArgPlaceholdersForOverload - Check a set of call operands for 884 /// placeholders. 885 static bool checkArgPlaceholdersForOverload(Sema &S, 886 MultiExprArg Args, 887 UnbridgedCastsSet &unbridged) { 888 for (unsigned i = 0, e = Args.size(); i != e; ++i) 889 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 890 return true; 891 892 return false; 893 } 894 895 // IsOverload - Determine whether the given New declaration is an 896 // overload of the declarations in Old. This routine returns false if 897 // New and Old cannot be overloaded, e.g., if New has the same 898 // signature as some function in Old (C++ 1.3.10) or if the Old 899 // declarations aren't functions (or function templates) at all. When 900 // it does return false, MatchedDecl will point to the decl that New 901 // cannot be overloaded with. This decl may be a UsingShadowDecl on 902 // top of the underlying declaration. 903 // 904 // Example: Given the following input: 905 // 906 // void f(int, float); // #1 907 // void f(int, int); // #2 908 // int f(int, int); // #3 909 // 910 // When we process #1, there is no previous declaration of "f", 911 // so IsOverload will not be used. 912 // 913 // When we process #2, Old contains only the FunctionDecl for #1. By 914 // comparing the parameter types, we see that #1 and #2 are overloaded 915 // (since they have different signatures), so this routine returns 916 // false; MatchedDecl is unchanged. 917 // 918 // When we process #3, Old is an overload set containing #1 and #2. We 919 // compare the signatures of #3 to #1 (they're overloaded, so we do 920 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 921 // identical (return types of functions are not part of the 922 // signature), IsOverload returns false and MatchedDecl will be set to 923 // point to the FunctionDecl for #2. 924 // 925 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 926 // into a class by a using declaration. The rules for whether to hide 927 // shadow declarations ignore some properties which otherwise figure 928 // into a function template's signature. 929 Sema::OverloadKind 930 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 931 NamedDecl *&Match, bool NewIsUsingDecl) { 932 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 933 I != E; ++I) { 934 NamedDecl *OldD = *I; 935 936 bool OldIsUsingDecl = false; 937 if (isa<UsingShadowDecl>(OldD)) { 938 OldIsUsingDecl = true; 939 940 // We can always introduce two using declarations into the same 941 // context, even if they have identical signatures. 942 if (NewIsUsingDecl) continue; 943 944 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 945 } 946 947 // A using-declaration does not conflict with another declaration 948 // if one of them is hidden. 949 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 950 continue; 951 952 // If either declaration was introduced by a using declaration, 953 // we'll need to use slightly different rules for matching. 954 // Essentially, these rules are the normal rules, except that 955 // function templates hide function templates with different 956 // return types or template parameter lists. 957 bool UseMemberUsingDeclRules = 958 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 959 !New->getFriendObjectKind(); 960 961 if (FunctionDecl *OldF = OldD->getAsFunction()) { 962 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 963 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 964 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 965 continue; 966 } 967 968 if (!isa<FunctionTemplateDecl>(OldD) && 969 !shouldLinkPossiblyHiddenDecl(*I, New)) 970 continue; 971 972 Match = *I; 973 return Ovl_Match; 974 } 975 } else if (isa<UsingDecl>(OldD)) { 976 // We can overload with these, which can show up when doing 977 // redeclaration checks for UsingDecls. 978 assert(Old.getLookupKind() == LookupUsingDeclName); 979 } else if (isa<TagDecl>(OldD)) { 980 // We can always overload with tags by hiding them. 981 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 982 // Optimistically assume that an unresolved using decl will 983 // overload; if it doesn't, we'll have to diagnose during 984 // template instantiation. 985 } else { 986 // (C++ 13p1): 987 // Only function declarations can be overloaded; object and type 988 // declarations cannot be overloaded. 989 Match = *I; 990 return Ovl_NonFunction; 991 } 992 } 993 994 return Ovl_Overload; 995 } 996 997 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 998 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 999 // C++ [basic.start.main]p2: This function shall not be overloaded. 1000 if (New->isMain()) 1001 return false; 1002 1003 // MSVCRT user defined entry points cannot be overloaded. 1004 if (New->isMSVCRTEntryPoint()) 1005 return false; 1006 1007 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1008 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1009 1010 // C++ [temp.fct]p2: 1011 // A function template can be overloaded with other function templates 1012 // and with normal (non-template) functions. 1013 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1014 return true; 1015 1016 // Is the function New an overload of the function Old? 1017 QualType OldQType = Context.getCanonicalType(Old->getType()); 1018 QualType NewQType = Context.getCanonicalType(New->getType()); 1019 1020 // Compare the signatures (C++ 1.3.10) of the two functions to 1021 // determine whether they are overloads. If we find any mismatch 1022 // in the signature, they are overloads. 1023 1024 // If either of these functions is a K&R-style function (no 1025 // prototype), then we consider them to have matching signatures. 1026 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1027 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1028 return false; 1029 1030 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1031 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1032 1033 // The signature of a function includes the types of its 1034 // parameters (C++ 1.3.10), which includes the presence or absence 1035 // of the ellipsis; see C++ DR 357). 1036 if (OldQType != NewQType && 1037 (OldType->getNumParams() != NewType->getNumParams() || 1038 OldType->isVariadic() != NewType->isVariadic() || 1039 !FunctionParamTypesAreEqual(OldType, NewType))) 1040 return true; 1041 1042 // C++ [temp.over.link]p4: 1043 // The signature of a function template consists of its function 1044 // signature, its return type and its template parameter list. The names 1045 // of the template parameters are significant only for establishing the 1046 // relationship between the template parameters and the rest of the 1047 // signature. 1048 // 1049 // We check the return type and template parameter lists for function 1050 // templates first; the remaining checks follow. 1051 // 1052 // However, we don't consider either of these when deciding whether 1053 // a member introduced by a shadow declaration is hidden. 1054 if (!UseMemberUsingDeclRules && NewTemplate && 1055 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1056 OldTemplate->getTemplateParameters(), 1057 false, TPL_TemplateMatch) || 1058 OldType->getReturnType() != NewType->getReturnType())) 1059 return true; 1060 1061 // If the function is a class member, its signature includes the 1062 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1063 // 1064 // As part of this, also check whether one of the member functions 1065 // is static, in which case they are not overloads (C++ 1066 // 13.1p2). While not part of the definition of the signature, 1067 // this check is important to determine whether these functions 1068 // can be overloaded. 1069 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1070 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1071 if (OldMethod && NewMethod && 1072 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1073 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1074 if (!UseMemberUsingDeclRules && 1075 (OldMethod->getRefQualifier() == RQ_None || 1076 NewMethod->getRefQualifier() == RQ_None)) { 1077 // C++0x [over.load]p2: 1078 // - Member function declarations with the same name and the same 1079 // parameter-type-list as well as member function template 1080 // declarations with the same name, the same parameter-type-list, and 1081 // the same template parameter lists cannot be overloaded if any of 1082 // them, but not all, have a ref-qualifier (8.3.5). 1083 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1084 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1085 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1086 } 1087 return true; 1088 } 1089 1090 // We may not have applied the implicit const for a constexpr member 1091 // function yet (because we haven't yet resolved whether this is a static 1092 // or non-static member function). Add it now, on the assumption that this 1093 // is a redeclaration of OldMethod. 1094 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1095 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1096 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1097 !isa<CXXConstructorDecl>(NewMethod)) 1098 NewQuals |= Qualifiers::Const; 1099 1100 // We do not allow overloading based off of '__restrict'. 1101 OldQuals &= ~Qualifiers::Restrict; 1102 NewQuals &= ~Qualifiers::Restrict; 1103 if (OldQuals != NewQuals) 1104 return true; 1105 } 1106 1107 // Though pass_object_size is placed on parameters and takes an argument, we 1108 // consider it to be a function-level modifier for the sake of function 1109 // identity. Either the function has one or more parameters with 1110 // pass_object_size or it doesn't. 1111 if (functionHasPassObjectSizeParams(New) != 1112 functionHasPassObjectSizeParams(Old)) 1113 return true; 1114 1115 // enable_if attributes are an order-sensitive part of the signature. 1116 for (specific_attr_iterator<EnableIfAttr> 1117 NewI = New->specific_attr_begin<EnableIfAttr>(), 1118 NewE = New->specific_attr_end<EnableIfAttr>(), 1119 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1120 OldE = Old->specific_attr_end<EnableIfAttr>(); 1121 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1122 if (NewI == NewE || OldI == OldE) 1123 return true; 1124 llvm::FoldingSetNodeID NewID, OldID; 1125 NewI->getCond()->Profile(NewID, Context, true); 1126 OldI->getCond()->Profile(OldID, Context, true); 1127 if (NewID != OldID) 1128 return true; 1129 } 1130 1131 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1132 // Don't allow overloading of destructors. (In theory we could, but it 1133 // would be a giant change to clang.) 1134 if (isa<CXXDestructorDecl>(New)) 1135 return false; 1136 1137 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1138 OldTarget = IdentifyCUDATarget(Old); 1139 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1140 return false; 1141 1142 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1143 1144 // Don't allow HD and global functions to overload other functions with the 1145 // same signature. We allow overloading based on CUDA attributes so that 1146 // functions can have different implementations on the host and device, but 1147 // HD/global functions "exist" in some sense on both the host and device, so 1148 // should have the same implementation on both sides. 1149 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1150 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1151 return false; 1152 1153 // Allow overloading of functions with same signature and different CUDA 1154 // target attributes. 1155 return NewTarget != OldTarget; 1156 } 1157 1158 // The signatures match; this is not an overload. 1159 return false; 1160 } 1161 1162 /// \brief Checks availability of the function depending on the current 1163 /// function context. Inside an unavailable function, unavailability is ignored. 1164 /// 1165 /// \returns true if \arg FD is unavailable and current context is inside 1166 /// an available function, false otherwise. 1167 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1168 if (!FD->isUnavailable()) 1169 return false; 1170 1171 // Walk up the context of the caller. 1172 Decl *C = cast<Decl>(CurContext); 1173 do { 1174 if (C->isUnavailable()) 1175 return false; 1176 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1177 return true; 1178 } 1179 1180 /// \brief Tries a user-defined conversion from From to ToType. 1181 /// 1182 /// Produces an implicit conversion sequence for when a standard conversion 1183 /// is not an option. See TryImplicitConversion for more information. 1184 static ImplicitConversionSequence 1185 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1186 bool SuppressUserConversions, 1187 bool AllowExplicit, 1188 bool InOverloadResolution, 1189 bool CStyle, 1190 bool AllowObjCWritebackConversion, 1191 bool AllowObjCConversionOnExplicit) { 1192 ImplicitConversionSequence ICS; 1193 1194 if (SuppressUserConversions) { 1195 // We're not in the case above, so there is no conversion that 1196 // we can perform. 1197 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1198 return ICS; 1199 } 1200 1201 // Attempt user-defined conversion. 1202 OverloadCandidateSet Conversions(From->getExprLoc(), 1203 OverloadCandidateSet::CSK_Normal); 1204 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1205 Conversions, AllowExplicit, 1206 AllowObjCConversionOnExplicit)) { 1207 case OR_Success: 1208 case OR_Deleted: 1209 ICS.setUserDefined(); 1210 // C++ [over.ics.user]p4: 1211 // A conversion of an expression of class type to the same class 1212 // type is given Exact Match rank, and a conversion of an 1213 // expression of class type to a base class of that type is 1214 // given Conversion rank, in spite of the fact that a copy 1215 // constructor (i.e., a user-defined conversion function) is 1216 // called for those cases. 1217 if (CXXConstructorDecl *Constructor 1218 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1219 QualType FromCanon 1220 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1221 QualType ToCanon 1222 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1223 if (Constructor->isCopyConstructor() && 1224 (FromCanon == ToCanon || 1225 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1226 // Turn this into a "standard" conversion sequence, so that it 1227 // gets ranked with standard conversion sequences. 1228 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1229 ICS.setStandard(); 1230 ICS.Standard.setAsIdentityConversion(); 1231 ICS.Standard.setFromType(From->getType()); 1232 ICS.Standard.setAllToTypes(ToType); 1233 ICS.Standard.CopyConstructor = Constructor; 1234 ICS.Standard.FoundCopyConstructor = Found; 1235 if (ToCanon != FromCanon) 1236 ICS.Standard.Second = ICK_Derived_To_Base; 1237 } 1238 } 1239 break; 1240 1241 case OR_Ambiguous: 1242 ICS.setAmbiguous(); 1243 ICS.Ambiguous.setFromType(From->getType()); 1244 ICS.Ambiguous.setToType(ToType); 1245 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1246 Cand != Conversions.end(); ++Cand) 1247 if (Cand->Viable) 1248 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1249 break; 1250 1251 // Fall through. 1252 case OR_No_Viable_Function: 1253 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1254 break; 1255 } 1256 1257 return ICS; 1258 } 1259 1260 /// TryImplicitConversion - Attempt to perform an implicit conversion 1261 /// from the given expression (Expr) to the given type (ToType). This 1262 /// function returns an implicit conversion sequence that can be used 1263 /// to perform the initialization. Given 1264 /// 1265 /// void f(float f); 1266 /// void g(int i) { f(i); } 1267 /// 1268 /// this routine would produce an implicit conversion sequence to 1269 /// describe the initialization of f from i, which will be a standard 1270 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1271 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1272 // 1273 /// Note that this routine only determines how the conversion can be 1274 /// performed; it does not actually perform the conversion. As such, 1275 /// it will not produce any diagnostics if no conversion is available, 1276 /// but will instead return an implicit conversion sequence of kind 1277 /// "BadConversion". 1278 /// 1279 /// If @p SuppressUserConversions, then user-defined conversions are 1280 /// not permitted. 1281 /// If @p AllowExplicit, then explicit user-defined conversions are 1282 /// permitted. 1283 /// 1284 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1285 /// writeback conversion, which allows __autoreleasing id* parameters to 1286 /// be initialized with __strong id* or __weak id* arguments. 1287 static ImplicitConversionSequence 1288 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1289 bool SuppressUserConversions, 1290 bool AllowExplicit, 1291 bool InOverloadResolution, 1292 bool CStyle, 1293 bool AllowObjCWritebackConversion, 1294 bool AllowObjCConversionOnExplicit) { 1295 ImplicitConversionSequence ICS; 1296 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1297 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1298 ICS.setStandard(); 1299 return ICS; 1300 } 1301 1302 if (!S.getLangOpts().CPlusPlus) { 1303 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1304 return ICS; 1305 } 1306 1307 // C++ [over.ics.user]p4: 1308 // A conversion of an expression of class type to the same class 1309 // type is given Exact Match rank, and a conversion of an 1310 // expression of class type to a base class of that type is 1311 // given Conversion rank, in spite of the fact that a copy/move 1312 // constructor (i.e., a user-defined conversion function) is 1313 // called for those cases. 1314 QualType FromType = From->getType(); 1315 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1316 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1317 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1318 ICS.setStandard(); 1319 ICS.Standard.setAsIdentityConversion(); 1320 ICS.Standard.setFromType(FromType); 1321 ICS.Standard.setAllToTypes(ToType); 1322 1323 // We don't actually check at this point whether there is a valid 1324 // copy/move constructor, since overloading just assumes that it 1325 // exists. When we actually perform initialization, we'll find the 1326 // appropriate constructor to copy the returned object, if needed. 1327 ICS.Standard.CopyConstructor = nullptr; 1328 1329 // Determine whether this is considered a derived-to-base conversion. 1330 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1331 ICS.Standard.Second = ICK_Derived_To_Base; 1332 1333 return ICS; 1334 } 1335 1336 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1337 AllowExplicit, InOverloadResolution, CStyle, 1338 AllowObjCWritebackConversion, 1339 AllowObjCConversionOnExplicit); 1340 } 1341 1342 ImplicitConversionSequence 1343 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1344 bool SuppressUserConversions, 1345 bool AllowExplicit, 1346 bool InOverloadResolution, 1347 bool CStyle, 1348 bool AllowObjCWritebackConversion) { 1349 return ::TryImplicitConversion(*this, From, ToType, 1350 SuppressUserConversions, AllowExplicit, 1351 InOverloadResolution, CStyle, 1352 AllowObjCWritebackConversion, 1353 /*AllowObjCConversionOnExplicit=*/false); 1354 } 1355 1356 /// PerformImplicitConversion - Perform an implicit conversion of the 1357 /// expression From to the type ToType. Returns the 1358 /// converted expression. Flavor is the kind of conversion we're 1359 /// performing, used in the error message. If @p AllowExplicit, 1360 /// explicit user-defined conversions are permitted. 1361 ExprResult 1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1363 AssignmentAction Action, bool AllowExplicit) { 1364 ImplicitConversionSequence ICS; 1365 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1366 } 1367 1368 ExprResult 1369 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1370 AssignmentAction Action, bool AllowExplicit, 1371 ImplicitConversionSequence& ICS) { 1372 if (checkPlaceholderForOverload(*this, From)) 1373 return ExprError(); 1374 1375 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1376 bool AllowObjCWritebackConversion 1377 = getLangOpts().ObjCAutoRefCount && 1378 (Action == AA_Passing || Action == AA_Sending); 1379 if (getLangOpts().ObjC1) 1380 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1381 ToType, From->getType(), From); 1382 ICS = ::TryImplicitConversion(*this, From, ToType, 1383 /*SuppressUserConversions=*/false, 1384 AllowExplicit, 1385 /*InOverloadResolution=*/false, 1386 /*CStyle=*/false, 1387 AllowObjCWritebackConversion, 1388 /*AllowObjCConversionOnExplicit=*/false); 1389 return PerformImplicitConversion(From, ToType, ICS, Action); 1390 } 1391 1392 /// \brief Determine whether the conversion from FromType to ToType is a valid 1393 /// conversion that strips "noexcept" or "noreturn" off the nested function 1394 /// type. 1395 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1396 QualType &ResultTy) { 1397 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1398 return false; 1399 1400 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1401 // or F(t noexcept) -> F(t) 1402 // where F adds one of the following at most once: 1403 // - a pointer 1404 // - a member pointer 1405 // - a block pointer 1406 CanQualType CanTo = Context.getCanonicalType(ToType); 1407 CanQualType CanFrom = Context.getCanonicalType(FromType); 1408 Type::TypeClass TyClass = CanTo->getTypeClass(); 1409 if (TyClass != CanFrom->getTypeClass()) return false; 1410 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1411 if (TyClass == Type::Pointer) { 1412 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1413 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1414 } else if (TyClass == Type::BlockPointer) { 1415 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1416 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1417 } else if (TyClass == Type::MemberPointer) { 1418 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1419 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1420 } else { 1421 return false; 1422 } 1423 1424 TyClass = CanTo->getTypeClass(); 1425 if (TyClass != CanFrom->getTypeClass()) return false; 1426 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1427 return false; 1428 } 1429 1430 const auto *FromFn = cast<FunctionType>(CanFrom); 1431 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1432 1433 const auto *ToFn = dyn_cast<FunctionProtoType>(CanTo); 1434 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1435 1436 bool Changed = false; 1437 1438 // Drop 'noreturn' if not present in target type. 1439 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1440 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1441 Changed = true; 1442 } 1443 1444 // Drop 'noexcept' if not present in target type. 1445 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1446 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn); 1447 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1448 FromFn = cast<FunctionType>( 1449 Context.getFunctionType(FromFPT->getReturnType(), 1450 FromFPT->getParamTypes(), 1451 FromFPT->getExtProtoInfo().withExceptionSpec( 1452 FunctionProtoType::ExceptionSpecInfo())) 1453 .getTypePtr()); 1454 Changed = true; 1455 } 1456 } 1457 1458 if (!Changed) 1459 return false; 1460 1461 assert(QualType(FromFn, 0).isCanonical()); 1462 if (QualType(FromFn, 0) != CanTo) return false; 1463 1464 ResultTy = ToType; 1465 return true; 1466 } 1467 1468 /// \brief Determine whether the conversion from FromType to ToType is a valid 1469 /// vector conversion. 1470 /// 1471 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1472 /// conversion. 1473 static bool IsVectorConversion(Sema &S, QualType FromType, 1474 QualType ToType, ImplicitConversionKind &ICK) { 1475 // We need at least one of these types to be a vector type to have a vector 1476 // conversion. 1477 if (!ToType->isVectorType() && !FromType->isVectorType()) 1478 return false; 1479 1480 // Identical types require no conversions. 1481 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1482 return false; 1483 1484 // There are no conversions between extended vector types, only identity. 1485 if (ToType->isExtVectorType()) { 1486 // There are no conversions between extended vector types other than the 1487 // identity conversion. 1488 if (FromType->isExtVectorType()) 1489 return false; 1490 1491 // Vector splat from any arithmetic type to a vector. 1492 if (FromType->isArithmeticType()) { 1493 ICK = ICK_Vector_Splat; 1494 return true; 1495 } 1496 } 1497 1498 // We can perform the conversion between vector types in the following cases: 1499 // 1)vector types are equivalent AltiVec and GCC vector types 1500 // 2)lax vector conversions are permitted and the vector types are of the 1501 // same size 1502 if (ToType->isVectorType() && FromType->isVectorType()) { 1503 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1504 S.isLaxVectorConversion(FromType, ToType)) { 1505 ICK = ICK_Vector_Conversion; 1506 return true; 1507 } 1508 } 1509 1510 return false; 1511 } 1512 1513 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1514 bool InOverloadResolution, 1515 StandardConversionSequence &SCS, 1516 bool CStyle); 1517 1518 /// IsStandardConversion - Determines whether there is a standard 1519 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1520 /// expression From to the type ToType. Standard conversion sequences 1521 /// only consider non-class types; for conversions that involve class 1522 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1523 /// contain the standard conversion sequence required to perform this 1524 /// conversion and this routine will return true. Otherwise, this 1525 /// routine will return false and the value of SCS is unspecified. 1526 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1527 bool InOverloadResolution, 1528 StandardConversionSequence &SCS, 1529 bool CStyle, 1530 bool AllowObjCWritebackConversion) { 1531 QualType FromType = From->getType(); 1532 1533 // Standard conversions (C++ [conv]) 1534 SCS.setAsIdentityConversion(); 1535 SCS.IncompatibleObjC = false; 1536 SCS.setFromType(FromType); 1537 SCS.CopyConstructor = nullptr; 1538 1539 // There are no standard conversions for class types in C++, so 1540 // abort early. When overloading in C, however, we do permit them. 1541 if (S.getLangOpts().CPlusPlus && 1542 (FromType->isRecordType() || ToType->isRecordType())) 1543 return false; 1544 1545 // The first conversion can be an lvalue-to-rvalue conversion, 1546 // array-to-pointer conversion, or function-to-pointer conversion 1547 // (C++ 4p1). 1548 1549 if (FromType == S.Context.OverloadTy) { 1550 DeclAccessPair AccessPair; 1551 if (FunctionDecl *Fn 1552 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1553 AccessPair)) { 1554 // We were able to resolve the address of the overloaded function, 1555 // so we can convert to the type of that function. 1556 FromType = Fn->getType(); 1557 SCS.setFromType(FromType); 1558 1559 // we can sometimes resolve &foo<int> regardless of ToType, so check 1560 // if the type matches (identity) or we are converting to bool 1561 if (!S.Context.hasSameUnqualifiedType( 1562 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1563 QualType resultTy; 1564 // if the function type matches except for [[noreturn]], it's ok 1565 if (!S.IsFunctionConversion(FromType, 1566 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1567 // otherwise, only a boolean conversion is standard 1568 if (!ToType->isBooleanType()) 1569 return false; 1570 } 1571 1572 // Check if the "from" expression is taking the address of an overloaded 1573 // function and recompute the FromType accordingly. Take advantage of the 1574 // fact that non-static member functions *must* have such an address-of 1575 // expression. 1576 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1577 if (Method && !Method->isStatic()) { 1578 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1579 "Non-unary operator on non-static member address"); 1580 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1581 == UO_AddrOf && 1582 "Non-address-of operator on non-static member address"); 1583 const Type *ClassType 1584 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1585 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1586 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1587 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1588 UO_AddrOf && 1589 "Non-address-of operator for overloaded function expression"); 1590 FromType = S.Context.getPointerType(FromType); 1591 } 1592 1593 // Check that we've computed the proper type after overload resolution. 1594 assert(S.Context.hasSameType( 1595 FromType, 1596 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1597 } else { 1598 return false; 1599 } 1600 } 1601 // Lvalue-to-rvalue conversion (C++11 4.1): 1602 // A glvalue (3.10) of a non-function, non-array type T can 1603 // be converted to a prvalue. 1604 bool argIsLValue = From->isGLValue(); 1605 if (argIsLValue && 1606 !FromType->isFunctionType() && !FromType->isArrayType() && 1607 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1608 SCS.First = ICK_Lvalue_To_Rvalue; 1609 1610 // C11 6.3.2.1p2: 1611 // ... if the lvalue has atomic type, the value has the non-atomic version 1612 // of the type of the lvalue ... 1613 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1614 FromType = Atomic->getValueType(); 1615 1616 // If T is a non-class type, the type of the rvalue is the 1617 // cv-unqualified version of T. Otherwise, the type of the rvalue 1618 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1619 // just strip the qualifiers because they don't matter. 1620 FromType = FromType.getUnqualifiedType(); 1621 } else if (FromType->isArrayType()) { 1622 // Array-to-pointer conversion (C++ 4.2) 1623 SCS.First = ICK_Array_To_Pointer; 1624 1625 // An lvalue or rvalue of type "array of N T" or "array of unknown 1626 // bound of T" can be converted to an rvalue of type "pointer to 1627 // T" (C++ 4.2p1). 1628 FromType = S.Context.getArrayDecayedType(FromType); 1629 1630 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1631 // This conversion is deprecated in C++03 (D.4) 1632 SCS.DeprecatedStringLiteralToCharPtr = true; 1633 1634 // For the purpose of ranking in overload resolution 1635 // (13.3.3.1.1), this conversion is considered an 1636 // array-to-pointer conversion followed by a qualification 1637 // conversion (4.4). (C++ 4.2p2) 1638 SCS.Second = ICK_Identity; 1639 SCS.Third = ICK_Qualification; 1640 SCS.QualificationIncludesObjCLifetime = false; 1641 SCS.setAllToTypes(FromType); 1642 return true; 1643 } 1644 } else if (FromType->isFunctionType() && argIsLValue) { 1645 // Function-to-pointer conversion (C++ 4.3). 1646 SCS.First = ICK_Function_To_Pointer; 1647 1648 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1649 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1650 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1651 return false; 1652 1653 // An lvalue of function type T can be converted to an rvalue of 1654 // type "pointer to T." The result is a pointer to the 1655 // function. (C++ 4.3p1). 1656 FromType = S.Context.getPointerType(FromType); 1657 } else { 1658 // We don't require any conversions for the first step. 1659 SCS.First = ICK_Identity; 1660 } 1661 SCS.setToType(0, FromType); 1662 1663 // The second conversion can be an integral promotion, floating 1664 // point promotion, integral conversion, floating point conversion, 1665 // floating-integral conversion, pointer conversion, 1666 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1667 // For overloading in C, this can also be a "compatible-type" 1668 // conversion. 1669 bool IncompatibleObjC = false; 1670 ImplicitConversionKind SecondICK = ICK_Identity; 1671 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1672 // The unqualified versions of the types are the same: there's no 1673 // conversion to do. 1674 SCS.Second = ICK_Identity; 1675 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1676 // Integral promotion (C++ 4.5). 1677 SCS.Second = ICK_Integral_Promotion; 1678 FromType = ToType.getUnqualifiedType(); 1679 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1680 // Floating point promotion (C++ 4.6). 1681 SCS.Second = ICK_Floating_Promotion; 1682 FromType = ToType.getUnqualifiedType(); 1683 } else if (S.IsComplexPromotion(FromType, ToType)) { 1684 // Complex promotion (Clang extension) 1685 SCS.Second = ICK_Complex_Promotion; 1686 FromType = ToType.getUnqualifiedType(); 1687 } else if (ToType->isBooleanType() && 1688 (FromType->isArithmeticType() || 1689 FromType->isAnyPointerType() || 1690 FromType->isBlockPointerType() || 1691 FromType->isMemberPointerType() || 1692 FromType->isNullPtrType())) { 1693 // Boolean conversions (C++ 4.12). 1694 SCS.Second = ICK_Boolean_Conversion; 1695 FromType = S.Context.BoolTy; 1696 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1697 ToType->isIntegralType(S.Context)) { 1698 // Integral conversions (C++ 4.7). 1699 SCS.Second = ICK_Integral_Conversion; 1700 FromType = ToType.getUnqualifiedType(); 1701 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1702 // Complex conversions (C99 6.3.1.6) 1703 SCS.Second = ICK_Complex_Conversion; 1704 FromType = ToType.getUnqualifiedType(); 1705 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1706 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1707 // Complex-real conversions (C99 6.3.1.7) 1708 SCS.Second = ICK_Complex_Real; 1709 FromType = ToType.getUnqualifiedType(); 1710 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1711 // FIXME: disable conversions between long double and __float128 if 1712 // their representation is different until there is back end support 1713 // We of course allow this conversion if long double is really double. 1714 if (&S.Context.getFloatTypeSemantics(FromType) != 1715 &S.Context.getFloatTypeSemantics(ToType)) { 1716 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1717 ToType == S.Context.LongDoubleTy) || 1718 (FromType == S.Context.LongDoubleTy && 1719 ToType == S.Context.Float128Ty)); 1720 if (Float128AndLongDouble && 1721 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1722 &llvm::APFloat::IEEEdouble)) 1723 return false; 1724 } 1725 // Floating point conversions (C++ 4.8). 1726 SCS.Second = ICK_Floating_Conversion; 1727 FromType = ToType.getUnqualifiedType(); 1728 } else if ((FromType->isRealFloatingType() && 1729 ToType->isIntegralType(S.Context)) || 1730 (FromType->isIntegralOrUnscopedEnumerationType() && 1731 ToType->isRealFloatingType())) { 1732 // Floating-integral conversions (C++ 4.9). 1733 SCS.Second = ICK_Floating_Integral; 1734 FromType = ToType.getUnqualifiedType(); 1735 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1736 SCS.Second = ICK_Block_Pointer_Conversion; 1737 } else if (AllowObjCWritebackConversion && 1738 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1739 SCS.Second = ICK_Writeback_Conversion; 1740 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1741 FromType, IncompatibleObjC)) { 1742 // Pointer conversions (C++ 4.10). 1743 SCS.Second = ICK_Pointer_Conversion; 1744 SCS.IncompatibleObjC = IncompatibleObjC; 1745 FromType = FromType.getUnqualifiedType(); 1746 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1747 InOverloadResolution, FromType)) { 1748 // Pointer to member conversions (4.11). 1749 SCS.Second = ICK_Pointer_Member; 1750 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1751 SCS.Second = SecondICK; 1752 FromType = ToType.getUnqualifiedType(); 1753 } else if (!S.getLangOpts().CPlusPlus && 1754 S.Context.typesAreCompatible(ToType, FromType)) { 1755 // Compatible conversions (Clang extension for C function overloading) 1756 SCS.Second = ICK_Compatible_Conversion; 1757 FromType = ToType.getUnqualifiedType(); 1758 } else if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1759 // Function pointer conversions (removing 'noexcept') including removal of 1760 // 'noreturn' (Clang extension). 1761 SCS.Second = ICK_Function_Conversion; 1762 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1763 InOverloadResolution, 1764 SCS, CStyle)) { 1765 SCS.Second = ICK_TransparentUnionConversion; 1766 FromType = ToType; 1767 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1768 CStyle)) { 1769 // tryAtomicConversion has updated the standard conversion sequence 1770 // appropriately. 1771 return true; 1772 } else if (ToType->isEventT() && 1773 From->isIntegerConstantExpr(S.getASTContext()) && 1774 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1775 SCS.Second = ICK_Zero_Event_Conversion; 1776 FromType = ToType; 1777 } else { 1778 // No second conversion required. 1779 SCS.Second = ICK_Identity; 1780 } 1781 SCS.setToType(1, FromType); 1782 1783 QualType CanonFrom; 1784 QualType CanonTo; 1785 // The third conversion can be a qualification conversion (C++ 4p1). 1786 bool ObjCLifetimeConversion; 1787 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1788 ObjCLifetimeConversion)) { 1789 SCS.Third = ICK_Qualification; 1790 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1791 FromType = ToType; 1792 CanonFrom = S.Context.getCanonicalType(FromType); 1793 CanonTo = S.Context.getCanonicalType(ToType); 1794 } else { 1795 // No conversion required 1796 SCS.Third = ICK_Identity; 1797 1798 // C++ [over.best.ics]p6: 1799 // [...] Any difference in top-level cv-qualification is 1800 // subsumed by the initialization itself and does not constitute 1801 // a conversion. [...] 1802 CanonFrom = S.Context.getCanonicalType(FromType); 1803 CanonTo = S.Context.getCanonicalType(ToType); 1804 if (CanonFrom.getLocalUnqualifiedType() 1805 == CanonTo.getLocalUnqualifiedType() && 1806 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1807 FromType = ToType; 1808 CanonFrom = CanonTo; 1809 } 1810 } 1811 SCS.setToType(2, FromType); 1812 1813 if (CanonFrom == CanonTo) 1814 return true; 1815 1816 // If we have not converted the argument type to the parameter type, 1817 // this is a bad conversion sequence, unless we're resolving an overload in C. 1818 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1819 return false; 1820 1821 ExprResult ER = ExprResult{From}; 1822 Sema::AssignConvertType Conv = 1823 S.CheckSingleAssignmentConstraints(ToType, ER, 1824 /*Diagnose=*/false, 1825 /*DiagnoseCFAudited=*/false, 1826 /*ConvertRHS=*/false); 1827 ImplicitConversionKind SecondConv; 1828 switch (Conv) { 1829 case Sema::Compatible: 1830 SecondConv = ICK_C_Only_Conversion; 1831 break; 1832 // For our purposes, discarding qualifiers is just as bad as using an 1833 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1834 // qualifiers, as well. 1835 case Sema::CompatiblePointerDiscardsQualifiers: 1836 case Sema::IncompatiblePointer: 1837 case Sema::IncompatiblePointerSign: 1838 SecondConv = ICK_Incompatible_Pointer_Conversion; 1839 break; 1840 default: 1841 return false; 1842 } 1843 1844 // First can only be an lvalue conversion, so we pretend that this was the 1845 // second conversion. First should already be valid from earlier in the 1846 // function. 1847 SCS.Second = SecondConv; 1848 SCS.setToType(1, ToType); 1849 1850 // Third is Identity, because Second should rank us worse than any other 1851 // conversion. This could also be ICK_Qualification, but it's simpler to just 1852 // lump everything in with the second conversion, and we don't gain anything 1853 // from making this ICK_Qualification. 1854 SCS.Third = ICK_Identity; 1855 SCS.setToType(2, ToType); 1856 return true; 1857 } 1858 1859 static bool 1860 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1861 QualType &ToType, 1862 bool InOverloadResolution, 1863 StandardConversionSequence &SCS, 1864 bool CStyle) { 1865 1866 const RecordType *UT = ToType->getAsUnionType(); 1867 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1868 return false; 1869 // The field to initialize within the transparent union. 1870 RecordDecl *UD = UT->getDecl(); 1871 // It's compatible if the expression matches any of the fields. 1872 for (const auto *it : UD->fields()) { 1873 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1874 CStyle, /*ObjCWritebackConversion=*/false)) { 1875 ToType = it->getType(); 1876 return true; 1877 } 1878 } 1879 return false; 1880 } 1881 1882 /// IsIntegralPromotion - Determines whether the conversion from the 1883 /// expression From (whose potentially-adjusted type is FromType) to 1884 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1885 /// sets PromotedType to the promoted type. 1886 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1887 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1888 // All integers are built-in. 1889 if (!To) { 1890 return false; 1891 } 1892 1893 // An rvalue of type char, signed char, unsigned char, short int, or 1894 // unsigned short int can be converted to an rvalue of type int if 1895 // int can represent all the values of the source type; otherwise, 1896 // the source rvalue can be converted to an rvalue of type unsigned 1897 // int (C++ 4.5p1). 1898 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1899 !FromType->isEnumeralType()) { 1900 if (// We can promote any signed, promotable integer type to an int 1901 (FromType->isSignedIntegerType() || 1902 // We can promote any unsigned integer type whose size is 1903 // less than int to an int. 1904 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1905 return To->getKind() == BuiltinType::Int; 1906 } 1907 1908 return To->getKind() == BuiltinType::UInt; 1909 } 1910 1911 // C++11 [conv.prom]p3: 1912 // A prvalue of an unscoped enumeration type whose underlying type is not 1913 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1914 // following types that can represent all the values of the enumeration 1915 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1916 // unsigned int, long int, unsigned long int, long long int, or unsigned 1917 // long long int. If none of the types in that list can represent all the 1918 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1919 // type can be converted to an rvalue a prvalue of the extended integer type 1920 // with lowest integer conversion rank (4.13) greater than the rank of long 1921 // long in which all the values of the enumeration can be represented. If 1922 // there are two such extended types, the signed one is chosen. 1923 // C++11 [conv.prom]p4: 1924 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1925 // can be converted to a prvalue of its underlying type. Moreover, if 1926 // integral promotion can be applied to its underlying type, a prvalue of an 1927 // unscoped enumeration type whose underlying type is fixed can also be 1928 // converted to a prvalue of the promoted underlying type. 1929 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1930 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1931 // provided for a scoped enumeration. 1932 if (FromEnumType->getDecl()->isScoped()) 1933 return false; 1934 1935 // We can perform an integral promotion to the underlying type of the enum, 1936 // even if that's not the promoted type. Note that the check for promoting 1937 // the underlying type is based on the type alone, and does not consider 1938 // the bitfield-ness of the actual source expression. 1939 if (FromEnumType->getDecl()->isFixed()) { 1940 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1941 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1942 IsIntegralPromotion(nullptr, Underlying, ToType); 1943 } 1944 1945 // We have already pre-calculated the promotion type, so this is trivial. 1946 if (ToType->isIntegerType() && 1947 isCompleteType(From->getLocStart(), FromType)) 1948 return Context.hasSameUnqualifiedType( 1949 ToType, FromEnumType->getDecl()->getPromotionType()); 1950 } 1951 1952 // C++0x [conv.prom]p2: 1953 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1954 // to an rvalue a prvalue of the first of the following types that can 1955 // represent all the values of its underlying type: int, unsigned int, 1956 // long int, unsigned long int, long long int, or unsigned long long int. 1957 // If none of the types in that list can represent all the values of its 1958 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1959 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1960 // type. 1961 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1962 ToType->isIntegerType()) { 1963 // Determine whether the type we're converting from is signed or 1964 // unsigned. 1965 bool FromIsSigned = FromType->isSignedIntegerType(); 1966 uint64_t FromSize = Context.getTypeSize(FromType); 1967 1968 // The types we'll try to promote to, in the appropriate 1969 // order. Try each of these types. 1970 QualType PromoteTypes[6] = { 1971 Context.IntTy, Context.UnsignedIntTy, 1972 Context.LongTy, Context.UnsignedLongTy , 1973 Context.LongLongTy, Context.UnsignedLongLongTy 1974 }; 1975 for (int Idx = 0; Idx < 6; ++Idx) { 1976 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1977 if (FromSize < ToSize || 1978 (FromSize == ToSize && 1979 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1980 // We found the type that we can promote to. If this is the 1981 // type we wanted, we have a promotion. Otherwise, no 1982 // promotion. 1983 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1984 } 1985 } 1986 } 1987 1988 // An rvalue for an integral bit-field (9.6) can be converted to an 1989 // rvalue of type int if int can represent all the values of the 1990 // bit-field; otherwise, it can be converted to unsigned int if 1991 // unsigned int can represent all the values of the bit-field. If 1992 // the bit-field is larger yet, no integral promotion applies to 1993 // it. If the bit-field has an enumerated type, it is treated as any 1994 // other value of that type for promotion purposes (C++ 4.5p3). 1995 // FIXME: We should delay checking of bit-fields until we actually perform the 1996 // conversion. 1997 if (From) { 1998 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1999 llvm::APSInt BitWidth; 2000 if (FromType->isIntegralType(Context) && 2001 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2002 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2003 ToSize = Context.getTypeSize(ToType); 2004 2005 // Are we promoting to an int from a bitfield that fits in an int? 2006 if (BitWidth < ToSize || 2007 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2008 return To->getKind() == BuiltinType::Int; 2009 } 2010 2011 // Are we promoting to an unsigned int from an unsigned bitfield 2012 // that fits into an unsigned int? 2013 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2014 return To->getKind() == BuiltinType::UInt; 2015 } 2016 2017 return false; 2018 } 2019 } 2020 } 2021 2022 // An rvalue of type bool can be converted to an rvalue of type int, 2023 // with false becoming zero and true becoming one (C++ 4.5p4). 2024 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2025 return true; 2026 } 2027 2028 return false; 2029 } 2030 2031 /// IsFloatingPointPromotion - Determines whether the conversion from 2032 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2033 /// returns true and sets PromotedType to the promoted type. 2034 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2035 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2036 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2037 /// An rvalue of type float can be converted to an rvalue of type 2038 /// double. (C++ 4.6p1). 2039 if (FromBuiltin->getKind() == BuiltinType::Float && 2040 ToBuiltin->getKind() == BuiltinType::Double) 2041 return true; 2042 2043 // C99 6.3.1.5p1: 2044 // When a float is promoted to double or long double, or a 2045 // double is promoted to long double [...]. 2046 if (!getLangOpts().CPlusPlus && 2047 (FromBuiltin->getKind() == BuiltinType::Float || 2048 FromBuiltin->getKind() == BuiltinType::Double) && 2049 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2050 ToBuiltin->getKind() == BuiltinType::Float128)) 2051 return true; 2052 2053 // Half can be promoted to float. 2054 if (!getLangOpts().NativeHalfType && 2055 FromBuiltin->getKind() == BuiltinType::Half && 2056 ToBuiltin->getKind() == BuiltinType::Float) 2057 return true; 2058 } 2059 2060 return false; 2061 } 2062 2063 /// \brief Determine if a conversion is a complex promotion. 2064 /// 2065 /// A complex promotion is defined as a complex -> complex conversion 2066 /// where the conversion between the underlying real types is a 2067 /// floating-point or integral promotion. 2068 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2069 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2070 if (!FromComplex) 2071 return false; 2072 2073 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2074 if (!ToComplex) 2075 return false; 2076 2077 return IsFloatingPointPromotion(FromComplex->getElementType(), 2078 ToComplex->getElementType()) || 2079 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2080 ToComplex->getElementType()); 2081 } 2082 2083 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2084 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2085 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2086 /// if non-empty, will be a pointer to ToType that may or may not have 2087 /// the right set of qualifiers on its pointee. 2088 /// 2089 static QualType 2090 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2091 QualType ToPointee, QualType ToType, 2092 ASTContext &Context, 2093 bool StripObjCLifetime = false) { 2094 assert((FromPtr->getTypeClass() == Type::Pointer || 2095 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2096 "Invalid similarly-qualified pointer type"); 2097 2098 /// Conversions to 'id' subsume cv-qualifier conversions. 2099 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2100 return ToType.getUnqualifiedType(); 2101 2102 QualType CanonFromPointee 2103 = Context.getCanonicalType(FromPtr->getPointeeType()); 2104 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2105 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2106 2107 if (StripObjCLifetime) 2108 Quals.removeObjCLifetime(); 2109 2110 // Exact qualifier match -> return the pointer type we're converting to. 2111 if (CanonToPointee.getLocalQualifiers() == Quals) { 2112 // ToType is exactly what we need. Return it. 2113 if (!ToType.isNull()) 2114 return ToType.getUnqualifiedType(); 2115 2116 // Build a pointer to ToPointee. It has the right qualifiers 2117 // already. 2118 if (isa<ObjCObjectPointerType>(ToType)) 2119 return Context.getObjCObjectPointerType(ToPointee); 2120 return Context.getPointerType(ToPointee); 2121 } 2122 2123 // Just build a canonical type that has the right qualifiers. 2124 QualType QualifiedCanonToPointee 2125 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2126 2127 if (isa<ObjCObjectPointerType>(ToType)) 2128 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2129 return Context.getPointerType(QualifiedCanonToPointee); 2130 } 2131 2132 static bool isNullPointerConstantForConversion(Expr *Expr, 2133 bool InOverloadResolution, 2134 ASTContext &Context) { 2135 // Handle value-dependent integral null pointer constants correctly. 2136 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2137 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2138 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2139 return !InOverloadResolution; 2140 2141 return Expr->isNullPointerConstant(Context, 2142 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2143 : Expr::NPC_ValueDependentIsNull); 2144 } 2145 2146 /// IsPointerConversion - Determines whether the conversion of the 2147 /// expression From, which has the (possibly adjusted) type FromType, 2148 /// can be converted to the type ToType via a pointer conversion (C++ 2149 /// 4.10). If so, returns true and places the converted type (that 2150 /// might differ from ToType in its cv-qualifiers at some level) into 2151 /// ConvertedType. 2152 /// 2153 /// This routine also supports conversions to and from block pointers 2154 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2155 /// pointers to interfaces. FIXME: Once we've determined the 2156 /// appropriate overloading rules for Objective-C, we may want to 2157 /// split the Objective-C checks into a different routine; however, 2158 /// GCC seems to consider all of these conversions to be pointer 2159 /// conversions, so for now they live here. IncompatibleObjC will be 2160 /// set if the conversion is an allowed Objective-C conversion that 2161 /// should result in a warning. 2162 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2163 bool InOverloadResolution, 2164 QualType& ConvertedType, 2165 bool &IncompatibleObjC) { 2166 IncompatibleObjC = false; 2167 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2168 IncompatibleObjC)) 2169 return true; 2170 2171 // Conversion from a null pointer constant to any Objective-C pointer type. 2172 if (ToType->isObjCObjectPointerType() && 2173 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2174 ConvertedType = ToType; 2175 return true; 2176 } 2177 2178 // Blocks: Block pointers can be converted to void*. 2179 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2180 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2181 ConvertedType = ToType; 2182 return true; 2183 } 2184 // Blocks: A null pointer constant can be converted to a block 2185 // pointer type. 2186 if (ToType->isBlockPointerType() && 2187 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2188 ConvertedType = ToType; 2189 return true; 2190 } 2191 2192 // If the left-hand-side is nullptr_t, the right side can be a null 2193 // pointer constant. 2194 if (ToType->isNullPtrType() && 2195 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2196 ConvertedType = ToType; 2197 return true; 2198 } 2199 2200 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2201 if (!ToTypePtr) 2202 return false; 2203 2204 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2205 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2206 ConvertedType = ToType; 2207 return true; 2208 } 2209 2210 // Beyond this point, both types need to be pointers 2211 // , including objective-c pointers. 2212 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2213 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2214 !getLangOpts().ObjCAutoRefCount) { 2215 ConvertedType = BuildSimilarlyQualifiedPointerType( 2216 FromType->getAs<ObjCObjectPointerType>(), 2217 ToPointeeType, 2218 ToType, Context); 2219 return true; 2220 } 2221 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2222 if (!FromTypePtr) 2223 return false; 2224 2225 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2226 2227 // If the unqualified pointee types are the same, this can't be a 2228 // pointer conversion, so don't do all of the work below. 2229 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2230 return false; 2231 2232 // An rvalue of type "pointer to cv T," where T is an object type, 2233 // can be converted to an rvalue of type "pointer to cv void" (C++ 2234 // 4.10p2). 2235 if (FromPointeeType->isIncompleteOrObjectType() && 2236 ToPointeeType->isVoidType()) { 2237 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2238 ToPointeeType, 2239 ToType, Context, 2240 /*StripObjCLifetime=*/true); 2241 return true; 2242 } 2243 2244 // MSVC allows implicit function to void* type conversion. 2245 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2246 ToPointeeType->isVoidType()) { 2247 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2248 ToPointeeType, 2249 ToType, Context); 2250 return true; 2251 } 2252 2253 // When we're overloading in C, we allow a special kind of pointer 2254 // conversion for compatible-but-not-identical pointee types. 2255 if (!getLangOpts().CPlusPlus && 2256 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2257 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2258 ToPointeeType, 2259 ToType, Context); 2260 return true; 2261 } 2262 2263 // C++ [conv.ptr]p3: 2264 // 2265 // An rvalue of type "pointer to cv D," where D is a class type, 2266 // can be converted to an rvalue of type "pointer to cv B," where 2267 // B is a base class (clause 10) of D. If B is an inaccessible 2268 // (clause 11) or ambiguous (10.2) base class of D, a program that 2269 // necessitates this conversion is ill-formed. The result of the 2270 // conversion is a pointer to the base class sub-object of the 2271 // derived class object. The null pointer value is converted to 2272 // the null pointer value of the destination type. 2273 // 2274 // Note that we do not check for ambiguity or inaccessibility 2275 // here. That is handled by CheckPointerConversion. 2276 if (getLangOpts().CPlusPlus && 2277 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2278 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2279 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2280 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2281 ToPointeeType, 2282 ToType, Context); 2283 return true; 2284 } 2285 2286 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2287 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2288 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2289 ToPointeeType, 2290 ToType, Context); 2291 return true; 2292 } 2293 2294 return false; 2295 } 2296 2297 /// \brief Adopt the given qualifiers for the given type. 2298 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2299 Qualifiers TQs = T.getQualifiers(); 2300 2301 // Check whether qualifiers already match. 2302 if (TQs == Qs) 2303 return T; 2304 2305 if (Qs.compatiblyIncludes(TQs)) 2306 return Context.getQualifiedType(T, Qs); 2307 2308 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2309 } 2310 2311 /// isObjCPointerConversion - Determines whether this is an 2312 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2313 /// with the same arguments and return values. 2314 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2315 QualType& ConvertedType, 2316 bool &IncompatibleObjC) { 2317 if (!getLangOpts().ObjC1) 2318 return false; 2319 2320 // The set of qualifiers on the type we're converting from. 2321 Qualifiers FromQualifiers = FromType.getQualifiers(); 2322 2323 // First, we handle all conversions on ObjC object pointer types. 2324 const ObjCObjectPointerType* ToObjCPtr = 2325 ToType->getAs<ObjCObjectPointerType>(); 2326 const ObjCObjectPointerType *FromObjCPtr = 2327 FromType->getAs<ObjCObjectPointerType>(); 2328 2329 if (ToObjCPtr && FromObjCPtr) { 2330 // If the pointee types are the same (ignoring qualifications), 2331 // then this is not a pointer conversion. 2332 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2333 FromObjCPtr->getPointeeType())) 2334 return false; 2335 2336 // Conversion between Objective-C pointers. 2337 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2338 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2339 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2340 if (getLangOpts().CPlusPlus && LHS && RHS && 2341 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2342 FromObjCPtr->getPointeeType())) 2343 return false; 2344 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2345 ToObjCPtr->getPointeeType(), 2346 ToType, Context); 2347 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2348 return true; 2349 } 2350 2351 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2352 // Okay: this is some kind of implicit downcast of Objective-C 2353 // interfaces, which is permitted. However, we're going to 2354 // complain about it. 2355 IncompatibleObjC = true; 2356 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2357 ToObjCPtr->getPointeeType(), 2358 ToType, Context); 2359 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2360 return true; 2361 } 2362 } 2363 // Beyond this point, both types need to be C pointers or block pointers. 2364 QualType ToPointeeType; 2365 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2366 ToPointeeType = ToCPtr->getPointeeType(); 2367 else if (const BlockPointerType *ToBlockPtr = 2368 ToType->getAs<BlockPointerType>()) { 2369 // Objective C++: We're able to convert from a pointer to any object 2370 // to a block pointer type. 2371 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2372 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2373 return true; 2374 } 2375 ToPointeeType = ToBlockPtr->getPointeeType(); 2376 } 2377 else if (FromType->getAs<BlockPointerType>() && 2378 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2379 // Objective C++: We're able to convert from a block pointer type to a 2380 // pointer to any object. 2381 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2382 return true; 2383 } 2384 else 2385 return false; 2386 2387 QualType FromPointeeType; 2388 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2389 FromPointeeType = FromCPtr->getPointeeType(); 2390 else if (const BlockPointerType *FromBlockPtr = 2391 FromType->getAs<BlockPointerType>()) 2392 FromPointeeType = FromBlockPtr->getPointeeType(); 2393 else 2394 return false; 2395 2396 // If we have pointers to pointers, recursively check whether this 2397 // is an Objective-C conversion. 2398 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2399 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2400 IncompatibleObjC)) { 2401 // We always complain about this conversion. 2402 IncompatibleObjC = true; 2403 ConvertedType = Context.getPointerType(ConvertedType); 2404 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2405 return true; 2406 } 2407 // Allow conversion of pointee being objective-c pointer to another one; 2408 // as in I* to id. 2409 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2410 ToPointeeType->getAs<ObjCObjectPointerType>() && 2411 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2412 IncompatibleObjC)) { 2413 2414 ConvertedType = Context.getPointerType(ConvertedType); 2415 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2416 return true; 2417 } 2418 2419 // If we have pointers to functions or blocks, check whether the only 2420 // differences in the argument and result types are in Objective-C 2421 // pointer conversions. If so, we permit the conversion (but 2422 // complain about it). 2423 const FunctionProtoType *FromFunctionType 2424 = FromPointeeType->getAs<FunctionProtoType>(); 2425 const FunctionProtoType *ToFunctionType 2426 = ToPointeeType->getAs<FunctionProtoType>(); 2427 if (FromFunctionType && ToFunctionType) { 2428 // If the function types are exactly the same, this isn't an 2429 // Objective-C pointer conversion. 2430 if (Context.getCanonicalType(FromPointeeType) 2431 == Context.getCanonicalType(ToPointeeType)) 2432 return false; 2433 2434 // Perform the quick checks that will tell us whether these 2435 // function types are obviously different. 2436 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2437 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2438 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2439 return false; 2440 2441 bool HasObjCConversion = false; 2442 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2443 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2444 // Okay, the types match exactly. Nothing to do. 2445 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2446 ToFunctionType->getReturnType(), 2447 ConvertedType, IncompatibleObjC)) { 2448 // Okay, we have an Objective-C pointer conversion. 2449 HasObjCConversion = true; 2450 } else { 2451 // Function types are too different. Abort. 2452 return false; 2453 } 2454 2455 // Check argument types. 2456 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2457 ArgIdx != NumArgs; ++ArgIdx) { 2458 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2459 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2460 if (Context.getCanonicalType(FromArgType) 2461 == Context.getCanonicalType(ToArgType)) { 2462 // Okay, the types match exactly. Nothing to do. 2463 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2464 ConvertedType, IncompatibleObjC)) { 2465 // Okay, we have an Objective-C pointer conversion. 2466 HasObjCConversion = true; 2467 } else { 2468 // Argument types are too different. Abort. 2469 return false; 2470 } 2471 } 2472 2473 if (HasObjCConversion) { 2474 // We had an Objective-C conversion. Allow this pointer 2475 // conversion, but complain about it. 2476 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2477 IncompatibleObjC = true; 2478 return true; 2479 } 2480 } 2481 2482 return false; 2483 } 2484 2485 /// \brief Determine whether this is an Objective-C writeback conversion, 2486 /// used for parameter passing when performing automatic reference counting. 2487 /// 2488 /// \param FromType The type we're converting form. 2489 /// 2490 /// \param ToType The type we're converting to. 2491 /// 2492 /// \param ConvertedType The type that will be produced after applying 2493 /// this conversion. 2494 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2495 QualType &ConvertedType) { 2496 if (!getLangOpts().ObjCAutoRefCount || 2497 Context.hasSameUnqualifiedType(FromType, ToType)) 2498 return false; 2499 2500 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2501 QualType ToPointee; 2502 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2503 ToPointee = ToPointer->getPointeeType(); 2504 else 2505 return false; 2506 2507 Qualifiers ToQuals = ToPointee.getQualifiers(); 2508 if (!ToPointee->isObjCLifetimeType() || 2509 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2510 !ToQuals.withoutObjCLifetime().empty()) 2511 return false; 2512 2513 // Argument must be a pointer to __strong to __weak. 2514 QualType FromPointee; 2515 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2516 FromPointee = FromPointer->getPointeeType(); 2517 else 2518 return false; 2519 2520 Qualifiers FromQuals = FromPointee.getQualifiers(); 2521 if (!FromPointee->isObjCLifetimeType() || 2522 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2523 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2524 return false; 2525 2526 // Make sure that we have compatible qualifiers. 2527 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2528 if (!ToQuals.compatiblyIncludes(FromQuals)) 2529 return false; 2530 2531 // Remove qualifiers from the pointee type we're converting from; they 2532 // aren't used in the compatibility check belong, and we'll be adding back 2533 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2534 FromPointee = FromPointee.getUnqualifiedType(); 2535 2536 // The unqualified form of the pointee types must be compatible. 2537 ToPointee = ToPointee.getUnqualifiedType(); 2538 bool IncompatibleObjC; 2539 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2540 FromPointee = ToPointee; 2541 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2542 IncompatibleObjC)) 2543 return false; 2544 2545 /// \brief Construct the type we're converting to, which is a pointer to 2546 /// __autoreleasing pointee. 2547 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2548 ConvertedType = Context.getPointerType(FromPointee); 2549 return true; 2550 } 2551 2552 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2553 QualType& ConvertedType) { 2554 QualType ToPointeeType; 2555 if (const BlockPointerType *ToBlockPtr = 2556 ToType->getAs<BlockPointerType>()) 2557 ToPointeeType = ToBlockPtr->getPointeeType(); 2558 else 2559 return false; 2560 2561 QualType FromPointeeType; 2562 if (const BlockPointerType *FromBlockPtr = 2563 FromType->getAs<BlockPointerType>()) 2564 FromPointeeType = FromBlockPtr->getPointeeType(); 2565 else 2566 return false; 2567 // We have pointer to blocks, check whether the only 2568 // differences in the argument and result types are in Objective-C 2569 // pointer conversions. If so, we permit the conversion. 2570 2571 const FunctionProtoType *FromFunctionType 2572 = FromPointeeType->getAs<FunctionProtoType>(); 2573 const FunctionProtoType *ToFunctionType 2574 = ToPointeeType->getAs<FunctionProtoType>(); 2575 2576 if (!FromFunctionType || !ToFunctionType) 2577 return false; 2578 2579 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2580 return true; 2581 2582 // Perform the quick checks that will tell us whether these 2583 // function types are obviously different. 2584 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2585 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2586 return false; 2587 2588 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2589 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2590 if (FromEInfo != ToEInfo) 2591 return false; 2592 2593 bool IncompatibleObjC = false; 2594 if (Context.hasSameType(FromFunctionType->getReturnType(), 2595 ToFunctionType->getReturnType())) { 2596 // Okay, the types match exactly. Nothing to do. 2597 } else { 2598 QualType RHS = FromFunctionType->getReturnType(); 2599 QualType LHS = ToFunctionType->getReturnType(); 2600 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2601 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2602 LHS = LHS.getUnqualifiedType(); 2603 2604 if (Context.hasSameType(RHS,LHS)) { 2605 // OK exact match. 2606 } else if (isObjCPointerConversion(RHS, LHS, 2607 ConvertedType, IncompatibleObjC)) { 2608 if (IncompatibleObjC) 2609 return false; 2610 // Okay, we have an Objective-C pointer conversion. 2611 } 2612 else 2613 return false; 2614 } 2615 2616 // Check argument types. 2617 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2618 ArgIdx != NumArgs; ++ArgIdx) { 2619 IncompatibleObjC = false; 2620 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2621 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2622 if (Context.hasSameType(FromArgType, ToArgType)) { 2623 // Okay, the types match exactly. Nothing to do. 2624 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2625 ConvertedType, IncompatibleObjC)) { 2626 if (IncompatibleObjC) 2627 return false; 2628 // Okay, we have an Objective-C pointer conversion. 2629 } else 2630 // Argument types are too different. Abort. 2631 return false; 2632 } 2633 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2634 ToFunctionType)) 2635 return false; 2636 2637 ConvertedType = ToType; 2638 return true; 2639 } 2640 2641 enum { 2642 ft_default, 2643 ft_different_class, 2644 ft_parameter_arity, 2645 ft_parameter_mismatch, 2646 ft_return_type, 2647 ft_qualifer_mismatch, 2648 ft_noexcept 2649 }; 2650 2651 /// Attempts to get the FunctionProtoType from a Type. Handles 2652 /// MemberFunctionPointers properly. 2653 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2654 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2655 return FPT; 2656 2657 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2658 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2659 2660 return nullptr; 2661 } 2662 2663 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2664 /// function types. Catches different number of parameter, mismatch in 2665 /// parameter types, and different return types. 2666 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2667 QualType FromType, QualType ToType) { 2668 // If either type is not valid, include no extra info. 2669 if (FromType.isNull() || ToType.isNull()) { 2670 PDiag << ft_default; 2671 return; 2672 } 2673 2674 // Get the function type from the pointers. 2675 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2676 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2677 *ToMember = ToType->getAs<MemberPointerType>(); 2678 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2679 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2680 << QualType(FromMember->getClass(), 0); 2681 return; 2682 } 2683 FromType = FromMember->getPointeeType(); 2684 ToType = ToMember->getPointeeType(); 2685 } 2686 2687 if (FromType->isPointerType()) 2688 FromType = FromType->getPointeeType(); 2689 if (ToType->isPointerType()) 2690 ToType = ToType->getPointeeType(); 2691 2692 // Remove references. 2693 FromType = FromType.getNonReferenceType(); 2694 ToType = ToType.getNonReferenceType(); 2695 2696 // Don't print extra info for non-specialized template functions. 2697 if (FromType->isInstantiationDependentType() && 2698 !FromType->getAs<TemplateSpecializationType>()) { 2699 PDiag << ft_default; 2700 return; 2701 } 2702 2703 // No extra info for same types. 2704 if (Context.hasSameType(FromType, ToType)) { 2705 PDiag << ft_default; 2706 return; 2707 } 2708 2709 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2710 *ToFunction = tryGetFunctionProtoType(ToType); 2711 2712 // Both types need to be function types. 2713 if (!FromFunction || !ToFunction) { 2714 PDiag << ft_default; 2715 return; 2716 } 2717 2718 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2719 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2720 << FromFunction->getNumParams(); 2721 return; 2722 } 2723 2724 // Handle different parameter types. 2725 unsigned ArgPos; 2726 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2727 PDiag << ft_parameter_mismatch << ArgPos + 1 2728 << ToFunction->getParamType(ArgPos) 2729 << FromFunction->getParamType(ArgPos); 2730 return; 2731 } 2732 2733 // Handle different return type. 2734 if (!Context.hasSameType(FromFunction->getReturnType(), 2735 ToFunction->getReturnType())) { 2736 PDiag << ft_return_type << ToFunction->getReturnType() 2737 << FromFunction->getReturnType(); 2738 return; 2739 } 2740 2741 unsigned FromQuals = FromFunction->getTypeQuals(), 2742 ToQuals = ToFunction->getTypeQuals(); 2743 if (FromQuals != ToQuals) { 2744 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2745 return; 2746 } 2747 2748 // Handle exception specification differences on canonical type (in C++17 2749 // onwards). 2750 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2751 ->isNothrow(Context) != 2752 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2753 ->isNothrow(Context)) { 2754 PDiag << ft_noexcept; 2755 return; 2756 } 2757 2758 // Unable to find a difference, so add no extra info. 2759 PDiag << ft_default; 2760 } 2761 2762 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2763 /// for equality of their argument types. Caller has already checked that 2764 /// they have same number of arguments. If the parameters are different, 2765 /// ArgPos will have the parameter index of the first different parameter. 2766 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2767 const FunctionProtoType *NewType, 2768 unsigned *ArgPos) { 2769 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2770 N = NewType->param_type_begin(), 2771 E = OldType->param_type_end(); 2772 O && (O != E); ++O, ++N) { 2773 if (!Context.hasSameType(O->getUnqualifiedType(), 2774 N->getUnqualifiedType())) { 2775 if (ArgPos) 2776 *ArgPos = O - OldType->param_type_begin(); 2777 return false; 2778 } 2779 } 2780 return true; 2781 } 2782 2783 /// CheckPointerConversion - Check the pointer conversion from the 2784 /// expression From to the type ToType. This routine checks for 2785 /// ambiguous or inaccessible derived-to-base pointer 2786 /// conversions for which IsPointerConversion has already returned 2787 /// true. It returns true and produces a diagnostic if there was an 2788 /// error, or returns false otherwise. 2789 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2790 CastKind &Kind, 2791 CXXCastPath& BasePath, 2792 bool IgnoreBaseAccess, 2793 bool Diagnose) { 2794 QualType FromType = From->getType(); 2795 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2796 2797 Kind = CK_BitCast; 2798 2799 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2800 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2801 Expr::NPCK_ZeroExpression) { 2802 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2803 DiagRuntimeBehavior(From->getExprLoc(), From, 2804 PDiag(diag::warn_impcast_bool_to_null_pointer) 2805 << ToType << From->getSourceRange()); 2806 else if (!isUnevaluatedContext()) 2807 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2808 << ToType << From->getSourceRange(); 2809 } 2810 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2811 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2812 QualType FromPointeeType = FromPtrType->getPointeeType(), 2813 ToPointeeType = ToPtrType->getPointeeType(); 2814 2815 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2816 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2817 // We must have a derived-to-base conversion. Check an 2818 // ambiguous or inaccessible conversion. 2819 unsigned InaccessibleID = 0; 2820 unsigned AmbigiousID = 0; 2821 if (Diagnose) { 2822 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2823 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2824 } 2825 if (CheckDerivedToBaseConversion( 2826 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2827 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2828 &BasePath, IgnoreBaseAccess)) 2829 return true; 2830 2831 // The conversion was successful. 2832 Kind = CK_DerivedToBase; 2833 } 2834 2835 if (Diagnose && !IsCStyleOrFunctionalCast && 2836 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2837 assert(getLangOpts().MSVCCompat && 2838 "this should only be possible with MSVCCompat!"); 2839 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2840 << From->getSourceRange(); 2841 } 2842 } 2843 } else if (const ObjCObjectPointerType *ToPtrType = 2844 ToType->getAs<ObjCObjectPointerType>()) { 2845 if (const ObjCObjectPointerType *FromPtrType = 2846 FromType->getAs<ObjCObjectPointerType>()) { 2847 // Objective-C++ conversions are always okay. 2848 // FIXME: We should have a different class of conversions for the 2849 // Objective-C++ implicit conversions. 2850 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2851 return false; 2852 } else if (FromType->isBlockPointerType()) { 2853 Kind = CK_BlockPointerToObjCPointerCast; 2854 } else { 2855 Kind = CK_CPointerToObjCPointerCast; 2856 } 2857 } else if (ToType->isBlockPointerType()) { 2858 if (!FromType->isBlockPointerType()) 2859 Kind = CK_AnyPointerToBlockPointerCast; 2860 } 2861 2862 // We shouldn't fall into this case unless it's valid for other 2863 // reasons. 2864 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2865 Kind = CK_NullToPointer; 2866 2867 return false; 2868 } 2869 2870 /// IsMemberPointerConversion - Determines whether the conversion of the 2871 /// expression From, which has the (possibly adjusted) type FromType, can be 2872 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2873 /// If so, returns true and places the converted type (that might differ from 2874 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2875 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2876 QualType ToType, 2877 bool InOverloadResolution, 2878 QualType &ConvertedType) { 2879 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2880 if (!ToTypePtr) 2881 return false; 2882 2883 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2884 if (From->isNullPointerConstant(Context, 2885 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2886 : Expr::NPC_ValueDependentIsNull)) { 2887 ConvertedType = ToType; 2888 return true; 2889 } 2890 2891 // Otherwise, both types have to be member pointers. 2892 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2893 if (!FromTypePtr) 2894 return false; 2895 2896 // A pointer to member of B can be converted to a pointer to member of D, 2897 // where D is derived from B (C++ 4.11p2). 2898 QualType FromClass(FromTypePtr->getClass(), 0); 2899 QualType ToClass(ToTypePtr->getClass(), 0); 2900 2901 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2902 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2903 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2904 ToClass.getTypePtr()); 2905 return true; 2906 } 2907 2908 return false; 2909 } 2910 2911 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2912 /// expression From to the type ToType. This routine checks for ambiguous or 2913 /// virtual or inaccessible base-to-derived member pointer conversions 2914 /// for which IsMemberPointerConversion has already returned true. It returns 2915 /// true and produces a diagnostic if there was an error, or returns false 2916 /// otherwise. 2917 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2918 CastKind &Kind, 2919 CXXCastPath &BasePath, 2920 bool IgnoreBaseAccess) { 2921 QualType FromType = From->getType(); 2922 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2923 if (!FromPtrType) { 2924 // This must be a null pointer to member pointer conversion 2925 assert(From->isNullPointerConstant(Context, 2926 Expr::NPC_ValueDependentIsNull) && 2927 "Expr must be null pointer constant!"); 2928 Kind = CK_NullToMemberPointer; 2929 return false; 2930 } 2931 2932 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2933 assert(ToPtrType && "No member pointer cast has a target type " 2934 "that is not a member pointer."); 2935 2936 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2937 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2938 2939 // FIXME: What about dependent types? 2940 assert(FromClass->isRecordType() && "Pointer into non-class."); 2941 assert(ToClass->isRecordType() && "Pointer into non-class."); 2942 2943 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2944 /*DetectVirtual=*/true); 2945 bool DerivationOkay = 2946 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2947 assert(DerivationOkay && 2948 "Should not have been called if derivation isn't OK."); 2949 (void)DerivationOkay; 2950 2951 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2952 getUnqualifiedType())) { 2953 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2954 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2955 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2956 return true; 2957 } 2958 2959 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2960 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2961 << FromClass << ToClass << QualType(VBase, 0) 2962 << From->getSourceRange(); 2963 return true; 2964 } 2965 2966 if (!IgnoreBaseAccess) 2967 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2968 Paths.front(), 2969 diag::err_downcast_from_inaccessible_base); 2970 2971 // Must be a base to derived member conversion. 2972 BuildBasePathArray(Paths, BasePath); 2973 Kind = CK_BaseToDerivedMemberPointer; 2974 return false; 2975 } 2976 2977 /// Determine whether the lifetime conversion between the two given 2978 /// qualifiers sets is nontrivial. 2979 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2980 Qualifiers ToQuals) { 2981 // Converting anything to const __unsafe_unretained is trivial. 2982 if (ToQuals.hasConst() && 2983 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2984 return false; 2985 2986 return true; 2987 } 2988 2989 /// IsQualificationConversion - Determines whether the conversion from 2990 /// an rvalue of type FromType to ToType is a qualification conversion 2991 /// (C++ 4.4). 2992 /// 2993 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2994 /// when the qualification conversion involves a change in the Objective-C 2995 /// object lifetime. 2996 bool 2997 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2998 bool CStyle, bool &ObjCLifetimeConversion) { 2999 FromType = Context.getCanonicalType(FromType); 3000 ToType = Context.getCanonicalType(ToType); 3001 ObjCLifetimeConversion = false; 3002 3003 // If FromType and ToType are the same type, this is not a 3004 // qualification conversion. 3005 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3006 return false; 3007 3008 // (C++ 4.4p4): 3009 // A conversion can add cv-qualifiers at levels other than the first 3010 // in multi-level pointers, subject to the following rules: [...] 3011 bool PreviousToQualsIncludeConst = true; 3012 bool UnwrappedAnyPointer = false; 3013 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3014 // Within each iteration of the loop, we check the qualifiers to 3015 // determine if this still looks like a qualification 3016 // conversion. Then, if all is well, we unwrap one more level of 3017 // pointers or pointers-to-members and do it all again 3018 // until there are no more pointers or pointers-to-members left to 3019 // unwrap. 3020 UnwrappedAnyPointer = true; 3021 3022 Qualifiers FromQuals = FromType.getQualifiers(); 3023 Qualifiers ToQuals = ToType.getQualifiers(); 3024 3025 // Ignore __unaligned qualifier if this type is void. 3026 if (ToType.getUnqualifiedType()->isVoidType()) 3027 FromQuals.removeUnaligned(); 3028 3029 // Objective-C ARC: 3030 // Check Objective-C lifetime conversions. 3031 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3032 UnwrappedAnyPointer) { 3033 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3034 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3035 ObjCLifetimeConversion = true; 3036 FromQuals.removeObjCLifetime(); 3037 ToQuals.removeObjCLifetime(); 3038 } else { 3039 // Qualification conversions cannot cast between different 3040 // Objective-C lifetime qualifiers. 3041 return false; 3042 } 3043 } 3044 3045 // Allow addition/removal of GC attributes but not changing GC attributes. 3046 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3047 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3048 FromQuals.removeObjCGCAttr(); 3049 ToQuals.removeObjCGCAttr(); 3050 } 3051 3052 // -- for every j > 0, if const is in cv 1,j then const is in cv 3053 // 2,j, and similarly for volatile. 3054 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3055 return false; 3056 3057 // -- if the cv 1,j and cv 2,j are different, then const is in 3058 // every cv for 0 < k < j. 3059 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3060 && !PreviousToQualsIncludeConst) 3061 return false; 3062 3063 // Keep track of whether all prior cv-qualifiers in the "to" type 3064 // include const. 3065 PreviousToQualsIncludeConst 3066 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3067 } 3068 3069 // We are left with FromType and ToType being the pointee types 3070 // after unwrapping the original FromType and ToType the same number 3071 // of types. If we unwrapped any pointers, and if FromType and 3072 // ToType have the same unqualified type (since we checked 3073 // qualifiers above), then this is a qualification conversion. 3074 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3075 } 3076 3077 /// \brief - Determine whether this is a conversion from a scalar type to an 3078 /// atomic type. 3079 /// 3080 /// If successful, updates \c SCS's second and third steps in the conversion 3081 /// sequence to finish the conversion. 3082 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3083 bool InOverloadResolution, 3084 StandardConversionSequence &SCS, 3085 bool CStyle) { 3086 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3087 if (!ToAtomic) 3088 return false; 3089 3090 StandardConversionSequence InnerSCS; 3091 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3092 InOverloadResolution, InnerSCS, 3093 CStyle, /*AllowObjCWritebackConversion=*/false)) 3094 return false; 3095 3096 SCS.Second = InnerSCS.Second; 3097 SCS.setToType(1, InnerSCS.getToType(1)); 3098 SCS.Third = InnerSCS.Third; 3099 SCS.QualificationIncludesObjCLifetime 3100 = InnerSCS.QualificationIncludesObjCLifetime; 3101 SCS.setToType(2, InnerSCS.getToType(2)); 3102 return true; 3103 } 3104 3105 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3106 CXXConstructorDecl *Constructor, 3107 QualType Type) { 3108 const FunctionProtoType *CtorType = 3109 Constructor->getType()->getAs<FunctionProtoType>(); 3110 if (CtorType->getNumParams() > 0) { 3111 QualType FirstArg = CtorType->getParamType(0); 3112 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3113 return true; 3114 } 3115 return false; 3116 } 3117 3118 static OverloadingResult 3119 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3120 CXXRecordDecl *To, 3121 UserDefinedConversionSequence &User, 3122 OverloadCandidateSet &CandidateSet, 3123 bool AllowExplicit) { 3124 for (auto *D : S.LookupConstructors(To)) { 3125 auto Info = getConstructorInfo(D); 3126 if (!Info) 3127 continue; 3128 3129 bool Usable = !Info.Constructor->isInvalidDecl() && 3130 S.isInitListConstructor(Info.Constructor) && 3131 (AllowExplicit || !Info.Constructor->isExplicit()); 3132 if (Usable) { 3133 // If the first argument is (a reference to) the target type, 3134 // suppress conversions. 3135 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3136 S.Context, Info.Constructor, ToType); 3137 if (Info.ConstructorTmpl) 3138 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3139 /*ExplicitArgs*/ nullptr, From, 3140 CandidateSet, SuppressUserConversions); 3141 else 3142 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3143 CandidateSet, SuppressUserConversions); 3144 } 3145 } 3146 3147 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3148 3149 OverloadCandidateSet::iterator Best; 3150 switch (auto Result = 3151 CandidateSet.BestViableFunction(S, From->getLocStart(), 3152 Best, true)) { 3153 case OR_Deleted: 3154 case OR_Success: { 3155 // Record the standard conversion we used and the conversion function. 3156 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3157 QualType ThisType = Constructor->getThisType(S.Context); 3158 // Initializer lists don't have conversions as such. 3159 User.Before.setAsIdentityConversion(); 3160 User.HadMultipleCandidates = HadMultipleCandidates; 3161 User.ConversionFunction = Constructor; 3162 User.FoundConversionFunction = Best->FoundDecl; 3163 User.After.setAsIdentityConversion(); 3164 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3165 User.After.setAllToTypes(ToType); 3166 return Result; 3167 } 3168 3169 case OR_No_Viable_Function: 3170 return OR_No_Viable_Function; 3171 case OR_Ambiguous: 3172 return OR_Ambiguous; 3173 } 3174 3175 llvm_unreachable("Invalid OverloadResult!"); 3176 } 3177 3178 /// Determines whether there is a user-defined conversion sequence 3179 /// (C++ [over.ics.user]) that converts expression From to the type 3180 /// ToType. If such a conversion exists, User will contain the 3181 /// user-defined conversion sequence that performs such a conversion 3182 /// and this routine will return true. Otherwise, this routine returns 3183 /// false and User is unspecified. 3184 /// 3185 /// \param AllowExplicit true if the conversion should consider C++0x 3186 /// "explicit" conversion functions as well as non-explicit conversion 3187 /// functions (C++0x [class.conv.fct]p2). 3188 /// 3189 /// \param AllowObjCConversionOnExplicit true if the conversion should 3190 /// allow an extra Objective-C pointer conversion on uses of explicit 3191 /// constructors. Requires \c AllowExplicit to also be set. 3192 static OverloadingResult 3193 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3194 UserDefinedConversionSequence &User, 3195 OverloadCandidateSet &CandidateSet, 3196 bool AllowExplicit, 3197 bool AllowObjCConversionOnExplicit) { 3198 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3199 3200 // Whether we will only visit constructors. 3201 bool ConstructorsOnly = false; 3202 3203 // If the type we are conversion to is a class type, enumerate its 3204 // constructors. 3205 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3206 // C++ [over.match.ctor]p1: 3207 // When objects of class type are direct-initialized (8.5), or 3208 // copy-initialized from an expression of the same or a 3209 // derived class type (8.5), overload resolution selects the 3210 // constructor. [...] For copy-initialization, the candidate 3211 // functions are all the converting constructors (12.3.1) of 3212 // that class. The argument list is the expression-list within 3213 // the parentheses of the initializer. 3214 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3215 (From->getType()->getAs<RecordType>() && 3216 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3217 ConstructorsOnly = true; 3218 3219 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3220 // We're not going to find any constructors. 3221 } else if (CXXRecordDecl *ToRecordDecl 3222 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3223 3224 Expr **Args = &From; 3225 unsigned NumArgs = 1; 3226 bool ListInitializing = false; 3227 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3228 // But first, see if there is an init-list-constructor that will work. 3229 OverloadingResult Result = IsInitializerListConstructorConversion( 3230 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3231 if (Result != OR_No_Viable_Function) 3232 return Result; 3233 // Never mind. 3234 CandidateSet.clear(); 3235 3236 // If we're list-initializing, we pass the individual elements as 3237 // arguments, not the entire list. 3238 Args = InitList->getInits(); 3239 NumArgs = InitList->getNumInits(); 3240 ListInitializing = true; 3241 } 3242 3243 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3244 auto Info = getConstructorInfo(D); 3245 if (!Info) 3246 continue; 3247 3248 bool Usable = !Info.Constructor->isInvalidDecl(); 3249 if (ListInitializing) 3250 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3251 else 3252 Usable = Usable && 3253 Info.Constructor->isConvertingConstructor(AllowExplicit); 3254 if (Usable) { 3255 bool SuppressUserConversions = !ConstructorsOnly; 3256 if (SuppressUserConversions && ListInitializing) { 3257 SuppressUserConversions = false; 3258 if (NumArgs == 1) { 3259 // If the first argument is (a reference to) the target type, 3260 // suppress conversions. 3261 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3262 S.Context, Info.Constructor, ToType); 3263 } 3264 } 3265 if (Info.ConstructorTmpl) 3266 S.AddTemplateOverloadCandidate( 3267 Info.ConstructorTmpl, Info.FoundDecl, 3268 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3269 CandidateSet, SuppressUserConversions); 3270 else 3271 // Allow one user-defined conversion when user specifies a 3272 // From->ToType conversion via an static cast (c-style, etc). 3273 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3274 llvm::makeArrayRef(Args, NumArgs), 3275 CandidateSet, SuppressUserConversions); 3276 } 3277 } 3278 } 3279 } 3280 3281 // Enumerate conversion functions, if we're allowed to. 3282 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3283 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3284 // No conversion functions from incomplete types. 3285 } else if (const RecordType *FromRecordType 3286 = From->getType()->getAs<RecordType>()) { 3287 if (CXXRecordDecl *FromRecordDecl 3288 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3289 // Add all of the conversion functions as candidates. 3290 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3291 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3292 DeclAccessPair FoundDecl = I.getPair(); 3293 NamedDecl *D = FoundDecl.getDecl(); 3294 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3295 if (isa<UsingShadowDecl>(D)) 3296 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3297 3298 CXXConversionDecl *Conv; 3299 FunctionTemplateDecl *ConvTemplate; 3300 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3301 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3302 else 3303 Conv = cast<CXXConversionDecl>(D); 3304 3305 if (AllowExplicit || !Conv->isExplicit()) { 3306 if (ConvTemplate) 3307 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3308 ActingContext, From, ToType, 3309 CandidateSet, 3310 AllowObjCConversionOnExplicit); 3311 else 3312 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3313 From, ToType, CandidateSet, 3314 AllowObjCConversionOnExplicit); 3315 } 3316 } 3317 } 3318 } 3319 3320 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3321 3322 OverloadCandidateSet::iterator Best; 3323 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3324 Best, true)) { 3325 case OR_Success: 3326 case OR_Deleted: 3327 // Record the standard conversion we used and the conversion function. 3328 if (CXXConstructorDecl *Constructor 3329 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3330 // C++ [over.ics.user]p1: 3331 // If the user-defined conversion is specified by a 3332 // constructor (12.3.1), the initial standard conversion 3333 // sequence converts the source type to the type required by 3334 // the argument of the constructor. 3335 // 3336 QualType ThisType = Constructor->getThisType(S.Context); 3337 if (isa<InitListExpr>(From)) { 3338 // Initializer lists don't have conversions as such. 3339 User.Before.setAsIdentityConversion(); 3340 } else { 3341 if (Best->Conversions[0].isEllipsis()) 3342 User.EllipsisConversion = true; 3343 else { 3344 User.Before = Best->Conversions[0].Standard; 3345 User.EllipsisConversion = false; 3346 } 3347 } 3348 User.HadMultipleCandidates = HadMultipleCandidates; 3349 User.ConversionFunction = Constructor; 3350 User.FoundConversionFunction = Best->FoundDecl; 3351 User.After.setAsIdentityConversion(); 3352 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3353 User.After.setAllToTypes(ToType); 3354 return Result; 3355 } 3356 if (CXXConversionDecl *Conversion 3357 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3358 // C++ [over.ics.user]p1: 3359 // 3360 // [...] If the user-defined conversion is specified by a 3361 // conversion function (12.3.2), the initial standard 3362 // conversion sequence converts the source type to the 3363 // implicit object parameter of the conversion function. 3364 User.Before = Best->Conversions[0].Standard; 3365 User.HadMultipleCandidates = HadMultipleCandidates; 3366 User.ConversionFunction = Conversion; 3367 User.FoundConversionFunction = Best->FoundDecl; 3368 User.EllipsisConversion = false; 3369 3370 // C++ [over.ics.user]p2: 3371 // The second standard conversion sequence converts the 3372 // result of the user-defined conversion to the target type 3373 // for the sequence. Since an implicit conversion sequence 3374 // is an initialization, the special rules for 3375 // initialization by user-defined conversion apply when 3376 // selecting the best user-defined conversion for a 3377 // user-defined conversion sequence (see 13.3.3 and 3378 // 13.3.3.1). 3379 User.After = Best->FinalConversion; 3380 return Result; 3381 } 3382 llvm_unreachable("Not a constructor or conversion function?"); 3383 3384 case OR_No_Viable_Function: 3385 return OR_No_Viable_Function; 3386 3387 case OR_Ambiguous: 3388 return OR_Ambiguous; 3389 } 3390 3391 llvm_unreachable("Invalid OverloadResult!"); 3392 } 3393 3394 bool 3395 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3396 ImplicitConversionSequence ICS; 3397 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3398 OverloadCandidateSet::CSK_Normal); 3399 OverloadingResult OvResult = 3400 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3401 CandidateSet, false, false); 3402 if (OvResult == OR_Ambiguous) 3403 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3404 << From->getType() << ToType << From->getSourceRange(); 3405 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3406 if (!RequireCompleteType(From->getLocStart(), ToType, 3407 diag::err_typecheck_nonviable_condition_incomplete, 3408 From->getType(), From->getSourceRange())) 3409 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3410 << false << From->getType() << From->getSourceRange() << ToType; 3411 } else 3412 return false; 3413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3414 return true; 3415 } 3416 3417 /// \brief Compare the user-defined conversion functions or constructors 3418 /// of two user-defined conversion sequences to determine whether any ordering 3419 /// is possible. 3420 static ImplicitConversionSequence::CompareKind 3421 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3422 FunctionDecl *Function2) { 3423 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3424 return ImplicitConversionSequence::Indistinguishable; 3425 3426 // Objective-C++: 3427 // If both conversion functions are implicitly-declared conversions from 3428 // a lambda closure type to a function pointer and a block pointer, 3429 // respectively, always prefer the conversion to a function pointer, 3430 // because the function pointer is more lightweight and is more likely 3431 // to keep code working. 3432 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3433 if (!Conv1) 3434 return ImplicitConversionSequence::Indistinguishable; 3435 3436 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3437 if (!Conv2) 3438 return ImplicitConversionSequence::Indistinguishable; 3439 3440 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3441 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3442 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3443 if (Block1 != Block2) 3444 return Block1 ? ImplicitConversionSequence::Worse 3445 : ImplicitConversionSequence::Better; 3446 } 3447 3448 return ImplicitConversionSequence::Indistinguishable; 3449 } 3450 3451 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3452 const ImplicitConversionSequence &ICS) { 3453 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3454 (ICS.isUserDefined() && 3455 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3456 } 3457 3458 /// CompareImplicitConversionSequences - Compare two implicit 3459 /// conversion sequences to determine whether one is better than the 3460 /// other or if they are indistinguishable (C++ 13.3.3.2). 3461 static ImplicitConversionSequence::CompareKind 3462 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3463 const ImplicitConversionSequence& ICS1, 3464 const ImplicitConversionSequence& ICS2) 3465 { 3466 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3467 // conversion sequences (as defined in 13.3.3.1) 3468 // -- a standard conversion sequence (13.3.3.1.1) is a better 3469 // conversion sequence than a user-defined conversion sequence or 3470 // an ellipsis conversion sequence, and 3471 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3472 // conversion sequence than an ellipsis conversion sequence 3473 // (13.3.3.1.3). 3474 // 3475 // C++0x [over.best.ics]p10: 3476 // For the purpose of ranking implicit conversion sequences as 3477 // described in 13.3.3.2, the ambiguous conversion sequence is 3478 // treated as a user-defined sequence that is indistinguishable 3479 // from any other user-defined conversion sequence. 3480 3481 // String literal to 'char *' conversion has been deprecated in C++03. It has 3482 // been removed from C++11. We still accept this conversion, if it happens at 3483 // the best viable function. Otherwise, this conversion is considered worse 3484 // than ellipsis conversion. Consider this as an extension; this is not in the 3485 // standard. For example: 3486 // 3487 // int &f(...); // #1 3488 // void f(char*); // #2 3489 // void g() { int &r = f("foo"); } 3490 // 3491 // In C++03, we pick #2 as the best viable function. 3492 // In C++11, we pick #1 as the best viable function, because ellipsis 3493 // conversion is better than string-literal to char* conversion (since there 3494 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3495 // convert arguments, #2 would be the best viable function in C++11. 3496 // If the best viable function has this conversion, a warning will be issued 3497 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3498 3499 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3500 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3501 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3502 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3503 ? ImplicitConversionSequence::Worse 3504 : ImplicitConversionSequence::Better; 3505 3506 if (ICS1.getKindRank() < ICS2.getKindRank()) 3507 return ImplicitConversionSequence::Better; 3508 if (ICS2.getKindRank() < ICS1.getKindRank()) 3509 return ImplicitConversionSequence::Worse; 3510 3511 // The following checks require both conversion sequences to be of 3512 // the same kind. 3513 if (ICS1.getKind() != ICS2.getKind()) 3514 return ImplicitConversionSequence::Indistinguishable; 3515 3516 ImplicitConversionSequence::CompareKind Result = 3517 ImplicitConversionSequence::Indistinguishable; 3518 3519 // Two implicit conversion sequences of the same form are 3520 // indistinguishable conversion sequences unless one of the 3521 // following rules apply: (C++ 13.3.3.2p3): 3522 3523 // List-initialization sequence L1 is a better conversion sequence than 3524 // list-initialization sequence L2 if: 3525 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3526 // if not that, 3527 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3528 // and N1 is smaller than N2., 3529 // even if one of the other rules in this paragraph would otherwise apply. 3530 if (!ICS1.isBad()) { 3531 if (ICS1.isStdInitializerListElement() && 3532 !ICS2.isStdInitializerListElement()) 3533 return ImplicitConversionSequence::Better; 3534 if (!ICS1.isStdInitializerListElement() && 3535 ICS2.isStdInitializerListElement()) 3536 return ImplicitConversionSequence::Worse; 3537 } 3538 3539 if (ICS1.isStandard()) 3540 // Standard conversion sequence S1 is a better conversion sequence than 3541 // standard conversion sequence S2 if [...] 3542 Result = CompareStandardConversionSequences(S, Loc, 3543 ICS1.Standard, ICS2.Standard); 3544 else if (ICS1.isUserDefined()) { 3545 // User-defined conversion sequence U1 is a better conversion 3546 // sequence than another user-defined conversion sequence U2 if 3547 // they contain the same user-defined conversion function or 3548 // constructor and if the second standard conversion sequence of 3549 // U1 is better than the second standard conversion sequence of 3550 // U2 (C++ 13.3.3.2p3). 3551 if (ICS1.UserDefined.ConversionFunction == 3552 ICS2.UserDefined.ConversionFunction) 3553 Result = CompareStandardConversionSequences(S, Loc, 3554 ICS1.UserDefined.After, 3555 ICS2.UserDefined.After); 3556 else 3557 Result = compareConversionFunctions(S, 3558 ICS1.UserDefined.ConversionFunction, 3559 ICS2.UserDefined.ConversionFunction); 3560 } 3561 3562 return Result; 3563 } 3564 3565 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3566 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3567 Qualifiers Quals; 3568 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3569 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3570 } 3571 3572 return Context.hasSameUnqualifiedType(T1, T2); 3573 } 3574 3575 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3576 // determine if one is a proper subset of the other. 3577 static ImplicitConversionSequence::CompareKind 3578 compareStandardConversionSubsets(ASTContext &Context, 3579 const StandardConversionSequence& SCS1, 3580 const StandardConversionSequence& SCS2) { 3581 ImplicitConversionSequence::CompareKind Result 3582 = ImplicitConversionSequence::Indistinguishable; 3583 3584 // the identity conversion sequence is considered to be a subsequence of 3585 // any non-identity conversion sequence 3586 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3587 return ImplicitConversionSequence::Better; 3588 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3589 return ImplicitConversionSequence::Worse; 3590 3591 if (SCS1.Second != SCS2.Second) { 3592 if (SCS1.Second == ICK_Identity) 3593 Result = ImplicitConversionSequence::Better; 3594 else if (SCS2.Second == ICK_Identity) 3595 Result = ImplicitConversionSequence::Worse; 3596 else 3597 return ImplicitConversionSequence::Indistinguishable; 3598 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3599 return ImplicitConversionSequence::Indistinguishable; 3600 3601 if (SCS1.Third == SCS2.Third) { 3602 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3603 : ImplicitConversionSequence::Indistinguishable; 3604 } 3605 3606 if (SCS1.Third == ICK_Identity) 3607 return Result == ImplicitConversionSequence::Worse 3608 ? ImplicitConversionSequence::Indistinguishable 3609 : ImplicitConversionSequence::Better; 3610 3611 if (SCS2.Third == ICK_Identity) 3612 return Result == ImplicitConversionSequence::Better 3613 ? ImplicitConversionSequence::Indistinguishable 3614 : ImplicitConversionSequence::Worse; 3615 3616 return ImplicitConversionSequence::Indistinguishable; 3617 } 3618 3619 /// \brief Determine whether one of the given reference bindings is better 3620 /// than the other based on what kind of bindings they are. 3621 static bool 3622 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3623 const StandardConversionSequence &SCS2) { 3624 // C++0x [over.ics.rank]p3b4: 3625 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3626 // implicit object parameter of a non-static member function declared 3627 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3628 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3629 // lvalue reference to a function lvalue and S2 binds an rvalue 3630 // reference*. 3631 // 3632 // FIXME: Rvalue references. We're going rogue with the above edits, 3633 // because the semantics in the current C++0x working paper (N3225 at the 3634 // time of this writing) break the standard definition of std::forward 3635 // and std::reference_wrapper when dealing with references to functions. 3636 // Proposed wording changes submitted to CWG for consideration. 3637 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3638 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3639 return false; 3640 3641 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3642 SCS2.IsLvalueReference) || 3643 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3644 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3645 } 3646 3647 /// CompareStandardConversionSequences - Compare two standard 3648 /// conversion sequences to determine whether one is better than the 3649 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3650 static ImplicitConversionSequence::CompareKind 3651 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3652 const StandardConversionSequence& SCS1, 3653 const StandardConversionSequence& SCS2) 3654 { 3655 // Standard conversion sequence S1 is a better conversion sequence 3656 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3657 3658 // -- S1 is a proper subsequence of S2 (comparing the conversion 3659 // sequences in the canonical form defined by 13.3.3.1.1, 3660 // excluding any Lvalue Transformation; the identity conversion 3661 // sequence is considered to be a subsequence of any 3662 // non-identity conversion sequence) or, if not that, 3663 if (ImplicitConversionSequence::CompareKind CK 3664 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3665 return CK; 3666 3667 // -- the rank of S1 is better than the rank of S2 (by the rules 3668 // defined below), or, if not that, 3669 ImplicitConversionRank Rank1 = SCS1.getRank(); 3670 ImplicitConversionRank Rank2 = SCS2.getRank(); 3671 if (Rank1 < Rank2) 3672 return ImplicitConversionSequence::Better; 3673 else if (Rank2 < Rank1) 3674 return ImplicitConversionSequence::Worse; 3675 3676 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3677 // are indistinguishable unless one of the following rules 3678 // applies: 3679 3680 // A conversion that is not a conversion of a pointer, or 3681 // pointer to member, to bool is better than another conversion 3682 // that is such a conversion. 3683 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3684 return SCS2.isPointerConversionToBool() 3685 ? ImplicitConversionSequence::Better 3686 : ImplicitConversionSequence::Worse; 3687 3688 // C++ [over.ics.rank]p4b2: 3689 // 3690 // If class B is derived directly or indirectly from class A, 3691 // conversion of B* to A* is better than conversion of B* to 3692 // void*, and conversion of A* to void* is better than conversion 3693 // of B* to void*. 3694 bool SCS1ConvertsToVoid 3695 = SCS1.isPointerConversionToVoidPointer(S.Context); 3696 bool SCS2ConvertsToVoid 3697 = SCS2.isPointerConversionToVoidPointer(S.Context); 3698 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3699 // Exactly one of the conversion sequences is a conversion to 3700 // a void pointer; it's the worse conversion. 3701 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3702 : ImplicitConversionSequence::Worse; 3703 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3704 // Neither conversion sequence converts to a void pointer; compare 3705 // their derived-to-base conversions. 3706 if (ImplicitConversionSequence::CompareKind DerivedCK 3707 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3708 return DerivedCK; 3709 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3710 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3711 // Both conversion sequences are conversions to void 3712 // pointers. Compare the source types to determine if there's an 3713 // inheritance relationship in their sources. 3714 QualType FromType1 = SCS1.getFromType(); 3715 QualType FromType2 = SCS2.getFromType(); 3716 3717 // Adjust the types we're converting from via the array-to-pointer 3718 // conversion, if we need to. 3719 if (SCS1.First == ICK_Array_To_Pointer) 3720 FromType1 = S.Context.getArrayDecayedType(FromType1); 3721 if (SCS2.First == ICK_Array_To_Pointer) 3722 FromType2 = S.Context.getArrayDecayedType(FromType2); 3723 3724 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3725 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3726 3727 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3728 return ImplicitConversionSequence::Better; 3729 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3730 return ImplicitConversionSequence::Worse; 3731 3732 // Objective-C++: If one interface is more specific than the 3733 // other, it is the better one. 3734 const ObjCObjectPointerType* FromObjCPtr1 3735 = FromType1->getAs<ObjCObjectPointerType>(); 3736 const ObjCObjectPointerType* FromObjCPtr2 3737 = FromType2->getAs<ObjCObjectPointerType>(); 3738 if (FromObjCPtr1 && FromObjCPtr2) { 3739 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3740 FromObjCPtr2); 3741 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3742 FromObjCPtr1); 3743 if (AssignLeft != AssignRight) { 3744 return AssignLeft? ImplicitConversionSequence::Better 3745 : ImplicitConversionSequence::Worse; 3746 } 3747 } 3748 } 3749 3750 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3751 // bullet 3). 3752 if (ImplicitConversionSequence::CompareKind QualCK 3753 = CompareQualificationConversions(S, SCS1, SCS2)) 3754 return QualCK; 3755 3756 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3757 // Check for a better reference binding based on the kind of bindings. 3758 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3759 return ImplicitConversionSequence::Better; 3760 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3761 return ImplicitConversionSequence::Worse; 3762 3763 // C++ [over.ics.rank]p3b4: 3764 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3765 // which the references refer are the same type except for 3766 // top-level cv-qualifiers, and the type to which the reference 3767 // initialized by S2 refers is more cv-qualified than the type 3768 // to which the reference initialized by S1 refers. 3769 QualType T1 = SCS1.getToType(2); 3770 QualType T2 = SCS2.getToType(2); 3771 T1 = S.Context.getCanonicalType(T1); 3772 T2 = S.Context.getCanonicalType(T2); 3773 Qualifiers T1Quals, T2Quals; 3774 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3775 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3776 if (UnqualT1 == UnqualT2) { 3777 // Objective-C++ ARC: If the references refer to objects with different 3778 // lifetimes, prefer bindings that don't change lifetime. 3779 if (SCS1.ObjCLifetimeConversionBinding != 3780 SCS2.ObjCLifetimeConversionBinding) { 3781 return SCS1.ObjCLifetimeConversionBinding 3782 ? ImplicitConversionSequence::Worse 3783 : ImplicitConversionSequence::Better; 3784 } 3785 3786 // If the type is an array type, promote the element qualifiers to the 3787 // type for comparison. 3788 if (isa<ArrayType>(T1) && T1Quals) 3789 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3790 if (isa<ArrayType>(T2) && T2Quals) 3791 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3792 if (T2.isMoreQualifiedThan(T1)) 3793 return ImplicitConversionSequence::Better; 3794 else if (T1.isMoreQualifiedThan(T2)) 3795 return ImplicitConversionSequence::Worse; 3796 } 3797 } 3798 3799 // In Microsoft mode, prefer an integral conversion to a 3800 // floating-to-integral conversion if the integral conversion 3801 // is between types of the same size. 3802 // For example: 3803 // void f(float); 3804 // void f(int); 3805 // int main { 3806 // long a; 3807 // f(a); 3808 // } 3809 // Here, MSVC will call f(int) instead of generating a compile error 3810 // as clang will do in standard mode. 3811 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3812 SCS2.Second == ICK_Floating_Integral && 3813 S.Context.getTypeSize(SCS1.getFromType()) == 3814 S.Context.getTypeSize(SCS1.getToType(2))) 3815 return ImplicitConversionSequence::Better; 3816 3817 return ImplicitConversionSequence::Indistinguishable; 3818 } 3819 3820 /// CompareQualificationConversions - Compares two standard conversion 3821 /// sequences to determine whether they can be ranked based on their 3822 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3823 static ImplicitConversionSequence::CompareKind 3824 CompareQualificationConversions(Sema &S, 3825 const StandardConversionSequence& SCS1, 3826 const StandardConversionSequence& SCS2) { 3827 // C++ 13.3.3.2p3: 3828 // -- S1 and S2 differ only in their qualification conversion and 3829 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3830 // cv-qualification signature of type T1 is a proper subset of 3831 // the cv-qualification signature of type T2, and S1 is not the 3832 // deprecated string literal array-to-pointer conversion (4.2). 3833 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3834 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3835 return ImplicitConversionSequence::Indistinguishable; 3836 3837 // FIXME: the example in the standard doesn't use a qualification 3838 // conversion (!) 3839 QualType T1 = SCS1.getToType(2); 3840 QualType T2 = SCS2.getToType(2); 3841 T1 = S.Context.getCanonicalType(T1); 3842 T2 = S.Context.getCanonicalType(T2); 3843 Qualifiers T1Quals, T2Quals; 3844 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3845 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3846 3847 // If the types are the same, we won't learn anything by unwrapped 3848 // them. 3849 if (UnqualT1 == UnqualT2) 3850 return ImplicitConversionSequence::Indistinguishable; 3851 3852 // If the type is an array type, promote the element qualifiers to the type 3853 // for comparison. 3854 if (isa<ArrayType>(T1) && T1Quals) 3855 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3856 if (isa<ArrayType>(T2) && T2Quals) 3857 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3858 3859 ImplicitConversionSequence::CompareKind Result 3860 = ImplicitConversionSequence::Indistinguishable; 3861 3862 // Objective-C++ ARC: 3863 // Prefer qualification conversions not involving a change in lifetime 3864 // to qualification conversions that do not change lifetime. 3865 if (SCS1.QualificationIncludesObjCLifetime != 3866 SCS2.QualificationIncludesObjCLifetime) { 3867 Result = SCS1.QualificationIncludesObjCLifetime 3868 ? ImplicitConversionSequence::Worse 3869 : ImplicitConversionSequence::Better; 3870 } 3871 3872 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3873 // Within each iteration of the loop, we check the qualifiers to 3874 // determine if this still looks like a qualification 3875 // conversion. Then, if all is well, we unwrap one more level of 3876 // pointers or pointers-to-members and do it all again 3877 // until there are no more pointers or pointers-to-members left 3878 // to unwrap. This essentially mimics what 3879 // IsQualificationConversion does, but here we're checking for a 3880 // strict subset of qualifiers. 3881 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3882 // The qualifiers are the same, so this doesn't tell us anything 3883 // about how the sequences rank. 3884 ; 3885 else if (T2.isMoreQualifiedThan(T1)) { 3886 // T1 has fewer qualifiers, so it could be the better sequence. 3887 if (Result == ImplicitConversionSequence::Worse) 3888 // Neither has qualifiers that are a subset of the other's 3889 // qualifiers. 3890 return ImplicitConversionSequence::Indistinguishable; 3891 3892 Result = ImplicitConversionSequence::Better; 3893 } else if (T1.isMoreQualifiedThan(T2)) { 3894 // T2 has fewer qualifiers, so it could be the better sequence. 3895 if (Result == ImplicitConversionSequence::Better) 3896 // Neither has qualifiers that are a subset of the other's 3897 // qualifiers. 3898 return ImplicitConversionSequence::Indistinguishable; 3899 3900 Result = ImplicitConversionSequence::Worse; 3901 } else { 3902 // Qualifiers are disjoint. 3903 return ImplicitConversionSequence::Indistinguishable; 3904 } 3905 3906 // If the types after this point are equivalent, we're done. 3907 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3908 break; 3909 } 3910 3911 // Check that the winning standard conversion sequence isn't using 3912 // the deprecated string literal array to pointer conversion. 3913 switch (Result) { 3914 case ImplicitConversionSequence::Better: 3915 if (SCS1.DeprecatedStringLiteralToCharPtr) 3916 Result = ImplicitConversionSequence::Indistinguishable; 3917 break; 3918 3919 case ImplicitConversionSequence::Indistinguishable: 3920 break; 3921 3922 case ImplicitConversionSequence::Worse: 3923 if (SCS2.DeprecatedStringLiteralToCharPtr) 3924 Result = ImplicitConversionSequence::Indistinguishable; 3925 break; 3926 } 3927 3928 return Result; 3929 } 3930 3931 /// CompareDerivedToBaseConversions - Compares two standard conversion 3932 /// sequences to determine whether they can be ranked based on their 3933 /// various kinds of derived-to-base conversions (C++ 3934 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3935 /// conversions between Objective-C interface types. 3936 static ImplicitConversionSequence::CompareKind 3937 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3938 const StandardConversionSequence& SCS1, 3939 const StandardConversionSequence& SCS2) { 3940 QualType FromType1 = SCS1.getFromType(); 3941 QualType ToType1 = SCS1.getToType(1); 3942 QualType FromType2 = SCS2.getFromType(); 3943 QualType ToType2 = SCS2.getToType(1); 3944 3945 // Adjust the types we're converting from via the array-to-pointer 3946 // conversion, if we need to. 3947 if (SCS1.First == ICK_Array_To_Pointer) 3948 FromType1 = S.Context.getArrayDecayedType(FromType1); 3949 if (SCS2.First == ICK_Array_To_Pointer) 3950 FromType2 = S.Context.getArrayDecayedType(FromType2); 3951 3952 // Canonicalize all of the types. 3953 FromType1 = S.Context.getCanonicalType(FromType1); 3954 ToType1 = S.Context.getCanonicalType(ToType1); 3955 FromType2 = S.Context.getCanonicalType(FromType2); 3956 ToType2 = S.Context.getCanonicalType(ToType2); 3957 3958 // C++ [over.ics.rank]p4b3: 3959 // 3960 // If class B is derived directly or indirectly from class A and 3961 // class C is derived directly or indirectly from B, 3962 // 3963 // Compare based on pointer conversions. 3964 if (SCS1.Second == ICK_Pointer_Conversion && 3965 SCS2.Second == ICK_Pointer_Conversion && 3966 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3967 FromType1->isPointerType() && FromType2->isPointerType() && 3968 ToType1->isPointerType() && ToType2->isPointerType()) { 3969 QualType FromPointee1 3970 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3971 QualType ToPointee1 3972 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3973 QualType FromPointee2 3974 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3975 QualType ToPointee2 3976 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3977 3978 // -- conversion of C* to B* is better than conversion of C* to A*, 3979 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3980 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3981 return ImplicitConversionSequence::Better; 3982 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3983 return ImplicitConversionSequence::Worse; 3984 } 3985 3986 // -- conversion of B* to A* is better than conversion of C* to A*, 3987 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3988 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3989 return ImplicitConversionSequence::Better; 3990 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3991 return ImplicitConversionSequence::Worse; 3992 } 3993 } else if (SCS1.Second == ICK_Pointer_Conversion && 3994 SCS2.Second == ICK_Pointer_Conversion) { 3995 const ObjCObjectPointerType *FromPtr1 3996 = FromType1->getAs<ObjCObjectPointerType>(); 3997 const ObjCObjectPointerType *FromPtr2 3998 = FromType2->getAs<ObjCObjectPointerType>(); 3999 const ObjCObjectPointerType *ToPtr1 4000 = ToType1->getAs<ObjCObjectPointerType>(); 4001 const ObjCObjectPointerType *ToPtr2 4002 = ToType2->getAs<ObjCObjectPointerType>(); 4003 4004 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4005 // Apply the same conversion ranking rules for Objective-C pointer types 4006 // that we do for C++ pointers to class types. However, we employ the 4007 // Objective-C pseudo-subtyping relationship used for assignment of 4008 // Objective-C pointer types. 4009 bool FromAssignLeft 4010 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4011 bool FromAssignRight 4012 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4013 bool ToAssignLeft 4014 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4015 bool ToAssignRight 4016 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4017 4018 // A conversion to an a non-id object pointer type or qualified 'id' 4019 // type is better than a conversion to 'id'. 4020 if (ToPtr1->isObjCIdType() && 4021 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4022 return ImplicitConversionSequence::Worse; 4023 if (ToPtr2->isObjCIdType() && 4024 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4025 return ImplicitConversionSequence::Better; 4026 4027 // A conversion to a non-id object pointer type is better than a 4028 // conversion to a qualified 'id' type 4029 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4030 return ImplicitConversionSequence::Worse; 4031 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4032 return ImplicitConversionSequence::Better; 4033 4034 // A conversion to an a non-Class object pointer type or qualified 'Class' 4035 // type is better than a conversion to 'Class'. 4036 if (ToPtr1->isObjCClassType() && 4037 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4038 return ImplicitConversionSequence::Worse; 4039 if (ToPtr2->isObjCClassType() && 4040 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4041 return ImplicitConversionSequence::Better; 4042 4043 // A conversion to a non-Class object pointer type is better than a 4044 // conversion to a qualified 'Class' type. 4045 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4046 return ImplicitConversionSequence::Worse; 4047 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4048 return ImplicitConversionSequence::Better; 4049 4050 // -- "conversion of C* to B* is better than conversion of C* to A*," 4051 if (S.Context.hasSameType(FromType1, FromType2) && 4052 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4053 (ToAssignLeft != ToAssignRight)) 4054 return ToAssignLeft? ImplicitConversionSequence::Worse 4055 : ImplicitConversionSequence::Better; 4056 4057 // -- "conversion of B* to A* is better than conversion of C* to A*," 4058 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4059 (FromAssignLeft != FromAssignRight)) 4060 return FromAssignLeft? ImplicitConversionSequence::Better 4061 : ImplicitConversionSequence::Worse; 4062 } 4063 } 4064 4065 // Ranking of member-pointer types. 4066 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4067 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4068 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4069 const MemberPointerType * FromMemPointer1 = 4070 FromType1->getAs<MemberPointerType>(); 4071 const MemberPointerType * ToMemPointer1 = 4072 ToType1->getAs<MemberPointerType>(); 4073 const MemberPointerType * FromMemPointer2 = 4074 FromType2->getAs<MemberPointerType>(); 4075 const MemberPointerType * ToMemPointer2 = 4076 ToType2->getAs<MemberPointerType>(); 4077 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4078 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4079 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4080 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4081 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4082 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4083 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4084 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4085 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4086 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4087 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4088 return ImplicitConversionSequence::Worse; 4089 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4090 return ImplicitConversionSequence::Better; 4091 } 4092 // conversion of B::* to C::* is better than conversion of A::* to C::* 4093 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4094 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4095 return ImplicitConversionSequence::Better; 4096 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4097 return ImplicitConversionSequence::Worse; 4098 } 4099 } 4100 4101 if (SCS1.Second == ICK_Derived_To_Base) { 4102 // -- conversion of C to B is better than conversion of C to A, 4103 // -- binding of an expression of type C to a reference of type 4104 // B& is better than binding an expression of type C to a 4105 // reference of type A&, 4106 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4107 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4108 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4109 return ImplicitConversionSequence::Better; 4110 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4111 return ImplicitConversionSequence::Worse; 4112 } 4113 4114 // -- conversion of B to A is better than conversion of C to A. 4115 // -- binding of an expression of type B to a reference of type 4116 // A& is better than binding an expression of type C to a 4117 // reference of type A&, 4118 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4119 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4120 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4121 return ImplicitConversionSequence::Better; 4122 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4123 return ImplicitConversionSequence::Worse; 4124 } 4125 } 4126 4127 return ImplicitConversionSequence::Indistinguishable; 4128 } 4129 4130 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4131 /// C++ class. 4132 static bool isTypeValid(QualType T) { 4133 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4134 return !Record->isInvalidDecl(); 4135 4136 return true; 4137 } 4138 4139 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4140 /// determine whether they are reference-related, 4141 /// reference-compatible, reference-compatible with added 4142 /// qualification, or incompatible, for use in C++ initialization by 4143 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4144 /// type, and the first type (T1) is the pointee type of the reference 4145 /// type being initialized. 4146 Sema::ReferenceCompareResult 4147 Sema::CompareReferenceRelationship(SourceLocation Loc, 4148 QualType OrigT1, QualType OrigT2, 4149 bool &DerivedToBase, 4150 bool &ObjCConversion, 4151 bool &ObjCLifetimeConversion) { 4152 assert(!OrigT1->isReferenceType() && 4153 "T1 must be the pointee type of the reference type"); 4154 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4155 4156 QualType T1 = Context.getCanonicalType(OrigT1); 4157 QualType T2 = Context.getCanonicalType(OrigT2); 4158 Qualifiers T1Quals, T2Quals; 4159 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4160 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4161 4162 // C++ [dcl.init.ref]p4: 4163 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4164 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4165 // T1 is a base class of T2. 4166 DerivedToBase = false; 4167 ObjCConversion = false; 4168 ObjCLifetimeConversion = false; 4169 if (UnqualT1 == UnqualT2) { 4170 // Nothing to do. 4171 } else if (isCompleteType(Loc, OrigT2) && 4172 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4173 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4174 DerivedToBase = true; 4175 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4176 UnqualT2->isObjCObjectOrInterfaceType() && 4177 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4178 ObjCConversion = true; 4179 else 4180 return Ref_Incompatible; 4181 4182 // At this point, we know that T1 and T2 are reference-related (at 4183 // least). 4184 4185 // If the type is an array type, promote the element qualifiers to the type 4186 // for comparison. 4187 if (isa<ArrayType>(T1) && T1Quals) 4188 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4189 if (isa<ArrayType>(T2) && T2Quals) 4190 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4191 4192 // C++ [dcl.init.ref]p4: 4193 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4194 // reference-related to T2 and cv1 is the same cv-qualification 4195 // as, or greater cv-qualification than, cv2. For purposes of 4196 // overload resolution, cases for which cv1 is greater 4197 // cv-qualification than cv2 are identified as 4198 // reference-compatible with added qualification (see 13.3.3.2). 4199 // 4200 // Note that we also require equivalence of Objective-C GC and address-space 4201 // qualifiers when performing these computations, so that e.g., an int in 4202 // address space 1 is not reference-compatible with an int in address 4203 // space 2. 4204 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4205 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4206 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4207 ObjCLifetimeConversion = true; 4208 4209 T1Quals.removeObjCLifetime(); 4210 T2Quals.removeObjCLifetime(); 4211 } 4212 4213 // MS compiler ignores __unaligned qualifier for references; do the same. 4214 T1Quals.removeUnaligned(); 4215 T2Quals.removeUnaligned(); 4216 4217 if (T1Quals == T2Quals) 4218 return Ref_Compatible; 4219 else if (T1Quals.compatiblyIncludes(T2Quals)) 4220 return Ref_Compatible_With_Added_Qualification; 4221 else 4222 return Ref_Related; 4223 } 4224 4225 /// \brief Look for a user-defined conversion to an value reference-compatible 4226 /// with DeclType. Return true if something definite is found. 4227 static bool 4228 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4229 QualType DeclType, SourceLocation DeclLoc, 4230 Expr *Init, QualType T2, bool AllowRvalues, 4231 bool AllowExplicit) { 4232 assert(T2->isRecordType() && "Can only find conversions of record types."); 4233 CXXRecordDecl *T2RecordDecl 4234 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4235 4236 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4237 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4238 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4239 NamedDecl *D = *I; 4240 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4241 if (isa<UsingShadowDecl>(D)) 4242 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4243 4244 FunctionTemplateDecl *ConvTemplate 4245 = dyn_cast<FunctionTemplateDecl>(D); 4246 CXXConversionDecl *Conv; 4247 if (ConvTemplate) 4248 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4249 else 4250 Conv = cast<CXXConversionDecl>(D); 4251 4252 // If this is an explicit conversion, and we're not allowed to consider 4253 // explicit conversions, skip it. 4254 if (!AllowExplicit && Conv->isExplicit()) 4255 continue; 4256 4257 if (AllowRvalues) { 4258 bool DerivedToBase = false; 4259 bool ObjCConversion = false; 4260 bool ObjCLifetimeConversion = false; 4261 4262 // If we are initializing an rvalue reference, don't permit conversion 4263 // functions that return lvalues. 4264 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4265 const ReferenceType *RefType 4266 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4267 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4268 continue; 4269 } 4270 4271 if (!ConvTemplate && 4272 S.CompareReferenceRelationship( 4273 DeclLoc, 4274 Conv->getConversionType().getNonReferenceType() 4275 .getUnqualifiedType(), 4276 DeclType.getNonReferenceType().getUnqualifiedType(), 4277 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4278 Sema::Ref_Incompatible) 4279 continue; 4280 } else { 4281 // If the conversion function doesn't return a reference type, 4282 // it can't be considered for this conversion. An rvalue reference 4283 // is only acceptable if its referencee is a function type. 4284 4285 const ReferenceType *RefType = 4286 Conv->getConversionType()->getAs<ReferenceType>(); 4287 if (!RefType || 4288 (!RefType->isLValueReferenceType() && 4289 !RefType->getPointeeType()->isFunctionType())) 4290 continue; 4291 } 4292 4293 if (ConvTemplate) 4294 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4295 Init, DeclType, CandidateSet, 4296 /*AllowObjCConversionOnExplicit=*/false); 4297 else 4298 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4299 DeclType, CandidateSet, 4300 /*AllowObjCConversionOnExplicit=*/false); 4301 } 4302 4303 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4304 4305 OverloadCandidateSet::iterator Best; 4306 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4307 case OR_Success: 4308 // C++ [over.ics.ref]p1: 4309 // 4310 // [...] If the parameter binds directly to the result of 4311 // applying a conversion function to the argument 4312 // expression, the implicit conversion sequence is a 4313 // user-defined conversion sequence (13.3.3.1.2), with the 4314 // second standard conversion sequence either an identity 4315 // conversion or, if the conversion function returns an 4316 // entity of a type that is a derived class of the parameter 4317 // type, a derived-to-base Conversion. 4318 if (!Best->FinalConversion.DirectBinding) 4319 return false; 4320 4321 ICS.setUserDefined(); 4322 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4323 ICS.UserDefined.After = Best->FinalConversion; 4324 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4325 ICS.UserDefined.ConversionFunction = Best->Function; 4326 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4327 ICS.UserDefined.EllipsisConversion = false; 4328 assert(ICS.UserDefined.After.ReferenceBinding && 4329 ICS.UserDefined.After.DirectBinding && 4330 "Expected a direct reference binding!"); 4331 return true; 4332 4333 case OR_Ambiguous: 4334 ICS.setAmbiguous(); 4335 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4336 Cand != CandidateSet.end(); ++Cand) 4337 if (Cand->Viable) 4338 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4339 return true; 4340 4341 case OR_No_Viable_Function: 4342 case OR_Deleted: 4343 // There was no suitable conversion, or we found a deleted 4344 // conversion; continue with other checks. 4345 return false; 4346 } 4347 4348 llvm_unreachable("Invalid OverloadResult!"); 4349 } 4350 4351 /// \brief Compute an implicit conversion sequence for reference 4352 /// initialization. 4353 static ImplicitConversionSequence 4354 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4355 SourceLocation DeclLoc, 4356 bool SuppressUserConversions, 4357 bool AllowExplicit) { 4358 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4359 4360 // Most paths end in a failed conversion. 4361 ImplicitConversionSequence ICS; 4362 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4363 4364 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4365 QualType T2 = Init->getType(); 4366 4367 // If the initializer is the address of an overloaded function, try 4368 // to resolve the overloaded function. If all goes well, T2 is the 4369 // type of the resulting function. 4370 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4371 DeclAccessPair Found; 4372 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4373 false, Found)) 4374 T2 = Fn->getType(); 4375 } 4376 4377 // Compute some basic properties of the types and the initializer. 4378 bool isRValRef = DeclType->isRValueReferenceType(); 4379 bool DerivedToBase = false; 4380 bool ObjCConversion = false; 4381 bool ObjCLifetimeConversion = false; 4382 Expr::Classification InitCategory = Init->Classify(S.Context); 4383 Sema::ReferenceCompareResult RefRelationship 4384 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4385 ObjCConversion, ObjCLifetimeConversion); 4386 4387 4388 // C++0x [dcl.init.ref]p5: 4389 // A reference to type "cv1 T1" is initialized by an expression 4390 // of type "cv2 T2" as follows: 4391 4392 // -- If reference is an lvalue reference and the initializer expression 4393 if (!isRValRef) { 4394 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4395 // reference-compatible with "cv2 T2," or 4396 // 4397 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4398 if (InitCategory.isLValue() && 4399 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4400 // C++ [over.ics.ref]p1: 4401 // When a parameter of reference type binds directly (8.5.3) 4402 // to an argument expression, the implicit conversion sequence 4403 // is the identity conversion, unless the argument expression 4404 // has a type that is a derived class of the parameter type, 4405 // in which case the implicit conversion sequence is a 4406 // derived-to-base Conversion (13.3.3.1). 4407 ICS.setStandard(); 4408 ICS.Standard.First = ICK_Identity; 4409 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4410 : ObjCConversion? ICK_Compatible_Conversion 4411 : ICK_Identity; 4412 ICS.Standard.Third = ICK_Identity; 4413 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4414 ICS.Standard.setToType(0, T2); 4415 ICS.Standard.setToType(1, T1); 4416 ICS.Standard.setToType(2, T1); 4417 ICS.Standard.ReferenceBinding = true; 4418 ICS.Standard.DirectBinding = true; 4419 ICS.Standard.IsLvalueReference = !isRValRef; 4420 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4421 ICS.Standard.BindsToRvalue = false; 4422 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4423 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4424 ICS.Standard.CopyConstructor = nullptr; 4425 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4426 4427 // Nothing more to do: the inaccessibility/ambiguity check for 4428 // derived-to-base conversions is suppressed when we're 4429 // computing the implicit conversion sequence (C++ 4430 // [over.best.ics]p2). 4431 return ICS; 4432 } 4433 4434 // -- has a class type (i.e., T2 is a class type), where T1 is 4435 // not reference-related to T2, and can be implicitly 4436 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4437 // is reference-compatible with "cv3 T3" 92) (this 4438 // conversion is selected by enumerating the applicable 4439 // conversion functions (13.3.1.6) and choosing the best 4440 // one through overload resolution (13.3)), 4441 if (!SuppressUserConversions && T2->isRecordType() && 4442 S.isCompleteType(DeclLoc, T2) && 4443 RefRelationship == Sema::Ref_Incompatible) { 4444 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4445 Init, T2, /*AllowRvalues=*/false, 4446 AllowExplicit)) 4447 return ICS; 4448 } 4449 } 4450 4451 // -- Otherwise, the reference shall be an lvalue reference to a 4452 // non-volatile const type (i.e., cv1 shall be const), or the reference 4453 // shall be an rvalue reference. 4454 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4455 return ICS; 4456 4457 // -- If the initializer expression 4458 // 4459 // -- is an xvalue, class prvalue, array prvalue or function 4460 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4461 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4462 (InitCategory.isXValue() || 4463 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4464 (InitCategory.isLValue() && T2->isFunctionType()))) { 4465 ICS.setStandard(); 4466 ICS.Standard.First = ICK_Identity; 4467 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4468 : ObjCConversion? ICK_Compatible_Conversion 4469 : ICK_Identity; 4470 ICS.Standard.Third = ICK_Identity; 4471 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4472 ICS.Standard.setToType(0, T2); 4473 ICS.Standard.setToType(1, T1); 4474 ICS.Standard.setToType(2, T1); 4475 ICS.Standard.ReferenceBinding = true; 4476 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4477 // binding unless we're binding to a class prvalue. 4478 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4479 // allow the use of rvalue references in C++98/03 for the benefit of 4480 // standard library implementors; therefore, we need the xvalue check here. 4481 ICS.Standard.DirectBinding = 4482 S.getLangOpts().CPlusPlus11 || 4483 !(InitCategory.isPRValue() || T2->isRecordType()); 4484 ICS.Standard.IsLvalueReference = !isRValRef; 4485 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4486 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4487 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4488 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4489 ICS.Standard.CopyConstructor = nullptr; 4490 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4491 return ICS; 4492 } 4493 4494 // -- has a class type (i.e., T2 is a class type), where T1 is not 4495 // reference-related to T2, and can be implicitly converted to 4496 // an xvalue, class prvalue, or function lvalue of type 4497 // "cv3 T3", where "cv1 T1" is reference-compatible with 4498 // "cv3 T3", 4499 // 4500 // then the reference is bound to the value of the initializer 4501 // expression in the first case and to the result of the conversion 4502 // in the second case (or, in either case, to an appropriate base 4503 // class subobject). 4504 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4505 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4506 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4507 Init, T2, /*AllowRvalues=*/true, 4508 AllowExplicit)) { 4509 // In the second case, if the reference is an rvalue reference 4510 // and the second standard conversion sequence of the 4511 // user-defined conversion sequence includes an lvalue-to-rvalue 4512 // conversion, the program is ill-formed. 4513 if (ICS.isUserDefined() && isRValRef && 4514 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4515 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4516 4517 return ICS; 4518 } 4519 4520 // A temporary of function type cannot be created; don't even try. 4521 if (T1->isFunctionType()) 4522 return ICS; 4523 4524 // -- Otherwise, a temporary of type "cv1 T1" is created and 4525 // initialized from the initializer expression using the 4526 // rules for a non-reference copy initialization (8.5). The 4527 // reference is then bound to the temporary. If T1 is 4528 // reference-related to T2, cv1 must be the same 4529 // cv-qualification as, or greater cv-qualification than, 4530 // cv2; otherwise, the program is ill-formed. 4531 if (RefRelationship == Sema::Ref_Related) { 4532 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4533 // we would be reference-compatible or reference-compatible with 4534 // added qualification. But that wasn't the case, so the reference 4535 // initialization fails. 4536 // 4537 // Note that we only want to check address spaces and cvr-qualifiers here. 4538 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4539 Qualifiers T1Quals = T1.getQualifiers(); 4540 Qualifiers T2Quals = T2.getQualifiers(); 4541 T1Quals.removeObjCGCAttr(); 4542 T1Quals.removeObjCLifetime(); 4543 T2Quals.removeObjCGCAttr(); 4544 T2Quals.removeObjCLifetime(); 4545 // MS compiler ignores __unaligned qualifier for references; do the same. 4546 T1Quals.removeUnaligned(); 4547 T2Quals.removeUnaligned(); 4548 if (!T1Quals.compatiblyIncludes(T2Quals)) 4549 return ICS; 4550 } 4551 4552 // If at least one of the types is a class type, the types are not 4553 // related, and we aren't allowed any user conversions, the 4554 // reference binding fails. This case is important for breaking 4555 // recursion, since TryImplicitConversion below will attempt to 4556 // create a temporary through the use of a copy constructor. 4557 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4558 (T1->isRecordType() || T2->isRecordType())) 4559 return ICS; 4560 4561 // If T1 is reference-related to T2 and the reference is an rvalue 4562 // reference, the initializer expression shall not be an lvalue. 4563 if (RefRelationship >= Sema::Ref_Related && 4564 isRValRef && Init->Classify(S.Context).isLValue()) 4565 return ICS; 4566 4567 // C++ [over.ics.ref]p2: 4568 // When a parameter of reference type is not bound directly to 4569 // an argument expression, the conversion sequence is the one 4570 // required to convert the argument expression to the 4571 // underlying type of the reference according to 4572 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4573 // to copy-initializing a temporary of the underlying type with 4574 // the argument expression. Any difference in top-level 4575 // cv-qualification is subsumed by the initialization itself 4576 // and does not constitute a conversion. 4577 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4578 /*AllowExplicit=*/false, 4579 /*InOverloadResolution=*/false, 4580 /*CStyle=*/false, 4581 /*AllowObjCWritebackConversion=*/false, 4582 /*AllowObjCConversionOnExplicit=*/false); 4583 4584 // Of course, that's still a reference binding. 4585 if (ICS.isStandard()) { 4586 ICS.Standard.ReferenceBinding = true; 4587 ICS.Standard.IsLvalueReference = !isRValRef; 4588 ICS.Standard.BindsToFunctionLvalue = false; 4589 ICS.Standard.BindsToRvalue = true; 4590 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4591 ICS.Standard.ObjCLifetimeConversionBinding = false; 4592 } else if (ICS.isUserDefined()) { 4593 const ReferenceType *LValRefType = 4594 ICS.UserDefined.ConversionFunction->getReturnType() 4595 ->getAs<LValueReferenceType>(); 4596 4597 // C++ [over.ics.ref]p3: 4598 // Except for an implicit object parameter, for which see 13.3.1, a 4599 // standard conversion sequence cannot be formed if it requires [...] 4600 // binding an rvalue reference to an lvalue other than a function 4601 // lvalue. 4602 // Note that the function case is not possible here. 4603 if (DeclType->isRValueReferenceType() && LValRefType) { 4604 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4605 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4606 // reference to an rvalue! 4607 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4608 return ICS; 4609 } 4610 4611 ICS.UserDefined.After.ReferenceBinding = true; 4612 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4613 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4614 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4615 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4616 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4617 } 4618 4619 return ICS; 4620 } 4621 4622 static ImplicitConversionSequence 4623 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4624 bool SuppressUserConversions, 4625 bool InOverloadResolution, 4626 bool AllowObjCWritebackConversion, 4627 bool AllowExplicit = false); 4628 4629 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4630 /// initializer list From. 4631 static ImplicitConversionSequence 4632 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4633 bool SuppressUserConversions, 4634 bool InOverloadResolution, 4635 bool AllowObjCWritebackConversion) { 4636 // C++11 [over.ics.list]p1: 4637 // When an argument is an initializer list, it is not an expression and 4638 // special rules apply for converting it to a parameter type. 4639 4640 ImplicitConversionSequence Result; 4641 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4642 4643 // We need a complete type for what follows. Incomplete types can never be 4644 // initialized from init lists. 4645 if (!S.isCompleteType(From->getLocStart(), ToType)) 4646 return Result; 4647 4648 // Per DR1467: 4649 // If the parameter type is a class X and the initializer list has a single 4650 // element of type cv U, where U is X or a class derived from X, the 4651 // implicit conversion sequence is the one required to convert the element 4652 // to the parameter type. 4653 // 4654 // Otherwise, if the parameter type is a character array [... ] 4655 // and the initializer list has a single element that is an 4656 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4657 // implicit conversion sequence is the identity conversion. 4658 if (From->getNumInits() == 1) { 4659 if (ToType->isRecordType()) { 4660 QualType InitType = From->getInit(0)->getType(); 4661 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4662 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4663 return TryCopyInitialization(S, From->getInit(0), ToType, 4664 SuppressUserConversions, 4665 InOverloadResolution, 4666 AllowObjCWritebackConversion); 4667 } 4668 // FIXME: Check the other conditions here: array of character type, 4669 // initializer is a string literal. 4670 if (ToType->isArrayType()) { 4671 InitializedEntity Entity = 4672 InitializedEntity::InitializeParameter(S.Context, ToType, 4673 /*Consumed=*/false); 4674 if (S.CanPerformCopyInitialization(Entity, From)) { 4675 Result.setStandard(); 4676 Result.Standard.setAsIdentityConversion(); 4677 Result.Standard.setFromType(ToType); 4678 Result.Standard.setAllToTypes(ToType); 4679 return Result; 4680 } 4681 } 4682 } 4683 4684 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4685 // C++11 [over.ics.list]p2: 4686 // If the parameter type is std::initializer_list<X> or "array of X" and 4687 // all the elements can be implicitly converted to X, the implicit 4688 // conversion sequence is the worst conversion necessary to convert an 4689 // element of the list to X. 4690 // 4691 // C++14 [over.ics.list]p3: 4692 // Otherwise, if the parameter type is "array of N X", if the initializer 4693 // list has exactly N elements or if it has fewer than N elements and X is 4694 // default-constructible, and if all the elements of the initializer list 4695 // can be implicitly converted to X, the implicit conversion sequence is 4696 // the worst conversion necessary to convert an element of the list to X. 4697 // 4698 // FIXME: We're missing a lot of these checks. 4699 bool toStdInitializerList = false; 4700 QualType X; 4701 if (ToType->isArrayType()) 4702 X = S.Context.getAsArrayType(ToType)->getElementType(); 4703 else 4704 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4705 if (!X.isNull()) { 4706 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4707 Expr *Init = From->getInit(i); 4708 ImplicitConversionSequence ICS = 4709 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4710 InOverloadResolution, 4711 AllowObjCWritebackConversion); 4712 // If a single element isn't convertible, fail. 4713 if (ICS.isBad()) { 4714 Result = ICS; 4715 break; 4716 } 4717 // Otherwise, look for the worst conversion. 4718 if (Result.isBad() || 4719 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4720 Result) == 4721 ImplicitConversionSequence::Worse) 4722 Result = ICS; 4723 } 4724 4725 // For an empty list, we won't have computed any conversion sequence. 4726 // Introduce the identity conversion sequence. 4727 if (From->getNumInits() == 0) { 4728 Result.setStandard(); 4729 Result.Standard.setAsIdentityConversion(); 4730 Result.Standard.setFromType(ToType); 4731 Result.Standard.setAllToTypes(ToType); 4732 } 4733 4734 Result.setStdInitializerListElement(toStdInitializerList); 4735 return Result; 4736 } 4737 4738 // C++14 [over.ics.list]p4: 4739 // C++11 [over.ics.list]p3: 4740 // Otherwise, if the parameter is a non-aggregate class X and overload 4741 // resolution chooses a single best constructor [...] the implicit 4742 // conversion sequence is a user-defined conversion sequence. If multiple 4743 // constructors are viable but none is better than the others, the 4744 // implicit conversion sequence is a user-defined conversion sequence. 4745 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4746 // This function can deal with initializer lists. 4747 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4748 /*AllowExplicit=*/false, 4749 InOverloadResolution, /*CStyle=*/false, 4750 AllowObjCWritebackConversion, 4751 /*AllowObjCConversionOnExplicit=*/false); 4752 } 4753 4754 // C++14 [over.ics.list]p5: 4755 // C++11 [over.ics.list]p4: 4756 // Otherwise, if the parameter has an aggregate type which can be 4757 // initialized from the initializer list [...] the implicit conversion 4758 // sequence is a user-defined conversion sequence. 4759 if (ToType->isAggregateType()) { 4760 // Type is an aggregate, argument is an init list. At this point it comes 4761 // down to checking whether the initialization works. 4762 // FIXME: Find out whether this parameter is consumed or not. 4763 InitializedEntity Entity = 4764 InitializedEntity::InitializeParameter(S.Context, ToType, 4765 /*Consumed=*/false); 4766 if (S.CanPerformCopyInitialization(Entity, From)) { 4767 Result.setUserDefined(); 4768 Result.UserDefined.Before.setAsIdentityConversion(); 4769 // Initializer lists don't have a type. 4770 Result.UserDefined.Before.setFromType(QualType()); 4771 Result.UserDefined.Before.setAllToTypes(QualType()); 4772 4773 Result.UserDefined.After.setAsIdentityConversion(); 4774 Result.UserDefined.After.setFromType(ToType); 4775 Result.UserDefined.After.setAllToTypes(ToType); 4776 Result.UserDefined.ConversionFunction = nullptr; 4777 } 4778 return Result; 4779 } 4780 4781 // C++14 [over.ics.list]p6: 4782 // C++11 [over.ics.list]p5: 4783 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4784 if (ToType->isReferenceType()) { 4785 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4786 // mention initializer lists in any way. So we go by what list- 4787 // initialization would do and try to extrapolate from that. 4788 4789 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4790 4791 // If the initializer list has a single element that is reference-related 4792 // to the parameter type, we initialize the reference from that. 4793 if (From->getNumInits() == 1) { 4794 Expr *Init = From->getInit(0); 4795 4796 QualType T2 = Init->getType(); 4797 4798 // If the initializer is the address of an overloaded function, try 4799 // to resolve the overloaded function. If all goes well, T2 is the 4800 // type of the resulting function. 4801 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4802 DeclAccessPair Found; 4803 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4804 Init, ToType, false, Found)) 4805 T2 = Fn->getType(); 4806 } 4807 4808 // Compute some basic properties of the types and the initializer. 4809 bool dummy1 = false; 4810 bool dummy2 = false; 4811 bool dummy3 = false; 4812 Sema::ReferenceCompareResult RefRelationship 4813 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4814 dummy2, dummy3); 4815 4816 if (RefRelationship >= Sema::Ref_Related) { 4817 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4818 SuppressUserConversions, 4819 /*AllowExplicit=*/false); 4820 } 4821 } 4822 4823 // Otherwise, we bind the reference to a temporary created from the 4824 // initializer list. 4825 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4826 InOverloadResolution, 4827 AllowObjCWritebackConversion); 4828 if (Result.isFailure()) 4829 return Result; 4830 assert(!Result.isEllipsis() && 4831 "Sub-initialization cannot result in ellipsis conversion."); 4832 4833 // Can we even bind to a temporary? 4834 if (ToType->isRValueReferenceType() || 4835 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4836 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4837 Result.UserDefined.After; 4838 SCS.ReferenceBinding = true; 4839 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4840 SCS.BindsToRvalue = true; 4841 SCS.BindsToFunctionLvalue = false; 4842 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4843 SCS.ObjCLifetimeConversionBinding = false; 4844 } else 4845 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4846 From, ToType); 4847 return Result; 4848 } 4849 4850 // C++14 [over.ics.list]p7: 4851 // C++11 [over.ics.list]p6: 4852 // Otherwise, if the parameter type is not a class: 4853 if (!ToType->isRecordType()) { 4854 // - if the initializer list has one element that is not itself an 4855 // initializer list, the implicit conversion sequence is the one 4856 // required to convert the element to the parameter type. 4857 unsigned NumInits = From->getNumInits(); 4858 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4859 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4860 SuppressUserConversions, 4861 InOverloadResolution, 4862 AllowObjCWritebackConversion); 4863 // - if the initializer list has no elements, the implicit conversion 4864 // sequence is the identity conversion. 4865 else if (NumInits == 0) { 4866 Result.setStandard(); 4867 Result.Standard.setAsIdentityConversion(); 4868 Result.Standard.setFromType(ToType); 4869 Result.Standard.setAllToTypes(ToType); 4870 } 4871 return Result; 4872 } 4873 4874 // C++14 [over.ics.list]p8: 4875 // C++11 [over.ics.list]p7: 4876 // In all cases other than those enumerated above, no conversion is possible 4877 return Result; 4878 } 4879 4880 /// TryCopyInitialization - Try to copy-initialize a value of type 4881 /// ToType from the expression From. Return the implicit conversion 4882 /// sequence required to pass this argument, which may be a bad 4883 /// conversion sequence (meaning that the argument cannot be passed to 4884 /// a parameter of this type). If @p SuppressUserConversions, then we 4885 /// do not permit any user-defined conversion sequences. 4886 static ImplicitConversionSequence 4887 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4888 bool SuppressUserConversions, 4889 bool InOverloadResolution, 4890 bool AllowObjCWritebackConversion, 4891 bool AllowExplicit) { 4892 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4893 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4894 InOverloadResolution,AllowObjCWritebackConversion); 4895 4896 if (ToType->isReferenceType()) 4897 return TryReferenceInit(S, From, ToType, 4898 /*FIXME:*/From->getLocStart(), 4899 SuppressUserConversions, 4900 AllowExplicit); 4901 4902 return TryImplicitConversion(S, From, ToType, 4903 SuppressUserConversions, 4904 /*AllowExplicit=*/false, 4905 InOverloadResolution, 4906 /*CStyle=*/false, 4907 AllowObjCWritebackConversion, 4908 /*AllowObjCConversionOnExplicit=*/false); 4909 } 4910 4911 static bool TryCopyInitialization(const CanQualType FromQTy, 4912 const CanQualType ToQTy, 4913 Sema &S, 4914 SourceLocation Loc, 4915 ExprValueKind FromVK) { 4916 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4917 ImplicitConversionSequence ICS = 4918 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4919 4920 return !ICS.isBad(); 4921 } 4922 4923 /// TryObjectArgumentInitialization - Try to initialize the object 4924 /// parameter of the given member function (@c Method) from the 4925 /// expression @p From. 4926 static ImplicitConversionSequence 4927 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4928 Expr::Classification FromClassification, 4929 CXXMethodDecl *Method, 4930 CXXRecordDecl *ActingContext) { 4931 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4932 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4933 // const volatile object. 4934 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4935 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4936 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4937 4938 // Set up the conversion sequence as a "bad" conversion, to allow us 4939 // to exit early. 4940 ImplicitConversionSequence ICS; 4941 4942 // We need to have an object of class type. 4943 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4944 FromType = PT->getPointeeType(); 4945 4946 // When we had a pointer, it's implicitly dereferenced, so we 4947 // better have an lvalue. 4948 assert(FromClassification.isLValue()); 4949 } 4950 4951 assert(FromType->isRecordType()); 4952 4953 // C++0x [over.match.funcs]p4: 4954 // For non-static member functions, the type of the implicit object 4955 // parameter is 4956 // 4957 // - "lvalue reference to cv X" for functions declared without a 4958 // ref-qualifier or with the & ref-qualifier 4959 // - "rvalue reference to cv X" for functions declared with the && 4960 // ref-qualifier 4961 // 4962 // where X is the class of which the function is a member and cv is the 4963 // cv-qualification on the member function declaration. 4964 // 4965 // However, when finding an implicit conversion sequence for the argument, we 4966 // are not allowed to create temporaries or perform user-defined conversions 4967 // (C++ [over.match.funcs]p5). We perform a simplified version of 4968 // reference binding here, that allows class rvalues to bind to 4969 // non-constant references. 4970 4971 // First check the qualifiers. 4972 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4973 if (ImplicitParamType.getCVRQualifiers() 4974 != FromTypeCanon.getLocalCVRQualifiers() && 4975 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4976 ICS.setBad(BadConversionSequence::bad_qualifiers, 4977 FromType, ImplicitParamType); 4978 return ICS; 4979 } 4980 4981 // Check that we have either the same type or a derived type. It 4982 // affects the conversion rank. 4983 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4984 ImplicitConversionKind SecondKind; 4985 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4986 SecondKind = ICK_Identity; 4987 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4988 SecondKind = ICK_Derived_To_Base; 4989 else { 4990 ICS.setBad(BadConversionSequence::unrelated_class, 4991 FromType, ImplicitParamType); 4992 return ICS; 4993 } 4994 4995 // Check the ref-qualifier. 4996 switch (Method->getRefQualifier()) { 4997 case RQ_None: 4998 // Do nothing; we don't care about lvalueness or rvalueness. 4999 break; 5000 5001 case RQ_LValue: 5002 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5003 // non-const lvalue reference cannot bind to an rvalue 5004 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5005 ImplicitParamType); 5006 return ICS; 5007 } 5008 break; 5009 5010 case RQ_RValue: 5011 if (!FromClassification.isRValue()) { 5012 // rvalue reference cannot bind to an lvalue 5013 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5014 ImplicitParamType); 5015 return ICS; 5016 } 5017 break; 5018 } 5019 5020 // Success. Mark this as a reference binding. 5021 ICS.setStandard(); 5022 ICS.Standard.setAsIdentityConversion(); 5023 ICS.Standard.Second = SecondKind; 5024 ICS.Standard.setFromType(FromType); 5025 ICS.Standard.setAllToTypes(ImplicitParamType); 5026 ICS.Standard.ReferenceBinding = true; 5027 ICS.Standard.DirectBinding = true; 5028 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5029 ICS.Standard.BindsToFunctionLvalue = false; 5030 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5031 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5032 = (Method->getRefQualifier() == RQ_None); 5033 return ICS; 5034 } 5035 5036 /// PerformObjectArgumentInitialization - Perform initialization of 5037 /// the implicit object parameter for the given Method with the given 5038 /// expression. 5039 ExprResult 5040 Sema::PerformObjectArgumentInitialization(Expr *From, 5041 NestedNameSpecifier *Qualifier, 5042 NamedDecl *FoundDecl, 5043 CXXMethodDecl *Method) { 5044 QualType FromRecordType, DestType; 5045 QualType ImplicitParamRecordType = 5046 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5047 5048 Expr::Classification FromClassification; 5049 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5050 FromRecordType = PT->getPointeeType(); 5051 DestType = Method->getThisType(Context); 5052 FromClassification = Expr::Classification::makeSimpleLValue(); 5053 } else { 5054 FromRecordType = From->getType(); 5055 DestType = ImplicitParamRecordType; 5056 FromClassification = From->Classify(Context); 5057 } 5058 5059 // Note that we always use the true parent context when performing 5060 // the actual argument initialization. 5061 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5062 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5063 Method->getParent()); 5064 if (ICS.isBad()) { 5065 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5066 Qualifiers FromQs = FromRecordType.getQualifiers(); 5067 Qualifiers ToQs = DestType.getQualifiers(); 5068 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5069 if (CVR) { 5070 Diag(From->getLocStart(), 5071 diag::err_member_function_call_bad_cvr) 5072 << Method->getDeclName() << FromRecordType << (CVR - 1) 5073 << From->getSourceRange(); 5074 Diag(Method->getLocation(), diag::note_previous_decl) 5075 << Method->getDeclName(); 5076 return ExprError(); 5077 } 5078 } 5079 5080 return Diag(From->getLocStart(), 5081 diag::err_implicit_object_parameter_init) 5082 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5083 } 5084 5085 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5086 ExprResult FromRes = 5087 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5088 if (FromRes.isInvalid()) 5089 return ExprError(); 5090 From = FromRes.get(); 5091 } 5092 5093 if (!Context.hasSameType(From->getType(), DestType)) 5094 From = ImpCastExprToType(From, DestType, CK_NoOp, 5095 From->getValueKind()).get(); 5096 return From; 5097 } 5098 5099 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5100 /// expression From to bool (C++0x [conv]p3). 5101 static ImplicitConversionSequence 5102 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5103 return TryImplicitConversion(S, From, S.Context.BoolTy, 5104 /*SuppressUserConversions=*/false, 5105 /*AllowExplicit=*/true, 5106 /*InOverloadResolution=*/false, 5107 /*CStyle=*/false, 5108 /*AllowObjCWritebackConversion=*/false, 5109 /*AllowObjCConversionOnExplicit=*/false); 5110 } 5111 5112 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5113 /// of the expression From to bool (C++0x [conv]p3). 5114 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5115 if (checkPlaceholderForOverload(*this, From)) 5116 return ExprError(); 5117 5118 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5119 if (!ICS.isBad()) 5120 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5121 5122 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5123 return Diag(From->getLocStart(), 5124 diag::err_typecheck_bool_condition) 5125 << From->getType() << From->getSourceRange(); 5126 return ExprError(); 5127 } 5128 5129 /// Check that the specified conversion is permitted in a converted constant 5130 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5131 /// is acceptable. 5132 static bool CheckConvertedConstantConversions(Sema &S, 5133 StandardConversionSequence &SCS) { 5134 // Since we know that the target type is an integral or unscoped enumeration 5135 // type, most conversion kinds are impossible. All possible First and Third 5136 // conversions are fine. 5137 switch (SCS.Second) { 5138 case ICK_Identity: 5139 case ICK_Function_Conversion: 5140 case ICK_Integral_Promotion: 5141 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5142 return true; 5143 5144 case ICK_Boolean_Conversion: 5145 // Conversion from an integral or unscoped enumeration type to bool is 5146 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5147 // conversion, so we allow it in a converted constant expression. 5148 // 5149 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5150 // a lot of popular code. We should at least add a warning for this 5151 // (non-conforming) extension. 5152 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5153 SCS.getToType(2)->isBooleanType(); 5154 5155 case ICK_Pointer_Conversion: 5156 case ICK_Pointer_Member: 5157 // C++1z: null pointer conversions and null member pointer conversions are 5158 // only permitted if the source type is std::nullptr_t. 5159 return SCS.getFromType()->isNullPtrType(); 5160 5161 case ICK_Floating_Promotion: 5162 case ICK_Complex_Promotion: 5163 case ICK_Floating_Conversion: 5164 case ICK_Complex_Conversion: 5165 case ICK_Floating_Integral: 5166 case ICK_Compatible_Conversion: 5167 case ICK_Derived_To_Base: 5168 case ICK_Vector_Conversion: 5169 case ICK_Vector_Splat: 5170 case ICK_Complex_Real: 5171 case ICK_Block_Pointer_Conversion: 5172 case ICK_TransparentUnionConversion: 5173 case ICK_Writeback_Conversion: 5174 case ICK_Zero_Event_Conversion: 5175 case ICK_C_Only_Conversion: 5176 case ICK_Incompatible_Pointer_Conversion: 5177 return false; 5178 5179 case ICK_Lvalue_To_Rvalue: 5180 case ICK_Array_To_Pointer: 5181 case ICK_Function_To_Pointer: 5182 llvm_unreachable("found a first conversion kind in Second"); 5183 5184 case ICK_Qualification: 5185 llvm_unreachable("found a third conversion kind in Second"); 5186 5187 case ICK_Num_Conversion_Kinds: 5188 break; 5189 } 5190 5191 llvm_unreachable("unknown conversion kind"); 5192 } 5193 5194 /// CheckConvertedConstantExpression - Check that the expression From is a 5195 /// converted constant expression of type T, perform the conversion and produce 5196 /// the converted expression, per C++11 [expr.const]p3. 5197 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5198 QualType T, APValue &Value, 5199 Sema::CCEKind CCE, 5200 bool RequireInt) { 5201 assert(S.getLangOpts().CPlusPlus11 && 5202 "converted constant expression outside C++11"); 5203 5204 if (checkPlaceholderForOverload(S, From)) 5205 return ExprError(); 5206 5207 // C++1z [expr.const]p3: 5208 // A converted constant expression of type T is an expression, 5209 // implicitly converted to type T, where the converted 5210 // expression is a constant expression and the implicit conversion 5211 // sequence contains only [... list of conversions ...]. 5212 // C++1z [stmt.if]p2: 5213 // If the if statement is of the form if constexpr, the value of the 5214 // condition shall be a contextually converted constant expression of type 5215 // bool. 5216 ImplicitConversionSequence ICS = 5217 CCE == Sema::CCEK_ConstexprIf 5218 ? TryContextuallyConvertToBool(S, From) 5219 : TryCopyInitialization(S, From, T, 5220 /*SuppressUserConversions=*/false, 5221 /*InOverloadResolution=*/false, 5222 /*AllowObjcWritebackConversion=*/false, 5223 /*AllowExplicit=*/false); 5224 StandardConversionSequence *SCS = nullptr; 5225 switch (ICS.getKind()) { 5226 case ImplicitConversionSequence::StandardConversion: 5227 SCS = &ICS.Standard; 5228 break; 5229 case ImplicitConversionSequence::UserDefinedConversion: 5230 // We are converting to a non-class type, so the Before sequence 5231 // must be trivial. 5232 SCS = &ICS.UserDefined.After; 5233 break; 5234 case ImplicitConversionSequence::AmbiguousConversion: 5235 case ImplicitConversionSequence::BadConversion: 5236 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5237 return S.Diag(From->getLocStart(), 5238 diag::err_typecheck_converted_constant_expression) 5239 << From->getType() << From->getSourceRange() << T; 5240 return ExprError(); 5241 5242 case ImplicitConversionSequence::EllipsisConversion: 5243 llvm_unreachable("ellipsis conversion in converted constant expression"); 5244 } 5245 5246 // Check that we would only use permitted conversions. 5247 if (!CheckConvertedConstantConversions(S, *SCS)) { 5248 return S.Diag(From->getLocStart(), 5249 diag::err_typecheck_converted_constant_expression_disallowed) 5250 << From->getType() << From->getSourceRange() << T; 5251 } 5252 // [...] and where the reference binding (if any) binds directly. 5253 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5254 return S.Diag(From->getLocStart(), 5255 diag::err_typecheck_converted_constant_expression_indirect) 5256 << From->getType() << From->getSourceRange() << T; 5257 } 5258 5259 ExprResult Result = 5260 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5261 if (Result.isInvalid()) 5262 return Result; 5263 5264 // Check for a narrowing implicit conversion. 5265 APValue PreNarrowingValue; 5266 QualType PreNarrowingType; 5267 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5268 PreNarrowingType)) { 5269 case NK_Variable_Narrowing: 5270 // Implicit conversion to a narrower type, and the value is not a constant 5271 // expression. We'll diagnose this in a moment. 5272 case NK_Not_Narrowing: 5273 break; 5274 5275 case NK_Constant_Narrowing: 5276 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5277 << CCE << /*Constant*/1 5278 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5279 break; 5280 5281 case NK_Type_Narrowing: 5282 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5283 << CCE << /*Constant*/0 << From->getType() << T; 5284 break; 5285 } 5286 5287 // Check the expression is a constant expression. 5288 SmallVector<PartialDiagnosticAt, 8> Notes; 5289 Expr::EvalResult Eval; 5290 Eval.Diag = &Notes; 5291 5292 if ((T->isReferenceType() 5293 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5294 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5295 (RequireInt && !Eval.Val.isInt())) { 5296 // The expression can't be folded, so we can't keep it at this position in 5297 // the AST. 5298 Result = ExprError(); 5299 } else { 5300 Value = Eval.Val; 5301 5302 if (Notes.empty()) { 5303 // It's a constant expression. 5304 return Result; 5305 } 5306 } 5307 5308 // It's not a constant expression. Produce an appropriate diagnostic. 5309 if (Notes.size() == 1 && 5310 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5311 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5312 else { 5313 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5314 << CCE << From->getSourceRange(); 5315 for (unsigned I = 0; I < Notes.size(); ++I) 5316 S.Diag(Notes[I].first, Notes[I].second); 5317 } 5318 return ExprError(); 5319 } 5320 5321 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5322 APValue &Value, CCEKind CCE) { 5323 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5324 } 5325 5326 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5327 llvm::APSInt &Value, 5328 CCEKind CCE) { 5329 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5330 5331 APValue V; 5332 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5333 if (!R.isInvalid()) 5334 Value = V.getInt(); 5335 return R; 5336 } 5337 5338 5339 /// dropPointerConversions - If the given standard conversion sequence 5340 /// involves any pointer conversions, remove them. This may change 5341 /// the result type of the conversion sequence. 5342 static void dropPointerConversion(StandardConversionSequence &SCS) { 5343 if (SCS.Second == ICK_Pointer_Conversion) { 5344 SCS.Second = ICK_Identity; 5345 SCS.Third = ICK_Identity; 5346 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5347 } 5348 } 5349 5350 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5351 /// convert the expression From to an Objective-C pointer type. 5352 static ImplicitConversionSequence 5353 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5354 // Do an implicit conversion to 'id'. 5355 QualType Ty = S.Context.getObjCIdType(); 5356 ImplicitConversionSequence ICS 5357 = TryImplicitConversion(S, From, Ty, 5358 // FIXME: Are these flags correct? 5359 /*SuppressUserConversions=*/false, 5360 /*AllowExplicit=*/true, 5361 /*InOverloadResolution=*/false, 5362 /*CStyle=*/false, 5363 /*AllowObjCWritebackConversion=*/false, 5364 /*AllowObjCConversionOnExplicit=*/true); 5365 5366 // Strip off any final conversions to 'id'. 5367 switch (ICS.getKind()) { 5368 case ImplicitConversionSequence::BadConversion: 5369 case ImplicitConversionSequence::AmbiguousConversion: 5370 case ImplicitConversionSequence::EllipsisConversion: 5371 break; 5372 5373 case ImplicitConversionSequence::UserDefinedConversion: 5374 dropPointerConversion(ICS.UserDefined.After); 5375 break; 5376 5377 case ImplicitConversionSequence::StandardConversion: 5378 dropPointerConversion(ICS.Standard); 5379 break; 5380 } 5381 5382 return ICS; 5383 } 5384 5385 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5386 /// conversion of the expression From to an Objective-C pointer type. 5387 /// Returns a valid but null ExprResult if no conversion sequence exists. 5388 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5389 if (checkPlaceholderForOverload(*this, From)) 5390 return ExprError(); 5391 5392 QualType Ty = Context.getObjCIdType(); 5393 ImplicitConversionSequence ICS = 5394 TryContextuallyConvertToObjCPointer(*this, From); 5395 if (!ICS.isBad()) 5396 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5397 return ExprResult(); 5398 } 5399 5400 /// Determine whether the provided type is an integral type, or an enumeration 5401 /// type of a permitted flavor. 5402 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5403 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5404 : T->isIntegralOrUnscopedEnumerationType(); 5405 } 5406 5407 static ExprResult 5408 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5409 Sema::ContextualImplicitConverter &Converter, 5410 QualType T, UnresolvedSetImpl &ViableConversions) { 5411 5412 if (Converter.Suppress) 5413 return ExprError(); 5414 5415 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5416 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5417 CXXConversionDecl *Conv = 5418 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5419 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5420 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5421 } 5422 return From; 5423 } 5424 5425 static bool 5426 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5427 Sema::ContextualImplicitConverter &Converter, 5428 QualType T, bool HadMultipleCandidates, 5429 UnresolvedSetImpl &ExplicitConversions) { 5430 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5431 DeclAccessPair Found = ExplicitConversions[0]; 5432 CXXConversionDecl *Conversion = 5433 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5434 5435 // The user probably meant to invoke the given explicit 5436 // conversion; use it. 5437 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5438 std::string TypeStr; 5439 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5440 5441 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5442 << FixItHint::CreateInsertion(From->getLocStart(), 5443 "static_cast<" + TypeStr + ">(") 5444 << FixItHint::CreateInsertion( 5445 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5446 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5447 5448 // If we aren't in a SFINAE context, build a call to the 5449 // explicit conversion function. 5450 if (SemaRef.isSFINAEContext()) 5451 return true; 5452 5453 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5454 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5455 HadMultipleCandidates); 5456 if (Result.isInvalid()) 5457 return true; 5458 // Record usage of conversion in an implicit cast. 5459 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5460 CK_UserDefinedConversion, Result.get(), 5461 nullptr, Result.get()->getValueKind()); 5462 } 5463 return false; 5464 } 5465 5466 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5467 Sema::ContextualImplicitConverter &Converter, 5468 QualType T, bool HadMultipleCandidates, 5469 DeclAccessPair &Found) { 5470 CXXConversionDecl *Conversion = 5471 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5472 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5473 5474 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5475 if (!Converter.SuppressConversion) { 5476 if (SemaRef.isSFINAEContext()) 5477 return true; 5478 5479 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5480 << From->getSourceRange(); 5481 } 5482 5483 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5484 HadMultipleCandidates); 5485 if (Result.isInvalid()) 5486 return true; 5487 // Record usage of conversion in an implicit cast. 5488 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5489 CK_UserDefinedConversion, Result.get(), 5490 nullptr, Result.get()->getValueKind()); 5491 return false; 5492 } 5493 5494 static ExprResult finishContextualImplicitConversion( 5495 Sema &SemaRef, SourceLocation Loc, Expr *From, 5496 Sema::ContextualImplicitConverter &Converter) { 5497 if (!Converter.match(From->getType()) && !Converter.Suppress) 5498 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5499 << From->getSourceRange(); 5500 5501 return SemaRef.DefaultLvalueConversion(From); 5502 } 5503 5504 static void 5505 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5506 UnresolvedSetImpl &ViableConversions, 5507 OverloadCandidateSet &CandidateSet) { 5508 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5509 DeclAccessPair FoundDecl = ViableConversions[I]; 5510 NamedDecl *D = FoundDecl.getDecl(); 5511 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5512 if (isa<UsingShadowDecl>(D)) 5513 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5514 5515 CXXConversionDecl *Conv; 5516 FunctionTemplateDecl *ConvTemplate; 5517 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5518 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5519 else 5520 Conv = cast<CXXConversionDecl>(D); 5521 5522 if (ConvTemplate) 5523 SemaRef.AddTemplateConversionCandidate( 5524 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5525 /*AllowObjCConversionOnExplicit=*/false); 5526 else 5527 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5528 ToType, CandidateSet, 5529 /*AllowObjCConversionOnExplicit=*/false); 5530 } 5531 } 5532 5533 /// \brief Attempt to convert the given expression to a type which is accepted 5534 /// by the given converter. 5535 /// 5536 /// This routine will attempt to convert an expression of class type to a 5537 /// type accepted by the specified converter. In C++11 and before, the class 5538 /// must have a single non-explicit conversion function converting to a matching 5539 /// type. In C++1y, there can be multiple such conversion functions, but only 5540 /// one target type. 5541 /// 5542 /// \param Loc The source location of the construct that requires the 5543 /// conversion. 5544 /// 5545 /// \param From The expression we're converting from. 5546 /// 5547 /// \param Converter Used to control and diagnose the conversion process. 5548 /// 5549 /// \returns The expression, converted to an integral or enumeration type if 5550 /// successful. 5551 ExprResult Sema::PerformContextualImplicitConversion( 5552 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5553 // We can't perform any more checking for type-dependent expressions. 5554 if (From->isTypeDependent()) 5555 return From; 5556 5557 // Process placeholders immediately. 5558 if (From->hasPlaceholderType()) { 5559 ExprResult result = CheckPlaceholderExpr(From); 5560 if (result.isInvalid()) 5561 return result; 5562 From = result.get(); 5563 } 5564 5565 // If the expression already has a matching type, we're golden. 5566 QualType T = From->getType(); 5567 if (Converter.match(T)) 5568 return DefaultLvalueConversion(From); 5569 5570 // FIXME: Check for missing '()' if T is a function type? 5571 5572 // We can only perform contextual implicit conversions on objects of class 5573 // type. 5574 const RecordType *RecordTy = T->getAs<RecordType>(); 5575 if (!RecordTy || !getLangOpts().CPlusPlus) { 5576 if (!Converter.Suppress) 5577 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5578 return From; 5579 } 5580 5581 // We must have a complete class type. 5582 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5583 ContextualImplicitConverter &Converter; 5584 Expr *From; 5585 5586 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5587 : Converter(Converter), From(From) {} 5588 5589 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5590 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5591 } 5592 } IncompleteDiagnoser(Converter, From); 5593 5594 if (Converter.Suppress ? !isCompleteType(Loc, T) 5595 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5596 return From; 5597 5598 // Look for a conversion to an integral or enumeration type. 5599 UnresolvedSet<4> 5600 ViableConversions; // These are *potentially* viable in C++1y. 5601 UnresolvedSet<4> ExplicitConversions; 5602 const auto &Conversions = 5603 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5604 5605 bool HadMultipleCandidates = 5606 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5607 5608 // To check that there is only one target type, in C++1y: 5609 QualType ToType; 5610 bool HasUniqueTargetType = true; 5611 5612 // Collect explicit or viable (potentially in C++1y) conversions. 5613 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5614 NamedDecl *D = (*I)->getUnderlyingDecl(); 5615 CXXConversionDecl *Conversion; 5616 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5617 if (ConvTemplate) { 5618 if (getLangOpts().CPlusPlus14) 5619 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5620 else 5621 continue; // C++11 does not consider conversion operator templates(?). 5622 } else 5623 Conversion = cast<CXXConversionDecl>(D); 5624 5625 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5626 "Conversion operator templates are considered potentially " 5627 "viable in C++1y"); 5628 5629 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5630 if (Converter.match(CurToType) || ConvTemplate) { 5631 5632 if (Conversion->isExplicit()) { 5633 // FIXME: For C++1y, do we need this restriction? 5634 // cf. diagnoseNoViableConversion() 5635 if (!ConvTemplate) 5636 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5637 } else { 5638 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5639 if (ToType.isNull()) 5640 ToType = CurToType.getUnqualifiedType(); 5641 else if (HasUniqueTargetType && 5642 (CurToType.getUnqualifiedType() != ToType)) 5643 HasUniqueTargetType = false; 5644 } 5645 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5646 } 5647 } 5648 } 5649 5650 if (getLangOpts().CPlusPlus14) { 5651 // C++1y [conv]p6: 5652 // ... An expression e of class type E appearing in such a context 5653 // is said to be contextually implicitly converted to a specified 5654 // type T and is well-formed if and only if e can be implicitly 5655 // converted to a type T that is determined as follows: E is searched 5656 // for conversion functions whose return type is cv T or reference to 5657 // cv T such that T is allowed by the context. There shall be 5658 // exactly one such T. 5659 5660 // If no unique T is found: 5661 if (ToType.isNull()) { 5662 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5663 HadMultipleCandidates, 5664 ExplicitConversions)) 5665 return ExprError(); 5666 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5667 } 5668 5669 // If more than one unique Ts are found: 5670 if (!HasUniqueTargetType) 5671 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5672 ViableConversions); 5673 5674 // If one unique T is found: 5675 // First, build a candidate set from the previously recorded 5676 // potentially viable conversions. 5677 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5678 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5679 CandidateSet); 5680 5681 // Then, perform overload resolution over the candidate set. 5682 OverloadCandidateSet::iterator Best; 5683 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5684 case OR_Success: { 5685 // Apply this conversion. 5686 DeclAccessPair Found = 5687 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5688 if (recordConversion(*this, Loc, From, Converter, T, 5689 HadMultipleCandidates, Found)) 5690 return ExprError(); 5691 break; 5692 } 5693 case OR_Ambiguous: 5694 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5695 ViableConversions); 5696 case OR_No_Viable_Function: 5697 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5698 HadMultipleCandidates, 5699 ExplicitConversions)) 5700 return ExprError(); 5701 // fall through 'OR_Deleted' case. 5702 case OR_Deleted: 5703 // We'll complain below about a non-integral condition type. 5704 break; 5705 } 5706 } else { 5707 switch (ViableConversions.size()) { 5708 case 0: { 5709 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5710 HadMultipleCandidates, 5711 ExplicitConversions)) 5712 return ExprError(); 5713 5714 // We'll complain below about a non-integral condition type. 5715 break; 5716 } 5717 case 1: { 5718 // Apply this conversion. 5719 DeclAccessPair Found = ViableConversions[0]; 5720 if (recordConversion(*this, Loc, From, Converter, T, 5721 HadMultipleCandidates, Found)) 5722 return ExprError(); 5723 break; 5724 } 5725 default: 5726 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5727 ViableConversions); 5728 } 5729 } 5730 5731 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5732 } 5733 5734 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5735 /// an acceptable non-member overloaded operator for a call whose 5736 /// arguments have types T1 (and, if non-empty, T2). This routine 5737 /// implements the check in C++ [over.match.oper]p3b2 concerning 5738 /// enumeration types. 5739 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5740 FunctionDecl *Fn, 5741 ArrayRef<Expr *> Args) { 5742 QualType T1 = Args[0]->getType(); 5743 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5744 5745 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5746 return true; 5747 5748 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5749 return true; 5750 5751 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5752 if (Proto->getNumParams() < 1) 5753 return false; 5754 5755 if (T1->isEnumeralType()) { 5756 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5757 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5758 return true; 5759 } 5760 5761 if (Proto->getNumParams() < 2) 5762 return false; 5763 5764 if (!T2.isNull() && T2->isEnumeralType()) { 5765 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5766 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5767 return true; 5768 } 5769 5770 return false; 5771 } 5772 5773 /// AddOverloadCandidate - Adds the given function to the set of 5774 /// candidate functions, using the given function call arguments. If 5775 /// @p SuppressUserConversions, then don't allow user-defined 5776 /// conversions via constructors or conversion operators. 5777 /// 5778 /// \param PartialOverloading true if we are performing "partial" overloading 5779 /// based on an incomplete set of function arguments. This feature is used by 5780 /// code completion. 5781 void 5782 Sema::AddOverloadCandidate(FunctionDecl *Function, 5783 DeclAccessPair FoundDecl, 5784 ArrayRef<Expr *> Args, 5785 OverloadCandidateSet &CandidateSet, 5786 bool SuppressUserConversions, 5787 bool PartialOverloading, 5788 bool AllowExplicit) { 5789 const FunctionProtoType *Proto 5790 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5791 assert(Proto && "Functions without a prototype cannot be overloaded"); 5792 assert(!Function->getDescribedFunctionTemplate() && 5793 "Use AddTemplateOverloadCandidate for function templates"); 5794 5795 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5796 if (!isa<CXXConstructorDecl>(Method)) { 5797 // If we get here, it's because we're calling a member function 5798 // that is named without a member access expression (e.g., 5799 // "this->f") that was either written explicitly or created 5800 // implicitly. This can happen with a qualified call to a member 5801 // function, e.g., X::f(). We use an empty type for the implied 5802 // object argument (C++ [over.call.func]p3), and the acting context 5803 // is irrelevant. 5804 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5805 QualType(), Expr::Classification::makeSimpleLValue(), 5806 Args, CandidateSet, SuppressUserConversions, 5807 PartialOverloading); 5808 return; 5809 } 5810 // We treat a constructor like a non-member function, since its object 5811 // argument doesn't participate in overload resolution. 5812 } 5813 5814 if (!CandidateSet.isNewCandidate(Function)) 5815 return; 5816 5817 // C++ [over.match.oper]p3: 5818 // if no operand has a class type, only those non-member functions in the 5819 // lookup set that have a first parameter of type T1 or "reference to 5820 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5821 // is a right operand) a second parameter of type T2 or "reference to 5822 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5823 // candidate functions. 5824 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5825 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5826 return; 5827 5828 // C++11 [class.copy]p11: [DR1402] 5829 // A defaulted move constructor that is defined as deleted is ignored by 5830 // overload resolution. 5831 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5832 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5833 Constructor->isMoveConstructor()) 5834 return; 5835 5836 // Overload resolution is always an unevaluated context. 5837 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5838 5839 // Add this candidate 5840 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5841 Candidate.FoundDecl = FoundDecl; 5842 Candidate.Function = Function; 5843 Candidate.Viable = true; 5844 Candidate.IsSurrogate = false; 5845 Candidate.IgnoreObjectArgument = false; 5846 Candidate.ExplicitCallArguments = Args.size(); 5847 5848 if (Constructor) { 5849 // C++ [class.copy]p3: 5850 // A member function template is never instantiated to perform the copy 5851 // of a class object to an object of its class type. 5852 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5853 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5854 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5855 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5856 ClassType))) { 5857 Candidate.Viable = false; 5858 Candidate.FailureKind = ovl_fail_illegal_constructor; 5859 return; 5860 } 5861 } 5862 5863 unsigned NumParams = Proto->getNumParams(); 5864 5865 // (C++ 13.3.2p2): A candidate function having fewer than m 5866 // parameters is viable only if it has an ellipsis in its parameter 5867 // list (8.3.5). 5868 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5869 !Proto->isVariadic()) { 5870 Candidate.Viable = false; 5871 Candidate.FailureKind = ovl_fail_too_many_arguments; 5872 return; 5873 } 5874 5875 // (C++ 13.3.2p2): A candidate function having more than m parameters 5876 // is viable only if the (m+1)st parameter has a default argument 5877 // (8.3.6). For the purposes of overload resolution, the 5878 // parameter list is truncated on the right, so that there are 5879 // exactly m parameters. 5880 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5881 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5882 // Not enough arguments. 5883 Candidate.Viable = false; 5884 Candidate.FailureKind = ovl_fail_too_few_arguments; 5885 return; 5886 } 5887 5888 // (CUDA B.1): Check for invalid calls between targets. 5889 if (getLangOpts().CUDA) 5890 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5891 // Skip the check for callers that are implicit members, because in this 5892 // case we may not yet know what the member's target is; the target is 5893 // inferred for the member automatically, based on the bases and fields of 5894 // the class. 5895 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5896 Candidate.Viable = false; 5897 Candidate.FailureKind = ovl_fail_bad_target; 5898 return; 5899 } 5900 5901 // Determine the implicit conversion sequences for each of the 5902 // arguments. 5903 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5904 if (ArgIdx < NumParams) { 5905 // (C++ 13.3.2p3): for F to be a viable function, there shall 5906 // exist for each argument an implicit conversion sequence 5907 // (13.3.3.1) that converts that argument to the corresponding 5908 // parameter of F. 5909 QualType ParamType = Proto->getParamType(ArgIdx); 5910 Candidate.Conversions[ArgIdx] 5911 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5912 SuppressUserConversions, 5913 /*InOverloadResolution=*/true, 5914 /*AllowObjCWritebackConversion=*/ 5915 getLangOpts().ObjCAutoRefCount, 5916 AllowExplicit); 5917 if (Candidate.Conversions[ArgIdx].isBad()) { 5918 Candidate.Viable = false; 5919 Candidate.FailureKind = ovl_fail_bad_conversion; 5920 return; 5921 } 5922 } else { 5923 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5924 // argument for which there is no corresponding parameter is 5925 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5926 Candidate.Conversions[ArgIdx].setEllipsis(); 5927 } 5928 } 5929 5930 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5931 Candidate.Viable = false; 5932 Candidate.FailureKind = ovl_fail_enable_if; 5933 Candidate.DeductionFailure.Data = FailedAttr; 5934 return; 5935 } 5936 } 5937 5938 ObjCMethodDecl * 5939 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5940 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5941 if (Methods.size() <= 1) 5942 return nullptr; 5943 5944 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5945 bool Match = true; 5946 ObjCMethodDecl *Method = Methods[b]; 5947 unsigned NumNamedArgs = Sel.getNumArgs(); 5948 // Method might have more arguments than selector indicates. This is due 5949 // to addition of c-style arguments in method. 5950 if (Method->param_size() > NumNamedArgs) 5951 NumNamedArgs = Method->param_size(); 5952 if (Args.size() < NumNamedArgs) 5953 continue; 5954 5955 for (unsigned i = 0; i < NumNamedArgs; i++) { 5956 // We can't do any type-checking on a type-dependent argument. 5957 if (Args[i]->isTypeDependent()) { 5958 Match = false; 5959 break; 5960 } 5961 5962 ParmVarDecl *param = Method->parameters()[i]; 5963 Expr *argExpr = Args[i]; 5964 assert(argExpr && "SelectBestMethod(): missing expression"); 5965 5966 // Strip the unbridged-cast placeholder expression off unless it's 5967 // a consumed argument. 5968 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5969 !param->hasAttr<CFConsumedAttr>()) 5970 argExpr = stripARCUnbridgedCast(argExpr); 5971 5972 // If the parameter is __unknown_anytype, move on to the next method. 5973 if (param->getType() == Context.UnknownAnyTy) { 5974 Match = false; 5975 break; 5976 } 5977 5978 ImplicitConversionSequence ConversionState 5979 = TryCopyInitialization(*this, argExpr, param->getType(), 5980 /*SuppressUserConversions*/false, 5981 /*InOverloadResolution=*/true, 5982 /*AllowObjCWritebackConversion=*/ 5983 getLangOpts().ObjCAutoRefCount, 5984 /*AllowExplicit*/false); 5985 // This function looks for a reasonably-exact match, so we consider 5986 // incompatible pointer conversions to be a failure here. 5987 if (ConversionState.isBad() || 5988 (ConversionState.isStandard() && 5989 ConversionState.Standard.Second == 5990 ICK_Incompatible_Pointer_Conversion)) { 5991 Match = false; 5992 break; 5993 } 5994 } 5995 // Promote additional arguments to variadic methods. 5996 if (Match && Method->isVariadic()) { 5997 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5998 if (Args[i]->isTypeDependent()) { 5999 Match = false; 6000 break; 6001 } 6002 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6003 nullptr); 6004 if (Arg.isInvalid()) { 6005 Match = false; 6006 break; 6007 } 6008 } 6009 } else { 6010 // Check for extra arguments to non-variadic methods. 6011 if (Args.size() != NumNamedArgs) 6012 Match = false; 6013 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6014 // Special case when selectors have no argument. In this case, select 6015 // one with the most general result type of 'id'. 6016 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6017 QualType ReturnT = Methods[b]->getReturnType(); 6018 if (ReturnT->isObjCIdType()) 6019 return Methods[b]; 6020 } 6021 } 6022 } 6023 6024 if (Match) 6025 return Method; 6026 } 6027 return nullptr; 6028 } 6029 6030 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6031 // enable_if is order-sensitive. As a result, we need to reverse things 6032 // sometimes. Size of 4 elements is arbitrary. 6033 static SmallVector<EnableIfAttr *, 4> 6034 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6035 SmallVector<EnableIfAttr *, 4> Result; 6036 if (!Function->hasAttrs()) 6037 return Result; 6038 6039 const auto &FuncAttrs = Function->getAttrs(); 6040 for (Attr *Attr : FuncAttrs) 6041 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6042 Result.push_back(EnableIf); 6043 6044 std::reverse(Result.begin(), Result.end()); 6045 return Result; 6046 } 6047 6048 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6049 bool MissingImplicitThis) { 6050 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 6051 if (EnableIfAttrs.empty()) 6052 return nullptr; 6053 6054 SFINAETrap Trap(*this); 6055 SmallVector<Expr *, 16> ConvertedArgs; 6056 bool InitializationFailed = false; 6057 6058 // Ignore any variadic arguments. Converting them is pointless, since the 6059 // user can't refer to them in the enable_if condition. 6060 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6061 6062 // Convert the arguments. 6063 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6064 ExprResult R; 6065 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 6066 !cast<CXXMethodDecl>(Function)->isStatic() && 6067 !isa<CXXConstructorDecl>(Function)) { 6068 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6069 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 6070 Method, Method); 6071 } else { 6072 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6073 Context, Function->getParamDecl(I)), 6074 SourceLocation(), Args[I]); 6075 } 6076 6077 if (R.isInvalid()) { 6078 InitializationFailed = true; 6079 break; 6080 } 6081 6082 ConvertedArgs.push_back(R.get()); 6083 } 6084 6085 if (InitializationFailed || Trap.hasErrorOccurred()) 6086 return EnableIfAttrs[0]; 6087 6088 // Push default arguments if needed. 6089 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6090 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6091 ParmVarDecl *P = Function->getParamDecl(i); 6092 ExprResult R = PerformCopyInitialization( 6093 InitializedEntity::InitializeParameter(Context, 6094 Function->getParamDecl(i)), 6095 SourceLocation(), 6096 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6097 : P->getDefaultArg()); 6098 if (R.isInvalid()) { 6099 InitializationFailed = true; 6100 break; 6101 } 6102 ConvertedArgs.push_back(R.get()); 6103 } 6104 6105 if (InitializationFailed || Trap.hasErrorOccurred()) 6106 return EnableIfAttrs[0]; 6107 } 6108 6109 for (auto *EIA : EnableIfAttrs) { 6110 APValue Result; 6111 // FIXME: This doesn't consider value-dependent cases, because doing so is 6112 // very difficult. Ideally, we should handle them more gracefully. 6113 if (!EIA->getCond()->EvaluateWithSubstitution( 6114 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6115 return EIA; 6116 6117 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6118 return EIA; 6119 } 6120 return nullptr; 6121 } 6122 6123 /// \brief Add all of the function declarations in the given function set to 6124 /// the overload candidate set. 6125 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6126 ArrayRef<Expr *> Args, 6127 OverloadCandidateSet& CandidateSet, 6128 TemplateArgumentListInfo *ExplicitTemplateArgs, 6129 bool SuppressUserConversions, 6130 bool PartialOverloading) { 6131 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6132 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6133 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6134 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6135 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6136 cast<CXXMethodDecl>(FD)->getParent(), 6137 Args[0]->getType(), Args[0]->Classify(Context), 6138 Args.slice(1), CandidateSet, 6139 SuppressUserConversions, PartialOverloading); 6140 else 6141 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6142 SuppressUserConversions, PartialOverloading); 6143 } else { 6144 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6145 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6146 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6147 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6148 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6149 ExplicitTemplateArgs, 6150 Args[0]->getType(), 6151 Args[0]->Classify(Context), Args.slice(1), 6152 CandidateSet, SuppressUserConversions, 6153 PartialOverloading); 6154 else 6155 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6156 ExplicitTemplateArgs, Args, 6157 CandidateSet, SuppressUserConversions, 6158 PartialOverloading); 6159 } 6160 } 6161 } 6162 6163 /// AddMethodCandidate - Adds a named decl (which is some kind of 6164 /// method) as a method candidate to the given overload set. 6165 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6166 QualType ObjectType, 6167 Expr::Classification ObjectClassification, 6168 ArrayRef<Expr *> Args, 6169 OverloadCandidateSet& CandidateSet, 6170 bool SuppressUserConversions) { 6171 NamedDecl *Decl = FoundDecl.getDecl(); 6172 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6173 6174 if (isa<UsingShadowDecl>(Decl)) 6175 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6176 6177 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6178 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6179 "Expected a member function template"); 6180 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6181 /*ExplicitArgs*/ nullptr, 6182 ObjectType, ObjectClassification, 6183 Args, CandidateSet, 6184 SuppressUserConversions); 6185 } else { 6186 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6187 ObjectType, ObjectClassification, 6188 Args, 6189 CandidateSet, SuppressUserConversions); 6190 } 6191 } 6192 6193 /// AddMethodCandidate - Adds the given C++ member function to the set 6194 /// of candidate functions, using the given function call arguments 6195 /// and the object argument (@c Object). For example, in a call 6196 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6197 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6198 /// allow user-defined conversions via constructors or conversion 6199 /// operators. 6200 void 6201 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6202 CXXRecordDecl *ActingContext, QualType ObjectType, 6203 Expr::Classification ObjectClassification, 6204 ArrayRef<Expr *> Args, 6205 OverloadCandidateSet &CandidateSet, 6206 bool SuppressUserConversions, 6207 bool PartialOverloading) { 6208 const FunctionProtoType *Proto 6209 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6210 assert(Proto && "Methods without a prototype cannot be overloaded"); 6211 assert(!isa<CXXConstructorDecl>(Method) && 6212 "Use AddOverloadCandidate for constructors"); 6213 6214 if (!CandidateSet.isNewCandidate(Method)) 6215 return; 6216 6217 // C++11 [class.copy]p23: [DR1402] 6218 // A defaulted move assignment operator that is defined as deleted is 6219 // ignored by overload resolution. 6220 if (Method->isDefaulted() && Method->isDeleted() && 6221 Method->isMoveAssignmentOperator()) 6222 return; 6223 6224 // Overload resolution is always an unevaluated context. 6225 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6226 6227 // Add this candidate 6228 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6229 Candidate.FoundDecl = FoundDecl; 6230 Candidate.Function = Method; 6231 Candidate.IsSurrogate = false; 6232 Candidate.IgnoreObjectArgument = false; 6233 Candidate.ExplicitCallArguments = Args.size(); 6234 6235 unsigned NumParams = Proto->getNumParams(); 6236 6237 // (C++ 13.3.2p2): A candidate function having fewer than m 6238 // parameters is viable only if it has an ellipsis in its parameter 6239 // list (8.3.5). 6240 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6241 !Proto->isVariadic()) { 6242 Candidate.Viable = false; 6243 Candidate.FailureKind = ovl_fail_too_many_arguments; 6244 return; 6245 } 6246 6247 // (C++ 13.3.2p2): A candidate function having more than m parameters 6248 // is viable only if the (m+1)st parameter has a default argument 6249 // (8.3.6). For the purposes of overload resolution, the 6250 // parameter list is truncated on the right, so that there are 6251 // exactly m parameters. 6252 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6253 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6254 // Not enough arguments. 6255 Candidate.Viable = false; 6256 Candidate.FailureKind = ovl_fail_too_few_arguments; 6257 return; 6258 } 6259 6260 Candidate.Viable = true; 6261 6262 if (Method->isStatic() || ObjectType.isNull()) 6263 // The implicit object argument is ignored. 6264 Candidate.IgnoreObjectArgument = true; 6265 else { 6266 // Determine the implicit conversion sequence for the object 6267 // parameter. 6268 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6269 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6270 Method, ActingContext); 6271 if (Candidate.Conversions[0].isBad()) { 6272 Candidate.Viable = false; 6273 Candidate.FailureKind = ovl_fail_bad_conversion; 6274 return; 6275 } 6276 } 6277 6278 // (CUDA B.1): Check for invalid calls between targets. 6279 if (getLangOpts().CUDA) 6280 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6281 if (!IsAllowedCUDACall(Caller, Method)) { 6282 Candidate.Viable = false; 6283 Candidate.FailureKind = ovl_fail_bad_target; 6284 return; 6285 } 6286 6287 // Determine the implicit conversion sequences for each of the 6288 // arguments. 6289 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6290 if (ArgIdx < NumParams) { 6291 // (C++ 13.3.2p3): for F to be a viable function, there shall 6292 // exist for each argument an implicit conversion sequence 6293 // (13.3.3.1) that converts that argument to the corresponding 6294 // parameter of F. 6295 QualType ParamType = Proto->getParamType(ArgIdx); 6296 Candidate.Conversions[ArgIdx + 1] 6297 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6298 SuppressUserConversions, 6299 /*InOverloadResolution=*/true, 6300 /*AllowObjCWritebackConversion=*/ 6301 getLangOpts().ObjCAutoRefCount); 6302 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6303 Candidate.Viable = false; 6304 Candidate.FailureKind = ovl_fail_bad_conversion; 6305 return; 6306 } 6307 } else { 6308 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6309 // argument for which there is no corresponding parameter is 6310 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6311 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6312 } 6313 } 6314 6315 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6316 Candidate.Viable = false; 6317 Candidate.FailureKind = ovl_fail_enable_if; 6318 Candidate.DeductionFailure.Data = FailedAttr; 6319 return; 6320 } 6321 } 6322 6323 /// \brief Add a C++ member function template as a candidate to the candidate 6324 /// set, using template argument deduction to produce an appropriate member 6325 /// function template specialization. 6326 void 6327 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6328 DeclAccessPair FoundDecl, 6329 CXXRecordDecl *ActingContext, 6330 TemplateArgumentListInfo *ExplicitTemplateArgs, 6331 QualType ObjectType, 6332 Expr::Classification ObjectClassification, 6333 ArrayRef<Expr *> Args, 6334 OverloadCandidateSet& CandidateSet, 6335 bool SuppressUserConversions, 6336 bool PartialOverloading) { 6337 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6338 return; 6339 6340 // C++ [over.match.funcs]p7: 6341 // In each case where a candidate is a function template, candidate 6342 // function template specializations are generated using template argument 6343 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6344 // candidate functions in the usual way.113) A given name can refer to one 6345 // or more function templates and also to a set of overloaded non-template 6346 // functions. In such a case, the candidate functions generated from each 6347 // function template are combined with the set of non-template candidate 6348 // functions. 6349 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6350 FunctionDecl *Specialization = nullptr; 6351 if (TemplateDeductionResult Result 6352 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6353 Specialization, Info, PartialOverloading)) { 6354 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6355 Candidate.FoundDecl = FoundDecl; 6356 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6357 Candidate.Viable = false; 6358 Candidate.FailureKind = ovl_fail_bad_deduction; 6359 Candidate.IsSurrogate = false; 6360 Candidate.IgnoreObjectArgument = false; 6361 Candidate.ExplicitCallArguments = Args.size(); 6362 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6363 Info); 6364 return; 6365 } 6366 6367 // Add the function template specialization produced by template argument 6368 // deduction as a candidate. 6369 assert(Specialization && "Missing member function template specialization?"); 6370 assert(isa<CXXMethodDecl>(Specialization) && 6371 "Specialization is not a member function?"); 6372 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6373 ActingContext, ObjectType, ObjectClassification, Args, 6374 CandidateSet, SuppressUserConversions, PartialOverloading); 6375 } 6376 6377 /// \brief Add a C++ function template specialization as a candidate 6378 /// in the candidate set, using template argument deduction to produce 6379 /// an appropriate function template specialization. 6380 void 6381 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6382 DeclAccessPair FoundDecl, 6383 TemplateArgumentListInfo *ExplicitTemplateArgs, 6384 ArrayRef<Expr *> Args, 6385 OverloadCandidateSet& CandidateSet, 6386 bool SuppressUserConversions, 6387 bool PartialOverloading) { 6388 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6389 return; 6390 6391 // C++ [over.match.funcs]p7: 6392 // In each case where a candidate is a function template, candidate 6393 // function template specializations are generated using template argument 6394 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6395 // candidate functions in the usual way.113) A given name can refer to one 6396 // or more function templates and also to a set of overloaded non-template 6397 // functions. In such a case, the candidate functions generated from each 6398 // function template are combined with the set of non-template candidate 6399 // functions. 6400 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6401 FunctionDecl *Specialization = nullptr; 6402 if (TemplateDeductionResult Result 6403 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6404 Specialization, Info, PartialOverloading)) { 6405 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6406 Candidate.FoundDecl = FoundDecl; 6407 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6408 Candidate.Viable = false; 6409 Candidate.FailureKind = ovl_fail_bad_deduction; 6410 Candidate.IsSurrogate = false; 6411 Candidate.IgnoreObjectArgument = false; 6412 Candidate.ExplicitCallArguments = Args.size(); 6413 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6414 Info); 6415 return; 6416 } 6417 6418 // Add the function template specialization produced by template argument 6419 // deduction as a candidate. 6420 assert(Specialization && "Missing function template specialization?"); 6421 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6422 SuppressUserConversions, PartialOverloading); 6423 } 6424 6425 /// Determine whether this is an allowable conversion from the result 6426 /// of an explicit conversion operator to the expected type, per C++ 6427 /// [over.match.conv]p1 and [over.match.ref]p1. 6428 /// 6429 /// \param ConvType The return type of the conversion function. 6430 /// 6431 /// \param ToType The type we are converting to. 6432 /// 6433 /// \param AllowObjCPointerConversion Allow a conversion from one 6434 /// Objective-C pointer to another. 6435 /// 6436 /// \returns true if the conversion is allowable, false otherwise. 6437 static bool isAllowableExplicitConversion(Sema &S, 6438 QualType ConvType, QualType ToType, 6439 bool AllowObjCPointerConversion) { 6440 QualType ToNonRefType = ToType.getNonReferenceType(); 6441 6442 // Easy case: the types are the same. 6443 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6444 return true; 6445 6446 // Allow qualification conversions. 6447 bool ObjCLifetimeConversion; 6448 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6449 ObjCLifetimeConversion)) 6450 return true; 6451 6452 // If we're not allowed to consider Objective-C pointer conversions, 6453 // we're done. 6454 if (!AllowObjCPointerConversion) 6455 return false; 6456 6457 // Is this an Objective-C pointer conversion? 6458 bool IncompatibleObjC = false; 6459 QualType ConvertedType; 6460 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6461 IncompatibleObjC); 6462 } 6463 6464 /// AddConversionCandidate - Add a C++ conversion function as a 6465 /// candidate in the candidate set (C++ [over.match.conv], 6466 /// C++ [over.match.copy]). From is the expression we're converting from, 6467 /// and ToType is the type that we're eventually trying to convert to 6468 /// (which may or may not be the same type as the type that the 6469 /// conversion function produces). 6470 void 6471 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6472 DeclAccessPair FoundDecl, 6473 CXXRecordDecl *ActingContext, 6474 Expr *From, QualType ToType, 6475 OverloadCandidateSet& CandidateSet, 6476 bool AllowObjCConversionOnExplicit) { 6477 assert(!Conversion->getDescribedFunctionTemplate() && 6478 "Conversion function templates use AddTemplateConversionCandidate"); 6479 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6480 if (!CandidateSet.isNewCandidate(Conversion)) 6481 return; 6482 6483 // If the conversion function has an undeduced return type, trigger its 6484 // deduction now. 6485 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6486 if (DeduceReturnType(Conversion, From->getExprLoc())) 6487 return; 6488 ConvType = Conversion->getConversionType().getNonReferenceType(); 6489 } 6490 6491 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6492 // operator is only a candidate if its return type is the target type or 6493 // can be converted to the target type with a qualification conversion. 6494 if (Conversion->isExplicit() && 6495 !isAllowableExplicitConversion(*this, ConvType, ToType, 6496 AllowObjCConversionOnExplicit)) 6497 return; 6498 6499 // Overload resolution is always an unevaluated context. 6500 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6501 6502 // Add this candidate 6503 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6504 Candidate.FoundDecl = FoundDecl; 6505 Candidate.Function = Conversion; 6506 Candidate.IsSurrogate = false; 6507 Candidate.IgnoreObjectArgument = false; 6508 Candidate.FinalConversion.setAsIdentityConversion(); 6509 Candidate.FinalConversion.setFromType(ConvType); 6510 Candidate.FinalConversion.setAllToTypes(ToType); 6511 Candidate.Viable = true; 6512 Candidate.ExplicitCallArguments = 1; 6513 6514 // C++ [over.match.funcs]p4: 6515 // For conversion functions, the function is considered to be a member of 6516 // the class of the implicit implied object argument for the purpose of 6517 // defining the type of the implicit object parameter. 6518 // 6519 // Determine the implicit conversion sequence for the implicit 6520 // object parameter. 6521 QualType ImplicitParamType = From->getType(); 6522 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6523 ImplicitParamType = FromPtrType->getPointeeType(); 6524 CXXRecordDecl *ConversionContext 6525 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6526 6527 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6528 *this, CandidateSet.getLocation(), From->getType(), 6529 From->Classify(Context), Conversion, ConversionContext); 6530 6531 if (Candidate.Conversions[0].isBad()) { 6532 Candidate.Viable = false; 6533 Candidate.FailureKind = ovl_fail_bad_conversion; 6534 return; 6535 } 6536 6537 // We won't go through a user-defined type conversion function to convert a 6538 // derived to base as such conversions are given Conversion Rank. They only 6539 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6540 QualType FromCanon 6541 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6542 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6543 if (FromCanon == ToCanon || 6544 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6545 Candidate.Viable = false; 6546 Candidate.FailureKind = ovl_fail_trivial_conversion; 6547 return; 6548 } 6549 6550 // To determine what the conversion from the result of calling the 6551 // conversion function to the type we're eventually trying to 6552 // convert to (ToType), we need to synthesize a call to the 6553 // conversion function and attempt copy initialization from it. This 6554 // makes sure that we get the right semantics with respect to 6555 // lvalues/rvalues and the type. Fortunately, we can allocate this 6556 // call on the stack and we don't need its arguments to be 6557 // well-formed. 6558 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6559 VK_LValue, From->getLocStart()); 6560 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6561 Context.getPointerType(Conversion->getType()), 6562 CK_FunctionToPointerDecay, 6563 &ConversionRef, VK_RValue); 6564 6565 QualType ConversionType = Conversion->getConversionType(); 6566 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6567 Candidate.Viable = false; 6568 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6569 return; 6570 } 6571 6572 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6573 6574 // Note that it is safe to allocate CallExpr on the stack here because 6575 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6576 // allocator). 6577 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6578 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6579 From->getLocStart()); 6580 ImplicitConversionSequence ICS = 6581 TryCopyInitialization(*this, &Call, ToType, 6582 /*SuppressUserConversions=*/true, 6583 /*InOverloadResolution=*/false, 6584 /*AllowObjCWritebackConversion=*/false); 6585 6586 switch (ICS.getKind()) { 6587 case ImplicitConversionSequence::StandardConversion: 6588 Candidate.FinalConversion = ICS.Standard; 6589 6590 // C++ [over.ics.user]p3: 6591 // If the user-defined conversion is specified by a specialization of a 6592 // conversion function template, the second standard conversion sequence 6593 // shall have exact match rank. 6594 if (Conversion->getPrimaryTemplate() && 6595 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6596 Candidate.Viable = false; 6597 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6598 return; 6599 } 6600 6601 // C++0x [dcl.init.ref]p5: 6602 // In the second case, if the reference is an rvalue reference and 6603 // the second standard conversion sequence of the user-defined 6604 // conversion sequence includes an lvalue-to-rvalue conversion, the 6605 // program is ill-formed. 6606 if (ToType->isRValueReferenceType() && 6607 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6608 Candidate.Viable = false; 6609 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6610 return; 6611 } 6612 break; 6613 6614 case ImplicitConversionSequence::BadConversion: 6615 Candidate.Viable = false; 6616 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6617 return; 6618 6619 default: 6620 llvm_unreachable( 6621 "Can only end up with a standard conversion sequence or failure"); 6622 } 6623 6624 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6625 Candidate.Viable = false; 6626 Candidate.FailureKind = ovl_fail_enable_if; 6627 Candidate.DeductionFailure.Data = FailedAttr; 6628 return; 6629 } 6630 } 6631 6632 /// \brief Adds a conversion function template specialization 6633 /// candidate to the overload set, using template argument deduction 6634 /// to deduce the template arguments of the conversion function 6635 /// template from the type that we are converting to (C++ 6636 /// [temp.deduct.conv]). 6637 void 6638 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6639 DeclAccessPair FoundDecl, 6640 CXXRecordDecl *ActingDC, 6641 Expr *From, QualType ToType, 6642 OverloadCandidateSet &CandidateSet, 6643 bool AllowObjCConversionOnExplicit) { 6644 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6645 "Only conversion function templates permitted here"); 6646 6647 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6648 return; 6649 6650 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6651 CXXConversionDecl *Specialization = nullptr; 6652 if (TemplateDeductionResult Result 6653 = DeduceTemplateArguments(FunctionTemplate, ToType, 6654 Specialization, Info)) { 6655 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6656 Candidate.FoundDecl = FoundDecl; 6657 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6658 Candidate.Viable = false; 6659 Candidate.FailureKind = ovl_fail_bad_deduction; 6660 Candidate.IsSurrogate = false; 6661 Candidate.IgnoreObjectArgument = false; 6662 Candidate.ExplicitCallArguments = 1; 6663 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6664 Info); 6665 return; 6666 } 6667 6668 // Add the conversion function template specialization produced by 6669 // template argument deduction as a candidate. 6670 assert(Specialization && "Missing function template specialization?"); 6671 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6672 CandidateSet, AllowObjCConversionOnExplicit); 6673 } 6674 6675 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6676 /// converts the given @c Object to a function pointer via the 6677 /// conversion function @c Conversion, and then attempts to call it 6678 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6679 /// the type of function that we'll eventually be calling. 6680 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6681 DeclAccessPair FoundDecl, 6682 CXXRecordDecl *ActingContext, 6683 const FunctionProtoType *Proto, 6684 Expr *Object, 6685 ArrayRef<Expr *> Args, 6686 OverloadCandidateSet& CandidateSet) { 6687 if (!CandidateSet.isNewCandidate(Conversion)) 6688 return; 6689 6690 // Overload resolution is always an unevaluated context. 6691 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6692 6693 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6694 Candidate.FoundDecl = FoundDecl; 6695 Candidate.Function = nullptr; 6696 Candidate.Surrogate = Conversion; 6697 Candidate.Viable = true; 6698 Candidate.IsSurrogate = true; 6699 Candidate.IgnoreObjectArgument = false; 6700 Candidate.ExplicitCallArguments = Args.size(); 6701 6702 // Determine the implicit conversion sequence for the implicit 6703 // object parameter. 6704 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6705 *this, CandidateSet.getLocation(), Object->getType(), 6706 Object->Classify(Context), Conversion, ActingContext); 6707 if (ObjectInit.isBad()) { 6708 Candidate.Viable = false; 6709 Candidate.FailureKind = ovl_fail_bad_conversion; 6710 Candidate.Conversions[0] = ObjectInit; 6711 return; 6712 } 6713 6714 // The first conversion is actually a user-defined conversion whose 6715 // first conversion is ObjectInit's standard conversion (which is 6716 // effectively a reference binding). Record it as such. 6717 Candidate.Conversions[0].setUserDefined(); 6718 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6719 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6720 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6721 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6722 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6723 Candidate.Conversions[0].UserDefined.After 6724 = Candidate.Conversions[0].UserDefined.Before; 6725 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6726 6727 // Find the 6728 unsigned NumParams = Proto->getNumParams(); 6729 6730 // (C++ 13.3.2p2): A candidate function having fewer than m 6731 // parameters is viable only if it has an ellipsis in its parameter 6732 // list (8.3.5). 6733 if (Args.size() > NumParams && !Proto->isVariadic()) { 6734 Candidate.Viable = false; 6735 Candidate.FailureKind = ovl_fail_too_many_arguments; 6736 return; 6737 } 6738 6739 // Function types don't have any default arguments, so just check if 6740 // we have enough arguments. 6741 if (Args.size() < NumParams) { 6742 // Not enough arguments. 6743 Candidate.Viable = false; 6744 Candidate.FailureKind = ovl_fail_too_few_arguments; 6745 return; 6746 } 6747 6748 // Determine the implicit conversion sequences for each of the 6749 // arguments. 6750 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6751 if (ArgIdx < NumParams) { 6752 // (C++ 13.3.2p3): for F to be a viable function, there shall 6753 // exist for each argument an implicit conversion sequence 6754 // (13.3.3.1) that converts that argument to the corresponding 6755 // parameter of F. 6756 QualType ParamType = Proto->getParamType(ArgIdx); 6757 Candidate.Conversions[ArgIdx + 1] 6758 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6759 /*SuppressUserConversions=*/false, 6760 /*InOverloadResolution=*/false, 6761 /*AllowObjCWritebackConversion=*/ 6762 getLangOpts().ObjCAutoRefCount); 6763 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6764 Candidate.Viable = false; 6765 Candidate.FailureKind = ovl_fail_bad_conversion; 6766 return; 6767 } 6768 } else { 6769 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6770 // argument for which there is no corresponding parameter is 6771 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6772 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6773 } 6774 } 6775 6776 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6777 Candidate.Viable = false; 6778 Candidate.FailureKind = ovl_fail_enable_if; 6779 Candidate.DeductionFailure.Data = FailedAttr; 6780 return; 6781 } 6782 } 6783 6784 /// \brief Add overload candidates for overloaded operators that are 6785 /// member functions. 6786 /// 6787 /// Add the overloaded operator candidates that are member functions 6788 /// for the operator Op that was used in an operator expression such 6789 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6790 /// CandidateSet will store the added overload candidates. (C++ 6791 /// [over.match.oper]). 6792 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6793 SourceLocation OpLoc, 6794 ArrayRef<Expr *> Args, 6795 OverloadCandidateSet& CandidateSet, 6796 SourceRange OpRange) { 6797 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6798 6799 // C++ [over.match.oper]p3: 6800 // For a unary operator @ with an operand of a type whose 6801 // cv-unqualified version is T1, and for a binary operator @ with 6802 // a left operand of a type whose cv-unqualified version is T1 and 6803 // a right operand of a type whose cv-unqualified version is T2, 6804 // three sets of candidate functions, designated member 6805 // candidates, non-member candidates and built-in candidates, are 6806 // constructed as follows: 6807 QualType T1 = Args[0]->getType(); 6808 6809 // -- If T1 is a complete class type or a class currently being 6810 // defined, the set of member candidates is the result of the 6811 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6812 // the set of member candidates is empty. 6813 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6814 // Complete the type if it can be completed. 6815 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6816 return; 6817 // If the type is neither complete nor being defined, bail out now. 6818 if (!T1Rec->getDecl()->getDefinition()) 6819 return; 6820 6821 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6822 LookupQualifiedName(Operators, T1Rec->getDecl()); 6823 Operators.suppressDiagnostics(); 6824 6825 for (LookupResult::iterator Oper = Operators.begin(), 6826 OperEnd = Operators.end(); 6827 Oper != OperEnd; 6828 ++Oper) 6829 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6830 Args[0]->Classify(Context), 6831 Args.slice(1), 6832 CandidateSet, 6833 /* SuppressUserConversions = */ false); 6834 } 6835 } 6836 6837 /// AddBuiltinCandidate - Add a candidate for a built-in 6838 /// operator. ResultTy and ParamTys are the result and parameter types 6839 /// of the built-in candidate, respectively. Args and NumArgs are the 6840 /// arguments being passed to the candidate. IsAssignmentOperator 6841 /// should be true when this built-in candidate is an assignment 6842 /// operator. NumContextualBoolArguments is the number of arguments 6843 /// (at the beginning of the argument list) that will be contextually 6844 /// converted to bool. 6845 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6846 ArrayRef<Expr *> Args, 6847 OverloadCandidateSet& CandidateSet, 6848 bool IsAssignmentOperator, 6849 unsigned NumContextualBoolArguments) { 6850 // Overload resolution is always an unevaluated context. 6851 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6852 6853 // Add this candidate 6854 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6855 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6856 Candidate.Function = nullptr; 6857 Candidate.IsSurrogate = false; 6858 Candidate.IgnoreObjectArgument = false; 6859 Candidate.BuiltinTypes.ResultTy = ResultTy; 6860 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6861 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6862 6863 // Determine the implicit conversion sequences for each of the 6864 // arguments. 6865 Candidate.Viable = true; 6866 Candidate.ExplicitCallArguments = Args.size(); 6867 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6868 // C++ [over.match.oper]p4: 6869 // For the built-in assignment operators, conversions of the 6870 // left operand are restricted as follows: 6871 // -- no temporaries are introduced to hold the left operand, and 6872 // -- no user-defined conversions are applied to the left 6873 // operand to achieve a type match with the left-most 6874 // parameter of a built-in candidate. 6875 // 6876 // We block these conversions by turning off user-defined 6877 // conversions, since that is the only way that initialization of 6878 // a reference to a non-class type can occur from something that 6879 // is not of the same type. 6880 if (ArgIdx < NumContextualBoolArguments) { 6881 assert(ParamTys[ArgIdx] == Context.BoolTy && 6882 "Contextual conversion to bool requires bool type"); 6883 Candidate.Conversions[ArgIdx] 6884 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6885 } else { 6886 Candidate.Conversions[ArgIdx] 6887 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6888 ArgIdx == 0 && IsAssignmentOperator, 6889 /*InOverloadResolution=*/false, 6890 /*AllowObjCWritebackConversion=*/ 6891 getLangOpts().ObjCAutoRefCount); 6892 } 6893 if (Candidate.Conversions[ArgIdx].isBad()) { 6894 Candidate.Viable = false; 6895 Candidate.FailureKind = ovl_fail_bad_conversion; 6896 break; 6897 } 6898 } 6899 } 6900 6901 namespace { 6902 6903 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6904 /// candidate operator functions for built-in operators (C++ 6905 /// [over.built]). The types are separated into pointer types and 6906 /// enumeration types. 6907 class BuiltinCandidateTypeSet { 6908 /// TypeSet - A set of types. 6909 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6910 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6911 6912 /// PointerTypes - The set of pointer types that will be used in the 6913 /// built-in candidates. 6914 TypeSet PointerTypes; 6915 6916 /// MemberPointerTypes - The set of member pointer types that will be 6917 /// used in the built-in candidates. 6918 TypeSet MemberPointerTypes; 6919 6920 /// EnumerationTypes - The set of enumeration types that will be 6921 /// used in the built-in candidates. 6922 TypeSet EnumerationTypes; 6923 6924 /// \brief The set of vector types that will be used in the built-in 6925 /// candidates. 6926 TypeSet VectorTypes; 6927 6928 /// \brief A flag indicating non-record types are viable candidates 6929 bool HasNonRecordTypes; 6930 6931 /// \brief A flag indicating whether either arithmetic or enumeration types 6932 /// were present in the candidate set. 6933 bool HasArithmeticOrEnumeralTypes; 6934 6935 /// \brief A flag indicating whether the nullptr type was present in the 6936 /// candidate set. 6937 bool HasNullPtrType; 6938 6939 /// Sema - The semantic analysis instance where we are building the 6940 /// candidate type set. 6941 Sema &SemaRef; 6942 6943 /// Context - The AST context in which we will build the type sets. 6944 ASTContext &Context; 6945 6946 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6947 const Qualifiers &VisibleQuals); 6948 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6949 6950 public: 6951 /// iterator - Iterates through the types that are part of the set. 6952 typedef TypeSet::iterator iterator; 6953 6954 BuiltinCandidateTypeSet(Sema &SemaRef) 6955 : HasNonRecordTypes(false), 6956 HasArithmeticOrEnumeralTypes(false), 6957 HasNullPtrType(false), 6958 SemaRef(SemaRef), 6959 Context(SemaRef.Context) { } 6960 6961 void AddTypesConvertedFrom(QualType Ty, 6962 SourceLocation Loc, 6963 bool AllowUserConversions, 6964 bool AllowExplicitConversions, 6965 const Qualifiers &VisibleTypeConversionsQuals); 6966 6967 /// pointer_begin - First pointer type found; 6968 iterator pointer_begin() { return PointerTypes.begin(); } 6969 6970 /// pointer_end - Past the last pointer type found; 6971 iterator pointer_end() { return PointerTypes.end(); } 6972 6973 /// member_pointer_begin - First member pointer type found; 6974 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6975 6976 /// member_pointer_end - Past the last member pointer type found; 6977 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6978 6979 /// enumeration_begin - First enumeration type found; 6980 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6981 6982 /// enumeration_end - Past the last enumeration type found; 6983 iterator enumeration_end() { return EnumerationTypes.end(); } 6984 6985 iterator vector_begin() { return VectorTypes.begin(); } 6986 iterator vector_end() { return VectorTypes.end(); } 6987 6988 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6989 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6990 bool hasNullPtrType() const { return HasNullPtrType; } 6991 }; 6992 6993 } // end anonymous namespace 6994 6995 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6996 /// the set of pointer types along with any more-qualified variants of 6997 /// that type. For example, if @p Ty is "int const *", this routine 6998 /// will add "int const *", "int const volatile *", "int const 6999 /// restrict *", and "int const volatile restrict *" to the set of 7000 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7001 /// false otherwise. 7002 /// 7003 /// FIXME: what to do about extended qualifiers? 7004 bool 7005 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7006 const Qualifiers &VisibleQuals) { 7007 7008 // Insert this type. 7009 if (!PointerTypes.insert(Ty)) 7010 return false; 7011 7012 QualType PointeeTy; 7013 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7014 bool buildObjCPtr = false; 7015 if (!PointerTy) { 7016 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7017 PointeeTy = PTy->getPointeeType(); 7018 buildObjCPtr = true; 7019 } else { 7020 PointeeTy = PointerTy->getPointeeType(); 7021 } 7022 7023 // Don't add qualified variants of arrays. For one, they're not allowed 7024 // (the qualifier would sink to the element type), and for another, the 7025 // only overload situation where it matters is subscript or pointer +- int, 7026 // and those shouldn't have qualifier variants anyway. 7027 if (PointeeTy->isArrayType()) 7028 return true; 7029 7030 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7031 bool hasVolatile = VisibleQuals.hasVolatile(); 7032 bool hasRestrict = VisibleQuals.hasRestrict(); 7033 7034 // Iterate through all strict supersets of BaseCVR. 7035 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7036 if ((CVR | BaseCVR) != CVR) continue; 7037 // Skip over volatile if no volatile found anywhere in the types. 7038 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7039 7040 // Skip over restrict if no restrict found anywhere in the types, or if 7041 // the type cannot be restrict-qualified. 7042 if ((CVR & Qualifiers::Restrict) && 7043 (!hasRestrict || 7044 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7045 continue; 7046 7047 // Build qualified pointee type. 7048 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7049 7050 // Build qualified pointer type. 7051 QualType QPointerTy; 7052 if (!buildObjCPtr) 7053 QPointerTy = Context.getPointerType(QPointeeTy); 7054 else 7055 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7056 7057 // Insert qualified pointer type. 7058 PointerTypes.insert(QPointerTy); 7059 } 7060 7061 return true; 7062 } 7063 7064 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7065 /// to the set of pointer types along with any more-qualified variants of 7066 /// that type. For example, if @p Ty is "int const *", this routine 7067 /// will add "int const *", "int const volatile *", "int const 7068 /// restrict *", and "int const volatile restrict *" to the set of 7069 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7070 /// false otherwise. 7071 /// 7072 /// FIXME: what to do about extended qualifiers? 7073 bool 7074 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7075 QualType Ty) { 7076 // Insert this type. 7077 if (!MemberPointerTypes.insert(Ty)) 7078 return false; 7079 7080 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7081 assert(PointerTy && "type was not a member pointer type!"); 7082 7083 QualType PointeeTy = PointerTy->getPointeeType(); 7084 // Don't add qualified variants of arrays. For one, they're not allowed 7085 // (the qualifier would sink to the element type), and for another, the 7086 // only overload situation where it matters is subscript or pointer +- int, 7087 // and those shouldn't have qualifier variants anyway. 7088 if (PointeeTy->isArrayType()) 7089 return true; 7090 const Type *ClassTy = PointerTy->getClass(); 7091 7092 // Iterate through all strict supersets of the pointee type's CVR 7093 // qualifiers. 7094 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7095 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7096 if ((CVR | BaseCVR) != CVR) continue; 7097 7098 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7099 MemberPointerTypes.insert( 7100 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7101 } 7102 7103 return true; 7104 } 7105 7106 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7107 /// Ty can be implicit converted to the given set of @p Types. We're 7108 /// primarily interested in pointer types and enumeration types. We also 7109 /// take member pointer types, for the conditional operator. 7110 /// AllowUserConversions is true if we should look at the conversion 7111 /// functions of a class type, and AllowExplicitConversions if we 7112 /// should also include the explicit conversion functions of a class 7113 /// type. 7114 void 7115 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7116 SourceLocation Loc, 7117 bool AllowUserConversions, 7118 bool AllowExplicitConversions, 7119 const Qualifiers &VisibleQuals) { 7120 // Only deal with canonical types. 7121 Ty = Context.getCanonicalType(Ty); 7122 7123 // Look through reference types; they aren't part of the type of an 7124 // expression for the purposes of conversions. 7125 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7126 Ty = RefTy->getPointeeType(); 7127 7128 // If we're dealing with an array type, decay to the pointer. 7129 if (Ty->isArrayType()) 7130 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7131 7132 // Otherwise, we don't care about qualifiers on the type. 7133 Ty = Ty.getLocalUnqualifiedType(); 7134 7135 // Flag if we ever add a non-record type. 7136 const RecordType *TyRec = Ty->getAs<RecordType>(); 7137 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7138 7139 // Flag if we encounter an arithmetic type. 7140 HasArithmeticOrEnumeralTypes = 7141 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7142 7143 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7144 PointerTypes.insert(Ty); 7145 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7146 // Insert our type, and its more-qualified variants, into the set 7147 // of types. 7148 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7149 return; 7150 } else if (Ty->isMemberPointerType()) { 7151 // Member pointers are far easier, since the pointee can't be converted. 7152 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7153 return; 7154 } else if (Ty->isEnumeralType()) { 7155 HasArithmeticOrEnumeralTypes = true; 7156 EnumerationTypes.insert(Ty); 7157 } else if (Ty->isVectorType()) { 7158 // We treat vector types as arithmetic types in many contexts as an 7159 // extension. 7160 HasArithmeticOrEnumeralTypes = true; 7161 VectorTypes.insert(Ty); 7162 } else if (Ty->isNullPtrType()) { 7163 HasNullPtrType = true; 7164 } else if (AllowUserConversions && TyRec) { 7165 // No conversion functions in incomplete types. 7166 if (!SemaRef.isCompleteType(Loc, Ty)) 7167 return; 7168 7169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7170 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7171 if (isa<UsingShadowDecl>(D)) 7172 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7173 7174 // Skip conversion function templates; they don't tell us anything 7175 // about which builtin types we can convert to. 7176 if (isa<FunctionTemplateDecl>(D)) 7177 continue; 7178 7179 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7180 if (AllowExplicitConversions || !Conv->isExplicit()) { 7181 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7182 VisibleQuals); 7183 } 7184 } 7185 } 7186 } 7187 7188 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7189 /// the volatile- and non-volatile-qualified assignment operators for the 7190 /// given type to the candidate set. 7191 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7192 QualType T, 7193 ArrayRef<Expr *> Args, 7194 OverloadCandidateSet &CandidateSet) { 7195 QualType ParamTypes[2]; 7196 7197 // T& operator=(T&, T) 7198 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7199 ParamTypes[1] = T; 7200 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7201 /*IsAssignmentOperator=*/true); 7202 7203 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7204 // volatile T& operator=(volatile T&, T) 7205 ParamTypes[0] 7206 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7207 ParamTypes[1] = T; 7208 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7209 /*IsAssignmentOperator=*/true); 7210 } 7211 } 7212 7213 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7214 /// if any, found in visible type conversion functions found in ArgExpr's type. 7215 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7216 Qualifiers VRQuals; 7217 const RecordType *TyRec; 7218 if (const MemberPointerType *RHSMPType = 7219 ArgExpr->getType()->getAs<MemberPointerType>()) 7220 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7221 else 7222 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7223 if (!TyRec) { 7224 // Just to be safe, assume the worst case. 7225 VRQuals.addVolatile(); 7226 VRQuals.addRestrict(); 7227 return VRQuals; 7228 } 7229 7230 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7231 if (!ClassDecl->hasDefinition()) 7232 return VRQuals; 7233 7234 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7235 if (isa<UsingShadowDecl>(D)) 7236 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7237 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7238 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7239 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7240 CanTy = ResTypeRef->getPointeeType(); 7241 // Need to go down the pointer/mempointer chain and add qualifiers 7242 // as see them. 7243 bool done = false; 7244 while (!done) { 7245 if (CanTy.isRestrictQualified()) 7246 VRQuals.addRestrict(); 7247 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7248 CanTy = ResTypePtr->getPointeeType(); 7249 else if (const MemberPointerType *ResTypeMPtr = 7250 CanTy->getAs<MemberPointerType>()) 7251 CanTy = ResTypeMPtr->getPointeeType(); 7252 else 7253 done = true; 7254 if (CanTy.isVolatileQualified()) 7255 VRQuals.addVolatile(); 7256 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7257 return VRQuals; 7258 } 7259 } 7260 } 7261 return VRQuals; 7262 } 7263 7264 namespace { 7265 7266 /// \brief Helper class to manage the addition of builtin operator overload 7267 /// candidates. It provides shared state and utility methods used throughout 7268 /// the process, as well as a helper method to add each group of builtin 7269 /// operator overloads from the standard to a candidate set. 7270 class BuiltinOperatorOverloadBuilder { 7271 // Common instance state available to all overload candidate addition methods. 7272 Sema &S; 7273 ArrayRef<Expr *> Args; 7274 Qualifiers VisibleTypeConversionsQuals; 7275 bool HasArithmeticOrEnumeralCandidateType; 7276 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7277 OverloadCandidateSet &CandidateSet; 7278 7279 // Define some constants used to index and iterate over the arithemetic types 7280 // provided via the getArithmeticType() method below. 7281 // The "promoted arithmetic types" are the arithmetic 7282 // types are that preserved by promotion (C++ [over.built]p2). 7283 static const unsigned FirstIntegralType = 4; 7284 static const unsigned LastIntegralType = 21; 7285 static const unsigned FirstPromotedIntegralType = 4, 7286 LastPromotedIntegralType = 12; 7287 static const unsigned FirstPromotedArithmeticType = 0, 7288 LastPromotedArithmeticType = 12; 7289 static const unsigned NumArithmeticTypes = 21; 7290 7291 /// \brief Get the canonical type for a given arithmetic type index. 7292 CanQualType getArithmeticType(unsigned index) { 7293 assert(index < NumArithmeticTypes); 7294 static CanQualType ASTContext::* const 7295 ArithmeticTypes[NumArithmeticTypes] = { 7296 // Start of promoted types. 7297 &ASTContext::FloatTy, 7298 &ASTContext::DoubleTy, 7299 &ASTContext::LongDoubleTy, 7300 &ASTContext::Float128Ty, 7301 7302 // Start of integral types. 7303 &ASTContext::IntTy, 7304 &ASTContext::LongTy, 7305 &ASTContext::LongLongTy, 7306 &ASTContext::Int128Ty, 7307 &ASTContext::UnsignedIntTy, 7308 &ASTContext::UnsignedLongTy, 7309 &ASTContext::UnsignedLongLongTy, 7310 &ASTContext::UnsignedInt128Ty, 7311 // End of promoted types. 7312 7313 &ASTContext::BoolTy, 7314 &ASTContext::CharTy, 7315 &ASTContext::WCharTy, 7316 &ASTContext::Char16Ty, 7317 &ASTContext::Char32Ty, 7318 &ASTContext::SignedCharTy, 7319 &ASTContext::ShortTy, 7320 &ASTContext::UnsignedCharTy, 7321 &ASTContext::UnsignedShortTy, 7322 // End of integral types. 7323 // FIXME: What about complex? What about half? 7324 }; 7325 return S.Context.*ArithmeticTypes[index]; 7326 } 7327 7328 /// \brief Gets the canonical type resulting from the usual arithemetic 7329 /// converions for the given arithmetic types. 7330 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7331 // Accelerator table for performing the usual arithmetic conversions. 7332 // The rules are basically: 7333 // - if either is floating-point, use the wider floating-point 7334 // - if same signedness, use the higher rank 7335 // - if same size, use unsigned of the higher rank 7336 // - use the larger type 7337 // These rules, together with the axiom that higher ranks are 7338 // never smaller, are sufficient to precompute all of these results 7339 // *except* when dealing with signed types of higher rank. 7340 // (we could precompute SLL x UI for all known platforms, but it's 7341 // better not to make any assumptions). 7342 // We assume that int128 has a higher rank than long long on all platforms. 7343 enum PromotedType : int8_t { 7344 Dep=-1, 7345 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7346 }; 7347 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7348 [LastPromotedArithmeticType] = { 7349 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7350 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7351 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7352 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7353 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7354 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7355 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7356 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7357 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7358 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7359 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7360 }; 7361 7362 assert(L < LastPromotedArithmeticType); 7363 assert(R < LastPromotedArithmeticType); 7364 int Idx = ConversionsTable[L][R]; 7365 7366 // Fast path: the table gives us a concrete answer. 7367 if (Idx != Dep) return getArithmeticType(Idx); 7368 7369 // Slow path: we need to compare widths. 7370 // An invariant is that the signed type has higher rank. 7371 CanQualType LT = getArithmeticType(L), 7372 RT = getArithmeticType(R); 7373 unsigned LW = S.Context.getIntWidth(LT), 7374 RW = S.Context.getIntWidth(RT); 7375 7376 // If they're different widths, use the signed type. 7377 if (LW > RW) return LT; 7378 else if (LW < RW) return RT; 7379 7380 // Otherwise, use the unsigned type of the signed type's rank. 7381 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7382 assert(L == SLL || R == SLL); 7383 return S.Context.UnsignedLongLongTy; 7384 } 7385 7386 /// \brief Helper method to factor out the common pattern of adding overloads 7387 /// for '++' and '--' builtin operators. 7388 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7389 bool HasVolatile, 7390 bool HasRestrict) { 7391 QualType ParamTypes[2] = { 7392 S.Context.getLValueReferenceType(CandidateTy), 7393 S.Context.IntTy 7394 }; 7395 7396 // Non-volatile version. 7397 if (Args.size() == 1) 7398 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7399 else 7400 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7401 7402 // Use a heuristic to reduce number of builtin candidates in the set: 7403 // add volatile version only if there are conversions to a volatile type. 7404 if (HasVolatile) { 7405 ParamTypes[0] = 7406 S.Context.getLValueReferenceType( 7407 S.Context.getVolatileType(CandidateTy)); 7408 if (Args.size() == 1) 7409 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7410 else 7411 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7412 } 7413 7414 // Add restrict version only if there are conversions to a restrict type 7415 // and our candidate type is a non-restrict-qualified pointer. 7416 if (HasRestrict && CandidateTy->isAnyPointerType() && 7417 !CandidateTy.isRestrictQualified()) { 7418 ParamTypes[0] 7419 = S.Context.getLValueReferenceType( 7420 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7421 if (Args.size() == 1) 7422 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7423 else 7424 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7425 7426 if (HasVolatile) { 7427 ParamTypes[0] 7428 = S.Context.getLValueReferenceType( 7429 S.Context.getCVRQualifiedType(CandidateTy, 7430 (Qualifiers::Volatile | 7431 Qualifiers::Restrict))); 7432 if (Args.size() == 1) 7433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7434 else 7435 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7436 } 7437 } 7438 7439 } 7440 7441 public: 7442 BuiltinOperatorOverloadBuilder( 7443 Sema &S, ArrayRef<Expr *> Args, 7444 Qualifiers VisibleTypeConversionsQuals, 7445 bool HasArithmeticOrEnumeralCandidateType, 7446 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7447 OverloadCandidateSet &CandidateSet) 7448 : S(S), Args(Args), 7449 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7450 HasArithmeticOrEnumeralCandidateType( 7451 HasArithmeticOrEnumeralCandidateType), 7452 CandidateTypes(CandidateTypes), 7453 CandidateSet(CandidateSet) { 7454 // Validate some of our static helper constants in debug builds. 7455 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7456 "Invalid first promoted integral type"); 7457 assert(getArithmeticType(LastPromotedIntegralType - 1) 7458 == S.Context.UnsignedInt128Ty && 7459 "Invalid last promoted integral type"); 7460 assert(getArithmeticType(FirstPromotedArithmeticType) 7461 == S.Context.FloatTy && 7462 "Invalid first promoted arithmetic type"); 7463 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7464 == S.Context.UnsignedInt128Ty && 7465 "Invalid last promoted arithmetic type"); 7466 } 7467 7468 // C++ [over.built]p3: 7469 // 7470 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7471 // is either volatile or empty, there exist candidate operator 7472 // functions of the form 7473 // 7474 // VQ T& operator++(VQ T&); 7475 // T operator++(VQ T&, int); 7476 // 7477 // C++ [over.built]p4: 7478 // 7479 // For every pair (T, VQ), where T is an arithmetic type other 7480 // than bool, and VQ is either volatile or empty, there exist 7481 // candidate operator functions of the form 7482 // 7483 // VQ T& operator--(VQ T&); 7484 // T operator--(VQ T&, int); 7485 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7486 if (!HasArithmeticOrEnumeralCandidateType) 7487 return; 7488 7489 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7490 Arith < NumArithmeticTypes; ++Arith) { 7491 addPlusPlusMinusMinusStyleOverloads( 7492 getArithmeticType(Arith), 7493 VisibleTypeConversionsQuals.hasVolatile(), 7494 VisibleTypeConversionsQuals.hasRestrict()); 7495 } 7496 } 7497 7498 // C++ [over.built]p5: 7499 // 7500 // For every pair (T, VQ), where T is a cv-qualified or 7501 // cv-unqualified object type, and VQ is either volatile or 7502 // empty, there exist candidate operator functions of the form 7503 // 7504 // T*VQ& operator++(T*VQ&); 7505 // T*VQ& operator--(T*VQ&); 7506 // T* operator++(T*VQ&, int); 7507 // T* operator--(T*VQ&, int); 7508 void addPlusPlusMinusMinusPointerOverloads() { 7509 for (BuiltinCandidateTypeSet::iterator 7510 Ptr = CandidateTypes[0].pointer_begin(), 7511 PtrEnd = CandidateTypes[0].pointer_end(); 7512 Ptr != PtrEnd; ++Ptr) { 7513 // Skip pointer types that aren't pointers to object types. 7514 if (!(*Ptr)->getPointeeType()->isObjectType()) 7515 continue; 7516 7517 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7518 (!(*Ptr).isVolatileQualified() && 7519 VisibleTypeConversionsQuals.hasVolatile()), 7520 (!(*Ptr).isRestrictQualified() && 7521 VisibleTypeConversionsQuals.hasRestrict())); 7522 } 7523 } 7524 7525 // C++ [over.built]p6: 7526 // For every cv-qualified or cv-unqualified object type T, there 7527 // exist candidate operator functions of the form 7528 // 7529 // T& operator*(T*); 7530 // 7531 // C++ [over.built]p7: 7532 // For every function type T that does not have cv-qualifiers or a 7533 // ref-qualifier, there exist candidate operator functions of the form 7534 // T& operator*(T*); 7535 void addUnaryStarPointerOverloads() { 7536 for (BuiltinCandidateTypeSet::iterator 7537 Ptr = CandidateTypes[0].pointer_begin(), 7538 PtrEnd = CandidateTypes[0].pointer_end(); 7539 Ptr != PtrEnd; ++Ptr) { 7540 QualType ParamTy = *Ptr; 7541 QualType PointeeTy = ParamTy->getPointeeType(); 7542 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7543 continue; 7544 7545 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7546 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7547 continue; 7548 7549 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7550 &ParamTy, Args, CandidateSet); 7551 } 7552 } 7553 7554 // C++ [over.built]p9: 7555 // For every promoted arithmetic type T, there exist candidate 7556 // operator functions of the form 7557 // 7558 // T operator+(T); 7559 // T operator-(T); 7560 void addUnaryPlusOrMinusArithmeticOverloads() { 7561 if (!HasArithmeticOrEnumeralCandidateType) 7562 return; 7563 7564 for (unsigned Arith = FirstPromotedArithmeticType; 7565 Arith < LastPromotedArithmeticType; ++Arith) { 7566 QualType ArithTy = getArithmeticType(Arith); 7567 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7568 } 7569 7570 // Extension: We also add these operators for vector types. 7571 for (BuiltinCandidateTypeSet::iterator 7572 Vec = CandidateTypes[0].vector_begin(), 7573 VecEnd = CandidateTypes[0].vector_end(); 7574 Vec != VecEnd; ++Vec) { 7575 QualType VecTy = *Vec; 7576 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7577 } 7578 } 7579 7580 // C++ [over.built]p8: 7581 // For every type T, there exist candidate operator functions of 7582 // the form 7583 // 7584 // T* operator+(T*); 7585 void addUnaryPlusPointerOverloads() { 7586 for (BuiltinCandidateTypeSet::iterator 7587 Ptr = CandidateTypes[0].pointer_begin(), 7588 PtrEnd = CandidateTypes[0].pointer_end(); 7589 Ptr != PtrEnd; ++Ptr) { 7590 QualType ParamTy = *Ptr; 7591 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7592 } 7593 } 7594 7595 // C++ [over.built]p10: 7596 // For every promoted integral type T, there exist candidate 7597 // operator functions of the form 7598 // 7599 // T operator~(T); 7600 void addUnaryTildePromotedIntegralOverloads() { 7601 if (!HasArithmeticOrEnumeralCandidateType) 7602 return; 7603 7604 for (unsigned Int = FirstPromotedIntegralType; 7605 Int < LastPromotedIntegralType; ++Int) { 7606 QualType IntTy = getArithmeticType(Int); 7607 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7608 } 7609 7610 // Extension: We also add this operator for vector types. 7611 for (BuiltinCandidateTypeSet::iterator 7612 Vec = CandidateTypes[0].vector_begin(), 7613 VecEnd = CandidateTypes[0].vector_end(); 7614 Vec != VecEnd; ++Vec) { 7615 QualType VecTy = *Vec; 7616 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7617 } 7618 } 7619 7620 // C++ [over.match.oper]p16: 7621 // For every pointer to member type T, there exist candidate operator 7622 // functions of the form 7623 // 7624 // bool operator==(T,T); 7625 // bool operator!=(T,T); 7626 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7627 /// Set of (canonical) types that we've already handled. 7628 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7629 7630 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7631 for (BuiltinCandidateTypeSet::iterator 7632 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7633 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7634 MemPtr != MemPtrEnd; 7635 ++MemPtr) { 7636 // Don't add the same builtin candidate twice. 7637 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7638 continue; 7639 7640 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7641 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7642 } 7643 } 7644 } 7645 7646 // C++ [over.built]p15: 7647 // 7648 // For every T, where T is an enumeration type, a pointer type, or 7649 // std::nullptr_t, there exist candidate operator functions of the form 7650 // 7651 // bool operator<(T, T); 7652 // bool operator>(T, T); 7653 // bool operator<=(T, T); 7654 // bool operator>=(T, T); 7655 // bool operator==(T, T); 7656 // bool operator!=(T, T); 7657 void addRelationalPointerOrEnumeralOverloads() { 7658 // C++ [over.match.oper]p3: 7659 // [...]the built-in candidates include all of the candidate operator 7660 // functions defined in 13.6 that, compared to the given operator, [...] 7661 // do not have the same parameter-type-list as any non-template non-member 7662 // candidate. 7663 // 7664 // Note that in practice, this only affects enumeration types because there 7665 // aren't any built-in candidates of record type, and a user-defined operator 7666 // must have an operand of record or enumeration type. Also, the only other 7667 // overloaded operator with enumeration arguments, operator=, 7668 // cannot be overloaded for enumeration types, so this is the only place 7669 // where we must suppress candidates like this. 7670 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7671 UserDefinedBinaryOperators; 7672 7673 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7674 if (CandidateTypes[ArgIdx].enumeration_begin() != 7675 CandidateTypes[ArgIdx].enumeration_end()) { 7676 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7677 CEnd = CandidateSet.end(); 7678 C != CEnd; ++C) { 7679 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7680 continue; 7681 7682 if (C->Function->isFunctionTemplateSpecialization()) 7683 continue; 7684 7685 QualType FirstParamType = 7686 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7687 QualType SecondParamType = 7688 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7689 7690 // Skip if either parameter isn't of enumeral type. 7691 if (!FirstParamType->isEnumeralType() || 7692 !SecondParamType->isEnumeralType()) 7693 continue; 7694 7695 // Add this operator to the set of known user-defined operators. 7696 UserDefinedBinaryOperators.insert( 7697 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7698 S.Context.getCanonicalType(SecondParamType))); 7699 } 7700 } 7701 } 7702 7703 /// Set of (canonical) types that we've already handled. 7704 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7705 7706 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7707 for (BuiltinCandidateTypeSet::iterator 7708 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7709 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7710 Ptr != PtrEnd; ++Ptr) { 7711 // Don't add the same builtin candidate twice. 7712 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7713 continue; 7714 7715 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7716 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7717 } 7718 for (BuiltinCandidateTypeSet::iterator 7719 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7720 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7721 Enum != EnumEnd; ++Enum) { 7722 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7723 7724 // Don't add the same builtin candidate twice, or if a user defined 7725 // candidate exists. 7726 if (!AddedTypes.insert(CanonType).second || 7727 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7728 CanonType))) 7729 continue; 7730 7731 QualType ParamTypes[2] = { *Enum, *Enum }; 7732 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7733 } 7734 7735 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7736 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7737 if (AddedTypes.insert(NullPtrTy).second && 7738 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7739 NullPtrTy))) { 7740 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7741 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7742 CandidateSet); 7743 } 7744 } 7745 } 7746 } 7747 7748 // C++ [over.built]p13: 7749 // 7750 // For every cv-qualified or cv-unqualified object type T 7751 // there exist candidate operator functions of the form 7752 // 7753 // T* operator+(T*, ptrdiff_t); 7754 // T& operator[](T*, ptrdiff_t); [BELOW] 7755 // T* operator-(T*, ptrdiff_t); 7756 // T* operator+(ptrdiff_t, T*); 7757 // T& operator[](ptrdiff_t, T*); [BELOW] 7758 // 7759 // C++ [over.built]p14: 7760 // 7761 // For every T, where T is a pointer to object type, there 7762 // exist candidate operator functions of the form 7763 // 7764 // ptrdiff_t operator-(T, T); 7765 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7766 /// Set of (canonical) types that we've already handled. 7767 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7768 7769 for (int Arg = 0; Arg < 2; ++Arg) { 7770 QualType AsymmetricParamTypes[2] = { 7771 S.Context.getPointerDiffType(), 7772 S.Context.getPointerDiffType(), 7773 }; 7774 for (BuiltinCandidateTypeSet::iterator 7775 Ptr = CandidateTypes[Arg].pointer_begin(), 7776 PtrEnd = CandidateTypes[Arg].pointer_end(); 7777 Ptr != PtrEnd; ++Ptr) { 7778 QualType PointeeTy = (*Ptr)->getPointeeType(); 7779 if (!PointeeTy->isObjectType()) 7780 continue; 7781 7782 AsymmetricParamTypes[Arg] = *Ptr; 7783 if (Arg == 0 || Op == OO_Plus) { 7784 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7785 // T* operator+(ptrdiff_t, T*); 7786 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7787 } 7788 if (Op == OO_Minus) { 7789 // ptrdiff_t operator-(T, T); 7790 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7791 continue; 7792 7793 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7794 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7795 Args, CandidateSet); 7796 } 7797 } 7798 } 7799 } 7800 7801 // C++ [over.built]p12: 7802 // 7803 // For every pair of promoted arithmetic types L and R, there 7804 // exist candidate operator functions of the form 7805 // 7806 // LR operator*(L, R); 7807 // LR operator/(L, R); 7808 // LR operator+(L, R); 7809 // LR operator-(L, R); 7810 // bool operator<(L, R); 7811 // bool operator>(L, R); 7812 // bool operator<=(L, R); 7813 // bool operator>=(L, R); 7814 // bool operator==(L, R); 7815 // bool operator!=(L, R); 7816 // 7817 // where LR is the result of the usual arithmetic conversions 7818 // between types L and R. 7819 // 7820 // C++ [over.built]p24: 7821 // 7822 // For every pair of promoted arithmetic types L and R, there exist 7823 // candidate operator functions of the form 7824 // 7825 // LR operator?(bool, L, R); 7826 // 7827 // where LR is the result of the usual arithmetic conversions 7828 // between types L and R. 7829 // Our candidates ignore the first parameter. 7830 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7831 if (!HasArithmeticOrEnumeralCandidateType) 7832 return; 7833 7834 for (unsigned Left = FirstPromotedArithmeticType; 7835 Left < LastPromotedArithmeticType; ++Left) { 7836 for (unsigned Right = FirstPromotedArithmeticType; 7837 Right < LastPromotedArithmeticType; ++Right) { 7838 QualType LandR[2] = { getArithmeticType(Left), 7839 getArithmeticType(Right) }; 7840 QualType Result = 7841 isComparison ? S.Context.BoolTy 7842 : getUsualArithmeticConversions(Left, Right); 7843 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7844 } 7845 } 7846 7847 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7848 // conditional operator for vector types. 7849 for (BuiltinCandidateTypeSet::iterator 7850 Vec1 = CandidateTypes[0].vector_begin(), 7851 Vec1End = CandidateTypes[0].vector_end(); 7852 Vec1 != Vec1End; ++Vec1) { 7853 for (BuiltinCandidateTypeSet::iterator 7854 Vec2 = CandidateTypes[1].vector_begin(), 7855 Vec2End = CandidateTypes[1].vector_end(); 7856 Vec2 != Vec2End; ++Vec2) { 7857 QualType LandR[2] = { *Vec1, *Vec2 }; 7858 QualType Result = S.Context.BoolTy; 7859 if (!isComparison) { 7860 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7861 Result = *Vec1; 7862 else 7863 Result = *Vec2; 7864 } 7865 7866 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7867 } 7868 } 7869 } 7870 7871 // C++ [over.built]p17: 7872 // 7873 // For every pair of promoted integral types L and R, there 7874 // exist candidate operator functions of the form 7875 // 7876 // LR operator%(L, R); 7877 // LR operator&(L, R); 7878 // LR operator^(L, R); 7879 // LR operator|(L, R); 7880 // L operator<<(L, R); 7881 // L operator>>(L, R); 7882 // 7883 // where LR is the result of the usual arithmetic conversions 7884 // between types L and R. 7885 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7886 if (!HasArithmeticOrEnumeralCandidateType) 7887 return; 7888 7889 for (unsigned Left = FirstPromotedIntegralType; 7890 Left < LastPromotedIntegralType; ++Left) { 7891 for (unsigned Right = FirstPromotedIntegralType; 7892 Right < LastPromotedIntegralType; ++Right) { 7893 QualType LandR[2] = { getArithmeticType(Left), 7894 getArithmeticType(Right) }; 7895 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7896 ? LandR[0] 7897 : getUsualArithmeticConversions(Left, Right); 7898 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7899 } 7900 } 7901 } 7902 7903 // C++ [over.built]p20: 7904 // 7905 // For every pair (T, VQ), where T is an enumeration or 7906 // pointer to member type and VQ is either volatile or 7907 // empty, there exist candidate operator functions of the form 7908 // 7909 // VQ T& operator=(VQ T&, T); 7910 void addAssignmentMemberPointerOrEnumeralOverloads() { 7911 /// Set of (canonical) types that we've already handled. 7912 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7913 7914 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7915 for (BuiltinCandidateTypeSet::iterator 7916 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7917 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7918 Enum != EnumEnd; ++Enum) { 7919 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7920 continue; 7921 7922 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7923 } 7924 7925 for (BuiltinCandidateTypeSet::iterator 7926 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7927 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7928 MemPtr != MemPtrEnd; ++MemPtr) { 7929 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7930 continue; 7931 7932 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7933 } 7934 } 7935 } 7936 7937 // C++ [over.built]p19: 7938 // 7939 // For every pair (T, VQ), where T is any type and VQ is either 7940 // volatile or empty, there exist candidate operator functions 7941 // of the form 7942 // 7943 // T*VQ& operator=(T*VQ&, T*); 7944 // 7945 // C++ [over.built]p21: 7946 // 7947 // For every pair (T, VQ), where T is a cv-qualified or 7948 // cv-unqualified object type and VQ is either volatile or 7949 // empty, there exist candidate operator functions of the form 7950 // 7951 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7952 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7953 void addAssignmentPointerOverloads(bool isEqualOp) { 7954 /// Set of (canonical) types that we've already handled. 7955 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7956 7957 for (BuiltinCandidateTypeSet::iterator 7958 Ptr = CandidateTypes[0].pointer_begin(), 7959 PtrEnd = CandidateTypes[0].pointer_end(); 7960 Ptr != PtrEnd; ++Ptr) { 7961 // If this is operator=, keep track of the builtin candidates we added. 7962 if (isEqualOp) 7963 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7964 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7965 continue; 7966 7967 // non-volatile version 7968 QualType ParamTypes[2] = { 7969 S.Context.getLValueReferenceType(*Ptr), 7970 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7971 }; 7972 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7973 /*IsAssigmentOperator=*/ isEqualOp); 7974 7975 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7976 VisibleTypeConversionsQuals.hasVolatile(); 7977 if (NeedVolatile) { 7978 // volatile version 7979 ParamTypes[0] = 7980 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7981 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7982 /*IsAssigmentOperator=*/isEqualOp); 7983 } 7984 7985 if (!(*Ptr).isRestrictQualified() && 7986 VisibleTypeConversionsQuals.hasRestrict()) { 7987 // restrict version 7988 ParamTypes[0] 7989 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7991 /*IsAssigmentOperator=*/isEqualOp); 7992 7993 if (NeedVolatile) { 7994 // volatile restrict version 7995 ParamTypes[0] 7996 = S.Context.getLValueReferenceType( 7997 S.Context.getCVRQualifiedType(*Ptr, 7998 (Qualifiers::Volatile | 7999 Qualifiers::Restrict))); 8000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8001 /*IsAssigmentOperator=*/isEqualOp); 8002 } 8003 } 8004 } 8005 8006 if (isEqualOp) { 8007 for (BuiltinCandidateTypeSet::iterator 8008 Ptr = CandidateTypes[1].pointer_begin(), 8009 PtrEnd = CandidateTypes[1].pointer_end(); 8010 Ptr != PtrEnd; ++Ptr) { 8011 // Make sure we don't add the same candidate twice. 8012 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8013 continue; 8014 8015 QualType ParamTypes[2] = { 8016 S.Context.getLValueReferenceType(*Ptr), 8017 *Ptr, 8018 }; 8019 8020 // non-volatile version 8021 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8022 /*IsAssigmentOperator=*/true); 8023 8024 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8025 VisibleTypeConversionsQuals.hasVolatile(); 8026 if (NeedVolatile) { 8027 // volatile version 8028 ParamTypes[0] = 8029 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8030 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8031 /*IsAssigmentOperator=*/true); 8032 } 8033 8034 if (!(*Ptr).isRestrictQualified() && 8035 VisibleTypeConversionsQuals.hasRestrict()) { 8036 // restrict version 8037 ParamTypes[0] 8038 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8039 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8040 /*IsAssigmentOperator=*/true); 8041 8042 if (NeedVolatile) { 8043 // volatile restrict version 8044 ParamTypes[0] 8045 = S.Context.getLValueReferenceType( 8046 S.Context.getCVRQualifiedType(*Ptr, 8047 (Qualifiers::Volatile | 8048 Qualifiers::Restrict))); 8049 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8050 /*IsAssigmentOperator=*/true); 8051 } 8052 } 8053 } 8054 } 8055 } 8056 8057 // C++ [over.built]p18: 8058 // 8059 // For every triple (L, VQ, R), where L is an arithmetic type, 8060 // VQ is either volatile or empty, and R is a promoted 8061 // arithmetic type, there exist candidate operator functions of 8062 // the form 8063 // 8064 // VQ L& operator=(VQ L&, R); 8065 // VQ L& operator*=(VQ L&, R); 8066 // VQ L& operator/=(VQ L&, R); 8067 // VQ L& operator+=(VQ L&, R); 8068 // VQ L& operator-=(VQ L&, R); 8069 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8070 if (!HasArithmeticOrEnumeralCandidateType) 8071 return; 8072 8073 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8074 for (unsigned Right = FirstPromotedArithmeticType; 8075 Right < LastPromotedArithmeticType; ++Right) { 8076 QualType ParamTypes[2]; 8077 ParamTypes[1] = getArithmeticType(Right); 8078 8079 // Add this built-in operator as a candidate (VQ is empty). 8080 ParamTypes[0] = 8081 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8082 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8083 /*IsAssigmentOperator=*/isEqualOp); 8084 8085 // Add this built-in operator as a candidate (VQ is 'volatile'). 8086 if (VisibleTypeConversionsQuals.hasVolatile()) { 8087 ParamTypes[0] = 8088 S.Context.getVolatileType(getArithmeticType(Left)); 8089 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8090 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8091 /*IsAssigmentOperator=*/isEqualOp); 8092 } 8093 } 8094 } 8095 8096 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8097 for (BuiltinCandidateTypeSet::iterator 8098 Vec1 = CandidateTypes[0].vector_begin(), 8099 Vec1End = CandidateTypes[0].vector_end(); 8100 Vec1 != Vec1End; ++Vec1) { 8101 for (BuiltinCandidateTypeSet::iterator 8102 Vec2 = CandidateTypes[1].vector_begin(), 8103 Vec2End = CandidateTypes[1].vector_end(); 8104 Vec2 != Vec2End; ++Vec2) { 8105 QualType ParamTypes[2]; 8106 ParamTypes[1] = *Vec2; 8107 // Add this built-in operator as a candidate (VQ is empty). 8108 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8109 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8110 /*IsAssigmentOperator=*/isEqualOp); 8111 8112 // Add this built-in operator as a candidate (VQ is 'volatile'). 8113 if (VisibleTypeConversionsQuals.hasVolatile()) { 8114 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8115 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8116 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8117 /*IsAssigmentOperator=*/isEqualOp); 8118 } 8119 } 8120 } 8121 } 8122 8123 // C++ [over.built]p22: 8124 // 8125 // For every triple (L, VQ, R), where L is an integral type, VQ 8126 // is either volatile or empty, and R is a promoted integral 8127 // type, there exist candidate operator functions of the form 8128 // 8129 // VQ L& operator%=(VQ L&, R); 8130 // VQ L& operator<<=(VQ L&, R); 8131 // VQ L& operator>>=(VQ L&, R); 8132 // VQ L& operator&=(VQ L&, R); 8133 // VQ L& operator^=(VQ L&, R); 8134 // VQ L& operator|=(VQ L&, R); 8135 void addAssignmentIntegralOverloads() { 8136 if (!HasArithmeticOrEnumeralCandidateType) 8137 return; 8138 8139 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8140 for (unsigned Right = FirstPromotedIntegralType; 8141 Right < LastPromotedIntegralType; ++Right) { 8142 QualType ParamTypes[2]; 8143 ParamTypes[1] = getArithmeticType(Right); 8144 8145 // Add this built-in operator as a candidate (VQ is empty). 8146 ParamTypes[0] = 8147 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8148 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8149 if (VisibleTypeConversionsQuals.hasVolatile()) { 8150 // Add this built-in operator as a candidate (VQ is 'volatile'). 8151 ParamTypes[0] = getArithmeticType(Left); 8152 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8153 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8155 } 8156 } 8157 } 8158 } 8159 8160 // C++ [over.operator]p23: 8161 // 8162 // There also exist candidate operator functions of the form 8163 // 8164 // bool operator!(bool); 8165 // bool operator&&(bool, bool); 8166 // bool operator||(bool, bool); 8167 void addExclaimOverload() { 8168 QualType ParamTy = S.Context.BoolTy; 8169 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8170 /*IsAssignmentOperator=*/false, 8171 /*NumContextualBoolArguments=*/1); 8172 } 8173 void addAmpAmpOrPipePipeOverload() { 8174 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8175 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8176 /*IsAssignmentOperator=*/false, 8177 /*NumContextualBoolArguments=*/2); 8178 } 8179 8180 // C++ [over.built]p13: 8181 // 8182 // For every cv-qualified or cv-unqualified object type T there 8183 // exist candidate operator functions of the form 8184 // 8185 // T* operator+(T*, ptrdiff_t); [ABOVE] 8186 // T& operator[](T*, ptrdiff_t); 8187 // T* operator-(T*, ptrdiff_t); [ABOVE] 8188 // T* operator+(ptrdiff_t, T*); [ABOVE] 8189 // T& operator[](ptrdiff_t, T*); 8190 void addSubscriptOverloads() { 8191 for (BuiltinCandidateTypeSet::iterator 8192 Ptr = CandidateTypes[0].pointer_begin(), 8193 PtrEnd = CandidateTypes[0].pointer_end(); 8194 Ptr != PtrEnd; ++Ptr) { 8195 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8196 QualType PointeeType = (*Ptr)->getPointeeType(); 8197 if (!PointeeType->isObjectType()) 8198 continue; 8199 8200 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8201 8202 // T& operator[](T*, ptrdiff_t) 8203 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8204 } 8205 8206 for (BuiltinCandidateTypeSet::iterator 8207 Ptr = CandidateTypes[1].pointer_begin(), 8208 PtrEnd = CandidateTypes[1].pointer_end(); 8209 Ptr != PtrEnd; ++Ptr) { 8210 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8211 QualType PointeeType = (*Ptr)->getPointeeType(); 8212 if (!PointeeType->isObjectType()) 8213 continue; 8214 8215 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8216 8217 // T& operator[](ptrdiff_t, T*) 8218 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8219 } 8220 } 8221 8222 // C++ [over.built]p11: 8223 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8224 // C1 is the same type as C2 or is a derived class of C2, T is an object 8225 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8226 // there exist candidate operator functions of the form 8227 // 8228 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8229 // 8230 // where CV12 is the union of CV1 and CV2. 8231 void addArrowStarOverloads() { 8232 for (BuiltinCandidateTypeSet::iterator 8233 Ptr = CandidateTypes[0].pointer_begin(), 8234 PtrEnd = CandidateTypes[0].pointer_end(); 8235 Ptr != PtrEnd; ++Ptr) { 8236 QualType C1Ty = (*Ptr); 8237 QualType C1; 8238 QualifierCollector Q1; 8239 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8240 if (!isa<RecordType>(C1)) 8241 continue; 8242 // heuristic to reduce number of builtin candidates in the set. 8243 // Add volatile/restrict version only if there are conversions to a 8244 // volatile/restrict type. 8245 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8246 continue; 8247 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8248 continue; 8249 for (BuiltinCandidateTypeSet::iterator 8250 MemPtr = CandidateTypes[1].member_pointer_begin(), 8251 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8252 MemPtr != MemPtrEnd; ++MemPtr) { 8253 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8254 QualType C2 = QualType(mptr->getClass(), 0); 8255 C2 = C2.getUnqualifiedType(); 8256 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8257 break; 8258 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8259 // build CV12 T& 8260 QualType T = mptr->getPointeeType(); 8261 if (!VisibleTypeConversionsQuals.hasVolatile() && 8262 T.isVolatileQualified()) 8263 continue; 8264 if (!VisibleTypeConversionsQuals.hasRestrict() && 8265 T.isRestrictQualified()) 8266 continue; 8267 T = Q1.apply(S.Context, T); 8268 QualType ResultTy = S.Context.getLValueReferenceType(T); 8269 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8270 } 8271 } 8272 } 8273 8274 // Note that we don't consider the first argument, since it has been 8275 // contextually converted to bool long ago. The candidates below are 8276 // therefore added as binary. 8277 // 8278 // C++ [over.built]p25: 8279 // For every type T, where T is a pointer, pointer-to-member, or scoped 8280 // enumeration type, there exist candidate operator functions of the form 8281 // 8282 // T operator?(bool, T, T); 8283 // 8284 void addConditionalOperatorOverloads() { 8285 /// Set of (canonical) types that we've already handled. 8286 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8287 8288 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8289 for (BuiltinCandidateTypeSet::iterator 8290 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8291 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8292 Ptr != PtrEnd; ++Ptr) { 8293 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8294 continue; 8295 8296 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8297 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8298 } 8299 8300 for (BuiltinCandidateTypeSet::iterator 8301 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8302 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8303 MemPtr != MemPtrEnd; ++MemPtr) { 8304 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8305 continue; 8306 8307 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8308 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8309 } 8310 8311 if (S.getLangOpts().CPlusPlus11) { 8312 for (BuiltinCandidateTypeSet::iterator 8313 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8314 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8315 Enum != EnumEnd; ++Enum) { 8316 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8317 continue; 8318 8319 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8320 continue; 8321 8322 QualType ParamTypes[2] = { *Enum, *Enum }; 8323 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8324 } 8325 } 8326 } 8327 } 8328 }; 8329 8330 } // end anonymous namespace 8331 8332 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8333 /// operator overloads to the candidate set (C++ [over.built]), based 8334 /// on the operator @p Op and the arguments given. For example, if the 8335 /// operator is a binary '+', this routine might add "int 8336 /// operator+(int, int)" to cover integer addition. 8337 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8338 SourceLocation OpLoc, 8339 ArrayRef<Expr *> Args, 8340 OverloadCandidateSet &CandidateSet) { 8341 // Find all of the types that the arguments can convert to, but only 8342 // if the operator we're looking at has built-in operator candidates 8343 // that make use of these types. Also record whether we encounter non-record 8344 // candidate types or either arithmetic or enumeral candidate types. 8345 Qualifiers VisibleTypeConversionsQuals; 8346 VisibleTypeConversionsQuals.addConst(); 8347 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8348 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8349 8350 bool HasNonRecordCandidateType = false; 8351 bool HasArithmeticOrEnumeralCandidateType = false; 8352 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8353 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8354 CandidateTypes.emplace_back(*this); 8355 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8356 OpLoc, 8357 true, 8358 (Op == OO_Exclaim || 8359 Op == OO_AmpAmp || 8360 Op == OO_PipePipe), 8361 VisibleTypeConversionsQuals); 8362 HasNonRecordCandidateType = HasNonRecordCandidateType || 8363 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8364 HasArithmeticOrEnumeralCandidateType = 8365 HasArithmeticOrEnumeralCandidateType || 8366 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8367 } 8368 8369 // Exit early when no non-record types have been added to the candidate set 8370 // for any of the arguments to the operator. 8371 // 8372 // We can't exit early for !, ||, or &&, since there we have always have 8373 // 'bool' overloads. 8374 if (!HasNonRecordCandidateType && 8375 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8376 return; 8377 8378 // Setup an object to manage the common state for building overloads. 8379 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8380 VisibleTypeConversionsQuals, 8381 HasArithmeticOrEnumeralCandidateType, 8382 CandidateTypes, CandidateSet); 8383 8384 // Dispatch over the operation to add in only those overloads which apply. 8385 switch (Op) { 8386 case OO_None: 8387 case NUM_OVERLOADED_OPERATORS: 8388 llvm_unreachable("Expected an overloaded operator"); 8389 8390 case OO_New: 8391 case OO_Delete: 8392 case OO_Array_New: 8393 case OO_Array_Delete: 8394 case OO_Call: 8395 llvm_unreachable( 8396 "Special operators don't use AddBuiltinOperatorCandidates"); 8397 8398 case OO_Comma: 8399 case OO_Arrow: 8400 case OO_Coawait: 8401 // C++ [over.match.oper]p3: 8402 // -- For the operator ',', the unary operator '&', the 8403 // operator '->', or the operator 'co_await', the 8404 // built-in candidates set is empty. 8405 break; 8406 8407 case OO_Plus: // '+' is either unary or binary 8408 if (Args.size() == 1) 8409 OpBuilder.addUnaryPlusPointerOverloads(); 8410 // Fall through. 8411 8412 case OO_Minus: // '-' is either unary or binary 8413 if (Args.size() == 1) { 8414 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8415 } else { 8416 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8417 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8418 } 8419 break; 8420 8421 case OO_Star: // '*' is either unary or binary 8422 if (Args.size() == 1) 8423 OpBuilder.addUnaryStarPointerOverloads(); 8424 else 8425 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8426 break; 8427 8428 case OO_Slash: 8429 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8430 break; 8431 8432 case OO_PlusPlus: 8433 case OO_MinusMinus: 8434 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8435 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8436 break; 8437 8438 case OO_EqualEqual: 8439 case OO_ExclaimEqual: 8440 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8441 // Fall through. 8442 8443 case OO_Less: 8444 case OO_Greater: 8445 case OO_LessEqual: 8446 case OO_GreaterEqual: 8447 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8448 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8449 break; 8450 8451 case OO_Percent: 8452 case OO_Caret: 8453 case OO_Pipe: 8454 case OO_LessLess: 8455 case OO_GreaterGreater: 8456 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8457 break; 8458 8459 case OO_Amp: // '&' is either unary or binary 8460 if (Args.size() == 1) 8461 // C++ [over.match.oper]p3: 8462 // -- For the operator ',', the unary operator '&', or the 8463 // operator '->', the built-in candidates set is empty. 8464 break; 8465 8466 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8467 break; 8468 8469 case OO_Tilde: 8470 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8471 break; 8472 8473 case OO_Equal: 8474 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8475 // Fall through. 8476 8477 case OO_PlusEqual: 8478 case OO_MinusEqual: 8479 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8480 // Fall through. 8481 8482 case OO_StarEqual: 8483 case OO_SlashEqual: 8484 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8485 break; 8486 8487 case OO_PercentEqual: 8488 case OO_LessLessEqual: 8489 case OO_GreaterGreaterEqual: 8490 case OO_AmpEqual: 8491 case OO_CaretEqual: 8492 case OO_PipeEqual: 8493 OpBuilder.addAssignmentIntegralOverloads(); 8494 break; 8495 8496 case OO_Exclaim: 8497 OpBuilder.addExclaimOverload(); 8498 break; 8499 8500 case OO_AmpAmp: 8501 case OO_PipePipe: 8502 OpBuilder.addAmpAmpOrPipePipeOverload(); 8503 break; 8504 8505 case OO_Subscript: 8506 OpBuilder.addSubscriptOverloads(); 8507 break; 8508 8509 case OO_ArrowStar: 8510 OpBuilder.addArrowStarOverloads(); 8511 break; 8512 8513 case OO_Conditional: 8514 OpBuilder.addConditionalOperatorOverloads(); 8515 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8516 break; 8517 } 8518 } 8519 8520 /// \brief Add function candidates found via argument-dependent lookup 8521 /// to the set of overloading candidates. 8522 /// 8523 /// This routine performs argument-dependent name lookup based on the 8524 /// given function name (which may also be an operator name) and adds 8525 /// all of the overload candidates found by ADL to the overload 8526 /// candidate set (C++ [basic.lookup.argdep]). 8527 void 8528 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8529 SourceLocation Loc, 8530 ArrayRef<Expr *> Args, 8531 TemplateArgumentListInfo *ExplicitTemplateArgs, 8532 OverloadCandidateSet& CandidateSet, 8533 bool PartialOverloading) { 8534 ADLResult Fns; 8535 8536 // FIXME: This approach for uniquing ADL results (and removing 8537 // redundant candidates from the set) relies on pointer-equality, 8538 // which means we need to key off the canonical decl. However, 8539 // always going back to the canonical decl might not get us the 8540 // right set of default arguments. What default arguments are 8541 // we supposed to consider on ADL candidates, anyway? 8542 8543 // FIXME: Pass in the explicit template arguments? 8544 ArgumentDependentLookup(Name, Loc, Args, Fns); 8545 8546 // Erase all of the candidates we already knew about. 8547 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8548 CandEnd = CandidateSet.end(); 8549 Cand != CandEnd; ++Cand) 8550 if (Cand->Function) { 8551 Fns.erase(Cand->Function); 8552 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8553 Fns.erase(FunTmpl); 8554 } 8555 8556 // For each of the ADL candidates we found, add it to the overload 8557 // set. 8558 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8559 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8560 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8561 if (ExplicitTemplateArgs) 8562 continue; 8563 8564 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8565 PartialOverloading); 8566 } else 8567 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8568 FoundDecl, ExplicitTemplateArgs, 8569 Args, CandidateSet, PartialOverloading); 8570 } 8571 } 8572 8573 namespace { 8574 enum class Comparison { Equal, Better, Worse }; 8575 } 8576 8577 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8578 /// overload resolution. 8579 /// 8580 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8581 /// Cand1's first N enable_if attributes have precisely the same conditions as 8582 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8583 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8584 /// 8585 /// Note that you can have a pair of candidates such that Cand1's enable_if 8586 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8587 /// worse than Cand1's. 8588 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8589 const FunctionDecl *Cand2) { 8590 // Common case: One (or both) decls don't have enable_if attrs. 8591 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8592 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8593 if (!Cand1Attr || !Cand2Attr) { 8594 if (Cand1Attr == Cand2Attr) 8595 return Comparison::Equal; 8596 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8597 } 8598 8599 // FIXME: The next several lines are just 8600 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8601 // instead of reverse order which is how they're stored in the AST. 8602 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8603 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8604 8605 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8606 // has fewer enable_if attributes than Cand2. 8607 if (Cand1Attrs.size() < Cand2Attrs.size()) 8608 return Comparison::Worse; 8609 8610 auto Cand1I = Cand1Attrs.begin(); 8611 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8612 for (auto &Cand2A : Cand2Attrs) { 8613 Cand1ID.clear(); 8614 Cand2ID.clear(); 8615 8616 auto &Cand1A = *Cand1I++; 8617 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8618 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8619 if (Cand1ID != Cand2ID) 8620 return Comparison::Worse; 8621 } 8622 8623 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8624 } 8625 8626 /// isBetterOverloadCandidate - Determines whether the first overload 8627 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8628 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8629 const OverloadCandidate &Cand2, 8630 SourceLocation Loc, 8631 bool UserDefinedConversion) { 8632 // Define viable functions to be better candidates than non-viable 8633 // functions. 8634 if (!Cand2.Viable) 8635 return Cand1.Viable; 8636 else if (!Cand1.Viable) 8637 return false; 8638 8639 // C++ [over.match.best]p1: 8640 // 8641 // -- if F is a static member function, ICS1(F) is defined such 8642 // that ICS1(F) is neither better nor worse than ICS1(G) for 8643 // any function G, and, symmetrically, ICS1(G) is neither 8644 // better nor worse than ICS1(F). 8645 unsigned StartArg = 0; 8646 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8647 StartArg = 1; 8648 8649 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8650 // We don't allow incompatible pointer conversions in C++. 8651 if (!S.getLangOpts().CPlusPlus) 8652 return ICS.isStandard() && 8653 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8654 8655 // The only ill-formed conversion we allow in C++ is the string literal to 8656 // char* conversion, which is only considered ill-formed after C++11. 8657 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8658 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8659 }; 8660 8661 // Define functions that don't require ill-formed conversions for a given 8662 // argument to be better candidates than functions that do. 8663 unsigned NumArgs = Cand1.NumConversions; 8664 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8665 bool HasBetterConversion = false; 8666 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8667 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8668 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8669 if (Cand1Bad != Cand2Bad) { 8670 if (Cand1Bad) 8671 return false; 8672 HasBetterConversion = true; 8673 } 8674 } 8675 8676 if (HasBetterConversion) 8677 return true; 8678 8679 // C++ [over.match.best]p1: 8680 // A viable function F1 is defined to be a better function than another 8681 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8682 // conversion sequence than ICSi(F2), and then... 8683 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8684 switch (CompareImplicitConversionSequences(S, Loc, 8685 Cand1.Conversions[ArgIdx], 8686 Cand2.Conversions[ArgIdx])) { 8687 case ImplicitConversionSequence::Better: 8688 // Cand1 has a better conversion sequence. 8689 HasBetterConversion = true; 8690 break; 8691 8692 case ImplicitConversionSequence::Worse: 8693 // Cand1 can't be better than Cand2. 8694 return false; 8695 8696 case ImplicitConversionSequence::Indistinguishable: 8697 // Do nothing. 8698 break; 8699 } 8700 } 8701 8702 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8703 // ICSj(F2), or, if not that, 8704 if (HasBetterConversion) 8705 return true; 8706 8707 // -- the context is an initialization by user-defined conversion 8708 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8709 // from the return type of F1 to the destination type (i.e., 8710 // the type of the entity being initialized) is a better 8711 // conversion sequence than the standard conversion sequence 8712 // from the return type of F2 to the destination type. 8713 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8714 isa<CXXConversionDecl>(Cand1.Function) && 8715 isa<CXXConversionDecl>(Cand2.Function)) { 8716 // First check whether we prefer one of the conversion functions over the 8717 // other. This only distinguishes the results in non-standard, extension 8718 // cases such as the conversion from a lambda closure type to a function 8719 // pointer or block. 8720 ImplicitConversionSequence::CompareKind Result = 8721 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8722 if (Result == ImplicitConversionSequence::Indistinguishable) 8723 Result = CompareStandardConversionSequences(S, Loc, 8724 Cand1.FinalConversion, 8725 Cand2.FinalConversion); 8726 8727 if (Result != ImplicitConversionSequence::Indistinguishable) 8728 return Result == ImplicitConversionSequence::Better; 8729 8730 // FIXME: Compare kind of reference binding if conversion functions 8731 // convert to a reference type used in direct reference binding, per 8732 // C++14 [over.match.best]p1 section 2 bullet 3. 8733 } 8734 8735 // -- F1 is a non-template function and F2 is a function template 8736 // specialization, or, if not that, 8737 bool Cand1IsSpecialization = Cand1.Function && 8738 Cand1.Function->getPrimaryTemplate(); 8739 bool Cand2IsSpecialization = Cand2.Function && 8740 Cand2.Function->getPrimaryTemplate(); 8741 if (Cand1IsSpecialization != Cand2IsSpecialization) 8742 return Cand2IsSpecialization; 8743 8744 // -- F1 and F2 are function template specializations, and the function 8745 // template for F1 is more specialized than the template for F2 8746 // according to the partial ordering rules described in 14.5.5.2, or, 8747 // if not that, 8748 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8749 if (FunctionTemplateDecl *BetterTemplate 8750 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8751 Cand2.Function->getPrimaryTemplate(), 8752 Loc, 8753 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8754 : TPOC_Call, 8755 Cand1.ExplicitCallArguments, 8756 Cand2.ExplicitCallArguments)) 8757 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8758 } 8759 8760 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8761 // A derived-class constructor beats an (inherited) base class constructor. 8762 bool Cand1IsInherited = 8763 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8764 bool Cand2IsInherited = 8765 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8766 if (Cand1IsInherited != Cand2IsInherited) 8767 return Cand2IsInherited; 8768 else if (Cand1IsInherited) { 8769 assert(Cand2IsInherited); 8770 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8771 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8772 if (Cand1Class->isDerivedFrom(Cand2Class)) 8773 return true; 8774 if (Cand2Class->isDerivedFrom(Cand1Class)) 8775 return false; 8776 // Inherited from sibling base classes: still ambiguous. 8777 } 8778 8779 // Check for enable_if value-based overload resolution. 8780 if (Cand1.Function && Cand2.Function) { 8781 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8782 if (Cmp != Comparison::Equal) 8783 return Cmp == Comparison::Better; 8784 } 8785 8786 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8787 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8788 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8789 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8790 } 8791 8792 bool HasPS1 = Cand1.Function != nullptr && 8793 functionHasPassObjectSizeParams(Cand1.Function); 8794 bool HasPS2 = Cand2.Function != nullptr && 8795 functionHasPassObjectSizeParams(Cand2.Function); 8796 return HasPS1 != HasPS2 && HasPS1; 8797 } 8798 8799 /// Determine whether two declarations are "equivalent" for the purposes of 8800 /// name lookup and overload resolution. This applies when the same internal/no 8801 /// linkage entity is defined by two modules (probably by textually including 8802 /// the same header). In such a case, we don't consider the declarations to 8803 /// declare the same entity, but we also don't want lookups with both 8804 /// declarations visible to be ambiguous in some cases (this happens when using 8805 /// a modularized libstdc++). 8806 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8807 const NamedDecl *B) { 8808 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8809 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8810 if (!VA || !VB) 8811 return false; 8812 8813 // The declarations must be declaring the same name as an internal linkage 8814 // entity in different modules. 8815 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8816 VB->getDeclContext()->getRedeclContext()) || 8817 getOwningModule(const_cast<ValueDecl *>(VA)) == 8818 getOwningModule(const_cast<ValueDecl *>(VB)) || 8819 VA->isExternallyVisible() || VB->isExternallyVisible()) 8820 return false; 8821 8822 // Check that the declarations appear to be equivalent. 8823 // 8824 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8825 // For constants and functions, we should check the initializer or body is 8826 // the same. For non-constant variables, we shouldn't allow it at all. 8827 if (Context.hasSameType(VA->getType(), VB->getType())) 8828 return true; 8829 8830 // Enum constants within unnamed enumerations will have different types, but 8831 // may still be similar enough to be interchangeable for our purposes. 8832 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8833 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8834 // Only handle anonymous enums. If the enumerations were named and 8835 // equivalent, they would have been merged to the same type. 8836 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8837 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8838 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8839 !Context.hasSameType(EnumA->getIntegerType(), 8840 EnumB->getIntegerType())) 8841 return false; 8842 // Allow this only if the value is the same for both enumerators. 8843 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8844 } 8845 } 8846 8847 // Nothing else is sufficiently similar. 8848 return false; 8849 } 8850 8851 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8852 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8853 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8854 8855 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8856 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8857 << !M << (M ? M->getFullModuleName() : ""); 8858 8859 for (auto *E : Equiv) { 8860 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8861 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8862 << !M << (M ? M->getFullModuleName() : ""); 8863 } 8864 } 8865 8866 /// \brief Computes the best viable function (C++ 13.3.3) 8867 /// within an overload candidate set. 8868 /// 8869 /// \param Loc The location of the function name (or operator symbol) for 8870 /// which overload resolution occurs. 8871 /// 8872 /// \param Best If overload resolution was successful or found a deleted 8873 /// function, \p Best points to the candidate function found. 8874 /// 8875 /// \returns The result of overload resolution. 8876 OverloadingResult 8877 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8878 iterator &Best, 8879 bool UserDefinedConversion) { 8880 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8881 std::transform(begin(), end(), std::back_inserter(Candidates), 8882 [](OverloadCandidate &Cand) { return &Cand; }); 8883 8884 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8885 // are accepted by both clang and NVCC. However, during a particular 8886 // compilation mode only one call variant is viable. We need to 8887 // exclude non-viable overload candidates from consideration based 8888 // only on their host/device attributes. Specifically, if one 8889 // candidate call is WrongSide and the other is SameSide, we ignore 8890 // the WrongSide candidate. 8891 if (S.getLangOpts().CUDA) { 8892 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8893 bool ContainsSameSideCandidate = 8894 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8895 return Cand->Function && 8896 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8897 Sema::CFP_SameSide; 8898 }); 8899 if (ContainsSameSideCandidate) { 8900 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8901 return Cand->Function && 8902 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8903 Sema::CFP_WrongSide; 8904 }; 8905 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8906 IsWrongSideCandidate), 8907 Candidates.end()); 8908 } 8909 } 8910 8911 // Find the best viable function. 8912 Best = end(); 8913 for (auto *Cand : Candidates) 8914 if (Cand->Viable) 8915 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8916 UserDefinedConversion)) 8917 Best = Cand; 8918 8919 // If we didn't find any viable functions, abort. 8920 if (Best == end()) 8921 return OR_No_Viable_Function; 8922 8923 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8924 8925 // Make sure that this function is better than every other viable 8926 // function. If not, we have an ambiguity. 8927 for (auto *Cand : Candidates) { 8928 if (Cand->Viable && 8929 Cand != Best && 8930 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8931 UserDefinedConversion)) { 8932 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8933 Cand->Function)) { 8934 EquivalentCands.push_back(Cand->Function); 8935 continue; 8936 } 8937 8938 Best = end(); 8939 return OR_Ambiguous; 8940 } 8941 } 8942 8943 // Best is the best viable function. 8944 if (Best->Function && 8945 (Best->Function->isDeleted() || 8946 S.isFunctionConsideredUnavailable(Best->Function))) 8947 return OR_Deleted; 8948 8949 if (!EquivalentCands.empty()) 8950 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8951 EquivalentCands); 8952 8953 return OR_Success; 8954 } 8955 8956 namespace { 8957 8958 enum OverloadCandidateKind { 8959 oc_function, 8960 oc_method, 8961 oc_constructor, 8962 oc_function_template, 8963 oc_method_template, 8964 oc_constructor_template, 8965 oc_implicit_default_constructor, 8966 oc_implicit_copy_constructor, 8967 oc_implicit_move_constructor, 8968 oc_implicit_copy_assignment, 8969 oc_implicit_move_assignment, 8970 oc_inherited_constructor, 8971 oc_inherited_constructor_template 8972 }; 8973 8974 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8975 NamedDecl *Found, 8976 FunctionDecl *Fn, 8977 std::string &Description) { 8978 bool isTemplate = false; 8979 8980 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8981 isTemplate = true; 8982 Description = S.getTemplateArgumentBindingsText( 8983 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8984 } 8985 8986 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8987 if (!Ctor->isImplicit()) { 8988 if (isa<ConstructorUsingShadowDecl>(Found)) 8989 return isTemplate ? oc_inherited_constructor_template 8990 : oc_inherited_constructor; 8991 else 8992 return isTemplate ? oc_constructor_template : oc_constructor; 8993 } 8994 8995 if (Ctor->isDefaultConstructor()) 8996 return oc_implicit_default_constructor; 8997 8998 if (Ctor->isMoveConstructor()) 8999 return oc_implicit_move_constructor; 9000 9001 assert(Ctor->isCopyConstructor() && 9002 "unexpected sort of implicit constructor"); 9003 return oc_implicit_copy_constructor; 9004 } 9005 9006 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9007 // This actually gets spelled 'candidate function' for now, but 9008 // it doesn't hurt to split it out. 9009 if (!Meth->isImplicit()) 9010 return isTemplate ? oc_method_template : oc_method; 9011 9012 if (Meth->isMoveAssignmentOperator()) 9013 return oc_implicit_move_assignment; 9014 9015 if (Meth->isCopyAssignmentOperator()) 9016 return oc_implicit_copy_assignment; 9017 9018 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9019 return oc_method; 9020 } 9021 9022 return isTemplate ? oc_function_template : oc_function; 9023 } 9024 9025 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9026 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9027 // set. 9028 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9029 S.Diag(FoundDecl->getLocation(), 9030 diag::note_ovl_candidate_inherited_constructor) 9031 << Shadow->getNominatedBaseClass(); 9032 } 9033 9034 } // end anonymous namespace 9035 9036 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9037 const FunctionDecl *FD) { 9038 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9039 bool AlwaysTrue; 9040 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9041 return false; 9042 if (!AlwaysTrue) 9043 return false; 9044 } 9045 return true; 9046 } 9047 9048 /// \brief Returns true if we can take the address of the function. 9049 /// 9050 /// \param Complain - If true, we'll emit a diagnostic 9051 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9052 /// we in overload resolution? 9053 /// \param Loc - The location of the statement we're complaining about. Ignored 9054 /// if we're not complaining, or if we're in overload resolution. 9055 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9056 bool Complain, 9057 bool InOverloadResolution, 9058 SourceLocation Loc) { 9059 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9060 if (Complain) { 9061 if (InOverloadResolution) 9062 S.Diag(FD->getLocStart(), 9063 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9064 else 9065 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9066 } 9067 return false; 9068 } 9069 9070 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9071 return P->hasAttr<PassObjectSizeAttr>(); 9072 }); 9073 if (I == FD->param_end()) 9074 return true; 9075 9076 if (Complain) { 9077 // Add one to ParamNo because it's user-facing 9078 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9079 if (InOverloadResolution) 9080 S.Diag(FD->getLocation(), 9081 diag::note_ovl_candidate_has_pass_object_size_params) 9082 << ParamNo; 9083 else 9084 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9085 << FD << ParamNo; 9086 } 9087 return false; 9088 } 9089 9090 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9091 const FunctionDecl *FD) { 9092 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9093 /*InOverloadResolution=*/true, 9094 /*Loc=*/SourceLocation()); 9095 } 9096 9097 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9098 bool Complain, 9099 SourceLocation Loc) { 9100 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9101 /*InOverloadResolution=*/false, 9102 Loc); 9103 } 9104 9105 // Notes the location of an overload candidate. 9106 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9107 QualType DestType, bool TakingAddress) { 9108 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9109 return; 9110 9111 std::string FnDesc; 9112 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9113 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9114 << (unsigned) K << FnDesc; 9115 9116 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9117 Diag(Fn->getLocation(), PD); 9118 MaybeEmitInheritedConstructorNote(*this, Found); 9119 } 9120 9121 // Notes the location of all overload candidates designated through 9122 // OverloadedExpr 9123 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9124 bool TakingAddress) { 9125 assert(OverloadedExpr->getType() == Context.OverloadTy); 9126 9127 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9128 OverloadExpr *OvlExpr = Ovl.Expression; 9129 9130 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9131 IEnd = OvlExpr->decls_end(); 9132 I != IEnd; ++I) { 9133 if (FunctionTemplateDecl *FunTmpl = 9134 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9135 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9136 TakingAddress); 9137 } else if (FunctionDecl *Fun 9138 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9139 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9140 } 9141 } 9142 } 9143 9144 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9145 /// "lead" diagnostic; it will be given two arguments, the source and 9146 /// target types of the conversion. 9147 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9148 Sema &S, 9149 SourceLocation CaretLoc, 9150 const PartialDiagnostic &PDiag) const { 9151 S.Diag(CaretLoc, PDiag) 9152 << Ambiguous.getFromType() << Ambiguous.getToType(); 9153 // FIXME: The note limiting machinery is borrowed from 9154 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9155 // refactoring here. 9156 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9157 unsigned CandsShown = 0; 9158 AmbiguousConversionSequence::const_iterator I, E; 9159 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9160 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9161 break; 9162 ++CandsShown; 9163 S.NoteOverloadCandidate(I->first, I->second); 9164 } 9165 if (I != E) 9166 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9167 } 9168 9169 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9170 unsigned I, bool TakingCandidateAddress) { 9171 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9172 assert(Conv.isBad()); 9173 assert(Cand->Function && "for now, candidate must be a function"); 9174 FunctionDecl *Fn = Cand->Function; 9175 9176 // There's a conversion slot for the object argument if this is a 9177 // non-constructor method. Note that 'I' corresponds the 9178 // conversion-slot index. 9179 bool isObjectArgument = false; 9180 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9181 if (I == 0) 9182 isObjectArgument = true; 9183 else 9184 I--; 9185 } 9186 9187 std::string FnDesc; 9188 OverloadCandidateKind FnKind = 9189 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9190 9191 Expr *FromExpr = Conv.Bad.FromExpr; 9192 QualType FromTy = Conv.Bad.getFromType(); 9193 QualType ToTy = Conv.Bad.getToType(); 9194 9195 if (FromTy == S.Context.OverloadTy) { 9196 assert(FromExpr && "overload set argument came from implicit argument?"); 9197 Expr *E = FromExpr->IgnoreParens(); 9198 if (isa<UnaryOperator>(E)) 9199 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9200 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9201 9202 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9203 << (unsigned) FnKind << FnDesc 9204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9205 << ToTy << Name << I+1; 9206 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9207 return; 9208 } 9209 9210 // Do some hand-waving analysis to see if the non-viability is due 9211 // to a qualifier mismatch. 9212 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9213 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9214 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9215 CToTy = RT->getPointeeType(); 9216 else { 9217 // TODO: detect and diagnose the full richness of const mismatches. 9218 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9219 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9220 CFromTy = FromPT->getPointeeType(); 9221 CToTy = ToPT->getPointeeType(); 9222 } 9223 } 9224 9225 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9226 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9227 Qualifiers FromQs = CFromTy.getQualifiers(); 9228 Qualifiers ToQs = CToTy.getQualifiers(); 9229 9230 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9232 << (unsigned) FnKind << FnDesc 9233 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9234 << FromTy 9235 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9236 << (unsigned) isObjectArgument << I+1; 9237 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9238 return; 9239 } 9240 9241 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9243 << (unsigned) FnKind << FnDesc 9244 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9245 << FromTy 9246 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9247 << (unsigned) isObjectArgument << I+1; 9248 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9249 return; 9250 } 9251 9252 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9253 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9254 << (unsigned) FnKind << FnDesc 9255 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9256 << FromTy 9257 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9258 << (unsigned) isObjectArgument << I+1; 9259 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9260 return; 9261 } 9262 9263 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9265 << (unsigned) FnKind << FnDesc 9266 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9267 << FromTy << FromQs.hasUnaligned() << I+1; 9268 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9269 return; 9270 } 9271 9272 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9273 assert(CVR && "unexpected qualifiers mismatch"); 9274 9275 if (isObjectArgument) { 9276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9277 << (unsigned) FnKind << FnDesc 9278 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9279 << FromTy << (CVR - 1); 9280 } else { 9281 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9282 << (unsigned) FnKind << FnDesc 9283 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9284 << FromTy << (CVR - 1) << I+1; 9285 } 9286 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9287 return; 9288 } 9289 9290 // Special diagnostic for failure to convert an initializer list, since 9291 // telling the user that it has type void is not useful. 9292 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9293 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9294 << (unsigned) FnKind << FnDesc 9295 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9296 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9297 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9298 return; 9299 } 9300 9301 // Diagnose references or pointers to incomplete types differently, 9302 // since it's far from impossible that the incompleteness triggered 9303 // the failure. 9304 QualType TempFromTy = FromTy.getNonReferenceType(); 9305 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9306 TempFromTy = PTy->getPointeeType(); 9307 if (TempFromTy->isIncompleteType()) { 9308 // Emit the generic diagnostic and, optionally, add the hints to it. 9309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9310 << (unsigned) FnKind << FnDesc 9311 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9312 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9313 << (unsigned) (Cand->Fix.Kind); 9314 9315 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9316 return; 9317 } 9318 9319 // Diagnose base -> derived pointer conversions. 9320 unsigned BaseToDerivedConversion = 0; 9321 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9322 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9323 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9324 FromPtrTy->getPointeeType()) && 9325 !FromPtrTy->getPointeeType()->isIncompleteType() && 9326 !ToPtrTy->getPointeeType()->isIncompleteType() && 9327 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9328 FromPtrTy->getPointeeType())) 9329 BaseToDerivedConversion = 1; 9330 } 9331 } else if (const ObjCObjectPointerType *FromPtrTy 9332 = FromTy->getAs<ObjCObjectPointerType>()) { 9333 if (const ObjCObjectPointerType *ToPtrTy 9334 = ToTy->getAs<ObjCObjectPointerType>()) 9335 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9336 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9337 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9338 FromPtrTy->getPointeeType()) && 9339 FromIface->isSuperClassOf(ToIface)) 9340 BaseToDerivedConversion = 2; 9341 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9342 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9343 !FromTy->isIncompleteType() && 9344 !ToRefTy->getPointeeType()->isIncompleteType() && 9345 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9346 BaseToDerivedConversion = 3; 9347 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9348 ToTy.getNonReferenceType().getCanonicalType() == 9349 FromTy.getNonReferenceType().getCanonicalType()) { 9350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9351 << (unsigned) FnKind << FnDesc 9352 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9353 << (unsigned) isObjectArgument << I + 1; 9354 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9355 return; 9356 } 9357 } 9358 9359 if (BaseToDerivedConversion) { 9360 S.Diag(Fn->getLocation(), 9361 diag::note_ovl_candidate_bad_base_to_derived_conv) 9362 << (unsigned) FnKind << FnDesc 9363 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9364 << (BaseToDerivedConversion - 1) 9365 << FromTy << ToTy << I+1; 9366 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9367 return; 9368 } 9369 9370 if (isa<ObjCObjectPointerType>(CFromTy) && 9371 isa<PointerType>(CToTy)) { 9372 Qualifiers FromQs = CFromTy.getQualifiers(); 9373 Qualifiers ToQs = CToTy.getQualifiers(); 9374 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9375 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9376 << (unsigned) FnKind << FnDesc 9377 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9378 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9379 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9380 return; 9381 } 9382 } 9383 9384 if (TakingCandidateAddress && 9385 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9386 return; 9387 9388 // Emit the generic diagnostic and, optionally, add the hints to it. 9389 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9390 FDiag << (unsigned) FnKind << FnDesc 9391 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9392 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9393 << (unsigned) (Cand->Fix.Kind); 9394 9395 // If we can fix the conversion, suggest the FixIts. 9396 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9397 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9398 FDiag << *HI; 9399 S.Diag(Fn->getLocation(), FDiag); 9400 9401 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9402 } 9403 9404 /// Additional arity mismatch diagnosis specific to a function overload 9405 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9406 /// over a candidate in any candidate set. 9407 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9408 unsigned NumArgs) { 9409 FunctionDecl *Fn = Cand->Function; 9410 unsigned MinParams = Fn->getMinRequiredArguments(); 9411 9412 // With invalid overloaded operators, it's possible that we think we 9413 // have an arity mismatch when in fact it looks like we have the 9414 // right number of arguments, because only overloaded operators have 9415 // the weird behavior of overloading member and non-member functions. 9416 // Just don't report anything. 9417 if (Fn->isInvalidDecl() && 9418 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9419 return true; 9420 9421 if (NumArgs < MinParams) { 9422 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9423 (Cand->FailureKind == ovl_fail_bad_deduction && 9424 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9425 } else { 9426 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9427 (Cand->FailureKind == ovl_fail_bad_deduction && 9428 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9429 } 9430 9431 return false; 9432 } 9433 9434 /// General arity mismatch diagnosis over a candidate in a candidate set. 9435 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9436 unsigned NumFormalArgs) { 9437 assert(isa<FunctionDecl>(D) && 9438 "The templated declaration should at least be a function" 9439 " when diagnosing bad template argument deduction due to too many" 9440 " or too few arguments"); 9441 9442 FunctionDecl *Fn = cast<FunctionDecl>(D); 9443 9444 // TODO: treat calls to a missing default constructor as a special case 9445 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9446 unsigned MinParams = Fn->getMinRequiredArguments(); 9447 9448 // at least / at most / exactly 9449 unsigned mode, modeCount; 9450 if (NumFormalArgs < MinParams) { 9451 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9452 FnTy->isTemplateVariadic()) 9453 mode = 0; // "at least" 9454 else 9455 mode = 2; // "exactly" 9456 modeCount = MinParams; 9457 } else { 9458 if (MinParams != FnTy->getNumParams()) 9459 mode = 1; // "at most" 9460 else 9461 mode = 2; // "exactly" 9462 modeCount = FnTy->getNumParams(); 9463 } 9464 9465 std::string Description; 9466 OverloadCandidateKind FnKind = 9467 ClassifyOverloadCandidate(S, Found, Fn, Description); 9468 9469 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9470 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9471 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9472 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9473 else 9474 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9475 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9476 << mode << modeCount << NumFormalArgs; 9477 MaybeEmitInheritedConstructorNote(S, Found); 9478 } 9479 9480 /// Arity mismatch diagnosis specific to a function overload candidate. 9481 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9482 unsigned NumFormalArgs) { 9483 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9484 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9485 } 9486 9487 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9488 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9489 return TD; 9490 llvm_unreachable("Unsupported: Getting the described template declaration" 9491 " for bad deduction diagnosis"); 9492 } 9493 9494 /// Diagnose a failed template-argument deduction. 9495 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9496 DeductionFailureInfo &DeductionFailure, 9497 unsigned NumArgs, 9498 bool TakingCandidateAddress) { 9499 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9500 NamedDecl *ParamD; 9501 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9502 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9503 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9504 switch (DeductionFailure.Result) { 9505 case Sema::TDK_Success: 9506 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9507 9508 case Sema::TDK_Incomplete: { 9509 assert(ParamD && "no parameter found for incomplete deduction result"); 9510 S.Diag(Templated->getLocation(), 9511 diag::note_ovl_candidate_incomplete_deduction) 9512 << ParamD->getDeclName(); 9513 MaybeEmitInheritedConstructorNote(S, Found); 9514 return; 9515 } 9516 9517 case Sema::TDK_Underqualified: { 9518 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9519 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9520 9521 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9522 9523 // Param will have been canonicalized, but it should just be a 9524 // qualified version of ParamD, so move the qualifiers to that. 9525 QualifierCollector Qs; 9526 Qs.strip(Param); 9527 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9528 assert(S.Context.hasSameType(Param, NonCanonParam)); 9529 9530 // Arg has also been canonicalized, but there's nothing we can do 9531 // about that. It also doesn't matter as much, because it won't 9532 // have any template parameters in it (because deduction isn't 9533 // done on dependent types). 9534 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9535 9536 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9537 << ParamD->getDeclName() << Arg << NonCanonParam; 9538 MaybeEmitInheritedConstructorNote(S, Found); 9539 return; 9540 } 9541 9542 case Sema::TDK_Inconsistent: { 9543 assert(ParamD && "no parameter found for inconsistent deduction result"); 9544 int which = 0; 9545 if (isa<TemplateTypeParmDecl>(ParamD)) 9546 which = 0; 9547 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9548 which = 1; 9549 else { 9550 which = 2; 9551 } 9552 9553 S.Diag(Templated->getLocation(), 9554 diag::note_ovl_candidate_inconsistent_deduction) 9555 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9556 << *DeductionFailure.getSecondArg(); 9557 MaybeEmitInheritedConstructorNote(S, Found); 9558 return; 9559 } 9560 9561 case Sema::TDK_InvalidExplicitArguments: 9562 assert(ParamD && "no parameter found for invalid explicit arguments"); 9563 if (ParamD->getDeclName()) 9564 S.Diag(Templated->getLocation(), 9565 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9566 << ParamD->getDeclName(); 9567 else { 9568 int index = 0; 9569 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9570 index = TTP->getIndex(); 9571 else if (NonTypeTemplateParmDecl *NTTP 9572 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9573 index = NTTP->getIndex(); 9574 else 9575 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9576 S.Diag(Templated->getLocation(), 9577 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9578 << (index + 1); 9579 } 9580 MaybeEmitInheritedConstructorNote(S, Found); 9581 return; 9582 9583 case Sema::TDK_TooManyArguments: 9584 case Sema::TDK_TooFewArguments: 9585 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9586 return; 9587 9588 case Sema::TDK_InstantiationDepth: 9589 S.Diag(Templated->getLocation(), 9590 diag::note_ovl_candidate_instantiation_depth); 9591 MaybeEmitInheritedConstructorNote(S, Found); 9592 return; 9593 9594 case Sema::TDK_SubstitutionFailure: { 9595 // Format the template argument list into the argument string. 9596 SmallString<128> TemplateArgString; 9597 if (TemplateArgumentList *Args = 9598 DeductionFailure.getTemplateArgumentList()) { 9599 TemplateArgString = " "; 9600 TemplateArgString += S.getTemplateArgumentBindingsText( 9601 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9602 } 9603 9604 // If this candidate was disabled by enable_if, say so. 9605 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9606 if (PDiag && PDiag->second.getDiagID() == 9607 diag::err_typename_nested_not_found_enable_if) { 9608 // FIXME: Use the source range of the condition, and the fully-qualified 9609 // name of the enable_if template. These are both present in PDiag. 9610 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9611 << "'enable_if'" << TemplateArgString; 9612 return; 9613 } 9614 9615 // Format the SFINAE diagnostic into the argument string. 9616 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9617 // formatted message in another diagnostic. 9618 SmallString<128> SFINAEArgString; 9619 SourceRange R; 9620 if (PDiag) { 9621 SFINAEArgString = ": "; 9622 R = SourceRange(PDiag->first, PDiag->first); 9623 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9624 } 9625 9626 S.Diag(Templated->getLocation(), 9627 diag::note_ovl_candidate_substitution_failure) 9628 << TemplateArgString << SFINAEArgString << R; 9629 MaybeEmitInheritedConstructorNote(S, Found); 9630 return; 9631 } 9632 9633 case Sema::TDK_FailedOverloadResolution: { 9634 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9635 S.Diag(Templated->getLocation(), 9636 diag::note_ovl_candidate_failed_overload_resolution) 9637 << R.Expression->getName(); 9638 return; 9639 } 9640 9641 case Sema::TDK_DeducedMismatch: { 9642 // Format the template argument list into the argument string. 9643 SmallString<128> TemplateArgString; 9644 if (TemplateArgumentList *Args = 9645 DeductionFailure.getTemplateArgumentList()) { 9646 TemplateArgString = " "; 9647 TemplateArgString += S.getTemplateArgumentBindingsText( 9648 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9649 } 9650 9651 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9652 << (*DeductionFailure.getCallArgIndex() + 1) 9653 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9654 << TemplateArgString; 9655 break; 9656 } 9657 9658 case Sema::TDK_NonDeducedMismatch: { 9659 // FIXME: Provide a source location to indicate what we couldn't match. 9660 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9661 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9662 if (FirstTA.getKind() == TemplateArgument::Template && 9663 SecondTA.getKind() == TemplateArgument::Template) { 9664 TemplateName FirstTN = FirstTA.getAsTemplate(); 9665 TemplateName SecondTN = SecondTA.getAsTemplate(); 9666 if (FirstTN.getKind() == TemplateName::Template && 9667 SecondTN.getKind() == TemplateName::Template) { 9668 if (FirstTN.getAsTemplateDecl()->getName() == 9669 SecondTN.getAsTemplateDecl()->getName()) { 9670 // FIXME: This fixes a bad diagnostic where both templates are named 9671 // the same. This particular case is a bit difficult since: 9672 // 1) It is passed as a string to the diagnostic printer. 9673 // 2) The diagnostic printer only attempts to find a better 9674 // name for types, not decls. 9675 // Ideally, this should folded into the diagnostic printer. 9676 S.Diag(Templated->getLocation(), 9677 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9678 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9679 return; 9680 } 9681 } 9682 } 9683 9684 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9685 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9686 return; 9687 9688 // FIXME: For generic lambda parameters, check if the function is a lambda 9689 // call operator, and if so, emit a prettier and more informative 9690 // diagnostic that mentions 'auto' and lambda in addition to 9691 // (or instead of?) the canonical template type parameters. 9692 S.Diag(Templated->getLocation(), 9693 diag::note_ovl_candidate_non_deduced_mismatch) 9694 << FirstTA << SecondTA; 9695 return; 9696 } 9697 // TODO: diagnose these individually, then kill off 9698 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9699 case Sema::TDK_MiscellaneousDeductionFailure: 9700 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9701 MaybeEmitInheritedConstructorNote(S, Found); 9702 return; 9703 } 9704 } 9705 9706 /// Diagnose a failed template-argument deduction, for function calls. 9707 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9708 unsigned NumArgs, 9709 bool TakingCandidateAddress) { 9710 unsigned TDK = Cand->DeductionFailure.Result; 9711 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9712 if (CheckArityMismatch(S, Cand, NumArgs)) 9713 return; 9714 } 9715 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9716 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9717 } 9718 9719 /// CUDA: diagnose an invalid call across targets. 9720 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9721 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9722 FunctionDecl *Callee = Cand->Function; 9723 9724 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9725 CalleeTarget = S.IdentifyCUDATarget(Callee); 9726 9727 std::string FnDesc; 9728 OverloadCandidateKind FnKind = 9729 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9730 9731 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9732 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9733 9734 // This could be an implicit constructor for which we could not infer the 9735 // target due to a collsion. Diagnose that case. 9736 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9737 if (Meth != nullptr && Meth->isImplicit()) { 9738 CXXRecordDecl *ParentClass = Meth->getParent(); 9739 Sema::CXXSpecialMember CSM; 9740 9741 switch (FnKind) { 9742 default: 9743 return; 9744 case oc_implicit_default_constructor: 9745 CSM = Sema::CXXDefaultConstructor; 9746 break; 9747 case oc_implicit_copy_constructor: 9748 CSM = Sema::CXXCopyConstructor; 9749 break; 9750 case oc_implicit_move_constructor: 9751 CSM = Sema::CXXMoveConstructor; 9752 break; 9753 case oc_implicit_copy_assignment: 9754 CSM = Sema::CXXCopyAssignment; 9755 break; 9756 case oc_implicit_move_assignment: 9757 CSM = Sema::CXXMoveAssignment; 9758 break; 9759 }; 9760 9761 bool ConstRHS = false; 9762 if (Meth->getNumParams()) { 9763 if (const ReferenceType *RT = 9764 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9765 ConstRHS = RT->getPointeeType().isConstQualified(); 9766 } 9767 } 9768 9769 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9770 /* ConstRHS */ ConstRHS, 9771 /* Diagnose */ true); 9772 } 9773 } 9774 9775 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9776 FunctionDecl *Callee = Cand->Function; 9777 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9778 9779 S.Diag(Callee->getLocation(), 9780 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9781 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9782 } 9783 9784 /// Generates a 'note' diagnostic for an overload candidate. We've 9785 /// already generated a primary error at the call site. 9786 /// 9787 /// It really does need to be a single diagnostic with its caret 9788 /// pointed at the candidate declaration. Yes, this creates some 9789 /// major challenges of technical writing. Yes, this makes pointing 9790 /// out problems with specific arguments quite awkward. It's still 9791 /// better than generating twenty screens of text for every failed 9792 /// overload. 9793 /// 9794 /// It would be great to be able to express per-candidate problems 9795 /// more richly for those diagnostic clients that cared, but we'd 9796 /// still have to be just as careful with the default diagnostics. 9797 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9798 unsigned NumArgs, 9799 bool TakingCandidateAddress) { 9800 FunctionDecl *Fn = Cand->Function; 9801 9802 // Note deleted candidates, but only if they're viable. 9803 if (Cand->Viable && (Fn->isDeleted() || 9804 S.isFunctionConsideredUnavailable(Fn))) { 9805 std::string FnDesc; 9806 OverloadCandidateKind FnKind = 9807 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9808 9809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9810 << FnKind << FnDesc 9811 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9812 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9813 return; 9814 } 9815 9816 // We don't really have anything else to say about viable candidates. 9817 if (Cand->Viable) { 9818 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9819 return; 9820 } 9821 9822 switch (Cand->FailureKind) { 9823 case ovl_fail_too_many_arguments: 9824 case ovl_fail_too_few_arguments: 9825 return DiagnoseArityMismatch(S, Cand, NumArgs); 9826 9827 case ovl_fail_bad_deduction: 9828 return DiagnoseBadDeduction(S, Cand, NumArgs, 9829 TakingCandidateAddress); 9830 9831 case ovl_fail_illegal_constructor: { 9832 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9833 << (Fn->getPrimaryTemplate() ? 1 : 0); 9834 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9835 return; 9836 } 9837 9838 case ovl_fail_trivial_conversion: 9839 case ovl_fail_bad_final_conversion: 9840 case ovl_fail_final_conversion_not_exact: 9841 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9842 9843 case ovl_fail_bad_conversion: { 9844 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9845 for (unsigned N = Cand->NumConversions; I != N; ++I) 9846 if (Cand->Conversions[I].isBad()) 9847 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9848 9849 // FIXME: this currently happens when we're called from SemaInit 9850 // when user-conversion overload fails. Figure out how to handle 9851 // those conditions and diagnose them well. 9852 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9853 } 9854 9855 case ovl_fail_bad_target: 9856 return DiagnoseBadTarget(S, Cand); 9857 9858 case ovl_fail_enable_if: 9859 return DiagnoseFailedEnableIfAttr(S, Cand); 9860 9861 case ovl_fail_addr_not_available: { 9862 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9863 (void)Available; 9864 assert(!Available); 9865 break; 9866 } 9867 } 9868 } 9869 9870 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9871 // Desugar the type of the surrogate down to a function type, 9872 // retaining as many typedefs as possible while still showing 9873 // the function type (and, therefore, its parameter types). 9874 QualType FnType = Cand->Surrogate->getConversionType(); 9875 bool isLValueReference = false; 9876 bool isRValueReference = false; 9877 bool isPointer = false; 9878 if (const LValueReferenceType *FnTypeRef = 9879 FnType->getAs<LValueReferenceType>()) { 9880 FnType = FnTypeRef->getPointeeType(); 9881 isLValueReference = true; 9882 } else if (const RValueReferenceType *FnTypeRef = 9883 FnType->getAs<RValueReferenceType>()) { 9884 FnType = FnTypeRef->getPointeeType(); 9885 isRValueReference = true; 9886 } 9887 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9888 FnType = FnTypePtr->getPointeeType(); 9889 isPointer = true; 9890 } 9891 // Desugar down to a function type. 9892 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9893 // Reconstruct the pointer/reference as appropriate. 9894 if (isPointer) FnType = S.Context.getPointerType(FnType); 9895 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9896 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9897 9898 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9899 << FnType; 9900 } 9901 9902 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9903 SourceLocation OpLoc, 9904 OverloadCandidate *Cand) { 9905 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9906 std::string TypeStr("operator"); 9907 TypeStr += Opc; 9908 TypeStr += "("; 9909 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9910 if (Cand->NumConversions == 1) { 9911 TypeStr += ")"; 9912 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9913 } else { 9914 TypeStr += ", "; 9915 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9916 TypeStr += ")"; 9917 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9918 } 9919 } 9920 9921 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9922 OverloadCandidate *Cand) { 9923 unsigned NoOperands = Cand->NumConversions; 9924 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9925 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9926 if (ICS.isBad()) break; // all meaningless after first invalid 9927 if (!ICS.isAmbiguous()) continue; 9928 9929 ICS.DiagnoseAmbiguousConversion( 9930 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9931 } 9932 } 9933 9934 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9935 if (Cand->Function) 9936 return Cand->Function->getLocation(); 9937 if (Cand->IsSurrogate) 9938 return Cand->Surrogate->getLocation(); 9939 return SourceLocation(); 9940 } 9941 9942 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9943 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9944 case Sema::TDK_Success: 9945 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9946 9947 case Sema::TDK_Invalid: 9948 case Sema::TDK_Incomplete: 9949 return 1; 9950 9951 case Sema::TDK_Underqualified: 9952 case Sema::TDK_Inconsistent: 9953 return 2; 9954 9955 case Sema::TDK_SubstitutionFailure: 9956 case Sema::TDK_DeducedMismatch: 9957 case Sema::TDK_NonDeducedMismatch: 9958 case Sema::TDK_MiscellaneousDeductionFailure: 9959 return 3; 9960 9961 case Sema::TDK_InstantiationDepth: 9962 case Sema::TDK_FailedOverloadResolution: 9963 return 4; 9964 9965 case Sema::TDK_InvalidExplicitArguments: 9966 return 5; 9967 9968 case Sema::TDK_TooManyArguments: 9969 case Sema::TDK_TooFewArguments: 9970 return 6; 9971 } 9972 llvm_unreachable("Unhandled deduction result"); 9973 } 9974 9975 namespace { 9976 struct CompareOverloadCandidatesForDisplay { 9977 Sema &S; 9978 SourceLocation Loc; 9979 size_t NumArgs; 9980 9981 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9982 : S(S), NumArgs(nArgs) {} 9983 9984 bool operator()(const OverloadCandidate *L, 9985 const OverloadCandidate *R) { 9986 // Fast-path this check. 9987 if (L == R) return false; 9988 9989 // Order first by viability. 9990 if (L->Viable) { 9991 if (!R->Viable) return true; 9992 9993 // TODO: introduce a tri-valued comparison for overload 9994 // candidates. Would be more worthwhile if we had a sort 9995 // that could exploit it. 9996 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9997 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9998 } else if (R->Viable) 9999 return false; 10000 10001 assert(L->Viable == R->Viable); 10002 10003 // Criteria by which we can sort non-viable candidates: 10004 if (!L->Viable) { 10005 // 1. Arity mismatches come after other candidates. 10006 if (L->FailureKind == ovl_fail_too_many_arguments || 10007 L->FailureKind == ovl_fail_too_few_arguments) { 10008 if (R->FailureKind == ovl_fail_too_many_arguments || 10009 R->FailureKind == ovl_fail_too_few_arguments) { 10010 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10011 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10012 if (LDist == RDist) { 10013 if (L->FailureKind == R->FailureKind) 10014 // Sort non-surrogates before surrogates. 10015 return !L->IsSurrogate && R->IsSurrogate; 10016 // Sort candidates requiring fewer parameters than there were 10017 // arguments given after candidates requiring more parameters 10018 // than there were arguments given. 10019 return L->FailureKind == ovl_fail_too_many_arguments; 10020 } 10021 return LDist < RDist; 10022 } 10023 return false; 10024 } 10025 if (R->FailureKind == ovl_fail_too_many_arguments || 10026 R->FailureKind == ovl_fail_too_few_arguments) 10027 return true; 10028 10029 // 2. Bad conversions come first and are ordered by the number 10030 // of bad conversions and quality of good conversions. 10031 if (L->FailureKind == ovl_fail_bad_conversion) { 10032 if (R->FailureKind != ovl_fail_bad_conversion) 10033 return true; 10034 10035 // The conversion that can be fixed with a smaller number of changes, 10036 // comes first. 10037 unsigned numLFixes = L->Fix.NumConversionsFixed; 10038 unsigned numRFixes = R->Fix.NumConversionsFixed; 10039 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10040 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10041 if (numLFixes != numRFixes) { 10042 return numLFixes < numRFixes; 10043 } 10044 10045 // If there's any ordering between the defined conversions... 10046 // FIXME: this might not be transitive. 10047 assert(L->NumConversions == R->NumConversions); 10048 10049 int leftBetter = 0; 10050 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10051 for (unsigned E = L->NumConversions; I != E; ++I) { 10052 switch (CompareImplicitConversionSequences(S, Loc, 10053 L->Conversions[I], 10054 R->Conversions[I])) { 10055 case ImplicitConversionSequence::Better: 10056 leftBetter++; 10057 break; 10058 10059 case ImplicitConversionSequence::Worse: 10060 leftBetter--; 10061 break; 10062 10063 case ImplicitConversionSequence::Indistinguishable: 10064 break; 10065 } 10066 } 10067 if (leftBetter > 0) return true; 10068 if (leftBetter < 0) return false; 10069 10070 } else if (R->FailureKind == ovl_fail_bad_conversion) 10071 return false; 10072 10073 if (L->FailureKind == ovl_fail_bad_deduction) { 10074 if (R->FailureKind != ovl_fail_bad_deduction) 10075 return true; 10076 10077 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10078 return RankDeductionFailure(L->DeductionFailure) 10079 < RankDeductionFailure(R->DeductionFailure); 10080 } else if (R->FailureKind == ovl_fail_bad_deduction) 10081 return false; 10082 10083 // TODO: others? 10084 } 10085 10086 // Sort everything else by location. 10087 SourceLocation LLoc = GetLocationForCandidate(L); 10088 SourceLocation RLoc = GetLocationForCandidate(R); 10089 10090 // Put candidates without locations (e.g. builtins) at the end. 10091 if (LLoc.isInvalid()) return false; 10092 if (RLoc.isInvalid()) return true; 10093 10094 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10095 } 10096 }; 10097 } 10098 10099 /// CompleteNonViableCandidate - Normally, overload resolution only 10100 /// computes up to the first. Produces the FixIt set if possible. 10101 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10102 ArrayRef<Expr *> Args) { 10103 assert(!Cand->Viable); 10104 10105 // Don't do anything on failures other than bad conversion. 10106 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10107 10108 // We only want the FixIts if all the arguments can be corrected. 10109 bool Unfixable = false; 10110 // Use a implicit copy initialization to check conversion fixes. 10111 Cand->Fix.setConversionChecker(TryCopyInitialization); 10112 10113 // Skip forward to the first bad conversion. 10114 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10115 unsigned ConvCount = Cand->NumConversions; 10116 while (true) { 10117 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10118 ConvIdx++; 10119 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10120 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10121 break; 10122 } 10123 } 10124 10125 if (ConvIdx == ConvCount) 10126 return; 10127 10128 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10129 "remaining conversion is initialized?"); 10130 10131 // FIXME: this should probably be preserved from the overload 10132 // operation somehow. 10133 bool SuppressUserConversions = false; 10134 10135 const FunctionProtoType* Proto; 10136 unsigned ArgIdx = ConvIdx; 10137 10138 if (Cand->IsSurrogate) { 10139 QualType ConvType 10140 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10141 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10142 ConvType = ConvPtrType->getPointeeType(); 10143 Proto = ConvType->getAs<FunctionProtoType>(); 10144 ArgIdx--; 10145 } else if (Cand->Function) { 10146 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10147 if (isa<CXXMethodDecl>(Cand->Function) && 10148 !isa<CXXConstructorDecl>(Cand->Function)) 10149 ArgIdx--; 10150 } else { 10151 // Builtin binary operator with a bad first conversion. 10152 assert(ConvCount <= 3); 10153 for (; ConvIdx != ConvCount; ++ConvIdx) 10154 Cand->Conversions[ConvIdx] 10155 = TryCopyInitialization(S, Args[ConvIdx], 10156 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10157 SuppressUserConversions, 10158 /*InOverloadResolution*/ true, 10159 /*AllowObjCWritebackConversion=*/ 10160 S.getLangOpts().ObjCAutoRefCount); 10161 return; 10162 } 10163 10164 // Fill in the rest of the conversions. 10165 unsigned NumParams = Proto->getNumParams(); 10166 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10167 if (ArgIdx < NumParams) { 10168 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10169 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10170 /*InOverloadResolution=*/true, 10171 /*AllowObjCWritebackConversion=*/ 10172 S.getLangOpts().ObjCAutoRefCount); 10173 // Store the FixIt in the candidate if it exists. 10174 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10175 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10176 } 10177 else 10178 Cand->Conversions[ConvIdx].setEllipsis(); 10179 } 10180 } 10181 10182 /// PrintOverloadCandidates - When overload resolution fails, prints 10183 /// diagnostic messages containing the candidates in the candidate 10184 /// set. 10185 void OverloadCandidateSet::NoteCandidates( 10186 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10187 StringRef Opc, SourceLocation OpLoc, 10188 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10189 // Sort the candidates by viability and position. Sorting directly would 10190 // be prohibitive, so we make a set of pointers and sort those. 10191 SmallVector<OverloadCandidate*, 32> Cands; 10192 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10193 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10194 if (!Filter(*Cand)) 10195 continue; 10196 if (Cand->Viable) 10197 Cands.push_back(Cand); 10198 else if (OCD == OCD_AllCandidates) { 10199 CompleteNonViableCandidate(S, Cand, Args); 10200 if (Cand->Function || Cand->IsSurrogate) 10201 Cands.push_back(Cand); 10202 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10203 // want to list every possible builtin candidate. 10204 } 10205 } 10206 10207 std::sort(Cands.begin(), Cands.end(), 10208 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10209 10210 bool ReportedAmbiguousConversions = false; 10211 10212 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10213 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10214 unsigned CandsShown = 0; 10215 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10216 OverloadCandidate *Cand = *I; 10217 10218 // Set an arbitrary limit on the number of candidate functions we'll spam 10219 // the user with. FIXME: This limit should depend on details of the 10220 // candidate list. 10221 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10222 break; 10223 } 10224 ++CandsShown; 10225 10226 if (Cand->Function) 10227 NoteFunctionCandidate(S, Cand, Args.size(), 10228 /*TakingCandidateAddress=*/false); 10229 else if (Cand->IsSurrogate) 10230 NoteSurrogateCandidate(S, Cand); 10231 else { 10232 assert(Cand->Viable && 10233 "Non-viable built-in candidates are not added to Cands."); 10234 // Generally we only see ambiguities including viable builtin 10235 // operators if overload resolution got screwed up by an 10236 // ambiguous user-defined conversion. 10237 // 10238 // FIXME: It's quite possible for different conversions to see 10239 // different ambiguities, though. 10240 if (!ReportedAmbiguousConversions) { 10241 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10242 ReportedAmbiguousConversions = true; 10243 } 10244 10245 // If this is a viable builtin, print it. 10246 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10247 } 10248 } 10249 10250 if (I != E) 10251 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10252 } 10253 10254 static SourceLocation 10255 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10256 return Cand->Specialization ? Cand->Specialization->getLocation() 10257 : SourceLocation(); 10258 } 10259 10260 namespace { 10261 struct CompareTemplateSpecCandidatesForDisplay { 10262 Sema &S; 10263 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10264 10265 bool operator()(const TemplateSpecCandidate *L, 10266 const TemplateSpecCandidate *R) { 10267 // Fast-path this check. 10268 if (L == R) 10269 return false; 10270 10271 // Assuming that both candidates are not matches... 10272 10273 // Sort by the ranking of deduction failures. 10274 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10275 return RankDeductionFailure(L->DeductionFailure) < 10276 RankDeductionFailure(R->DeductionFailure); 10277 10278 // Sort everything else by location. 10279 SourceLocation LLoc = GetLocationForCandidate(L); 10280 SourceLocation RLoc = GetLocationForCandidate(R); 10281 10282 // Put candidates without locations (e.g. builtins) at the end. 10283 if (LLoc.isInvalid()) 10284 return false; 10285 if (RLoc.isInvalid()) 10286 return true; 10287 10288 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10289 } 10290 }; 10291 } 10292 10293 /// Diagnose a template argument deduction failure. 10294 /// We are treating these failures as overload failures due to bad 10295 /// deductions. 10296 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10297 bool ForTakingAddress) { 10298 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10299 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10300 } 10301 10302 void TemplateSpecCandidateSet::destroyCandidates() { 10303 for (iterator i = begin(), e = end(); i != e; ++i) { 10304 i->DeductionFailure.Destroy(); 10305 } 10306 } 10307 10308 void TemplateSpecCandidateSet::clear() { 10309 destroyCandidates(); 10310 Candidates.clear(); 10311 } 10312 10313 /// NoteCandidates - When no template specialization match is found, prints 10314 /// diagnostic messages containing the non-matching specializations that form 10315 /// the candidate set. 10316 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10317 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10318 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10319 // Sort the candidates by position (assuming no candidate is a match). 10320 // Sorting directly would be prohibitive, so we make a set of pointers 10321 // and sort those. 10322 SmallVector<TemplateSpecCandidate *, 32> Cands; 10323 Cands.reserve(size()); 10324 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10325 if (Cand->Specialization) 10326 Cands.push_back(Cand); 10327 // Otherwise, this is a non-matching builtin candidate. We do not, 10328 // in general, want to list every possible builtin candidate. 10329 } 10330 10331 std::sort(Cands.begin(), Cands.end(), 10332 CompareTemplateSpecCandidatesForDisplay(S)); 10333 10334 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10335 // for generalization purposes (?). 10336 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10337 10338 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10339 unsigned CandsShown = 0; 10340 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10341 TemplateSpecCandidate *Cand = *I; 10342 10343 // Set an arbitrary limit on the number of candidates we'll spam 10344 // the user with. FIXME: This limit should depend on details of the 10345 // candidate list. 10346 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10347 break; 10348 ++CandsShown; 10349 10350 assert(Cand->Specialization && 10351 "Non-matching built-in candidates are not added to Cands."); 10352 Cand->NoteDeductionFailure(S, ForTakingAddress); 10353 } 10354 10355 if (I != E) 10356 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10357 } 10358 10359 // [PossiblyAFunctionType] --> [Return] 10360 // NonFunctionType --> NonFunctionType 10361 // R (A) --> R(A) 10362 // R (*)(A) --> R (A) 10363 // R (&)(A) --> R (A) 10364 // R (S::*)(A) --> R (A) 10365 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10366 QualType Ret = PossiblyAFunctionType; 10367 if (const PointerType *ToTypePtr = 10368 PossiblyAFunctionType->getAs<PointerType>()) 10369 Ret = ToTypePtr->getPointeeType(); 10370 else if (const ReferenceType *ToTypeRef = 10371 PossiblyAFunctionType->getAs<ReferenceType>()) 10372 Ret = ToTypeRef->getPointeeType(); 10373 else if (const MemberPointerType *MemTypePtr = 10374 PossiblyAFunctionType->getAs<MemberPointerType>()) 10375 Ret = MemTypePtr->getPointeeType(); 10376 Ret = 10377 Context.getCanonicalType(Ret).getUnqualifiedType(); 10378 return Ret; 10379 } 10380 10381 namespace { 10382 // A helper class to help with address of function resolution 10383 // - allows us to avoid passing around all those ugly parameters 10384 class AddressOfFunctionResolver { 10385 Sema& S; 10386 Expr* SourceExpr; 10387 const QualType& TargetType; 10388 QualType TargetFunctionType; // Extracted function type from target type 10389 10390 bool Complain; 10391 //DeclAccessPair& ResultFunctionAccessPair; 10392 ASTContext& Context; 10393 10394 bool TargetTypeIsNonStaticMemberFunction; 10395 bool FoundNonTemplateFunction; 10396 bool StaticMemberFunctionFromBoundPointer; 10397 bool HasComplained; 10398 10399 OverloadExpr::FindResult OvlExprInfo; 10400 OverloadExpr *OvlExpr; 10401 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10402 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10403 TemplateSpecCandidateSet FailedCandidates; 10404 10405 public: 10406 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10407 const QualType &TargetType, bool Complain) 10408 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10409 Complain(Complain), Context(S.getASTContext()), 10410 TargetTypeIsNonStaticMemberFunction( 10411 !!TargetType->getAs<MemberPointerType>()), 10412 FoundNonTemplateFunction(false), 10413 StaticMemberFunctionFromBoundPointer(false), 10414 HasComplained(false), 10415 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10416 OvlExpr(OvlExprInfo.Expression), 10417 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10418 ExtractUnqualifiedFunctionTypeFromTargetType(); 10419 10420 if (TargetFunctionType->isFunctionType()) { 10421 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10422 if (!UME->isImplicitAccess() && 10423 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10424 StaticMemberFunctionFromBoundPointer = true; 10425 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10426 DeclAccessPair dap; 10427 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10428 OvlExpr, false, &dap)) { 10429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10430 if (!Method->isStatic()) { 10431 // If the target type is a non-function type and the function found 10432 // is a non-static member function, pretend as if that was the 10433 // target, it's the only possible type to end up with. 10434 TargetTypeIsNonStaticMemberFunction = true; 10435 10436 // And skip adding the function if its not in the proper form. 10437 // We'll diagnose this due to an empty set of functions. 10438 if (!OvlExprInfo.HasFormOfMemberPointer) 10439 return; 10440 } 10441 10442 Matches.push_back(std::make_pair(dap, Fn)); 10443 } 10444 return; 10445 } 10446 10447 if (OvlExpr->hasExplicitTemplateArgs()) 10448 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10449 10450 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10451 // C++ [over.over]p4: 10452 // If more than one function is selected, [...] 10453 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10454 if (FoundNonTemplateFunction) 10455 EliminateAllTemplateMatches(); 10456 else 10457 EliminateAllExceptMostSpecializedTemplate(); 10458 } 10459 } 10460 10461 if (S.getLangOpts().CUDA && Matches.size() > 1) 10462 EliminateSuboptimalCudaMatches(); 10463 } 10464 10465 bool hasComplained() const { return HasComplained; } 10466 10467 private: 10468 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10469 QualType Discard; 10470 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10471 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10472 } 10473 10474 /// \return true if A is considered a better overload candidate for the 10475 /// desired type than B. 10476 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10477 // If A doesn't have exactly the correct type, we don't want to classify it 10478 // as "better" than anything else. This way, the user is required to 10479 // disambiguate for us if there are multiple candidates and no exact match. 10480 return candidateHasExactlyCorrectType(A) && 10481 (!candidateHasExactlyCorrectType(B) || 10482 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10483 } 10484 10485 /// \return true if we were able to eliminate all but one overload candidate, 10486 /// false otherwise. 10487 bool eliminiateSuboptimalOverloadCandidates() { 10488 // Same algorithm as overload resolution -- one pass to pick the "best", 10489 // another pass to be sure that nothing is better than the best. 10490 auto Best = Matches.begin(); 10491 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10492 if (isBetterCandidate(I->second, Best->second)) 10493 Best = I; 10494 10495 const FunctionDecl *BestFn = Best->second; 10496 auto IsBestOrInferiorToBest = [this, BestFn]( 10497 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10498 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10499 }; 10500 10501 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10502 // option, so we can potentially give the user a better error 10503 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10504 return false; 10505 Matches[0] = *Best; 10506 Matches.resize(1); 10507 return true; 10508 } 10509 10510 bool isTargetTypeAFunction() const { 10511 return TargetFunctionType->isFunctionType(); 10512 } 10513 10514 // [ToType] [Return] 10515 10516 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10517 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10518 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10519 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10520 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10521 } 10522 10523 // return true if any matching specializations were found 10524 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10525 const DeclAccessPair& CurAccessFunPair) { 10526 if (CXXMethodDecl *Method 10527 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10528 // Skip non-static function templates when converting to pointer, and 10529 // static when converting to member pointer. 10530 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10531 return false; 10532 } 10533 else if (TargetTypeIsNonStaticMemberFunction) 10534 return false; 10535 10536 // C++ [over.over]p2: 10537 // If the name is a function template, template argument deduction is 10538 // done (14.8.2.2), and if the argument deduction succeeds, the 10539 // resulting template argument list is used to generate a single 10540 // function template specialization, which is added to the set of 10541 // overloaded functions considered. 10542 FunctionDecl *Specialization = nullptr; 10543 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10544 if (Sema::TemplateDeductionResult Result 10545 = S.DeduceTemplateArguments(FunctionTemplate, 10546 &OvlExplicitTemplateArgs, 10547 TargetFunctionType, Specialization, 10548 Info, /*InOverloadResolution=*/true)) { 10549 // Make a note of the failed deduction for diagnostics. 10550 FailedCandidates.addCandidate() 10551 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10552 MakeDeductionFailureInfo(Context, Result, Info)); 10553 return false; 10554 } 10555 10556 // Template argument deduction ensures that we have an exact match or 10557 // compatible pointer-to-function arguments that would be adjusted by ICS. 10558 // This function template specicalization works. 10559 assert(S.isSameOrCompatibleFunctionType( 10560 Context.getCanonicalType(Specialization->getType()), 10561 Context.getCanonicalType(TargetFunctionType))); 10562 10563 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10564 return false; 10565 10566 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10567 return true; 10568 } 10569 10570 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10571 const DeclAccessPair& CurAccessFunPair) { 10572 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10573 // Skip non-static functions when converting to pointer, and static 10574 // when converting to member pointer. 10575 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10576 return false; 10577 } 10578 else if (TargetTypeIsNonStaticMemberFunction) 10579 return false; 10580 10581 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10582 if (S.getLangOpts().CUDA) 10583 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10584 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10585 return false; 10586 10587 // If any candidate has a placeholder return type, trigger its deduction 10588 // now. 10589 if (S.getLangOpts().CPlusPlus14 && 10590 FunDecl->getReturnType()->isUndeducedType() && 10591 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10592 HasComplained |= Complain; 10593 return false; 10594 } 10595 10596 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10597 return false; 10598 10599 // If we're in C, we need to support types that aren't exactly identical. 10600 if (!S.getLangOpts().CPlusPlus || 10601 candidateHasExactlyCorrectType(FunDecl)) { 10602 Matches.push_back(std::make_pair( 10603 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10604 FoundNonTemplateFunction = true; 10605 return true; 10606 } 10607 } 10608 10609 return false; 10610 } 10611 10612 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10613 bool Ret = false; 10614 10615 // If the overload expression doesn't have the form of a pointer to 10616 // member, don't try to convert it to a pointer-to-member type. 10617 if (IsInvalidFormOfPointerToMemberFunction()) 10618 return false; 10619 10620 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10621 E = OvlExpr->decls_end(); 10622 I != E; ++I) { 10623 // Look through any using declarations to find the underlying function. 10624 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10625 10626 // C++ [over.over]p3: 10627 // Non-member functions and static member functions match 10628 // targets of type "pointer-to-function" or "reference-to-function." 10629 // Nonstatic member functions match targets of 10630 // type "pointer-to-member-function." 10631 // Note that according to DR 247, the containing class does not matter. 10632 if (FunctionTemplateDecl *FunctionTemplate 10633 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10634 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10635 Ret = true; 10636 } 10637 // If we have explicit template arguments supplied, skip non-templates. 10638 else if (!OvlExpr->hasExplicitTemplateArgs() && 10639 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10640 Ret = true; 10641 } 10642 assert(Ret || Matches.empty()); 10643 return Ret; 10644 } 10645 10646 void EliminateAllExceptMostSpecializedTemplate() { 10647 // [...] and any given function template specialization F1 is 10648 // eliminated if the set contains a second function template 10649 // specialization whose function template is more specialized 10650 // than the function template of F1 according to the partial 10651 // ordering rules of 14.5.5.2. 10652 10653 // The algorithm specified above is quadratic. We instead use a 10654 // two-pass algorithm (similar to the one used to identify the 10655 // best viable function in an overload set) that identifies the 10656 // best function template (if it exists). 10657 10658 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10659 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10660 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10661 10662 // TODO: It looks like FailedCandidates does not serve much purpose 10663 // here, since the no_viable diagnostic has index 0. 10664 UnresolvedSetIterator Result = S.getMostSpecialized( 10665 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10666 SourceExpr->getLocStart(), S.PDiag(), 10667 S.PDiag(diag::err_addr_ovl_ambiguous) 10668 << Matches[0].second->getDeclName(), 10669 S.PDiag(diag::note_ovl_candidate) 10670 << (unsigned)oc_function_template, 10671 Complain, TargetFunctionType); 10672 10673 if (Result != MatchesCopy.end()) { 10674 // Make it the first and only element 10675 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10676 Matches[0].second = cast<FunctionDecl>(*Result); 10677 Matches.resize(1); 10678 } else 10679 HasComplained |= Complain; 10680 } 10681 10682 void EliminateAllTemplateMatches() { 10683 // [...] any function template specializations in the set are 10684 // eliminated if the set also contains a non-template function, [...] 10685 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10686 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10687 ++I; 10688 else { 10689 Matches[I] = Matches[--N]; 10690 Matches.resize(N); 10691 } 10692 } 10693 } 10694 10695 void EliminateSuboptimalCudaMatches() { 10696 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10697 } 10698 10699 public: 10700 void ComplainNoMatchesFound() const { 10701 assert(Matches.empty()); 10702 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10703 << OvlExpr->getName() << TargetFunctionType 10704 << OvlExpr->getSourceRange(); 10705 if (FailedCandidates.empty()) 10706 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10707 /*TakingAddress=*/true); 10708 else { 10709 // We have some deduction failure messages. Use them to diagnose 10710 // the function templates, and diagnose the non-template candidates 10711 // normally. 10712 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10713 IEnd = OvlExpr->decls_end(); 10714 I != IEnd; ++I) 10715 if (FunctionDecl *Fun = 10716 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10717 if (!functionHasPassObjectSizeParams(Fun)) 10718 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10719 /*TakingAddress=*/true); 10720 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10721 } 10722 } 10723 10724 bool IsInvalidFormOfPointerToMemberFunction() const { 10725 return TargetTypeIsNonStaticMemberFunction && 10726 !OvlExprInfo.HasFormOfMemberPointer; 10727 } 10728 10729 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10730 // TODO: Should we condition this on whether any functions might 10731 // have matched, or is it more appropriate to do that in callers? 10732 // TODO: a fixit wouldn't hurt. 10733 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10734 << TargetType << OvlExpr->getSourceRange(); 10735 } 10736 10737 bool IsStaticMemberFunctionFromBoundPointer() const { 10738 return StaticMemberFunctionFromBoundPointer; 10739 } 10740 10741 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10742 S.Diag(OvlExpr->getLocStart(), 10743 diag::err_invalid_form_pointer_member_function) 10744 << OvlExpr->getSourceRange(); 10745 } 10746 10747 void ComplainOfInvalidConversion() const { 10748 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10749 << OvlExpr->getName() << TargetType; 10750 } 10751 10752 void ComplainMultipleMatchesFound() const { 10753 assert(Matches.size() > 1); 10754 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10755 << OvlExpr->getName() 10756 << OvlExpr->getSourceRange(); 10757 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10758 /*TakingAddress=*/true); 10759 } 10760 10761 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10762 10763 int getNumMatches() const { return Matches.size(); } 10764 10765 FunctionDecl* getMatchingFunctionDecl() const { 10766 if (Matches.size() != 1) return nullptr; 10767 return Matches[0].second; 10768 } 10769 10770 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10771 if (Matches.size() != 1) return nullptr; 10772 return &Matches[0].first; 10773 } 10774 }; 10775 } 10776 10777 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10778 /// an overloaded function (C++ [over.over]), where @p From is an 10779 /// expression with overloaded function type and @p ToType is the type 10780 /// we're trying to resolve to. For example: 10781 /// 10782 /// @code 10783 /// int f(double); 10784 /// int f(int); 10785 /// 10786 /// int (*pfd)(double) = f; // selects f(double) 10787 /// @endcode 10788 /// 10789 /// This routine returns the resulting FunctionDecl if it could be 10790 /// resolved, and NULL otherwise. When @p Complain is true, this 10791 /// routine will emit diagnostics if there is an error. 10792 FunctionDecl * 10793 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10794 QualType TargetType, 10795 bool Complain, 10796 DeclAccessPair &FoundResult, 10797 bool *pHadMultipleCandidates) { 10798 assert(AddressOfExpr->getType() == Context.OverloadTy); 10799 10800 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10801 Complain); 10802 int NumMatches = Resolver.getNumMatches(); 10803 FunctionDecl *Fn = nullptr; 10804 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10805 if (NumMatches == 0 && ShouldComplain) { 10806 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10807 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10808 else 10809 Resolver.ComplainNoMatchesFound(); 10810 } 10811 else if (NumMatches > 1 && ShouldComplain) 10812 Resolver.ComplainMultipleMatchesFound(); 10813 else if (NumMatches == 1) { 10814 Fn = Resolver.getMatchingFunctionDecl(); 10815 assert(Fn); 10816 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10817 if (Complain) { 10818 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10819 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10820 else 10821 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10822 } 10823 } 10824 10825 if (pHadMultipleCandidates) 10826 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10827 return Fn; 10828 } 10829 10830 /// \brief Given an expression that refers to an overloaded function, try to 10831 /// resolve that function to a single function that can have its address taken. 10832 /// This will modify `Pair` iff it returns non-null. 10833 /// 10834 /// This routine can only realistically succeed if all but one candidates in the 10835 /// overload set for SrcExpr cannot have their addresses taken. 10836 FunctionDecl * 10837 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10838 DeclAccessPair &Pair) { 10839 OverloadExpr::FindResult R = OverloadExpr::find(E); 10840 OverloadExpr *Ovl = R.Expression; 10841 FunctionDecl *Result = nullptr; 10842 DeclAccessPair DAP; 10843 // Don't use the AddressOfResolver because we're specifically looking for 10844 // cases where we have one overload candidate that lacks 10845 // enable_if/pass_object_size/... 10846 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10847 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10848 if (!FD) 10849 return nullptr; 10850 10851 if (!checkAddressOfFunctionIsAvailable(FD)) 10852 continue; 10853 10854 // We have more than one result; quit. 10855 if (Result) 10856 return nullptr; 10857 DAP = I.getPair(); 10858 Result = FD; 10859 } 10860 10861 if (Result) 10862 Pair = DAP; 10863 return Result; 10864 } 10865 10866 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10867 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10868 /// will perform access checks, diagnose the use of the resultant decl, and, if 10869 /// necessary, perform a function-to-pointer decay. 10870 /// 10871 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10872 /// Otherwise, returns true. This may emit diagnostics and return true. 10873 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10874 ExprResult &SrcExpr) { 10875 Expr *E = SrcExpr.get(); 10876 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10877 10878 DeclAccessPair DAP; 10879 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10880 if (!Found) 10881 return false; 10882 10883 // Emitting multiple diagnostics for a function that is both inaccessible and 10884 // unavailable is consistent with our behavior elsewhere. So, always check 10885 // for both. 10886 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10887 CheckAddressOfMemberAccess(E, DAP); 10888 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10889 if (Fixed->getType()->isFunctionType()) 10890 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10891 else 10892 SrcExpr = Fixed; 10893 return true; 10894 } 10895 10896 /// \brief Given an expression that refers to an overloaded function, try to 10897 /// resolve that overloaded function expression down to a single function. 10898 /// 10899 /// This routine can only resolve template-ids that refer to a single function 10900 /// template, where that template-id refers to a single template whose template 10901 /// arguments are either provided by the template-id or have defaults, 10902 /// as described in C++0x [temp.arg.explicit]p3. 10903 /// 10904 /// If no template-ids are found, no diagnostics are emitted and NULL is 10905 /// returned. 10906 FunctionDecl * 10907 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10908 bool Complain, 10909 DeclAccessPair *FoundResult) { 10910 // C++ [over.over]p1: 10911 // [...] [Note: any redundant set of parentheses surrounding the 10912 // overloaded function name is ignored (5.1). ] 10913 // C++ [over.over]p1: 10914 // [...] The overloaded function name can be preceded by the & 10915 // operator. 10916 10917 // If we didn't actually find any template-ids, we're done. 10918 if (!ovl->hasExplicitTemplateArgs()) 10919 return nullptr; 10920 10921 TemplateArgumentListInfo ExplicitTemplateArgs; 10922 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10923 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10924 10925 // Look through all of the overloaded functions, searching for one 10926 // whose type matches exactly. 10927 FunctionDecl *Matched = nullptr; 10928 for (UnresolvedSetIterator I = ovl->decls_begin(), 10929 E = ovl->decls_end(); I != E; ++I) { 10930 // C++0x [temp.arg.explicit]p3: 10931 // [...] In contexts where deduction is done and fails, or in contexts 10932 // where deduction is not done, if a template argument list is 10933 // specified and it, along with any default template arguments, 10934 // identifies a single function template specialization, then the 10935 // template-id is an lvalue for the function template specialization. 10936 FunctionTemplateDecl *FunctionTemplate 10937 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10938 10939 // C++ [over.over]p2: 10940 // If the name is a function template, template argument deduction is 10941 // done (14.8.2.2), and if the argument deduction succeeds, the 10942 // resulting template argument list is used to generate a single 10943 // function template specialization, which is added to the set of 10944 // overloaded functions considered. 10945 FunctionDecl *Specialization = nullptr; 10946 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10947 if (TemplateDeductionResult Result 10948 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10949 Specialization, Info, 10950 /*InOverloadResolution=*/true)) { 10951 // Make a note of the failed deduction for diagnostics. 10952 // TODO: Actually use the failed-deduction info? 10953 FailedCandidates.addCandidate() 10954 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 10955 MakeDeductionFailureInfo(Context, Result, Info)); 10956 continue; 10957 } 10958 10959 assert(Specialization && "no specialization and no error?"); 10960 10961 // Multiple matches; we can't resolve to a single declaration. 10962 if (Matched) { 10963 if (Complain) { 10964 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10965 << ovl->getName(); 10966 NoteAllOverloadCandidates(ovl); 10967 } 10968 return nullptr; 10969 } 10970 10971 Matched = Specialization; 10972 if (FoundResult) *FoundResult = I.getPair(); 10973 } 10974 10975 if (Matched && getLangOpts().CPlusPlus14 && 10976 Matched->getReturnType()->isUndeducedType() && 10977 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10978 return nullptr; 10979 10980 return Matched; 10981 } 10982 10983 10984 10985 10986 // Resolve and fix an overloaded expression that can be resolved 10987 // because it identifies a single function template specialization. 10988 // 10989 // Last three arguments should only be supplied if Complain = true 10990 // 10991 // Return true if it was logically possible to so resolve the 10992 // expression, regardless of whether or not it succeeded. Always 10993 // returns true if 'complain' is set. 10994 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10995 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10996 bool complain, SourceRange OpRangeForComplaining, 10997 QualType DestTypeForComplaining, 10998 unsigned DiagIDForComplaining) { 10999 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11000 11001 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11002 11003 DeclAccessPair found; 11004 ExprResult SingleFunctionExpression; 11005 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11006 ovl.Expression, /*complain*/ false, &found)) { 11007 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11008 SrcExpr = ExprError(); 11009 return true; 11010 } 11011 11012 // It is only correct to resolve to an instance method if we're 11013 // resolving a form that's permitted to be a pointer to member. 11014 // Otherwise we'll end up making a bound member expression, which 11015 // is illegal in all the contexts we resolve like this. 11016 if (!ovl.HasFormOfMemberPointer && 11017 isa<CXXMethodDecl>(fn) && 11018 cast<CXXMethodDecl>(fn)->isInstance()) { 11019 if (!complain) return false; 11020 11021 Diag(ovl.Expression->getExprLoc(), 11022 diag::err_bound_member_function) 11023 << 0 << ovl.Expression->getSourceRange(); 11024 11025 // TODO: I believe we only end up here if there's a mix of 11026 // static and non-static candidates (otherwise the expression 11027 // would have 'bound member' type, not 'overload' type). 11028 // Ideally we would note which candidate was chosen and why 11029 // the static candidates were rejected. 11030 SrcExpr = ExprError(); 11031 return true; 11032 } 11033 11034 // Fix the expression to refer to 'fn'. 11035 SingleFunctionExpression = 11036 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11037 11038 // If desired, do function-to-pointer decay. 11039 if (doFunctionPointerConverion) { 11040 SingleFunctionExpression = 11041 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11042 if (SingleFunctionExpression.isInvalid()) { 11043 SrcExpr = ExprError(); 11044 return true; 11045 } 11046 } 11047 } 11048 11049 if (!SingleFunctionExpression.isUsable()) { 11050 if (complain) { 11051 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11052 << ovl.Expression->getName() 11053 << DestTypeForComplaining 11054 << OpRangeForComplaining 11055 << ovl.Expression->getQualifierLoc().getSourceRange(); 11056 NoteAllOverloadCandidates(SrcExpr.get()); 11057 11058 SrcExpr = ExprError(); 11059 return true; 11060 } 11061 11062 return false; 11063 } 11064 11065 SrcExpr = SingleFunctionExpression; 11066 return true; 11067 } 11068 11069 /// \brief Add a single candidate to the overload set. 11070 static void AddOverloadedCallCandidate(Sema &S, 11071 DeclAccessPair FoundDecl, 11072 TemplateArgumentListInfo *ExplicitTemplateArgs, 11073 ArrayRef<Expr *> Args, 11074 OverloadCandidateSet &CandidateSet, 11075 bool PartialOverloading, 11076 bool KnownValid) { 11077 NamedDecl *Callee = FoundDecl.getDecl(); 11078 if (isa<UsingShadowDecl>(Callee)) 11079 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11080 11081 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11082 if (ExplicitTemplateArgs) { 11083 assert(!KnownValid && "Explicit template arguments?"); 11084 return; 11085 } 11086 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11087 /*SuppressUsedConversions=*/false, 11088 PartialOverloading); 11089 return; 11090 } 11091 11092 if (FunctionTemplateDecl *FuncTemplate 11093 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11094 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11095 ExplicitTemplateArgs, Args, CandidateSet, 11096 /*SuppressUsedConversions=*/false, 11097 PartialOverloading); 11098 return; 11099 } 11100 11101 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11102 } 11103 11104 /// \brief Add the overload candidates named by callee and/or found by argument 11105 /// dependent lookup to the given overload set. 11106 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11107 ArrayRef<Expr *> Args, 11108 OverloadCandidateSet &CandidateSet, 11109 bool PartialOverloading) { 11110 11111 #ifndef NDEBUG 11112 // Verify that ArgumentDependentLookup is consistent with the rules 11113 // in C++0x [basic.lookup.argdep]p3: 11114 // 11115 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11116 // and let Y be the lookup set produced by argument dependent 11117 // lookup (defined as follows). If X contains 11118 // 11119 // -- a declaration of a class member, or 11120 // 11121 // -- a block-scope function declaration that is not a 11122 // using-declaration, or 11123 // 11124 // -- a declaration that is neither a function or a function 11125 // template 11126 // 11127 // then Y is empty. 11128 11129 if (ULE->requiresADL()) { 11130 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11131 E = ULE->decls_end(); I != E; ++I) { 11132 assert(!(*I)->getDeclContext()->isRecord()); 11133 assert(isa<UsingShadowDecl>(*I) || 11134 !(*I)->getDeclContext()->isFunctionOrMethod()); 11135 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11136 } 11137 } 11138 #endif 11139 11140 // It would be nice to avoid this copy. 11141 TemplateArgumentListInfo TABuffer; 11142 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11143 if (ULE->hasExplicitTemplateArgs()) { 11144 ULE->copyTemplateArgumentsInto(TABuffer); 11145 ExplicitTemplateArgs = &TABuffer; 11146 } 11147 11148 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11149 E = ULE->decls_end(); I != E; ++I) 11150 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11151 CandidateSet, PartialOverloading, 11152 /*KnownValid*/ true); 11153 11154 if (ULE->requiresADL()) 11155 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11156 Args, ExplicitTemplateArgs, 11157 CandidateSet, PartialOverloading); 11158 } 11159 11160 /// Determine whether a declaration with the specified name could be moved into 11161 /// a different namespace. 11162 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11163 switch (Name.getCXXOverloadedOperator()) { 11164 case OO_New: case OO_Array_New: 11165 case OO_Delete: case OO_Array_Delete: 11166 return false; 11167 11168 default: 11169 return true; 11170 } 11171 } 11172 11173 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11174 /// template, where the non-dependent name was declared after the template 11175 /// was defined. This is common in code written for a compilers which do not 11176 /// correctly implement two-stage name lookup. 11177 /// 11178 /// Returns true if a viable candidate was found and a diagnostic was issued. 11179 static bool 11180 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11181 const CXXScopeSpec &SS, LookupResult &R, 11182 OverloadCandidateSet::CandidateSetKind CSK, 11183 TemplateArgumentListInfo *ExplicitTemplateArgs, 11184 ArrayRef<Expr *> Args, 11185 bool *DoDiagnoseEmptyLookup = nullptr) { 11186 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11187 return false; 11188 11189 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11190 if (DC->isTransparentContext()) 11191 continue; 11192 11193 SemaRef.LookupQualifiedName(R, DC); 11194 11195 if (!R.empty()) { 11196 R.suppressDiagnostics(); 11197 11198 if (isa<CXXRecordDecl>(DC)) { 11199 // Don't diagnose names we find in classes; we get much better 11200 // diagnostics for these from DiagnoseEmptyLookup. 11201 R.clear(); 11202 if (DoDiagnoseEmptyLookup) 11203 *DoDiagnoseEmptyLookup = true; 11204 return false; 11205 } 11206 11207 OverloadCandidateSet Candidates(FnLoc, CSK); 11208 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11209 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11210 ExplicitTemplateArgs, Args, 11211 Candidates, false, /*KnownValid*/ false); 11212 11213 OverloadCandidateSet::iterator Best; 11214 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11215 // No viable functions. Don't bother the user with notes for functions 11216 // which don't work and shouldn't be found anyway. 11217 R.clear(); 11218 return false; 11219 } 11220 11221 // Find the namespaces where ADL would have looked, and suggest 11222 // declaring the function there instead. 11223 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11224 Sema::AssociatedClassSet AssociatedClasses; 11225 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11226 AssociatedNamespaces, 11227 AssociatedClasses); 11228 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11229 if (canBeDeclaredInNamespace(R.getLookupName())) { 11230 DeclContext *Std = SemaRef.getStdNamespace(); 11231 for (Sema::AssociatedNamespaceSet::iterator 11232 it = AssociatedNamespaces.begin(), 11233 end = AssociatedNamespaces.end(); it != end; ++it) { 11234 // Never suggest declaring a function within namespace 'std'. 11235 if (Std && Std->Encloses(*it)) 11236 continue; 11237 11238 // Never suggest declaring a function within a namespace with a 11239 // reserved name, like __gnu_cxx. 11240 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11241 if (NS && 11242 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11243 continue; 11244 11245 SuggestedNamespaces.insert(*it); 11246 } 11247 } 11248 11249 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11250 << R.getLookupName(); 11251 if (SuggestedNamespaces.empty()) { 11252 SemaRef.Diag(Best->Function->getLocation(), 11253 diag::note_not_found_by_two_phase_lookup) 11254 << R.getLookupName() << 0; 11255 } else if (SuggestedNamespaces.size() == 1) { 11256 SemaRef.Diag(Best->Function->getLocation(), 11257 diag::note_not_found_by_two_phase_lookup) 11258 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11259 } else { 11260 // FIXME: It would be useful to list the associated namespaces here, 11261 // but the diagnostics infrastructure doesn't provide a way to produce 11262 // a localized representation of a list of items. 11263 SemaRef.Diag(Best->Function->getLocation(), 11264 diag::note_not_found_by_two_phase_lookup) 11265 << R.getLookupName() << 2; 11266 } 11267 11268 // Try to recover by calling this function. 11269 return true; 11270 } 11271 11272 R.clear(); 11273 } 11274 11275 return false; 11276 } 11277 11278 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11279 /// template, where the non-dependent operator was declared after the template 11280 /// was defined. 11281 /// 11282 /// Returns true if a viable candidate was found and a diagnostic was issued. 11283 static bool 11284 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11285 SourceLocation OpLoc, 11286 ArrayRef<Expr *> Args) { 11287 DeclarationName OpName = 11288 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11289 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11290 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11291 OverloadCandidateSet::CSK_Operator, 11292 /*ExplicitTemplateArgs=*/nullptr, Args); 11293 } 11294 11295 namespace { 11296 class BuildRecoveryCallExprRAII { 11297 Sema &SemaRef; 11298 public: 11299 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11300 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11301 SemaRef.IsBuildingRecoveryCallExpr = true; 11302 } 11303 11304 ~BuildRecoveryCallExprRAII() { 11305 SemaRef.IsBuildingRecoveryCallExpr = false; 11306 } 11307 }; 11308 11309 } 11310 11311 static std::unique_ptr<CorrectionCandidateCallback> 11312 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11313 bool HasTemplateArgs, bool AllowTypoCorrection) { 11314 if (!AllowTypoCorrection) 11315 return llvm::make_unique<NoTypoCorrectionCCC>(); 11316 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11317 HasTemplateArgs, ME); 11318 } 11319 11320 /// Attempts to recover from a call where no functions were found. 11321 /// 11322 /// Returns true if new candidates were found. 11323 static ExprResult 11324 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11325 UnresolvedLookupExpr *ULE, 11326 SourceLocation LParenLoc, 11327 MutableArrayRef<Expr *> Args, 11328 SourceLocation RParenLoc, 11329 bool EmptyLookup, bool AllowTypoCorrection) { 11330 // Do not try to recover if it is already building a recovery call. 11331 // This stops infinite loops for template instantiations like 11332 // 11333 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11334 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11335 // 11336 if (SemaRef.IsBuildingRecoveryCallExpr) 11337 return ExprError(); 11338 BuildRecoveryCallExprRAII RCE(SemaRef); 11339 11340 CXXScopeSpec SS; 11341 SS.Adopt(ULE->getQualifierLoc()); 11342 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11343 11344 TemplateArgumentListInfo TABuffer; 11345 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11346 if (ULE->hasExplicitTemplateArgs()) { 11347 ULE->copyTemplateArgumentsInto(TABuffer); 11348 ExplicitTemplateArgs = &TABuffer; 11349 } 11350 11351 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11352 Sema::LookupOrdinaryName); 11353 bool DoDiagnoseEmptyLookup = EmptyLookup; 11354 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11355 OverloadCandidateSet::CSK_Normal, 11356 ExplicitTemplateArgs, Args, 11357 &DoDiagnoseEmptyLookup) && 11358 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11359 S, SS, R, 11360 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11361 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11362 ExplicitTemplateArgs, Args))) 11363 return ExprError(); 11364 11365 assert(!R.empty() && "lookup results empty despite recovery"); 11366 11367 // Build an implicit member call if appropriate. Just drop the 11368 // casts and such from the call, we don't really care. 11369 ExprResult NewFn = ExprError(); 11370 if ((*R.begin())->isCXXClassMember()) 11371 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11372 ExplicitTemplateArgs, S); 11373 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11374 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11375 ExplicitTemplateArgs); 11376 else 11377 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11378 11379 if (NewFn.isInvalid()) 11380 return ExprError(); 11381 11382 // This shouldn't cause an infinite loop because we're giving it 11383 // an expression with viable lookup results, which should never 11384 // end up here. 11385 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11386 MultiExprArg(Args.data(), Args.size()), 11387 RParenLoc); 11388 } 11389 11390 /// \brief Constructs and populates an OverloadedCandidateSet from 11391 /// the given function. 11392 /// \returns true when an the ExprResult output parameter has been set. 11393 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11394 UnresolvedLookupExpr *ULE, 11395 MultiExprArg Args, 11396 SourceLocation RParenLoc, 11397 OverloadCandidateSet *CandidateSet, 11398 ExprResult *Result) { 11399 #ifndef NDEBUG 11400 if (ULE->requiresADL()) { 11401 // To do ADL, we must have found an unqualified name. 11402 assert(!ULE->getQualifier() && "qualified name with ADL"); 11403 11404 // We don't perform ADL for implicit declarations of builtins. 11405 // Verify that this was correctly set up. 11406 FunctionDecl *F; 11407 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11408 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11409 F->getBuiltinID() && F->isImplicit()) 11410 llvm_unreachable("performing ADL for builtin"); 11411 11412 // We don't perform ADL in C. 11413 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11414 } 11415 #endif 11416 11417 UnbridgedCastsSet UnbridgedCasts; 11418 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11419 *Result = ExprError(); 11420 return true; 11421 } 11422 11423 // Add the functions denoted by the callee to the set of candidate 11424 // functions, including those from argument-dependent lookup. 11425 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11426 11427 if (getLangOpts().MSVCCompat && 11428 CurContext->isDependentContext() && !isSFINAEContext() && 11429 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11430 11431 OverloadCandidateSet::iterator Best; 11432 if (CandidateSet->empty() || 11433 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11434 OR_No_Viable_Function) { 11435 // In Microsoft mode, if we are inside a template class member function then 11436 // create a type dependent CallExpr. The goal is to postpone name lookup 11437 // to instantiation time to be able to search into type dependent base 11438 // classes. 11439 CallExpr *CE = new (Context) CallExpr( 11440 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11441 CE->setTypeDependent(true); 11442 CE->setValueDependent(true); 11443 CE->setInstantiationDependent(true); 11444 *Result = CE; 11445 return true; 11446 } 11447 } 11448 11449 if (CandidateSet->empty()) 11450 return false; 11451 11452 UnbridgedCasts.restore(); 11453 return false; 11454 } 11455 11456 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11457 /// the completed call expression. If overload resolution fails, emits 11458 /// diagnostics and returns ExprError() 11459 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11460 UnresolvedLookupExpr *ULE, 11461 SourceLocation LParenLoc, 11462 MultiExprArg Args, 11463 SourceLocation RParenLoc, 11464 Expr *ExecConfig, 11465 OverloadCandidateSet *CandidateSet, 11466 OverloadCandidateSet::iterator *Best, 11467 OverloadingResult OverloadResult, 11468 bool AllowTypoCorrection) { 11469 if (CandidateSet->empty()) 11470 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11471 RParenLoc, /*EmptyLookup=*/true, 11472 AllowTypoCorrection); 11473 11474 switch (OverloadResult) { 11475 case OR_Success: { 11476 FunctionDecl *FDecl = (*Best)->Function; 11477 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11478 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11479 return ExprError(); 11480 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11481 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11482 ExecConfig); 11483 } 11484 11485 case OR_No_Viable_Function: { 11486 // Try to recover by looking for viable functions which the user might 11487 // have meant to call. 11488 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11489 Args, RParenLoc, 11490 /*EmptyLookup=*/false, 11491 AllowTypoCorrection); 11492 if (!Recovery.isInvalid()) 11493 return Recovery; 11494 11495 // If the user passes in a function that we can't take the address of, we 11496 // generally end up emitting really bad error messages. Here, we attempt to 11497 // emit better ones. 11498 for (const Expr *Arg : Args) { 11499 if (!Arg->getType()->isFunctionType()) 11500 continue; 11501 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11502 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11503 if (FD && 11504 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11505 Arg->getExprLoc())) 11506 return ExprError(); 11507 } 11508 } 11509 11510 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11511 << ULE->getName() << Fn->getSourceRange(); 11512 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11513 break; 11514 } 11515 11516 case OR_Ambiguous: 11517 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11518 << ULE->getName() << Fn->getSourceRange(); 11519 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11520 break; 11521 11522 case OR_Deleted: { 11523 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11524 << (*Best)->Function->isDeleted() 11525 << ULE->getName() 11526 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11527 << Fn->getSourceRange(); 11528 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11529 11530 // We emitted an error for the unvailable/deleted function call but keep 11531 // the call in the AST. 11532 FunctionDecl *FDecl = (*Best)->Function; 11533 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11534 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11535 ExecConfig); 11536 } 11537 } 11538 11539 // Overload resolution failed. 11540 return ExprError(); 11541 } 11542 11543 static void markUnaddressableCandidatesUnviable(Sema &S, 11544 OverloadCandidateSet &CS) { 11545 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11546 if (I->Viable && 11547 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11548 I->Viable = false; 11549 I->FailureKind = ovl_fail_addr_not_available; 11550 } 11551 } 11552 } 11553 11554 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11555 /// (which eventually refers to the declaration Func) and the call 11556 /// arguments Args/NumArgs, attempt to resolve the function call down 11557 /// to a specific function. If overload resolution succeeds, returns 11558 /// the call expression produced by overload resolution. 11559 /// Otherwise, emits diagnostics and returns ExprError. 11560 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11561 UnresolvedLookupExpr *ULE, 11562 SourceLocation LParenLoc, 11563 MultiExprArg Args, 11564 SourceLocation RParenLoc, 11565 Expr *ExecConfig, 11566 bool AllowTypoCorrection, 11567 bool CalleesAddressIsTaken) { 11568 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11569 OverloadCandidateSet::CSK_Normal); 11570 ExprResult result; 11571 11572 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11573 &result)) 11574 return result; 11575 11576 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11577 // functions that aren't addressible are considered unviable. 11578 if (CalleesAddressIsTaken) 11579 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11580 11581 OverloadCandidateSet::iterator Best; 11582 OverloadingResult OverloadResult = 11583 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11584 11585 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11586 RParenLoc, ExecConfig, &CandidateSet, 11587 &Best, OverloadResult, 11588 AllowTypoCorrection); 11589 } 11590 11591 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11592 return Functions.size() > 1 || 11593 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11594 } 11595 11596 /// \brief Create a unary operation that may resolve to an overloaded 11597 /// operator. 11598 /// 11599 /// \param OpLoc The location of the operator itself (e.g., '*'). 11600 /// 11601 /// \param Opc The UnaryOperatorKind that describes this operator. 11602 /// 11603 /// \param Fns The set of non-member functions that will be 11604 /// considered by overload resolution. The caller needs to build this 11605 /// set based on the context using, e.g., 11606 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11607 /// set should not contain any member functions; those will be added 11608 /// by CreateOverloadedUnaryOp(). 11609 /// 11610 /// \param Input The input argument. 11611 ExprResult 11612 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11613 const UnresolvedSetImpl &Fns, 11614 Expr *Input) { 11615 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11616 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11617 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11618 // TODO: provide better source location info. 11619 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11620 11621 if (checkPlaceholderForOverload(*this, Input)) 11622 return ExprError(); 11623 11624 Expr *Args[2] = { Input, nullptr }; 11625 unsigned NumArgs = 1; 11626 11627 // For post-increment and post-decrement, add the implicit '0' as 11628 // the second argument, so that we know this is a post-increment or 11629 // post-decrement. 11630 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11631 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11632 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11633 SourceLocation()); 11634 NumArgs = 2; 11635 } 11636 11637 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11638 11639 if (Input->isTypeDependent()) { 11640 if (Fns.empty()) 11641 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11642 VK_RValue, OK_Ordinary, OpLoc); 11643 11644 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11645 UnresolvedLookupExpr *Fn 11646 = UnresolvedLookupExpr::Create(Context, NamingClass, 11647 NestedNameSpecifierLoc(), OpNameInfo, 11648 /*ADL*/ true, IsOverloaded(Fns), 11649 Fns.begin(), Fns.end()); 11650 return new (Context) 11651 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11652 VK_RValue, OpLoc, false); 11653 } 11654 11655 // Build an empty overload set. 11656 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11657 11658 // Add the candidates from the given function set. 11659 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11660 11661 // Add operator candidates that are member functions. 11662 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11663 11664 // Add candidates from ADL. 11665 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11666 /*ExplicitTemplateArgs*/nullptr, 11667 CandidateSet); 11668 11669 // Add builtin operator candidates. 11670 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11671 11672 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11673 11674 // Perform overload resolution. 11675 OverloadCandidateSet::iterator Best; 11676 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11677 case OR_Success: { 11678 // We found a built-in operator or an overloaded operator. 11679 FunctionDecl *FnDecl = Best->Function; 11680 11681 if (FnDecl) { 11682 // We matched an overloaded operator. Build a call to that 11683 // operator. 11684 11685 // Convert the arguments. 11686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11687 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11688 11689 ExprResult InputRes = 11690 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11691 Best->FoundDecl, Method); 11692 if (InputRes.isInvalid()) 11693 return ExprError(); 11694 Input = InputRes.get(); 11695 } else { 11696 // Convert the arguments. 11697 ExprResult InputInit 11698 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11699 Context, 11700 FnDecl->getParamDecl(0)), 11701 SourceLocation(), 11702 Input); 11703 if (InputInit.isInvalid()) 11704 return ExprError(); 11705 Input = InputInit.get(); 11706 } 11707 11708 // Build the actual expression node. 11709 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11710 HadMultipleCandidates, OpLoc); 11711 if (FnExpr.isInvalid()) 11712 return ExprError(); 11713 11714 // Determine the result type. 11715 QualType ResultTy = FnDecl->getReturnType(); 11716 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11717 ResultTy = ResultTy.getNonLValueExprType(Context); 11718 11719 Args[0] = Input; 11720 CallExpr *TheCall = 11721 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11722 ResultTy, VK, OpLoc, false); 11723 11724 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11725 return ExprError(); 11726 11727 return MaybeBindToTemporary(TheCall); 11728 } else { 11729 // We matched a built-in operator. Convert the arguments, then 11730 // break out so that we will build the appropriate built-in 11731 // operator node. 11732 ExprResult InputRes = 11733 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11734 Best->Conversions[0], AA_Passing); 11735 if (InputRes.isInvalid()) 11736 return ExprError(); 11737 Input = InputRes.get(); 11738 break; 11739 } 11740 } 11741 11742 case OR_No_Viable_Function: 11743 // This is an erroneous use of an operator which can be overloaded by 11744 // a non-member function. Check for non-member operators which were 11745 // defined too late to be candidates. 11746 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11747 // FIXME: Recover by calling the found function. 11748 return ExprError(); 11749 11750 // No viable function; fall through to handling this as a 11751 // built-in operator, which will produce an error message for us. 11752 break; 11753 11754 case OR_Ambiguous: 11755 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11756 << UnaryOperator::getOpcodeStr(Opc) 11757 << Input->getType() 11758 << Input->getSourceRange(); 11759 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11760 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11761 return ExprError(); 11762 11763 case OR_Deleted: 11764 Diag(OpLoc, diag::err_ovl_deleted_oper) 11765 << Best->Function->isDeleted() 11766 << UnaryOperator::getOpcodeStr(Opc) 11767 << getDeletedOrUnavailableSuffix(Best->Function) 11768 << Input->getSourceRange(); 11769 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11770 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11771 return ExprError(); 11772 } 11773 11774 // Either we found no viable overloaded operator or we matched a 11775 // built-in operator. In either case, fall through to trying to 11776 // build a built-in operation. 11777 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11778 } 11779 11780 /// \brief Create a binary operation that may resolve to an overloaded 11781 /// operator. 11782 /// 11783 /// \param OpLoc The location of the operator itself (e.g., '+'). 11784 /// 11785 /// \param Opc The BinaryOperatorKind that describes this operator. 11786 /// 11787 /// \param Fns The set of non-member functions that will be 11788 /// considered by overload resolution. The caller needs to build this 11789 /// set based on the context using, e.g., 11790 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11791 /// set should not contain any member functions; those will be added 11792 /// by CreateOverloadedBinOp(). 11793 /// 11794 /// \param LHS Left-hand argument. 11795 /// \param RHS Right-hand argument. 11796 ExprResult 11797 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11798 BinaryOperatorKind Opc, 11799 const UnresolvedSetImpl &Fns, 11800 Expr *LHS, Expr *RHS) { 11801 Expr *Args[2] = { LHS, RHS }; 11802 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11803 11804 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11805 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11806 11807 // If either side is type-dependent, create an appropriate dependent 11808 // expression. 11809 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11810 if (Fns.empty()) { 11811 // If there are no functions to store, just build a dependent 11812 // BinaryOperator or CompoundAssignment. 11813 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11814 return new (Context) BinaryOperator( 11815 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11816 OpLoc, FPFeatures.fp_contract); 11817 11818 return new (Context) CompoundAssignOperator( 11819 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11820 Context.DependentTy, Context.DependentTy, OpLoc, 11821 FPFeatures.fp_contract); 11822 } 11823 11824 // FIXME: save results of ADL from here? 11825 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11826 // TODO: provide better source location info in DNLoc component. 11827 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11828 UnresolvedLookupExpr *Fn 11829 = UnresolvedLookupExpr::Create(Context, NamingClass, 11830 NestedNameSpecifierLoc(), OpNameInfo, 11831 /*ADL*/ true, IsOverloaded(Fns), 11832 Fns.begin(), Fns.end()); 11833 return new (Context) 11834 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11835 VK_RValue, OpLoc, FPFeatures.fp_contract); 11836 } 11837 11838 // Always do placeholder-like conversions on the RHS. 11839 if (checkPlaceholderForOverload(*this, Args[1])) 11840 return ExprError(); 11841 11842 // Do placeholder-like conversion on the LHS; note that we should 11843 // not get here with a PseudoObject LHS. 11844 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11845 if (checkPlaceholderForOverload(*this, Args[0])) 11846 return ExprError(); 11847 11848 // If this is the assignment operator, we only perform overload resolution 11849 // if the left-hand side is a class or enumeration type. This is actually 11850 // a hack. The standard requires that we do overload resolution between the 11851 // various built-in candidates, but as DR507 points out, this can lead to 11852 // problems. So we do it this way, which pretty much follows what GCC does. 11853 // Note that we go the traditional code path for compound assignment forms. 11854 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11855 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11856 11857 // If this is the .* operator, which is not overloadable, just 11858 // create a built-in binary operator. 11859 if (Opc == BO_PtrMemD) 11860 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11861 11862 // Build an empty overload set. 11863 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11864 11865 // Add the candidates from the given function set. 11866 AddFunctionCandidates(Fns, Args, CandidateSet); 11867 11868 // Add operator candidates that are member functions. 11869 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11870 11871 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11872 // performed for an assignment operator (nor for operator[] nor operator->, 11873 // which don't get here). 11874 if (Opc != BO_Assign) 11875 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11876 /*ExplicitTemplateArgs*/ nullptr, 11877 CandidateSet); 11878 11879 // Add builtin operator candidates. 11880 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11881 11882 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11883 11884 // Perform overload resolution. 11885 OverloadCandidateSet::iterator Best; 11886 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11887 case OR_Success: { 11888 // We found a built-in operator or an overloaded operator. 11889 FunctionDecl *FnDecl = Best->Function; 11890 11891 if (FnDecl) { 11892 // We matched an overloaded operator. Build a call to that 11893 // operator. 11894 11895 // Convert the arguments. 11896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11897 // Best->Access is only meaningful for class members. 11898 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11899 11900 ExprResult Arg1 = 11901 PerformCopyInitialization( 11902 InitializedEntity::InitializeParameter(Context, 11903 FnDecl->getParamDecl(0)), 11904 SourceLocation(), Args[1]); 11905 if (Arg1.isInvalid()) 11906 return ExprError(); 11907 11908 ExprResult Arg0 = 11909 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11910 Best->FoundDecl, Method); 11911 if (Arg0.isInvalid()) 11912 return ExprError(); 11913 Args[0] = Arg0.getAs<Expr>(); 11914 Args[1] = RHS = Arg1.getAs<Expr>(); 11915 } else { 11916 // Convert the arguments. 11917 ExprResult Arg0 = PerformCopyInitialization( 11918 InitializedEntity::InitializeParameter(Context, 11919 FnDecl->getParamDecl(0)), 11920 SourceLocation(), Args[0]); 11921 if (Arg0.isInvalid()) 11922 return ExprError(); 11923 11924 ExprResult Arg1 = 11925 PerformCopyInitialization( 11926 InitializedEntity::InitializeParameter(Context, 11927 FnDecl->getParamDecl(1)), 11928 SourceLocation(), Args[1]); 11929 if (Arg1.isInvalid()) 11930 return ExprError(); 11931 Args[0] = LHS = Arg0.getAs<Expr>(); 11932 Args[1] = RHS = Arg1.getAs<Expr>(); 11933 } 11934 11935 // Build the actual expression node. 11936 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11937 Best->FoundDecl, 11938 HadMultipleCandidates, OpLoc); 11939 if (FnExpr.isInvalid()) 11940 return ExprError(); 11941 11942 // Determine the result type. 11943 QualType ResultTy = FnDecl->getReturnType(); 11944 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11945 ResultTy = ResultTy.getNonLValueExprType(Context); 11946 11947 CXXOperatorCallExpr *TheCall = 11948 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11949 Args, ResultTy, VK, OpLoc, 11950 FPFeatures.fp_contract); 11951 11952 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11953 FnDecl)) 11954 return ExprError(); 11955 11956 ArrayRef<const Expr *> ArgsArray(Args, 2); 11957 // Cut off the implicit 'this'. 11958 if (isa<CXXMethodDecl>(FnDecl)) 11959 ArgsArray = ArgsArray.slice(1); 11960 11961 // Check for a self move. 11962 if (Op == OO_Equal) 11963 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11964 11965 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11966 TheCall->getSourceRange(), VariadicDoesNotApply); 11967 11968 return MaybeBindToTemporary(TheCall); 11969 } else { 11970 // We matched a built-in operator. Convert the arguments, then 11971 // break out so that we will build the appropriate built-in 11972 // operator node. 11973 ExprResult ArgsRes0 = 11974 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11975 Best->Conversions[0], AA_Passing); 11976 if (ArgsRes0.isInvalid()) 11977 return ExprError(); 11978 Args[0] = ArgsRes0.get(); 11979 11980 ExprResult ArgsRes1 = 11981 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11982 Best->Conversions[1], AA_Passing); 11983 if (ArgsRes1.isInvalid()) 11984 return ExprError(); 11985 Args[1] = ArgsRes1.get(); 11986 break; 11987 } 11988 } 11989 11990 case OR_No_Viable_Function: { 11991 // C++ [over.match.oper]p9: 11992 // If the operator is the operator , [...] and there are no 11993 // viable functions, then the operator is assumed to be the 11994 // built-in operator and interpreted according to clause 5. 11995 if (Opc == BO_Comma) 11996 break; 11997 11998 // For class as left operand for assignment or compound assigment 11999 // operator do not fall through to handling in built-in, but report that 12000 // no overloaded assignment operator found 12001 ExprResult Result = ExprError(); 12002 if (Args[0]->getType()->isRecordType() && 12003 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12004 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12005 << BinaryOperator::getOpcodeStr(Opc) 12006 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12007 if (Args[0]->getType()->isIncompleteType()) { 12008 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12009 << Args[0]->getType() 12010 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12011 } 12012 } else { 12013 // This is an erroneous use of an operator which can be overloaded by 12014 // a non-member function. Check for non-member operators which were 12015 // defined too late to be candidates. 12016 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12017 // FIXME: Recover by calling the found function. 12018 return ExprError(); 12019 12020 // No viable function; try to create a built-in operation, which will 12021 // produce an error. Then, show the non-viable candidates. 12022 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12023 } 12024 assert(Result.isInvalid() && 12025 "C++ binary operator overloading is missing candidates!"); 12026 if (Result.isInvalid()) 12027 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12028 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12029 return Result; 12030 } 12031 12032 case OR_Ambiguous: 12033 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12034 << BinaryOperator::getOpcodeStr(Opc) 12035 << Args[0]->getType() << Args[1]->getType() 12036 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12037 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12038 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12039 return ExprError(); 12040 12041 case OR_Deleted: 12042 if (isImplicitlyDeleted(Best->Function)) { 12043 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12044 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12045 << Context.getRecordType(Method->getParent()) 12046 << getSpecialMember(Method); 12047 12048 // The user probably meant to call this special member. Just 12049 // explain why it's deleted. 12050 NoteDeletedFunction(Method); 12051 return ExprError(); 12052 } else { 12053 Diag(OpLoc, diag::err_ovl_deleted_oper) 12054 << Best->Function->isDeleted() 12055 << BinaryOperator::getOpcodeStr(Opc) 12056 << getDeletedOrUnavailableSuffix(Best->Function) 12057 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12058 } 12059 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12060 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12061 return ExprError(); 12062 } 12063 12064 // We matched a built-in operator; build it. 12065 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12066 } 12067 12068 ExprResult 12069 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12070 SourceLocation RLoc, 12071 Expr *Base, Expr *Idx) { 12072 Expr *Args[2] = { Base, Idx }; 12073 DeclarationName OpName = 12074 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12075 12076 // If either side is type-dependent, create an appropriate dependent 12077 // expression. 12078 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12079 12080 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12081 // CHECKME: no 'operator' keyword? 12082 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12083 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12084 UnresolvedLookupExpr *Fn 12085 = UnresolvedLookupExpr::Create(Context, NamingClass, 12086 NestedNameSpecifierLoc(), OpNameInfo, 12087 /*ADL*/ true, /*Overloaded*/ false, 12088 UnresolvedSetIterator(), 12089 UnresolvedSetIterator()); 12090 // Can't add any actual overloads yet 12091 12092 return new (Context) 12093 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12094 Context.DependentTy, VK_RValue, RLoc, false); 12095 } 12096 12097 // Handle placeholders on both operands. 12098 if (checkPlaceholderForOverload(*this, Args[0])) 12099 return ExprError(); 12100 if (checkPlaceholderForOverload(*this, Args[1])) 12101 return ExprError(); 12102 12103 // Build an empty overload set. 12104 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12105 12106 // Subscript can only be overloaded as a member function. 12107 12108 // Add operator candidates that are member functions. 12109 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12110 12111 // Add builtin operator candidates. 12112 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12113 12114 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12115 12116 // Perform overload resolution. 12117 OverloadCandidateSet::iterator Best; 12118 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12119 case OR_Success: { 12120 // We found a built-in operator or an overloaded operator. 12121 FunctionDecl *FnDecl = Best->Function; 12122 12123 if (FnDecl) { 12124 // We matched an overloaded operator. Build a call to that 12125 // operator. 12126 12127 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12128 12129 // Convert the arguments. 12130 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12131 ExprResult Arg0 = 12132 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12133 Best->FoundDecl, Method); 12134 if (Arg0.isInvalid()) 12135 return ExprError(); 12136 Args[0] = Arg0.get(); 12137 12138 // Convert the arguments. 12139 ExprResult InputInit 12140 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12141 Context, 12142 FnDecl->getParamDecl(0)), 12143 SourceLocation(), 12144 Args[1]); 12145 if (InputInit.isInvalid()) 12146 return ExprError(); 12147 12148 Args[1] = InputInit.getAs<Expr>(); 12149 12150 // Build the actual expression node. 12151 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12152 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12153 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12154 Best->FoundDecl, 12155 HadMultipleCandidates, 12156 OpLocInfo.getLoc(), 12157 OpLocInfo.getInfo()); 12158 if (FnExpr.isInvalid()) 12159 return ExprError(); 12160 12161 // Determine the result type 12162 QualType ResultTy = FnDecl->getReturnType(); 12163 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12164 ResultTy = ResultTy.getNonLValueExprType(Context); 12165 12166 CXXOperatorCallExpr *TheCall = 12167 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12168 FnExpr.get(), Args, 12169 ResultTy, VK, RLoc, 12170 false); 12171 12172 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12173 return ExprError(); 12174 12175 return MaybeBindToTemporary(TheCall); 12176 } else { 12177 // We matched a built-in operator. Convert the arguments, then 12178 // break out so that we will build the appropriate built-in 12179 // operator node. 12180 ExprResult ArgsRes0 = 12181 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12182 Best->Conversions[0], AA_Passing); 12183 if (ArgsRes0.isInvalid()) 12184 return ExprError(); 12185 Args[0] = ArgsRes0.get(); 12186 12187 ExprResult ArgsRes1 = 12188 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12189 Best->Conversions[1], AA_Passing); 12190 if (ArgsRes1.isInvalid()) 12191 return ExprError(); 12192 Args[1] = ArgsRes1.get(); 12193 12194 break; 12195 } 12196 } 12197 12198 case OR_No_Viable_Function: { 12199 if (CandidateSet.empty()) 12200 Diag(LLoc, diag::err_ovl_no_oper) 12201 << Args[0]->getType() << /*subscript*/ 0 12202 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12203 else 12204 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12205 << Args[0]->getType() 12206 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12207 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12208 "[]", LLoc); 12209 return ExprError(); 12210 } 12211 12212 case OR_Ambiguous: 12213 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12214 << "[]" 12215 << Args[0]->getType() << Args[1]->getType() 12216 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12217 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12218 "[]", LLoc); 12219 return ExprError(); 12220 12221 case OR_Deleted: 12222 Diag(LLoc, diag::err_ovl_deleted_oper) 12223 << Best->Function->isDeleted() << "[]" 12224 << getDeletedOrUnavailableSuffix(Best->Function) 12225 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12226 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12227 "[]", LLoc); 12228 return ExprError(); 12229 } 12230 12231 // We matched a built-in operator; build it. 12232 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12233 } 12234 12235 /// BuildCallToMemberFunction - Build a call to a member 12236 /// function. MemExpr is the expression that refers to the member 12237 /// function (and includes the object parameter), Args/NumArgs are the 12238 /// arguments to the function call (not including the object 12239 /// parameter). The caller needs to validate that the member 12240 /// expression refers to a non-static member function or an overloaded 12241 /// member function. 12242 ExprResult 12243 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12244 SourceLocation LParenLoc, 12245 MultiExprArg Args, 12246 SourceLocation RParenLoc) { 12247 assert(MemExprE->getType() == Context.BoundMemberTy || 12248 MemExprE->getType() == Context.OverloadTy); 12249 12250 // Dig out the member expression. This holds both the object 12251 // argument and the member function we're referring to. 12252 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12253 12254 // Determine whether this is a call to a pointer-to-member function. 12255 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12256 assert(op->getType() == Context.BoundMemberTy); 12257 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12258 12259 QualType fnType = 12260 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12261 12262 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12263 QualType resultType = proto->getCallResultType(Context); 12264 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12265 12266 // Check that the object type isn't more qualified than the 12267 // member function we're calling. 12268 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12269 12270 QualType objectType = op->getLHS()->getType(); 12271 if (op->getOpcode() == BO_PtrMemI) 12272 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12273 Qualifiers objectQuals = objectType.getQualifiers(); 12274 12275 Qualifiers difference = objectQuals - funcQuals; 12276 difference.removeObjCGCAttr(); 12277 difference.removeAddressSpace(); 12278 if (difference) { 12279 std::string qualsString = difference.getAsString(); 12280 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12281 << fnType.getUnqualifiedType() 12282 << qualsString 12283 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12284 } 12285 12286 CXXMemberCallExpr *call 12287 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12288 resultType, valueKind, RParenLoc); 12289 12290 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12291 call, nullptr)) 12292 return ExprError(); 12293 12294 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12295 return ExprError(); 12296 12297 if (CheckOtherCall(call, proto)) 12298 return ExprError(); 12299 12300 return MaybeBindToTemporary(call); 12301 } 12302 12303 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12304 return new (Context) 12305 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12306 12307 UnbridgedCastsSet UnbridgedCasts; 12308 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12309 return ExprError(); 12310 12311 MemberExpr *MemExpr; 12312 CXXMethodDecl *Method = nullptr; 12313 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12314 NestedNameSpecifier *Qualifier = nullptr; 12315 if (isa<MemberExpr>(NakedMemExpr)) { 12316 MemExpr = cast<MemberExpr>(NakedMemExpr); 12317 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12318 FoundDecl = MemExpr->getFoundDecl(); 12319 Qualifier = MemExpr->getQualifier(); 12320 UnbridgedCasts.restore(); 12321 } else { 12322 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12323 Qualifier = UnresExpr->getQualifier(); 12324 12325 QualType ObjectType = UnresExpr->getBaseType(); 12326 Expr::Classification ObjectClassification 12327 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12328 : UnresExpr->getBase()->Classify(Context); 12329 12330 // Add overload candidates 12331 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12332 OverloadCandidateSet::CSK_Normal); 12333 12334 // FIXME: avoid copy. 12335 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12336 if (UnresExpr->hasExplicitTemplateArgs()) { 12337 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12338 TemplateArgs = &TemplateArgsBuffer; 12339 } 12340 12341 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12342 E = UnresExpr->decls_end(); I != E; ++I) { 12343 12344 NamedDecl *Func = *I; 12345 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12346 if (isa<UsingShadowDecl>(Func)) 12347 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12348 12349 12350 // Microsoft supports direct constructor calls. 12351 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12352 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12353 Args, CandidateSet); 12354 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12355 // If explicit template arguments were provided, we can't call a 12356 // non-template member function. 12357 if (TemplateArgs) 12358 continue; 12359 12360 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12361 ObjectClassification, Args, CandidateSet, 12362 /*SuppressUserConversions=*/false); 12363 } else { 12364 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12365 I.getPair(), ActingDC, TemplateArgs, 12366 ObjectType, ObjectClassification, 12367 Args, CandidateSet, 12368 /*SuppressUsedConversions=*/false); 12369 } 12370 } 12371 12372 DeclarationName DeclName = UnresExpr->getMemberName(); 12373 12374 UnbridgedCasts.restore(); 12375 12376 OverloadCandidateSet::iterator Best; 12377 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12378 Best)) { 12379 case OR_Success: 12380 Method = cast<CXXMethodDecl>(Best->Function); 12381 FoundDecl = Best->FoundDecl; 12382 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12383 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12384 return ExprError(); 12385 // If FoundDecl is different from Method (such as if one is a template 12386 // and the other a specialization), make sure DiagnoseUseOfDecl is 12387 // called on both. 12388 // FIXME: This would be more comprehensively addressed by modifying 12389 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12390 // being used. 12391 if (Method != FoundDecl.getDecl() && 12392 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12393 return ExprError(); 12394 break; 12395 12396 case OR_No_Viable_Function: 12397 Diag(UnresExpr->getMemberLoc(), 12398 diag::err_ovl_no_viable_member_function_in_call) 12399 << DeclName << MemExprE->getSourceRange(); 12400 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12401 // FIXME: Leaking incoming expressions! 12402 return ExprError(); 12403 12404 case OR_Ambiguous: 12405 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12406 << DeclName << MemExprE->getSourceRange(); 12407 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12408 // FIXME: Leaking incoming expressions! 12409 return ExprError(); 12410 12411 case OR_Deleted: 12412 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12413 << Best->Function->isDeleted() 12414 << DeclName 12415 << getDeletedOrUnavailableSuffix(Best->Function) 12416 << MemExprE->getSourceRange(); 12417 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12418 // FIXME: Leaking incoming expressions! 12419 return ExprError(); 12420 } 12421 12422 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12423 12424 // If overload resolution picked a static member, build a 12425 // non-member call based on that function. 12426 if (Method->isStatic()) { 12427 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12428 RParenLoc); 12429 } 12430 12431 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12432 } 12433 12434 QualType ResultType = Method->getReturnType(); 12435 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12436 ResultType = ResultType.getNonLValueExprType(Context); 12437 12438 assert(Method && "Member call to something that isn't a method?"); 12439 CXXMemberCallExpr *TheCall = 12440 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12441 ResultType, VK, RParenLoc); 12442 12443 // Check for a valid return type. 12444 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12445 TheCall, Method)) 12446 return ExprError(); 12447 12448 // Convert the object argument (for a non-static member function call). 12449 // We only need to do this if there was actually an overload; otherwise 12450 // it was done at lookup. 12451 if (!Method->isStatic()) { 12452 ExprResult ObjectArg = 12453 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12454 FoundDecl, Method); 12455 if (ObjectArg.isInvalid()) 12456 return ExprError(); 12457 MemExpr->setBase(ObjectArg.get()); 12458 } 12459 12460 // Convert the rest of the arguments 12461 const FunctionProtoType *Proto = 12462 Method->getType()->getAs<FunctionProtoType>(); 12463 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12464 RParenLoc)) 12465 return ExprError(); 12466 12467 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12468 12469 if (CheckFunctionCall(Method, TheCall, Proto)) 12470 return ExprError(); 12471 12472 // In the case the method to call was not selected by the overloading 12473 // resolution process, we still need to handle the enable_if attribute. Do 12474 // that here, so it will not hide previous -- and more relevant -- errors 12475 if (isa<MemberExpr>(NakedMemExpr)) { 12476 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12477 Diag(MemExprE->getLocStart(), 12478 diag::err_ovl_no_viable_member_function_in_call) 12479 << Method << Method->getSourceRange(); 12480 Diag(Method->getLocation(), 12481 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12482 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12483 return ExprError(); 12484 } 12485 } 12486 12487 if ((isa<CXXConstructorDecl>(CurContext) || 12488 isa<CXXDestructorDecl>(CurContext)) && 12489 TheCall->getMethodDecl()->isPure()) { 12490 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12491 12492 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12493 MemExpr->performsVirtualDispatch(getLangOpts())) { 12494 Diag(MemExpr->getLocStart(), 12495 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12496 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12497 << MD->getParent()->getDeclName(); 12498 12499 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12500 if (getLangOpts().AppleKext) 12501 Diag(MemExpr->getLocStart(), 12502 diag::note_pure_qualified_call_kext) 12503 << MD->getParent()->getDeclName() 12504 << MD->getDeclName(); 12505 } 12506 } 12507 12508 if (CXXDestructorDecl *DD = 12509 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12510 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12511 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12512 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12513 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12514 MemExpr->getMemberLoc()); 12515 } 12516 12517 return MaybeBindToTemporary(TheCall); 12518 } 12519 12520 /// BuildCallToObjectOfClassType - Build a call to an object of class 12521 /// type (C++ [over.call.object]), which can end up invoking an 12522 /// overloaded function call operator (@c operator()) or performing a 12523 /// user-defined conversion on the object argument. 12524 ExprResult 12525 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12526 SourceLocation LParenLoc, 12527 MultiExprArg Args, 12528 SourceLocation RParenLoc) { 12529 if (checkPlaceholderForOverload(*this, Obj)) 12530 return ExprError(); 12531 ExprResult Object = Obj; 12532 12533 UnbridgedCastsSet UnbridgedCasts; 12534 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12535 return ExprError(); 12536 12537 assert(Object.get()->getType()->isRecordType() && 12538 "Requires object type argument"); 12539 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12540 12541 // C++ [over.call.object]p1: 12542 // If the primary-expression E in the function call syntax 12543 // evaluates to a class object of type "cv T", then the set of 12544 // candidate functions includes at least the function call 12545 // operators of T. The function call operators of T are obtained by 12546 // ordinary lookup of the name operator() in the context of 12547 // (E).operator(). 12548 OverloadCandidateSet CandidateSet(LParenLoc, 12549 OverloadCandidateSet::CSK_Operator); 12550 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12551 12552 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12553 diag::err_incomplete_object_call, Object.get())) 12554 return true; 12555 12556 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12557 LookupQualifiedName(R, Record->getDecl()); 12558 R.suppressDiagnostics(); 12559 12560 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12561 Oper != OperEnd; ++Oper) { 12562 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12563 Object.get()->Classify(Context), 12564 Args, CandidateSet, 12565 /*SuppressUserConversions=*/ false); 12566 } 12567 12568 // C++ [over.call.object]p2: 12569 // In addition, for each (non-explicit in C++0x) conversion function 12570 // declared in T of the form 12571 // 12572 // operator conversion-type-id () cv-qualifier; 12573 // 12574 // where cv-qualifier is the same cv-qualification as, or a 12575 // greater cv-qualification than, cv, and where conversion-type-id 12576 // denotes the type "pointer to function of (P1,...,Pn) returning 12577 // R", or the type "reference to pointer to function of 12578 // (P1,...,Pn) returning R", or the type "reference to function 12579 // of (P1,...,Pn) returning R", a surrogate call function [...] 12580 // is also considered as a candidate function. Similarly, 12581 // surrogate call functions are added to the set of candidate 12582 // functions for each conversion function declared in an 12583 // accessible base class provided the function is not hidden 12584 // within T by another intervening declaration. 12585 const auto &Conversions = 12586 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12587 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12588 NamedDecl *D = *I; 12589 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12590 if (isa<UsingShadowDecl>(D)) 12591 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12592 12593 // Skip over templated conversion functions; they aren't 12594 // surrogates. 12595 if (isa<FunctionTemplateDecl>(D)) 12596 continue; 12597 12598 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12599 if (!Conv->isExplicit()) { 12600 // Strip the reference type (if any) and then the pointer type (if 12601 // any) to get down to what might be a function type. 12602 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12603 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12604 ConvType = ConvPtrType->getPointeeType(); 12605 12606 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12607 { 12608 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12609 Object.get(), Args, CandidateSet); 12610 } 12611 } 12612 } 12613 12614 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12615 12616 // Perform overload resolution. 12617 OverloadCandidateSet::iterator Best; 12618 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12619 Best)) { 12620 case OR_Success: 12621 // Overload resolution succeeded; we'll build the appropriate call 12622 // below. 12623 break; 12624 12625 case OR_No_Viable_Function: 12626 if (CandidateSet.empty()) 12627 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12628 << Object.get()->getType() << /*call*/ 1 12629 << Object.get()->getSourceRange(); 12630 else 12631 Diag(Object.get()->getLocStart(), 12632 diag::err_ovl_no_viable_object_call) 12633 << Object.get()->getType() << Object.get()->getSourceRange(); 12634 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12635 break; 12636 12637 case OR_Ambiguous: 12638 Diag(Object.get()->getLocStart(), 12639 diag::err_ovl_ambiguous_object_call) 12640 << Object.get()->getType() << Object.get()->getSourceRange(); 12641 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12642 break; 12643 12644 case OR_Deleted: 12645 Diag(Object.get()->getLocStart(), 12646 diag::err_ovl_deleted_object_call) 12647 << Best->Function->isDeleted() 12648 << Object.get()->getType() 12649 << getDeletedOrUnavailableSuffix(Best->Function) 12650 << Object.get()->getSourceRange(); 12651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12652 break; 12653 } 12654 12655 if (Best == CandidateSet.end()) 12656 return true; 12657 12658 UnbridgedCasts.restore(); 12659 12660 if (Best->Function == nullptr) { 12661 // Since there is no function declaration, this is one of the 12662 // surrogate candidates. Dig out the conversion function. 12663 CXXConversionDecl *Conv 12664 = cast<CXXConversionDecl>( 12665 Best->Conversions[0].UserDefined.ConversionFunction); 12666 12667 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12668 Best->FoundDecl); 12669 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12670 return ExprError(); 12671 assert(Conv == Best->FoundDecl.getDecl() && 12672 "Found Decl & conversion-to-functionptr should be same, right?!"); 12673 // We selected one of the surrogate functions that converts the 12674 // object parameter to a function pointer. Perform the conversion 12675 // on the object argument, then let ActOnCallExpr finish the job. 12676 12677 // Create an implicit member expr to refer to the conversion operator. 12678 // and then call it. 12679 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12680 Conv, HadMultipleCandidates); 12681 if (Call.isInvalid()) 12682 return ExprError(); 12683 // Record usage of conversion in an implicit cast. 12684 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12685 CK_UserDefinedConversion, Call.get(), 12686 nullptr, VK_RValue); 12687 12688 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12689 } 12690 12691 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12692 12693 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12694 // that calls this method, using Object for the implicit object 12695 // parameter and passing along the remaining arguments. 12696 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12697 12698 // An error diagnostic has already been printed when parsing the declaration. 12699 if (Method->isInvalidDecl()) 12700 return ExprError(); 12701 12702 const FunctionProtoType *Proto = 12703 Method->getType()->getAs<FunctionProtoType>(); 12704 12705 unsigned NumParams = Proto->getNumParams(); 12706 12707 DeclarationNameInfo OpLocInfo( 12708 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12709 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12710 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12711 HadMultipleCandidates, 12712 OpLocInfo.getLoc(), 12713 OpLocInfo.getInfo()); 12714 if (NewFn.isInvalid()) 12715 return true; 12716 12717 // Build the full argument list for the method call (the implicit object 12718 // parameter is placed at the beginning of the list). 12719 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12720 MethodArgs[0] = Object.get(); 12721 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12722 12723 // Once we've built TheCall, all of the expressions are properly 12724 // owned. 12725 QualType ResultTy = Method->getReturnType(); 12726 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12727 ResultTy = ResultTy.getNonLValueExprType(Context); 12728 12729 CXXOperatorCallExpr *TheCall = new (Context) 12730 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12731 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12732 ResultTy, VK, RParenLoc, false); 12733 MethodArgs.reset(); 12734 12735 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12736 return true; 12737 12738 // We may have default arguments. If so, we need to allocate more 12739 // slots in the call for them. 12740 if (Args.size() < NumParams) 12741 TheCall->setNumArgs(Context, NumParams + 1); 12742 12743 bool IsError = false; 12744 12745 // Initialize the implicit object parameter. 12746 ExprResult ObjRes = 12747 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12748 Best->FoundDecl, Method); 12749 if (ObjRes.isInvalid()) 12750 IsError = true; 12751 else 12752 Object = ObjRes; 12753 TheCall->setArg(0, Object.get()); 12754 12755 // Check the argument types. 12756 for (unsigned i = 0; i != NumParams; i++) { 12757 Expr *Arg; 12758 if (i < Args.size()) { 12759 Arg = Args[i]; 12760 12761 // Pass the argument. 12762 12763 ExprResult InputInit 12764 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12765 Context, 12766 Method->getParamDecl(i)), 12767 SourceLocation(), Arg); 12768 12769 IsError |= InputInit.isInvalid(); 12770 Arg = InputInit.getAs<Expr>(); 12771 } else { 12772 ExprResult DefArg 12773 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12774 if (DefArg.isInvalid()) { 12775 IsError = true; 12776 break; 12777 } 12778 12779 Arg = DefArg.getAs<Expr>(); 12780 } 12781 12782 TheCall->setArg(i + 1, Arg); 12783 } 12784 12785 // If this is a variadic call, handle args passed through "...". 12786 if (Proto->isVariadic()) { 12787 // Promote the arguments (C99 6.5.2.2p7). 12788 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12789 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12790 nullptr); 12791 IsError |= Arg.isInvalid(); 12792 TheCall->setArg(i + 1, Arg.get()); 12793 } 12794 } 12795 12796 if (IsError) return true; 12797 12798 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12799 12800 if (CheckFunctionCall(Method, TheCall, Proto)) 12801 return true; 12802 12803 return MaybeBindToTemporary(TheCall); 12804 } 12805 12806 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12807 /// (if one exists), where @c Base is an expression of class type and 12808 /// @c Member is the name of the member we're trying to find. 12809 ExprResult 12810 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12811 bool *NoArrowOperatorFound) { 12812 assert(Base->getType()->isRecordType() && 12813 "left-hand side must have class type"); 12814 12815 if (checkPlaceholderForOverload(*this, Base)) 12816 return ExprError(); 12817 12818 SourceLocation Loc = Base->getExprLoc(); 12819 12820 // C++ [over.ref]p1: 12821 // 12822 // [...] An expression x->m is interpreted as (x.operator->())->m 12823 // for a class object x of type T if T::operator->() exists and if 12824 // the operator is selected as the best match function by the 12825 // overload resolution mechanism (13.3). 12826 DeclarationName OpName = 12827 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12828 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12829 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12830 12831 if (RequireCompleteType(Loc, Base->getType(), 12832 diag::err_typecheck_incomplete_tag, Base)) 12833 return ExprError(); 12834 12835 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12836 LookupQualifiedName(R, BaseRecord->getDecl()); 12837 R.suppressDiagnostics(); 12838 12839 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12840 Oper != OperEnd; ++Oper) { 12841 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12842 None, CandidateSet, /*SuppressUserConversions=*/false); 12843 } 12844 12845 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12846 12847 // Perform overload resolution. 12848 OverloadCandidateSet::iterator Best; 12849 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12850 case OR_Success: 12851 // Overload resolution succeeded; we'll build the call below. 12852 break; 12853 12854 case OR_No_Viable_Function: 12855 if (CandidateSet.empty()) { 12856 QualType BaseType = Base->getType(); 12857 if (NoArrowOperatorFound) { 12858 // Report this specific error to the caller instead of emitting a 12859 // diagnostic, as requested. 12860 *NoArrowOperatorFound = true; 12861 return ExprError(); 12862 } 12863 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12864 << BaseType << Base->getSourceRange(); 12865 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12866 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12867 << FixItHint::CreateReplacement(OpLoc, "."); 12868 } 12869 } else 12870 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12871 << "operator->" << Base->getSourceRange(); 12872 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12873 return ExprError(); 12874 12875 case OR_Ambiguous: 12876 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12877 << "->" << Base->getType() << Base->getSourceRange(); 12878 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12879 return ExprError(); 12880 12881 case OR_Deleted: 12882 Diag(OpLoc, diag::err_ovl_deleted_oper) 12883 << Best->Function->isDeleted() 12884 << "->" 12885 << getDeletedOrUnavailableSuffix(Best->Function) 12886 << Base->getSourceRange(); 12887 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12888 return ExprError(); 12889 } 12890 12891 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12892 12893 // Convert the object parameter. 12894 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12895 ExprResult BaseResult = 12896 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12897 Best->FoundDecl, Method); 12898 if (BaseResult.isInvalid()) 12899 return ExprError(); 12900 Base = BaseResult.get(); 12901 12902 // Build the operator call. 12903 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12904 HadMultipleCandidates, OpLoc); 12905 if (FnExpr.isInvalid()) 12906 return ExprError(); 12907 12908 QualType ResultTy = Method->getReturnType(); 12909 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12910 ResultTy = ResultTy.getNonLValueExprType(Context); 12911 CXXOperatorCallExpr *TheCall = 12912 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12913 Base, ResultTy, VK, OpLoc, false); 12914 12915 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12916 return ExprError(); 12917 12918 return MaybeBindToTemporary(TheCall); 12919 } 12920 12921 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12922 /// a literal operator described by the provided lookup results. 12923 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12924 DeclarationNameInfo &SuffixInfo, 12925 ArrayRef<Expr*> Args, 12926 SourceLocation LitEndLoc, 12927 TemplateArgumentListInfo *TemplateArgs) { 12928 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12929 12930 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12931 OverloadCandidateSet::CSK_Normal); 12932 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12933 /*SuppressUserConversions=*/true); 12934 12935 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12936 12937 // Perform overload resolution. This will usually be trivial, but might need 12938 // to perform substitutions for a literal operator template. 12939 OverloadCandidateSet::iterator Best; 12940 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12941 case OR_Success: 12942 case OR_Deleted: 12943 break; 12944 12945 case OR_No_Viable_Function: 12946 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12947 << R.getLookupName(); 12948 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12949 return ExprError(); 12950 12951 case OR_Ambiguous: 12952 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12953 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12954 return ExprError(); 12955 } 12956 12957 FunctionDecl *FD = Best->Function; 12958 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12959 HadMultipleCandidates, 12960 SuffixInfo.getLoc(), 12961 SuffixInfo.getInfo()); 12962 if (Fn.isInvalid()) 12963 return true; 12964 12965 // Check the argument types. This should almost always be a no-op, except 12966 // that array-to-pointer decay is applied to string literals. 12967 Expr *ConvArgs[2]; 12968 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12969 ExprResult InputInit = PerformCopyInitialization( 12970 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12971 SourceLocation(), Args[ArgIdx]); 12972 if (InputInit.isInvalid()) 12973 return true; 12974 ConvArgs[ArgIdx] = InputInit.get(); 12975 } 12976 12977 QualType ResultTy = FD->getReturnType(); 12978 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12979 ResultTy = ResultTy.getNonLValueExprType(Context); 12980 12981 UserDefinedLiteral *UDL = 12982 new (Context) UserDefinedLiteral(Context, Fn.get(), 12983 llvm::makeArrayRef(ConvArgs, Args.size()), 12984 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12985 12986 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12987 return ExprError(); 12988 12989 if (CheckFunctionCall(FD, UDL, nullptr)) 12990 return ExprError(); 12991 12992 return MaybeBindToTemporary(UDL); 12993 } 12994 12995 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12996 /// given LookupResult is non-empty, it is assumed to describe a member which 12997 /// will be invoked. Otherwise, the function will be found via argument 12998 /// dependent lookup. 12999 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13000 /// otherwise CallExpr is set to ExprError() and some non-success value 13001 /// is returned. 13002 Sema::ForRangeStatus 13003 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13004 SourceLocation RangeLoc, 13005 const DeclarationNameInfo &NameInfo, 13006 LookupResult &MemberLookup, 13007 OverloadCandidateSet *CandidateSet, 13008 Expr *Range, ExprResult *CallExpr) { 13009 Scope *S = nullptr; 13010 13011 CandidateSet->clear(); 13012 if (!MemberLookup.empty()) { 13013 ExprResult MemberRef = 13014 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13015 /*IsPtr=*/false, CXXScopeSpec(), 13016 /*TemplateKWLoc=*/SourceLocation(), 13017 /*FirstQualifierInScope=*/nullptr, 13018 MemberLookup, 13019 /*TemplateArgs=*/nullptr, S); 13020 if (MemberRef.isInvalid()) { 13021 *CallExpr = ExprError(); 13022 return FRS_DiagnosticIssued; 13023 } 13024 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13025 if (CallExpr->isInvalid()) { 13026 *CallExpr = ExprError(); 13027 return FRS_DiagnosticIssued; 13028 } 13029 } else { 13030 UnresolvedSet<0> FoundNames; 13031 UnresolvedLookupExpr *Fn = 13032 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13033 NestedNameSpecifierLoc(), NameInfo, 13034 /*NeedsADL=*/true, /*Overloaded=*/false, 13035 FoundNames.begin(), FoundNames.end()); 13036 13037 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13038 CandidateSet, CallExpr); 13039 if (CandidateSet->empty() || CandidateSetError) { 13040 *CallExpr = ExprError(); 13041 return FRS_NoViableFunction; 13042 } 13043 OverloadCandidateSet::iterator Best; 13044 OverloadingResult OverloadResult = 13045 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13046 13047 if (OverloadResult == OR_No_Viable_Function) { 13048 *CallExpr = ExprError(); 13049 return FRS_NoViableFunction; 13050 } 13051 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13052 Loc, nullptr, CandidateSet, &Best, 13053 OverloadResult, 13054 /*AllowTypoCorrection=*/false); 13055 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13056 *CallExpr = ExprError(); 13057 return FRS_DiagnosticIssued; 13058 } 13059 } 13060 return FRS_Success; 13061 } 13062 13063 13064 /// FixOverloadedFunctionReference - E is an expression that refers to 13065 /// a C++ overloaded function (possibly with some parentheses and 13066 /// perhaps a '&' around it). We have resolved the overloaded function 13067 /// to the function declaration Fn, so patch up the expression E to 13068 /// refer (possibly indirectly) to Fn. Returns the new expr. 13069 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13070 FunctionDecl *Fn) { 13071 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13072 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13073 Found, Fn); 13074 if (SubExpr == PE->getSubExpr()) 13075 return PE; 13076 13077 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13078 } 13079 13080 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13081 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13082 Found, Fn); 13083 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13084 SubExpr->getType()) && 13085 "Implicit cast type cannot be determined from overload"); 13086 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13087 if (SubExpr == ICE->getSubExpr()) 13088 return ICE; 13089 13090 return ImplicitCastExpr::Create(Context, ICE->getType(), 13091 ICE->getCastKind(), 13092 SubExpr, nullptr, 13093 ICE->getValueKind()); 13094 } 13095 13096 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13097 if (!GSE->isResultDependent()) { 13098 Expr *SubExpr = 13099 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13100 if (SubExpr == GSE->getResultExpr()) 13101 return GSE; 13102 13103 // Replace the resulting type information before rebuilding the generic 13104 // selection expression. 13105 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13106 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13107 unsigned ResultIdx = GSE->getResultIndex(); 13108 AssocExprs[ResultIdx] = SubExpr; 13109 13110 return new (Context) GenericSelectionExpr( 13111 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13112 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13113 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13114 ResultIdx); 13115 } 13116 // Rather than fall through to the unreachable, return the original generic 13117 // selection expression. 13118 return GSE; 13119 } 13120 13121 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13122 assert(UnOp->getOpcode() == UO_AddrOf && 13123 "Can only take the address of an overloaded function"); 13124 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13125 if (Method->isStatic()) { 13126 // Do nothing: static member functions aren't any different 13127 // from non-member functions. 13128 } else { 13129 // Fix the subexpression, which really has to be an 13130 // UnresolvedLookupExpr holding an overloaded member function 13131 // or template. 13132 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13133 Found, Fn); 13134 if (SubExpr == UnOp->getSubExpr()) 13135 return UnOp; 13136 13137 assert(isa<DeclRefExpr>(SubExpr) 13138 && "fixed to something other than a decl ref"); 13139 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13140 && "fixed to a member ref with no nested name qualifier"); 13141 13142 // We have taken the address of a pointer to member 13143 // function. Perform the computation here so that we get the 13144 // appropriate pointer to member type. 13145 QualType ClassType 13146 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13147 QualType MemPtrType 13148 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13149 // Under the MS ABI, lock down the inheritance model now. 13150 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13151 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13152 13153 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13154 VK_RValue, OK_Ordinary, 13155 UnOp->getOperatorLoc()); 13156 } 13157 } 13158 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13159 Found, Fn); 13160 if (SubExpr == UnOp->getSubExpr()) 13161 return UnOp; 13162 13163 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13164 Context.getPointerType(SubExpr->getType()), 13165 VK_RValue, OK_Ordinary, 13166 UnOp->getOperatorLoc()); 13167 } 13168 13169 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13170 // FIXME: avoid copy. 13171 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13172 if (ULE->hasExplicitTemplateArgs()) { 13173 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13174 TemplateArgs = &TemplateArgsBuffer; 13175 } 13176 13177 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13178 ULE->getQualifierLoc(), 13179 ULE->getTemplateKeywordLoc(), 13180 Fn, 13181 /*enclosing*/ false, // FIXME? 13182 ULE->getNameLoc(), 13183 Fn->getType(), 13184 VK_LValue, 13185 Found.getDecl(), 13186 TemplateArgs); 13187 MarkDeclRefReferenced(DRE); 13188 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13189 return DRE; 13190 } 13191 13192 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13193 // FIXME: avoid copy. 13194 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13195 if (MemExpr->hasExplicitTemplateArgs()) { 13196 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13197 TemplateArgs = &TemplateArgsBuffer; 13198 } 13199 13200 Expr *Base; 13201 13202 // If we're filling in a static method where we used to have an 13203 // implicit member access, rewrite to a simple decl ref. 13204 if (MemExpr->isImplicitAccess()) { 13205 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13206 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13207 MemExpr->getQualifierLoc(), 13208 MemExpr->getTemplateKeywordLoc(), 13209 Fn, 13210 /*enclosing*/ false, 13211 MemExpr->getMemberLoc(), 13212 Fn->getType(), 13213 VK_LValue, 13214 Found.getDecl(), 13215 TemplateArgs); 13216 MarkDeclRefReferenced(DRE); 13217 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13218 return DRE; 13219 } else { 13220 SourceLocation Loc = MemExpr->getMemberLoc(); 13221 if (MemExpr->getQualifier()) 13222 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13223 CheckCXXThisCapture(Loc); 13224 Base = new (Context) CXXThisExpr(Loc, 13225 MemExpr->getBaseType(), 13226 /*isImplicit=*/true); 13227 } 13228 } else 13229 Base = MemExpr->getBase(); 13230 13231 ExprValueKind valueKind; 13232 QualType type; 13233 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13234 valueKind = VK_LValue; 13235 type = Fn->getType(); 13236 } else { 13237 valueKind = VK_RValue; 13238 type = Context.BoundMemberTy; 13239 } 13240 13241 MemberExpr *ME = MemberExpr::Create( 13242 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13243 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13244 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13245 OK_Ordinary); 13246 ME->setHadMultipleCandidates(true); 13247 MarkMemberReferenced(ME); 13248 return ME; 13249 } 13250 13251 llvm_unreachable("Invalid reference to overloaded function"); 13252 } 13253 13254 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13255 DeclAccessPair Found, 13256 FunctionDecl *Fn) { 13257 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13258 } 13259