1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return std::any_of(FD->param_begin(), FD->param_end(), 43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 44 } 45 46 /// A convenience routine for creating a decayed reference to a function. 47 static ExprResult 48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 49 bool HadMultipleCandidates, 50 SourceLocation Loc = SourceLocation(), 51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 52 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 53 return ExprError(); 54 // If FoundDecl is different from Fn (such as if one is a template 55 // and the other a specialization), make sure DiagnoseUseOfDecl is 56 // called on both. 57 // FIXME: This would be more comprehensively addressed by modifying 58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 59 // being used. 60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 61 return ExprError(); 62 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 63 VK_LValue, Loc, LocInfo); 64 if (HadMultipleCandidates) 65 DRE->setHadMultipleCandidates(true); 66 67 S.MarkDeclRefReferenced(DRE); 68 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 69 CK_FunctionToPointerDecay); 70 } 71 72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 73 bool InOverloadResolution, 74 StandardConversionSequence &SCS, 75 bool CStyle, 76 bool AllowObjCWritebackConversion); 77 78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 79 QualType &ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle); 83 static OverloadingResult 84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 85 UserDefinedConversionSequence& User, 86 OverloadCandidateSet& Conversions, 87 bool AllowExplicit, 88 bool AllowObjCConversionOnExplicit); 89 90 91 static ImplicitConversionSequence::CompareKind 92 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 93 const StandardConversionSequence& SCS1, 94 const StandardConversionSequence& SCS2); 95 96 static ImplicitConversionSequence::CompareKind 97 CompareQualificationConversions(Sema &S, 98 const StandardConversionSequence& SCS1, 99 const StandardConversionSequence& SCS2); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 /// GetConversionRank - Retrieve the implicit conversion rank 107 /// corresponding to the given implicit conversion kind. 108 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 109 static const ImplicitConversionRank 110 Rank[(int)ICK_Num_Conversion_Kinds] = { 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Promotion, 120 ICR_Conversion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Complex_Real_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Writeback_Conversion, 135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 136 // it was omitted by the patch that added 137 // ICK_Zero_Event_Conversion 138 ICR_C_Conversion 139 }; 140 return Rank[(int)Kind]; 141 } 142 143 /// GetImplicitConversionName - Return the name of this kind of 144 /// implicit conversion. 145 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 147 "No conversion", 148 "Lvalue-to-rvalue", 149 "Array-to-pointer", 150 "Function-to-pointer", 151 "Noreturn adjustment", 152 "Qualification", 153 "Integral promotion", 154 "Floating point promotion", 155 "Complex promotion", 156 "Integral conversion", 157 "Floating conversion", 158 "Complex conversion", 159 "Floating-integral conversion", 160 "Pointer conversion", 161 "Pointer-to-member conversion", 162 "Boolean conversion", 163 "Compatible-types conversion", 164 "Derived-to-base conversion", 165 "Vector conversion", 166 "Vector splat", 167 "Complex-real conversion", 168 "Block Pointer conversion", 169 "Transparent Union Conversion", 170 "Writeback conversion", 171 "OpenCL Zero Event Conversion", 172 "C specific type conversion" 173 }; 174 return Name[Kind]; 175 } 176 177 /// StandardConversionSequence - Set the standard conversion 178 /// sequence to the identity conversion. 179 void StandardConversionSequence::setAsIdentityConversion() { 180 First = ICK_Identity; 181 Second = ICK_Identity; 182 Third = ICK_Identity; 183 DeprecatedStringLiteralToCharPtr = false; 184 QualificationIncludesObjCLifetime = false; 185 ReferenceBinding = false; 186 DirectBinding = false; 187 IsLvalueReference = true; 188 BindsToFunctionLvalue = false; 189 BindsToRvalue = false; 190 BindsImplicitObjectArgumentWithoutRefQualifier = false; 191 ObjCLifetimeConversionBinding = false; 192 CopyConstructor = nullptr; 193 } 194 195 /// getRank - Retrieve the rank of this standard conversion sequence 196 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 197 /// implicit conversions. 198 ImplicitConversionRank StandardConversionSequence::getRank() const { 199 ImplicitConversionRank Rank = ICR_Exact_Match; 200 if (GetConversionRank(First) > Rank) 201 Rank = GetConversionRank(First); 202 if (GetConversionRank(Second) > Rank) 203 Rank = GetConversionRank(Second); 204 if (GetConversionRank(Third) > Rank) 205 Rank = GetConversionRank(Third); 206 return Rank; 207 } 208 209 /// isPointerConversionToBool - Determines whether this conversion is 210 /// a conversion of a pointer or pointer-to-member to bool. This is 211 /// used as part of the ranking of standard conversion sequences 212 /// (C++ 13.3.3.2p4). 213 bool StandardConversionSequence::isPointerConversionToBool() const { 214 // Note that FromType has not necessarily been transformed by the 215 // array-to-pointer or function-to-pointer implicit conversions, so 216 // check for their presence as well as checking whether FromType is 217 // a pointer. 218 if (getToType(1)->isBooleanType() && 219 (getFromType()->isPointerType() || 220 getFromType()->isObjCObjectPointerType() || 221 getFromType()->isBlockPointerType() || 222 getFromType()->isNullPtrType() || 223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 224 return true; 225 226 return false; 227 } 228 229 /// isPointerConversionToVoidPointer - Determines whether this 230 /// conversion is a conversion of a pointer to a void pointer. This is 231 /// used as part of the ranking of standard conversion sequences (C++ 232 /// 13.3.3.2p4). 233 bool 234 StandardConversionSequence:: 235 isPointerConversionToVoidPointer(ASTContext& Context) const { 236 QualType FromType = getFromType(); 237 QualType ToType = getToType(1); 238 239 // Note that FromType has not necessarily been transformed by the 240 // array-to-pointer implicit conversion, so check for its presence 241 // and redo the conversion to get a pointer. 242 if (First == ICK_Array_To_Pointer) 243 FromType = Context.getArrayDecayedType(FromType); 244 245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 247 return ToPtrType->getPointeeType()->isVoidType(); 248 249 return false; 250 } 251 252 /// Skip any implicit casts which could be either part of a narrowing conversion 253 /// or after one in an implicit conversion. 254 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 256 switch (ICE->getCastKind()) { 257 case CK_NoOp: 258 case CK_IntegralCast: 259 case CK_IntegralToBoolean: 260 case CK_IntegralToFloating: 261 case CK_BooleanToSignedIntegral: 262 case CK_FloatingToIntegral: 263 case CK_FloatingToBoolean: 264 case CK_FloatingCast: 265 Converted = ICE->getSubExpr(); 266 continue; 267 268 default: 269 return Converted; 270 } 271 } 272 273 return Converted; 274 } 275 276 /// Check if this standard conversion sequence represents a narrowing 277 /// conversion, according to C++11 [dcl.init.list]p7. 278 /// 279 /// \param Ctx The AST context. 280 /// \param Converted The result of applying this standard conversion sequence. 281 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 282 /// value of the expression prior to the narrowing conversion. 283 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 284 /// type of the expression prior to the narrowing conversion. 285 NarrowingKind 286 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 287 const Expr *Converted, 288 APValue &ConstantValue, 289 QualType &ConstantType) const { 290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 291 292 // C++11 [dcl.init.list]p7: 293 // A narrowing conversion is an implicit conversion ... 294 QualType FromType = getToType(0); 295 QualType ToType = getToType(1); 296 switch (Second) { 297 // 'bool' is an integral type; dispatch to the right place to handle it. 298 case ICK_Boolean_Conversion: 299 if (FromType->isRealFloatingType()) 300 goto FloatingIntegralConversion; 301 if (FromType->isIntegralOrUnscopedEnumerationType()) 302 goto IntegralConversion; 303 // Boolean conversions can be from pointers and pointers to members 304 // [conv.bool], and those aren't considered narrowing conversions. 305 return NK_Not_Narrowing; 306 307 // -- from a floating-point type to an integer type, or 308 // 309 // -- from an integer type or unscoped enumeration type to a floating-point 310 // type, except where the source is a constant expression and the actual 311 // value after conversion will fit into the target type and will produce 312 // the original value when converted back to the original type, or 313 case ICK_Floating_Integral: 314 FloatingIntegralConversion: 315 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 316 return NK_Type_Narrowing; 317 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 318 llvm::APSInt IntConstantValue; 319 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 320 if (Initializer && 321 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 322 // Convert the integer to the floating type. 323 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 324 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 325 llvm::APFloat::rmNearestTiesToEven); 326 // And back. 327 llvm::APSInt ConvertedValue = IntConstantValue; 328 bool ignored; 329 Result.convertToInteger(ConvertedValue, 330 llvm::APFloat::rmTowardZero, &ignored); 331 // If the resulting value is different, this was a narrowing conversion. 332 if (IntConstantValue != ConvertedValue) { 333 ConstantValue = APValue(IntConstantValue); 334 ConstantType = Initializer->getType(); 335 return NK_Constant_Narrowing; 336 } 337 } else { 338 // Variables are always narrowings. 339 return NK_Variable_Narrowing; 340 } 341 } 342 return NK_Not_Narrowing; 343 344 // -- from long double to double or float, or from double to float, except 345 // where the source is a constant expression and the actual value after 346 // conversion is within the range of values that can be represented (even 347 // if it cannot be represented exactly), or 348 case ICK_Floating_Conversion: 349 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 350 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 351 // FromType is larger than ToType. 352 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 353 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 354 // Constant! 355 assert(ConstantValue.isFloat()); 356 llvm::APFloat FloatVal = ConstantValue.getFloat(); 357 // Convert the source value into the target type. 358 bool ignored; 359 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 360 Ctx.getFloatTypeSemantics(ToType), 361 llvm::APFloat::rmNearestTiesToEven, &ignored); 362 // If there was no overflow, the source value is within the range of 363 // values that can be represented. 364 if (ConvertStatus & llvm::APFloat::opOverflow) { 365 ConstantType = Initializer->getType(); 366 return NK_Constant_Narrowing; 367 } 368 } else { 369 return NK_Variable_Narrowing; 370 } 371 } 372 return NK_Not_Narrowing; 373 374 // -- from an integer type or unscoped enumeration type to an integer type 375 // that cannot represent all the values of the original type, except where 376 // the source is a constant expression and the actual value after 377 // conversion will fit into the target type and will produce the original 378 // value when converted back to the original type. 379 case ICK_Integral_Conversion: 380 IntegralConversion: { 381 assert(FromType->isIntegralOrUnscopedEnumerationType()); 382 assert(ToType->isIntegralOrUnscopedEnumerationType()); 383 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 384 const unsigned FromWidth = Ctx.getIntWidth(FromType); 385 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 386 const unsigned ToWidth = Ctx.getIntWidth(ToType); 387 388 if (FromWidth > ToWidth || 389 (FromWidth == ToWidth && FromSigned != ToSigned) || 390 (FromSigned && !ToSigned)) { 391 // Not all values of FromType can be represented in ToType. 392 llvm::APSInt InitializerValue; 393 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 394 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 395 // Such conversions on variables are always narrowing. 396 return NK_Variable_Narrowing; 397 } 398 bool Narrowing = false; 399 if (FromWidth < ToWidth) { 400 // Negative -> unsigned is narrowing. Otherwise, more bits is never 401 // narrowing. 402 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 403 Narrowing = true; 404 } else { 405 // Add a bit to the InitializerValue so we don't have to worry about 406 // signed vs. unsigned comparisons. 407 InitializerValue = InitializerValue.extend( 408 InitializerValue.getBitWidth() + 1); 409 // Convert the initializer to and from the target width and signed-ness. 410 llvm::APSInt ConvertedValue = InitializerValue; 411 ConvertedValue = ConvertedValue.trunc(ToWidth); 412 ConvertedValue.setIsSigned(ToSigned); 413 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 414 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 415 // If the result is different, this was a narrowing conversion. 416 if (ConvertedValue != InitializerValue) 417 Narrowing = true; 418 } 419 if (Narrowing) { 420 ConstantType = Initializer->getType(); 421 ConstantValue = APValue(InitializerValue); 422 return NK_Constant_Narrowing; 423 } 424 } 425 return NK_Not_Narrowing; 426 } 427 428 default: 429 // Other kinds of conversions are not narrowings. 430 return NK_Not_Narrowing; 431 } 432 } 433 434 /// dump - Print this standard conversion sequence to standard 435 /// error. Useful for debugging overloading issues. 436 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 437 raw_ostream &OS = llvm::errs(); 438 bool PrintedSomething = false; 439 if (First != ICK_Identity) { 440 OS << GetImplicitConversionName(First); 441 PrintedSomething = true; 442 } 443 444 if (Second != ICK_Identity) { 445 if (PrintedSomething) { 446 OS << " -> "; 447 } 448 OS << GetImplicitConversionName(Second); 449 450 if (CopyConstructor) { 451 OS << " (by copy constructor)"; 452 } else if (DirectBinding) { 453 OS << " (direct reference binding)"; 454 } else if (ReferenceBinding) { 455 OS << " (reference binding)"; 456 } 457 PrintedSomething = true; 458 } 459 460 if (Third != ICK_Identity) { 461 if (PrintedSomething) { 462 OS << " -> "; 463 } 464 OS << GetImplicitConversionName(Third); 465 PrintedSomething = true; 466 } 467 468 if (!PrintedSomething) { 469 OS << "No conversions required"; 470 } 471 } 472 473 /// dump - Print this user-defined conversion sequence to standard 474 /// error. Useful for debugging overloading issues. 475 void UserDefinedConversionSequence::dump() const { 476 raw_ostream &OS = llvm::errs(); 477 if (Before.First || Before.Second || Before.Third) { 478 Before.dump(); 479 OS << " -> "; 480 } 481 if (ConversionFunction) 482 OS << '\'' << *ConversionFunction << '\''; 483 else 484 OS << "aggregate initialization"; 485 if (After.First || After.Second || After.Third) { 486 OS << " -> "; 487 After.dump(); 488 } 489 } 490 491 /// dump - Print this implicit conversion sequence to standard 492 /// error. Useful for debugging overloading issues. 493 void ImplicitConversionSequence::dump() const { 494 raw_ostream &OS = llvm::errs(); 495 if (isStdInitializerListElement()) 496 OS << "Worst std::initializer_list element conversion: "; 497 switch (ConversionKind) { 498 case StandardConversion: 499 OS << "Standard conversion: "; 500 Standard.dump(); 501 break; 502 case UserDefinedConversion: 503 OS << "User-defined conversion: "; 504 UserDefined.dump(); 505 break; 506 case EllipsisConversion: 507 OS << "Ellipsis conversion"; 508 break; 509 case AmbiguousConversion: 510 OS << "Ambiguous conversion"; 511 break; 512 case BadConversion: 513 OS << "Bad conversion"; 514 break; 515 } 516 517 OS << "\n"; 518 } 519 520 void AmbiguousConversionSequence::construct() { 521 new (&conversions()) ConversionSet(); 522 } 523 524 void AmbiguousConversionSequence::destruct() { 525 conversions().~ConversionSet(); 526 } 527 528 void 529 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 530 FromTypePtr = O.FromTypePtr; 531 ToTypePtr = O.ToTypePtr; 532 new (&conversions()) ConversionSet(O.conversions()); 533 } 534 535 namespace { 536 // Structure used by DeductionFailureInfo to store 537 // template argument information. 538 struct DFIArguments { 539 TemplateArgument FirstArg; 540 TemplateArgument SecondArg; 541 }; 542 // Structure used by DeductionFailureInfo to store 543 // template parameter and template argument information. 544 struct DFIParamWithArguments : DFIArguments { 545 TemplateParameter Param; 546 }; 547 // Structure used by DeductionFailureInfo to store template argument 548 // information and the index of the problematic call argument. 549 struct DFIDeducedMismatchArgs : DFIArguments { 550 TemplateArgumentList *TemplateArgs; 551 unsigned CallArgIndex; 552 }; 553 } 554 555 /// \brief Convert from Sema's representation of template deduction information 556 /// to the form used in overload-candidate information. 557 DeductionFailureInfo 558 clang::MakeDeductionFailureInfo(ASTContext &Context, 559 Sema::TemplateDeductionResult TDK, 560 TemplateDeductionInfo &Info) { 561 DeductionFailureInfo Result; 562 Result.Result = static_cast<unsigned>(TDK); 563 Result.HasDiagnostic = false; 564 switch (TDK) { 565 case Sema::TDK_Success: 566 case Sema::TDK_Invalid: 567 case Sema::TDK_InstantiationDepth: 568 case Sema::TDK_TooManyArguments: 569 case Sema::TDK_TooFewArguments: 570 case Sema::TDK_MiscellaneousDeductionFailure: 571 Result.Data = nullptr; 572 break; 573 574 case Sema::TDK_Incomplete: 575 case Sema::TDK_InvalidExplicitArguments: 576 Result.Data = Info.Param.getOpaqueValue(); 577 break; 578 579 case Sema::TDK_DeducedMismatch: { 580 // FIXME: Should allocate from normal heap so that we can free this later. 581 auto *Saved = new (Context) DFIDeducedMismatchArgs; 582 Saved->FirstArg = Info.FirstArg; 583 Saved->SecondArg = Info.SecondArg; 584 Saved->TemplateArgs = Info.take(); 585 Saved->CallArgIndex = Info.CallArgIndex; 586 Result.Data = Saved; 587 break; 588 } 589 590 case Sema::TDK_NonDeducedMismatch: { 591 // FIXME: Should allocate from normal heap so that we can free this later. 592 DFIArguments *Saved = new (Context) DFIArguments; 593 Saved->FirstArg = Info.FirstArg; 594 Saved->SecondArg = Info.SecondArg; 595 Result.Data = Saved; 596 break; 597 } 598 599 case Sema::TDK_Inconsistent: 600 case Sema::TDK_Underqualified: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 603 Saved->Param = Info.Param; 604 Saved->FirstArg = Info.FirstArg; 605 Saved->SecondArg = Info.SecondArg; 606 Result.Data = Saved; 607 break; 608 } 609 610 case Sema::TDK_SubstitutionFailure: 611 Result.Data = Info.take(); 612 if (Info.hasSFINAEDiagnostic()) { 613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 614 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 615 Info.takeSFINAEDiagnostic(*Diag); 616 Result.HasDiagnostic = true; 617 } 618 break; 619 620 case Sema::TDK_FailedOverloadResolution: 621 Result.Data = Info.Expression; 622 break; 623 } 624 625 return Result; 626 } 627 628 void DeductionFailureInfo::Destroy() { 629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 630 case Sema::TDK_Success: 631 case Sema::TDK_Invalid: 632 case Sema::TDK_InstantiationDepth: 633 case Sema::TDK_Incomplete: 634 case Sema::TDK_TooManyArguments: 635 case Sema::TDK_TooFewArguments: 636 case Sema::TDK_InvalidExplicitArguments: 637 case Sema::TDK_FailedOverloadResolution: 638 break; 639 640 case Sema::TDK_Inconsistent: 641 case Sema::TDK_Underqualified: 642 case Sema::TDK_DeducedMismatch: 643 case Sema::TDK_NonDeducedMismatch: 644 // FIXME: Destroy the data? 645 Data = nullptr; 646 break; 647 648 case Sema::TDK_SubstitutionFailure: 649 // FIXME: Destroy the template argument list? 650 Data = nullptr; 651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 652 Diag->~PartialDiagnosticAt(); 653 HasDiagnostic = false; 654 } 655 break; 656 657 // Unhandled 658 case Sema::TDK_MiscellaneousDeductionFailure: 659 break; 660 } 661 } 662 663 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 664 if (HasDiagnostic) 665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 666 return nullptr; 667 } 668 669 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 671 case Sema::TDK_Success: 672 case Sema::TDK_Invalid: 673 case Sema::TDK_InstantiationDepth: 674 case Sema::TDK_TooManyArguments: 675 case Sema::TDK_TooFewArguments: 676 case Sema::TDK_SubstitutionFailure: 677 case Sema::TDK_DeducedMismatch: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return TemplateParameter(); 681 682 case Sema::TDK_Incomplete: 683 case Sema::TDK_InvalidExplicitArguments: 684 return TemplateParameter::getFromOpaqueValue(Data); 685 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 return static_cast<DFIParamWithArguments*>(Data)->Param; 689 690 // Unhandled 691 case Sema::TDK_MiscellaneousDeductionFailure: 692 break; 693 } 694 695 return TemplateParameter(); 696 } 697 698 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 700 case Sema::TDK_Success: 701 case Sema::TDK_Invalid: 702 case Sema::TDK_InstantiationDepth: 703 case Sema::TDK_TooManyArguments: 704 case Sema::TDK_TooFewArguments: 705 case Sema::TDK_Incomplete: 706 case Sema::TDK_InvalidExplicitArguments: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_NonDeducedMismatch: 710 case Sema::TDK_FailedOverloadResolution: 711 return nullptr; 712 713 case Sema::TDK_DeducedMismatch: 714 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 715 716 case Sema::TDK_SubstitutionFailure: 717 return static_cast<TemplateArgumentList*>(Data); 718 719 // Unhandled 720 case Sema::TDK_MiscellaneousDeductionFailure: 721 break; 722 } 723 724 return nullptr; 725 } 726 727 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 728 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 729 case Sema::TDK_Success: 730 case Sema::TDK_Invalid: 731 case Sema::TDK_InstantiationDepth: 732 case Sema::TDK_Incomplete: 733 case Sema::TDK_TooManyArguments: 734 case Sema::TDK_TooFewArguments: 735 case Sema::TDK_InvalidExplicitArguments: 736 case Sema::TDK_SubstitutionFailure: 737 case Sema::TDK_FailedOverloadResolution: 738 return nullptr; 739 740 case Sema::TDK_Inconsistent: 741 case Sema::TDK_Underqualified: 742 case Sema::TDK_DeducedMismatch: 743 case Sema::TDK_NonDeducedMismatch: 744 return &static_cast<DFIArguments*>(Data)->FirstArg; 745 746 // Unhandled 747 case Sema::TDK_MiscellaneousDeductionFailure: 748 break; 749 } 750 751 return nullptr; 752 } 753 754 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 755 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 756 case Sema::TDK_Success: 757 case Sema::TDK_Invalid: 758 case Sema::TDK_InstantiationDepth: 759 case Sema::TDK_Incomplete: 760 case Sema::TDK_TooManyArguments: 761 case Sema::TDK_TooFewArguments: 762 case Sema::TDK_InvalidExplicitArguments: 763 case Sema::TDK_SubstitutionFailure: 764 case Sema::TDK_FailedOverloadResolution: 765 return nullptr; 766 767 case Sema::TDK_Inconsistent: 768 case Sema::TDK_Underqualified: 769 case Sema::TDK_DeducedMismatch: 770 case Sema::TDK_NonDeducedMismatch: 771 return &static_cast<DFIArguments*>(Data)->SecondArg; 772 773 // Unhandled 774 case Sema::TDK_MiscellaneousDeductionFailure: 775 break; 776 } 777 778 return nullptr; 779 } 780 781 Expr *DeductionFailureInfo::getExpr() { 782 if (static_cast<Sema::TemplateDeductionResult>(Result) == 783 Sema::TDK_FailedOverloadResolution) 784 return static_cast<Expr*>(Data); 785 786 return nullptr; 787 } 788 789 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 790 if (static_cast<Sema::TemplateDeductionResult>(Result) == 791 Sema::TDK_DeducedMismatch) 792 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 793 794 return llvm::None; 795 } 796 797 void OverloadCandidateSet::destroyCandidates() { 798 for (iterator i = begin(), e = end(); i != e; ++i) { 799 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 800 i->Conversions[ii].~ImplicitConversionSequence(); 801 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 802 i->DeductionFailure.Destroy(); 803 } 804 } 805 806 void OverloadCandidateSet::clear() { 807 destroyCandidates(); 808 NumInlineSequences = 0; 809 Candidates.clear(); 810 Functions.clear(); 811 } 812 813 namespace { 814 class UnbridgedCastsSet { 815 struct Entry { 816 Expr **Addr; 817 Expr *Saved; 818 }; 819 SmallVector<Entry, 2> Entries; 820 821 public: 822 void save(Sema &S, Expr *&E) { 823 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 824 Entry entry = { &E, E }; 825 Entries.push_back(entry); 826 E = S.stripARCUnbridgedCast(E); 827 } 828 829 void restore() { 830 for (SmallVectorImpl<Entry>::iterator 831 i = Entries.begin(), e = Entries.end(); i != e; ++i) 832 *i->Addr = i->Saved; 833 } 834 }; 835 } 836 837 /// checkPlaceholderForOverload - Do any interesting placeholder-like 838 /// preprocessing on the given expression. 839 /// 840 /// \param unbridgedCasts a collection to which to add unbridged casts; 841 /// without this, they will be immediately diagnosed as errors 842 /// 843 /// Return true on unrecoverable error. 844 static bool 845 checkPlaceholderForOverload(Sema &S, Expr *&E, 846 UnbridgedCastsSet *unbridgedCasts = nullptr) { 847 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 848 // We can't handle overloaded expressions here because overload 849 // resolution might reasonably tweak them. 850 if (placeholder->getKind() == BuiltinType::Overload) return false; 851 852 // If the context potentially accepts unbridged ARC casts, strip 853 // the unbridged cast and add it to the collection for later restoration. 854 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 855 unbridgedCasts) { 856 unbridgedCasts->save(S, E); 857 return false; 858 } 859 860 // Go ahead and check everything else. 861 ExprResult result = S.CheckPlaceholderExpr(E); 862 if (result.isInvalid()) 863 return true; 864 865 E = result.get(); 866 return false; 867 } 868 869 // Nothing to do. 870 return false; 871 } 872 873 /// checkArgPlaceholdersForOverload - Check a set of call operands for 874 /// placeholders. 875 static bool checkArgPlaceholdersForOverload(Sema &S, 876 MultiExprArg Args, 877 UnbridgedCastsSet &unbridged) { 878 for (unsigned i = 0, e = Args.size(); i != e; ++i) 879 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 880 return true; 881 882 return false; 883 } 884 885 // IsOverload - Determine whether the given New declaration is an 886 // overload of the declarations in Old. This routine returns false if 887 // New and Old cannot be overloaded, e.g., if New has the same 888 // signature as some function in Old (C++ 1.3.10) or if the Old 889 // declarations aren't functions (or function templates) at all. When 890 // it does return false, MatchedDecl will point to the decl that New 891 // cannot be overloaded with. This decl may be a UsingShadowDecl on 892 // top of the underlying declaration. 893 // 894 // Example: Given the following input: 895 // 896 // void f(int, float); // #1 897 // void f(int, int); // #2 898 // int f(int, int); // #3 899 // 900 // When we process #1, there is no previous declaration of "f", 901 // so IsOverload will not be used. 902 // 903 // When we process #2, Old contains only the FunctionDecl for #1. By 904 // comparing the parameter types, we see that #1 and #2 are overloaded 905 // (since they have different signatures), so this routine returns 906 // false; MatchedDecl is unchanged. 907 // 908 // When we process #3, Old is an overload set containing #1 and #2. We 909 // compare the signatures of #3 to #1 (they're overloaded, so we do 910 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 911 // identical (return types of functions are not part of the 912 // signature), IsOverload returns false and MatchedDecl will be set to 913 // point to the FunctionDecl for #2. 914 // 915 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 916 // into a class by a using declaration. The rules for whether to hide 917 // shadow declarations ignore some properties which otherwise figure 918 // into a function template's signature. 919 Sema::OverloadKind 920 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 921 NamedDecl *&Match, bool NewIsUsingDecl) { 922 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 923 I != E; ++I) { 924 NamedDecl *OldD = *I; 925 926 bool OldIsUsingDecl = false; 927 if (isa<UsingShadowDecl>(OldD)) { 928 OldIsUsingDecl = true; 929 930 // We can always introduce two using declarations into the same 931 // context, even if they have identical signatures. 932 if (NewIsUsingDecl) continue; 933 934 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 935 } 936 937 // A using-declaration does not conflict with another declaration 938 // if one of them is hidden. 939 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 940 continue; 941 942 // If either declaration was introduced by a using declaration, 943 // we'll need to use slightly different rules for matching. 944 // Essentially, these rules are the normal rules, except that 945 // function templates hide function templates with different 946 // return types or template parameter lists. 947 bool UseMemberUsingDeclRules = 948 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 949 !New->getFriendObjectKind(); 950 951 if (FunctionDecl *OldF = OldD->getAsFunction()) { 952 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 953 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 954 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 955 continue; 956 } 957 958 if (!isa<FunctionTemplateDecl>(OldD) && 959 !shouldLinkPossiblyHiddenDecl(*I, New)) 960 continue; 961 962 Match = *I; 963 return Ovl_Match; 964 } 965 } else if (isa<UsingDecl>(OldD)) { 966 // We can overload with these, which can show up when doing 967 // redeclaration checks for UsingDecls. 968 assert(Old.getLookupKind() == LookupUsingDeclName); 969 } else if (isa<TagDecl>(OldD)) { 970 // We can always overload with tags by hiding them. 971 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 972 // Optimistically assume that an unresolved using decl will 973 // overload; if it doesn't, we'll have to diagnose during 974 // template instantiation. 975 } else { 976 // (C++ 13p1): 977 // Only function declarations can be overloaded; object and type 978 // declarations cannot be overloaded. 979 Match = *I; 980 return Ovl_NonFunction; 981 } 982 } 983 984 return Ovl_Overload; 985 } 986 987 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 988 bool UseUsingDeclRules) { 989 // C++ [basic.start.main]p2: This function shall not be overloaded. 990 if (New->isMain()) 991 return false; 992 993 // MSVCRT user defined entry points cannot be overloaded. 994 if (New->isMSVCRTEntryPoint()) 995 return false; 996 997 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 998 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 999 1000 // C++ [temp.fct]p2: 1001 // A function template can be overloaded with other function templates 1002 // and with normal (non-template) functions. 1003 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1004 return true; 1005 1006 // Is the function New an overload of the function Old? 1007 QualType OldQType = Context.getCanonicalType(Old->getType()); 1008 QualType NewQType = Context.getCanonicalType(New->getType()); 1009 1010 // Compare the signatures (C++ 1.3.10) of the two functions to 1011 // determine whether they are overloads. If we find any mismatch 1012 // in the signature, they are overloads. 1013 1014 // If either of these functions is a K&R-style function (no 1015 // prototype), then we consider them to have matching signatures. 1016 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1017 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1018 return false; 1019 1020 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1021 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1022 1023 // The signature of a function includes the types of its 1024 // parameters (C++ 1.3.10), which includes the presence or absence 1025 // of the ellipsis; see C++ DR 357). 1026 if (OldQType != NewQType && 1027 (OldType->getNumParams() != NewType->getNumParams() || 1028 OldType->isVariadic() != NewType->isVariadic() || 1029 !FunctionParamTypesAreEqual(OldType, NewType))) 1030 return true; 1031 1032 // C++ [temp.over.link]p4: 1033 // The signature of a function template consists of its function 1034 // signature, its return type and its template parameter list. The names 1035 // of the template parameters are significant only for establishing the 1036 // relationship between the template parameters and the rest of the 1037 // signature. 1038 // 1039 // We check the return type and template parameter lists for function 1040 // templates first; the remaining checks follow. 1041 // 1042 // However, we don't consider either of these when deciding whether 1043 // a member introduced by a shadow declaration is hidden. 1044 if (!UseUsingDeclRules && NewTemplate && 1045 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1046 OldTemplate->getTemplateParameters(), 1047 false, TPL_TemplateMatch) || 1048 OldType->getReturnType() != NewType->getReturnType())) 1049 return true; 1050 1051 // If the function is a class member, its signature includes the 1052 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1053 // 1054 // As part of this, also check whether one of the member functions 1055 // is static, in which case they are not overloads (C++ 1056 // 13.1p2). While not part of the definition of the signature, 1057 // this check is important to determine whether these functions 1058 // can be overloaded. 1059 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1060 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1061 if (OldMethod && NewMethod && 1062 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1063 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1064 if (!UseUsingDeclRules && 1065 (OldMethod->getRefQualifier() == RQ_None || 1066 NewMethod->getRefQualifier() == RQ_None)) { 1067 // C++0x [over.load]p2: 1068 // - Member function declarations with the same name and the same 1069 // parameter-type-list as well as member function template 1070 // declarations with the same name, the same parameter-type-list, and 1071 // the same template parameter lists cannot be overloaded if any of 1072 // them, but not all, have a ref-qualifier (8.3.5). 1073 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1074 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1075 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1076 } 1077 return true; 1078 } 1079 1080 // We may not have applied the implicit const for a constexpr member 1081 // function yet (because we haven't yet resolved whether this is a static 1082 // or non-static member function). Add it now, on the assumption that this 1083 // is a redeclaration of OldMethod. 1084 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1085 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1086 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1087 !isa<CXXConstructorDecl>(NewMethod)) 1088 NewQuals |= Qualifiers::Const; 1089 1090 // We do not allow overloading based off of '__restrict'. 1091 OldQuals &= ~Qualifiers::Restrict; 1092 NewQuals &= ~Qualifiers::Restrict; 1093 if (OldQuals != NewQuals) 1094 return true; 1095 } 1096 1097 // Though pass_object_size is placed on parameters and takes an argument, we 1098 // consider it to be a function-level modifier for the sake of function 1099 // identity. Either the function has one or more parameters with 1100 // pass_object_size or it doesn't. 1101 if (functionHasPassObjectSizeParams(New) != 1102 functionHasPassObjectSizeParams(Old)) 1103 return true; 1104 1105 // enable_if attributes are an order-sensitive part of the signature. 1106 for (specific_attr_iterator<EnableIfAttr> 1107 NewI = New->specific_attr_begin<EnableIfAttr>(), 1108 NewE = New->specific_attr_end<EnableIfAttr>(), 1109 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1110 OldE = Old->specific_attr_end<EnableIfAttr>(); 1111 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1112 if (NewI == NewE || OldI == OldE) 1113 return true; 1114 llvm::FoldingSetNodeID NewID, OldID; 1115 NewI->getCond()->Profile(NewID, Context, true); 1116 OldI->getCond()->Profile(OldID, Context, true); 1117 if (NewID != OldID) 1118 return true; 1119 } 1120 1121 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1122 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1123 OldTarget = IdentifyCUDATarget(Old); 1124 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1125 return false; 1126 1127 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1128 1129 // Don't allow mixing of HD with other kinds. This guarantees that 1130 // we have only one viable function with this signature on any 1131 // side of CUDA compilation . 1132 // __global__ functions can't be overloaded based on attribute 1133 // difference because, like HD, they also exist on both sides. 1134 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1135 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1136 return false; 1137 1138 // Allow overloading of functions with same signature, but 1139 // different CUDA target attributes. 1140 return NewTarget != OldTarget; 1141 } 1142 1143 // The signatures match; this is not an overload. 1144 return false; 1145 } 1146 1147 /// \brief Checks availability of the function depending on the current 1148 /// function context. Inside an unavailable function, unavailability is ignored. 1149 /// 1150 /// \returns true if \arg FD is unavailable and current context is inside 1151 /// an available function, false otherwise. 1152 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1153 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1154 } 1155 1156 /// \brief Tries a user-defined conversion from From to ToType. 1157 /// 1158 /// Produces an implicit conversion sequence for when a standard conversion 1159 /// is not an option. See TryImplicitConversion for more information. 1160 static ImplicitConversionSequence 1161 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1162 bool SuppressUserConversions, 1163 bool AllowExplicit, 1164 bool InOverloadResolution, 1165 bool CStyle, 1166 bool AllowObjCWritebackConversion, 1167 bool AllowObjCConversionOnExplicit) { 1168 ImplicitConversionSequence ICS; 1169 1170 if (SuppressUserConversions) { 1171 // We're not in the case above, so there is no conversion that 1172 // we can perform. 1173 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1174 return ICS; 1175 } 1176 1177 // Attempt user-defined conversion. 1178 OverloadCandidateSet Conversions(From->getExprLoc(), 1179 OverloadCandidateSet::CSK_Normal); 1180 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1181 Conversions, AllowExplicit, 1182 AllowObjCConversionOnExplicit)) { 1183 case OR_Success: 1184 case OR_Deleted: 1185 ICS.setUserDefined(); 1186 ICS.UserDefined.Before.setAsIdentityConversion(); 1187 // C++ [over.ics.user]p4: 1188 // A conversion of an expression of class type to the same class 1189 // type is given Exact Match rank, and a conversion of an 1190 // expression of class type to a base class of that type is 1191 // given Conversion rank, in spite of the fact that a copy 1192 // constructor (i.e., a user-defined conversion function) is 1193 // called for those cases. 1194 if (CXXConstructorDecl *Constructor 1195 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1196 QualType FromCanon 1197 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1198 QualType ToCanon 1199 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1200 if (Constructor->isCopyConstructor() && 1201 (FromCanon == ToCanon || 1202 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1203 // Turn this into a "standard" conversion sequence, so that it 1204 // gets ranked with standard conversion sequences. 1205 ICS.setStandard(); 1206 ICS.Standard.setAsIdentityConversion(); 1207 ICS.Standard.setFromType(From->getType()); 1208 ICS.Standard.setAllToTypes(ToType); 1209 ICS.Standard.CopyConstructor = Constructor; 1210 if (ToCanon != FromCanon) 1211 ICS.Standard.Second = ICK_Derived_To_Base; 1212 } 1213 } 1214 break; 1215 1216 case OR_Ambiguous: 1217 ICS.setAmbiguous(); 1218 ICS.Ambiguous.setFromType(From->getType()); 1219 ICS.Ambiguous.setToType(ToType); 1220 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1221 Cand != Conversions.end(); ++Cand) 1222 if (Cand->Viable) 1223 ICS.Ambiguous.addConversion(Cand->Function); 1224 break; 1225 1226 // Fall through. 1227 case OR_No_Viable_Function: 1228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1229 break; 1230 } 1231 1232 return ICS; 1233 } 1234 1235 /// TryImplicitConversion - Attempt to perform an implicit conversion 1236 /// from the given expression (Expr) to the given type (ToType). This 1237 /// function returns an implicit conversion sequence that can be used 1238 /// to perform the initialization. Given 1239 /// 1240 /// void f(float f); 1241 /// void g(int i) { f(i); } 1242 /// 1243 /// this routine would produce an implicit conversion sequence to 1244 /// describe the initialization of f from i, which will be a standard 1245 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1246 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1247 // 1248 /// Note that this routine only determines how the conversion can be 1249 /// performed; it does not actually perform the conversion. As such, 1250 /// it will not produce any diagnostics if no conversion is available, 1251 /// but will instead return an implicit conversion sequence of kind 1252 /// "BadConversion". 1253 /// 1254 /// If @p SuppressUserConversions, then user-defined conversions are 1255 /// not permitted. 1256 /// If @p AllowExplicit, then explicit user-defined conversions are 1257 /// permitted. 1258 /// 1259 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1260 /// writeback conversion, which allows __autoreleasing id* parameters to 1261 /// be initialized with __strong id* or __weak id* arguments. 1262 static ImplicitConversionSequence 1263 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1264 bool SuppressUserConversions, 1265 bool AllowExplicit, 1266 bool InOverloadResolution, 1267 bool CStyle, 1268 bool AllowObjCWritebackConversion, 1269 bool AllowObjCConversionOnExplicit) { 1270 ImplicitConversionSequence ICS; 1271 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1272 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1273 ICS.setStandard(); 1274 return ICS; 1275 } 1276 1277 if (!S.getLangOpts().CPlusPlus) { 1278 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1279 return ICS; 1280 } 1281 1282 // C++ [over.ics.user]p4: 1283 // A conversion of an expression of class type to the same class 1284 // type is given Exact Match rank, and a conversion of an 1285 // expression of class type to a base class of that type is 1286 // given Conversion rank, in spite of the fact that a copy/move 1287 // constructor (i.e., a user-defined conversion function) is 1288 // called for those cases. 1289 QualType FromType = From->getType(); 1290 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1291 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1292 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1293 ICS.setStandard(); 1294 ICS.Standard.setAsIdentityConversion(); 1295 ICS.Standard.setFromType(FromType); 1296 ICS.Standard.setAllToTypes(ToType); 1297 1298 // We don't actually check at this point whether there is a valid 1299 // copy/move constructor, since overloading just assumes that it 1300 // exists. When we actually perform initialization, we'll find the 1301 // appropriate constructor to copy the returned object, if needed. 1302 ICS.Standard.CopyConstructor = nullptr; 1303 1304 // Determine whether this is considered a derived-to-base conversion. 1305 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1306 ICS.Standard.Second = ICK_Derived_To_Base; 1307 1308 return ICS; 1309 } 1310 1311 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1312 AllowExplicit, InOverloadResolution, CStyle, 1313 AllowObjCWritebackConversion, 1314 AllowObjCConversionOnExplicit); 1315 } 1316 1317 ImplicitConversionSequence 1318 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1319 bool SuppressUserConversions, 1320 bool AllowExplicit, 1321 bool InOverloadResolution, 1322 bool CStyle, 1323 bool AllowObjCWritebackConversion) { 1324 return ::TryImplicitConversion(*this, From, ToType, 1325 SuppressUserConversions, AllowExplicit, 1326 InOverloadResolution, CStyle, 1327 AllowObjCWritebackConversion, 1328 /*AllowObjCConversionOnExplicit=*/false); 1329 } 1330 1331 /// PerformImplicitConversion - Perform an implicit conversion of the 1332 /// expression From to the type ToType. Returns the 1333 /// converted expression. Flavor is the kind of conversion we're 1334 /// performing, used in the error message. If @p AllowExplicit, 1335 /// explicit user-defined conversions are permitted. 1336 ExprResult 1337 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1338 AssignmentAction Action, bool AllowExplicit) { 1339 ImplicitConversionSequence ICS; 1340 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1341 } 1342 1343 ExprResult 1344 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1345 AssignmentAction Action, bool AllowExplicit, 1346 ImplicitConversionSequence& ICS) { 1347 if (checkPlaceholderForOverload(*this, From)) 1348 return ExprError(); 1349 1350 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1351 bool AllowObjCWritebackConversion 1352 = getLangOpts().ObjCAutoRefCount && 1353 (Action == AA_Passing || Action == AA_Sending); 1354 if (getLangOpts().ObjC1) 1355 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1356 ToType, From->getType(), From); 1357 ICS = ::TryImplicitConversion(*this, From, ToType, 1358 /*SuppressUserConversions=*/false, 1359 AllowExplicit, 1360 /*InOverloadResolution=*/false, 1361 /*CStyle=*/false, 1362 AllowObjCWritebackConversion, 1363 /*AllowObjCConversionOnExplicit=*/false); 1364 return PerformImplicitConversion(From, ToType, ICS, Action); 1365 } 1366 1367 /// \brief Determine whether the conversion from FromType to ToType is a valid 1368 /// conversion that strips "noreturn" off the nested function type. 1369 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1370 QualType &ResultTy) { 1371 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1372 return false; 1373 1374 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1375 // where F adds one of the following at most once: 1376 // - a pointer 1377 // - a member pointer 1378 // - a block pointer 1379 CanQualType CanTo = Context.getCanonicalType(ToType); 1380 CanQualType CanFrom = Context.getCanonicalType(FromType); 1381 Type::TypeClass TyClass = CanTo->getTypeClass(); 1382 if (TyClass != CanFrom->getTypeClass()) return false; 1383 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1384 if (TyClass == Type::Pointer) { 1385 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1386 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1387 } else if (TyClass == Type::BlockPointer) { 1388 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1389 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1390 } else if (TyClass == Type::MemberPointer) { 1391 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1392 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1393 } else { 1394 return false; 1395 } 1396 1397 TyClass = CanTo->getTypeClass(); 1398 if (TyClass != CanFrom->getTypeClass()) return false; 1399 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1400 return false; 1401 } 1402 1403 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1404 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1405 if (!EInfo.getNoReturn()) return false; 1406 1407 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1408 assert(QualType(FromFn, 0).isCanonical()); 1409 if (QualType(FromFn, 0) != CanTo) return false; 1410 1411 ResultTy = ToType; 1412 return true; 1413 } 1414 1415 /// \brief Determine whether the conversion from FromType to ToType is a valid 1416 /// vector conversion. 1417 /// 1418 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1419 /// conversion. 1420 static bool IsVectorConversion(Sema &S, QualType FromType, 1421 QualType ToType, ImplicitConversionKind &ICK) { 1422 // We need at least one of these types to be a vector type to have a vector 1423 // conversion. 1424 if (!ToType->isVectorType() && !FromType->isVectorType()) 1425 return false; 1426 1427 // Identical types require no conversions. 1428 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1429 return false; 1430 1431 // There are no conversions between extended vector types, only identity. 1432 if (ToType->isExtVectorType()) { 1433 // There are no conversions between extended vector types other than the 1434 // identity conversion. 1435 if (FromType->isExtVectorType()) 1436 return false; 1437 1438 // Vector splat from any arithmetic type to a vector. 1439 if (FromType->isArithmeticType()) { 1440 ICK = ICK_Vector_Splat; 1441 return true; 1442 } 1443 } 1444 1445 // We can perform the conversion between vector types in the following cases: 1446 // 1)vector types are equivalent AltiVec and GCC vector types 1447 // 2)lax vector conversions are permitted and the vector types are of the 1448 // same size 1449 if (ToType->isVectorType() && FromType->isVectorType()) { 1450 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1451 S.isLaxVectorConversion(FromType, ToType)) { 1452 ICK = ICK_Vector_Conversion; 1453 return true; 1454 } 1455 } 1456 1457 return false; 1458 } 1459 1460 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1461 bool InOverloadResolution, 1462 StandardConversionSequence &SCS, 1463 bool CStyle); 1464 1465 /// IsStandardConversion - Determines whether there is a standard 1466 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1467 /// expression From to the type ToType. Standard conversion sequences 1468 /// only consider non-class types; for conversions that involve class 1469 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1470 /// contain the standard conversion sequence required to perform this 1471 /// conversion and this routine will return true. Otherwise, this 1472 /// routine will return false and the value of SCS is unspecified. 1473 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1474 bool InOverloadResolution, 1475 StandardConversionSequence &SCS, 1476 bool CStyle, 1477 bool AllowObjCWritebackConversion) { 1478 QualType FromType = From->getType(); 1479 1480 // Standard conversions (C++ [conv]) 1481 SCS.setAsIdentityConversion(); 1482 SCS.IncompatibleObjC = false; 1483 SCS.setFromType(FromType); 1484 SCS.CopyConstructor = nullptr; 1485 1486 // There are no standard conversions for class types in C++, so 1487 // abort early. When overloading in C, however, we do permit them. 1488 if (S.getLangOpts().CPlusPlus && 1489 (FromType->isRecordType() || ToType->isRecordType())) 1490 return false; 1491 1492 // The first conversion can be an lvalue-to-rvalue conversion, 1493 // array-to-pointer conversion, or function-to-pointer conversion 1494 // (C++ 4p1). 1495 1496 if (FromType == S.Context.OverloadTy) { 1497 DeclAccessPair AccessPair; 1498 if (FunctionDecl *Fn 1499 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1500 AccessPair)) { 1501 // We were able to resolve the address of the overloaded function, 1502 // so we can convert to the type of that function. 1503 FromType = Fn->getType(); 1504 SCS.setFromType(FromType); 1505 1506 // we can sometimes resolve &foo<int> regardless of ToType, so check 1507 // if the type matches (identity) or we are converting to bool 1508 if (!S.Context.hasSameUnqualifiedType( 1509 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1510 QualType resultTy; 1511 // if the function type matches except for [[noreturn]], it's ok 1512 if (!S.IsNoReturnConversion(FromType, 1513 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1514 // otherwise, only a boolean conversion is standard 1515 if (!ToType->isBooleanType()) 1516 return false; 1517 } 1518 1519 // Check if the "from" expression is taking the address of an overloaded 1520 // function and recompute the FromType accordingly. Take advantage of the 1521 // fact that non-static member functions *must* have such an address-of 1522 // expression. 1523 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1524 if (Method && !Method->isStatic()) { 1525 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1526 "Non-unary operator on non-static member address"); 1527 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1528 == UO_AddrOf && 1529 "Non-address-of operator on non-static member address"); 1530 const Type *ClassType 1531 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1532 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1533 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1534 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1535 UO_AddrOf && 1536 "Non-address-of operator for overloaded function expression"); 1537 FromType = S.Context.getPointerType(FromType); 1538 } 1539 1540 // Check that we've computed the proper type after overload resolution. 1541 assert(S.Context.hasSameType( 1542 FromType, 1543 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1544 } else { 1545 return false; 1546 } 1547 } 1548 // Lvalue-to-rvalue conversion (C++11 4.1): 1549 // A glvalue (3.10) of a non-function, non-array type T can 1550 // be converted to a prvalue. 1551 bool argIsLValue = From->isGLValue(); 1552 if (argIsLValue && 1553 !FromType->isFunctionType() && !FromType->isArrayType() && 1554 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1555 SCS.First = ICK_Lvalue_To_Rvalue; 1556 1557 // C11 6.3.2.1p2: 1558 // ... if the lvalue has atomic type, the value has the non-atomic version 1559 // of the type of the lvalue ... 1560 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1561 FromType = Atomic->getValueType(); 1562 1563 // If T is a non-class type, the type of the rvalue is the 1564 // cv-unqualified version of T. Otherwise, the type of the rvalue 1565 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1566 // just strip the qualifiers because they don't matter. 1567 FromType = FromType.getUnqualifiedType(); 1568 } else if (FromType->isArrayType()) { 1569 // Array-to-pointer conversion (C++ 4.2) 1570 SCS.First = ICK_Array_To_Pointer; 1571 1572 // An lvalue or rvalue of type "array of N T" or "array of unknown 1573 // bound of T" can be converted to an rvalue of type "pointer to 1574 // T" (C++ 4.2p1). 1575 FromType = S.Context.getArrayDecayedType(FromType); 1576 1577 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1578 // This conversion is deprecated in C++03 (D.4) 1579 SCS.DeprecatedStringLiteralToCharPtr = true; 1580 1581 // For the purpose of ranking in overload resolution 1582 // (13.3.3.1.1), this conversion is considered an 1583 // array-to-pointer conversion followed by a qualification 1584 // conversion (4.4). (C++ 4.2p2) 1585 SCS.Second = ICK_Identity; 1586 SCS.Third = ICK_Qualification; 1587 SCS.QualificationIncludesObjCLifetime = false; 1588 SCS.setAllToTypes(FromType); 1589 return true; 1590 } 1591 } else if (FromType->isFunctionType() && argIsLValue) { 1592 // Function-to-pointer conversion (C++ 4.3). 1593 SCS.First = ICK_Function_To_Pointer; 1594 1595 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1596 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1597 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1598 return false; 1599 1600 // An lvalue of function type T can be converted to an rvalue of 1601 // type "pointer to T." The result is a pointer to the 1602 // function. (C++ 4.3p1). 1603 FromType = S.Context.getPointerType(FromType); 1604 } else { 1605 // We don't require any conversions for the first step. 1606 SCS.First = ICK_Identity; 1607 } 1608 SCS.setToType(0, FromType); 1609 1610 // The second conversion can be an integral promotion, floating 1611 // point promotion, integral conversion, floating point conversion, 1612 // floating-integral conversion, pointer conversion, 1613 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1614 // For overloading in C, this can also be a "compatible-type" 1615 // conversion. 1616 bool IncompatibleObjC = false; 1617 ImplicitConversionKind SecondICK = ICK_Identity; 1618 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1619 // The unqualified versions of the types are the same: there's no 1620 // conversion to do. 1621 SCS.Second = ICK_Identity; 1622 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1623 // Integral promotion (C++ 4.5). 1624 SCS.Second = ICK_Integral_Promotion; 1625 FromType = ToType.getUnqualifiedType(); 1626 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1627 // Floating point promotion (C++ 4.6). 1628 SCS.Second = ICK_Floating_Promotion; 1629 FromType = ToType.getUnqualifiedType(); 1630 } else if (S.IsComplexPromotion(FromType, ToType)) { 1631 // Complex promotion (Clang extension) 1632 SCS.Second = ICK_Complex_Promotion; 1633 FromType = ToType.getUnqualifiedType(); 1634 } else if (ToType->isBooleanType() && 1635 (FromType->isArithmeticType() || 1636 FromType->isAnyPointerType() || 1637 FromType->isBlockPointerType() || 1638 FromType->isMemberPointerType() || 1639 FromType->isNullPtrType())) { 1640 // Boolean conversions (C++ 4.12). 1641 SCS.Second = ICK_Boolean_Conversion; 1642 FromType = S.Context.BoolTy; 1643 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1644 ToType->isIntegralType(S.Context)) { 1645 // Integral conversions (C++ 4.7). 1646 SCS.Second = ICK_Integral_Conversion; 1647 FromType = ToType.getUnqualifiedType(); 1648 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1649 // Complex conversions (C99 6.3.1.6) 1650 SCS.Second = ICK_Complex_Conversion; 1651 FromType = ToType.getUnqualifiedType(); 1652 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1653 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1654 // Complex-real conversions (C99 6.3.1.7) 1655 SCS.Second = ICK_Complex_Real; 1656 FromType = ToType.getUnqualifiedType(); 1657 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1658 // Floating point conversions (C++ 4.8). 1659 SCS.Second = ICK_Floating_Conversion; 1660 FromType = ToType.getUnqualifiedType(); 1661 } else if ((FromType->isRealFloatingType() && 1662 ToType->isIntegralType(S.Context)) || 1663 (FromType->isIntegralOrUnscopedEnumerationType() && 1664 ToType->isRealFloatingType())) { 1665 // Floating-integral conversions (C++ 4.9). 1666 SCS.Second = ICK_Floating_Integral; 1667 FromType = ToType.getUnqualifiedType(); 1668 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1669 SCS.Second = ICK_Block_Pointer_Conversion; 1670 } else if (AllowObjCWritebackConversion && 1671 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1672 SCS.Second = ICK_Writeback_Conversion; 1673 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1674 FromType, IncompatibleObjC)) { 1675 // Pointer conversions (C++ 4.10). 1676 SCS.Second = ICK_Pointer_Conversion; 1677 SCS.IncompatibleObjC = IncompatibleObjC; 1678 FromType = FromType.getUnqualifiedType(); 1679 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1680 InOverloadResolution, FromType)) { 1681 // Pointer to member conversions (4.11). 1682 SCS.Second = ICK_Pointer_Member; 1683 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1684 SCS.Second = SecondICK; 1685 FromType = ToType.getUnqualifiedType(); 1686 } else if (!S.getLangOpts().CPlusPlus && 1687 S.Context.typesAreCompatible(ToType, FromType)) { 1688 // Compatible conversions (Clang extension for C function overloading) 1689 SCS.Second = ICK_Compatible_Conversion; 1690 FromType = ToType.getUnqualifiedType(); 1691 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1692 // Treat a conversion that strips "noreturn" as an identity conversion. 1693 SCS.Second = ICK_NoReturn_Adjustment; 1694 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1695 InOverloadResolution, 1696 SCS, CStyle)) { 1697 SCS.Second = ICK_TransparentUnionConversion; 1698 FromType = ToType; 1699 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1700 CStyle)) { 1701 // tryAtomicConversion has updated the standard conversion sequence 1702 // appropriately. 1703 return true; 1704 } else if (ToType->isEventT() && 1705 From->isIntegerConstantExpr(S.getASTContext()) && 1706 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1707 SCS.Second = ICK_Zero_Event_Conversion; 1708 FromType = ToType; 1709 } else { 1710 // No second conversion required. 1711 SCS.Second = ICK_Identity; 1712 } 1713 SCS.setToType(1, FromType); 1714 1715 QualType CanonFrom; 1716 QualType CanonTo; 1717 // The third conversion can be a qualification conversion (C++ 4p1). 1718 bool ObjCLifetimeConversion; 1719 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1720 ObjCLifetimeConversion)) { 1721 SCS.Third = ICK_Qualification; 1722 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1723 FromType = ToType; 1724 CanonFrom = S.Context.getCanonicalType(FromType); 1725 CanonTo = S.Context.getCanonicalType(ToType); 1726 } else { 1727 // No conversion required 1728 SCS.Third = ICK_Identity; 1729 1730 // C++ [over.best.ics]p6: 1731 // [...] Any difference in top-level cv-qualification is 1732 // subsumed by the initialization itself and does not constitute 1733 // a conversion. [...] 1734 CanonFrom = S.Context.getCanonicalType(FromType); 1735 CanonTo = S.Context.getCanonicalType(ToType); 1736 if (CanonFrom.getLocalUnqualifiedType() 1737 == CanonTo.getLocalUnqualifiedType() && 1738 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1739 FromType = ToType; 1740 CanonFrom = CanonTo; 1741 } 1742 } 1743 SCS.setToType(2, FromType); 1744 1745 if (CanonFrom == CanonTo) 1746 return true; 1747 1748 // If we have not converted the argument type to the parameter type, 1749 // this is a bad conversion sequence, unless we're resolving an overload in C. 1750 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1751 return false; 1752 1753 ExprResult ER = ExprResult{From}; 1754 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1755 /*Diagnose=*/false, 1756 /*DiagnoseCFAudited=*/false, 1757 /*ConvertRHS=*/false); 1758 if (Conv != Sema::Compatible) 1759 return false; 1760 1761 SCS.setAllToTypes(ToType); 1762 // We need to set all three because we want this conversion to rank terribly, 1763 // and we don't know what conversions it may overlap with. 1764 SCS.First = ICK_C_Only_Conversion; 1765 SCS.Second = ICK_C_Only_Conversion; 1766 SCS.Third = ICK_C_Only_Conversion; 1767 return true; 1768 } 1769 1770 static bool 1771 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1772 QualType &ToType, 1773 bool InOverloadResolution, 1774 StandardConversionSequence &SCS, 1775 bool CStyle) { 1776 1777 const RecordType *UT = ToType->getAsUnionType(); 1778 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1779 return false; 1780 // The field to initialize within the transparent union. 1781 RecordDecl *UD = UT->getDecl(); 1782 // It's compatible if the expression matches any of the fields. 1783 for (const auto *it : UD->fields()) { 1784 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1785 CStyle, /*ObjCWritebackConversion=*/false)) { 1786 ToType = it->getType(); 1787 return true; 1788 } 1789 } 1790 return false; 1791 } 1792 1793 /// IsIntegralPromotion - Determines whether the conversion from the 1794 /// expression From (whose potentially-adjusted type is FromType) to 1795 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1796 /// sets PromotedType to the promoted type. 1797 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1798 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1799 // All integers are built-in. 1800 if (!To) { 1801 return false; 1802 } 1803 1804 // An rvalue of type char, signed char, unsigned char, short int, or 1805 // unsigned short int can be converted to an rvalue of type int if 1806 // int can represent all the values of the source type; otherwise, 1807 // the source rvalue can be converted to an rvalue of type unsigned 1808 // int (C++ 4.5p1). 1809 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1810 !FromType->isEnumeralType()) { 1811 if (// We can promote any signed, promotable integer type to an int 1812 (FromType->isSignedIntegerType() || 1813 // We can promote any unsigned integer type whose size is 1814 // less than int to an int. 1815 (!FromType->isSignedIntegerType() && 1816 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1817 return To->getKind() == BuiltinType::Int; 1818 } 1819 1820 return To->getKind() == BuiltinType::UInt; 1821 } 1822 1823 // C++11 [conv.prom]p3: 1824 // A prvalue of an unscoped enumeration type whose underlying type is not 1825 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1826 // following types that can represent all the values of the enumeration 1827 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1828 // unsigned int, long int, unsigned long int, long long int, or unsigned 1829 // long long int. If none of the types in that list can represent all the 1830 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1831 // type can be converted to an rvalue a prvalue of the extended integer type 1832 // with lowest integer conversion rank (4.13) greater than the rank of long 1833 // long in which all the values of the enumeration can be represented. If 1834 // there are two such extended types, the signed one is chosen. 1835 // C++11 [conv.prom]p4: 1836 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1837 // can be converted to a prvalue of its underlying type. Moreover, if 1838 // integral promotion can be applied to its underlying type, a prvalue of an 1839 // unscoped enumeration type whose underlying type is fixed can also be 1840 // converted to a prvalue of the promoted underlying type. 1841 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1842 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1843 // provided for a scoped enumeration. 1844 if (FromEnumType->getDecl()->isScoped()) 1845 return false; 1846 1847 // We can perform an integral promotion to the underlying type of the enum, 1848 // even if that's not the promoted type. Note that the check for promoting 1849 // the underlying type is based on the type alone, and does not consider 1850 // the bitfield-ness of the actual source expression. 1851 if (FromEnumType->getDecl()->isFixed()) { 1852 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1853 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1854 IsIntegralPromotion(nullptr, Underlying, ToType); 1855 } 1856 1857 // We have already pre-calculated the promotion type, so this is trivial. 1858 if (ToType->isIntegerType() && 1859 isCompleteType(From->getLocStart(), FromType)) 1860 return Context.hasSameUnqualifiedType( 1861 ToType, FromEnumType->getDecl()->getPromotionType()); 1862 } 1863 1864 // C++0x [conv.prom]p2: 1865 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1866 // to an rvalue a prvalue of the first of the following types that can 1867 // represent all the values of its underlying type: int, unsigned int, 1868 // long int, unsigned long int, long long int, or unsigned long long int. 1869 // If none of the types in that list can represent all the values of its 1870 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1871 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1872 // type. 1873 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1874 ToType->isIntegerType()) { 1875 // Determine whether the type we're converting from is signed or 1876 // unsigned. 1877 bool FromIsSigned = FromType->isSignedIntegerType(); 1878 uint64_t FromSize = Context.getTypeSize(FromType); 1879 1880 // The types we'll try to promote to, in the appropriate 1881 // order. Try each of these types. 1882 QualType PromoteTypes[6] = { 1883 Context.IntTy, Context.UnsignedIntTy, 1884 Context.LongTy, Context.UnsignedLongTy , 1885 Context.LongLongTy, Context.UnsignedLongLongTy 1886 }; 1887 for (int Idx = 0; Idx < 6; ++Idx) { 1888 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1889 if (FromSize < ToSize || 1890 (FromSize == ToSize && 1891 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1892 // We found the type that we can promote to. If this is the 1893 // type we wanted, we have a promotion. Otherwise, no 1894 // promotion. 1895 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1896 } 1897 } 1898 } 1899 1900 // An rvalue for an integral bit-field (9.6) can be converted to an 1901 // rvalue of type int if int can represent all the values of the 1902 // bit-field; otherwise, it can be converted to unsigned int if 1903 // unsigned int can represent all the values of the bit-field. If 1904 // the bit-field is larger yet, no integral promotion applies to 1905 // it. If the bit-field has an enumerated type, it is treated as any 1906 // other value of that type for promotion purposes (C++ 4.5p3). 1907 // FIXME: We should delay checking of bit-fields until we actually perform the 1908 // conversion. 1909 if (From) { 1910 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1911 llvm::APSInt BitWidth; 1912 if (FromType->isIntegralType(Context) && 1913 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1914 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1915 ToSize = Context.getTypeSize(ToType); 1916 1917 // Are we promoting to an int from a bitfield that fits in an int? 1918 if (BitWidth < ToSize || 1919 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1920 return To->getKind() == BuiltinType::Int; 1921 } 1922 1923 // Are we promoting to an unsigned int from an unsigned bitfield 1924 // that fits into an unsigned int? 1925 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1926 return To->getKind() == BuiltinType::UInt; 1927 } 1928 1929 return false; 1930 } 1931 } 1932 } 1933 1934 // An rvalue of type bool can be converted to an rvalue of type int, 1935 // with false becoming zero and true becoming one (C++ 4.5p4). 1936 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1937 return true; 1938 } 1939 1940 return false; 1941 } 1942 1943 /// IsFloatingPointPromotion - Determines whether the conversion from 1944 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1945 /// returns true and sets PromotedType to the promoted type. 1946 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1947 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1948 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1949 /// An rvalue of type float can be converted to an rvalue of type 1950 /// double. (C++ 4.6p1). 1951 if (FromBuiltin->getKind() == BuiltinType::Float && 1952 ToBuiltin->getKind() == BuiltinType::Double) 1953 return true; 1954 1955 // C99 6.3.1.5p1: 1956 // When a float is promoted to double or long double, or a 1957 // double is promoted to long double [...]. 1958 if (!getLangOpts().CPlusPlus && 1959 (FromBuiltin->getKind() == BuiltinType::Float || 1960 FromBuiltin->getKind() == BuiltinType::Double) && 1961 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1962 return true; 1963 1964 // Half can be promoted to float. 1965 if (!getLangOpts().NativeHalfType && 1966 FromBuiltin->getKind() == BuiltinType::Half && 1967 ToBuiltin->getKind() == BuiltinType::Float) 1968 return true; 1969 } 1970 1971 return false; 1972 } 1973 1974 /// \brief Determine if a conversion is a complex promotion. 1975 /// 1976 /// A complex promotion is defined as a complex -> complex conversion 1977 /// where the conversion between the underlying real types is a 1978 /// floating-point or integral promotion. 1979 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1980 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1981 if (!FromComplex) 1982 return false; 1983 1984 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1985 if (!ToComplex) 1986 return false; 1987 1988 return IsFloatingPointPromotion(FromComplex->getElementType(), 1989 ToComplex->getElementType()) || 1990 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1991 ToComplex->getElementType()); 1992 } 1993 1994 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1995 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1996 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1997 /// if non-empty, will be a pointer to ToType that may or may not have 1998 /// the right set of qualifiers on its pointee. 1999 /// 2000 static QualType 2001 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2002 QualType ToPointee, QualType ToType, 2003 ASTContext &Context, 2004 bool StripObjCLifetime = false) { 2005 assert((FromPtr->getTypeClass() == Type::Pointer || 2006 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2007 "Invalid similarly-qualified pointer type"); 2008 2009 /// Conversions to 'id' subsume cv-qualifier conversions. 2010 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2011 return ToType.getUnqualifiedType(); 2012 2013 QualType CanonFromPointee 2014 = Context.getCanonicalType(FromPtr->getPointeeType()); 2015 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2016 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2017 2018 if (StripObjCLifetime) 2019 Quals.removeObjCLifetime(); 2020 2021 // Exact qualifier match -> return the pointer type we're converting to. 2022 if (CanonToPointee.getLocalQualifiers() == Quals) { 2023 // ToType is exactly what we need. Return it. 2024 if (!ToType.isNull()) 2025 return ToType.getUnqualifiedType(); 2026 2027 // Build a pointer to ToPointee. It has the right qualifiers 2028 // already. 2029 if (isa<ObjCObjectPointerType>(ToType)) 2030 return Context.getObjCObjectPointerType(ToPointee); 2031 return Context.getPointerType(ToPointee); 2032 } 2033 2034 // Just build a canonical type that has the right qualifiers. 2035 QualType QualifiedCanonToPointee 2036 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2037 2038 if (isa<ObjCObjectPointerType>(ToType)) 2039 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2040 return Context.getPointerType(QualifiedCanonToPointee); 2041 } 2042 2043 static bool isNullPointerConstantForConversion(Expr *Expr, 2044 bool InOverloadResolution, 2045 ASTContext &Context) { 2046 // Handle value-dependent integral null pointer constants correctly. 2047 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2048 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2049 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2050 return !InOverloadResolution; 2051 2052 return Expr->isNullPointerConstant(Context, 2053 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2054 : Expr::NPC_ValueDependentIsNull); 2055 } 2056 2057 /// IsPointerConversion - Determines whether the conversion of the 2058 /// expression From, which has the (possibly adjusted) type FromType, 2059 /// can be converted to the type ToType via a pointer conversion (C++ 2060 /// 4.10). If so, returns true and places the converted type (that 2061 /// might differ from ToType in its cv-qualifiers at some level) into 2062 /// ConvertedType. 2063 /// 2064 /// This routine also supports conversions to and from block pointers 2065 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2066 /// pointers to interfaces. FIXME: Once we've determined the 2067 /// appropriate overloading rules for Objective-C, we may want to 2068 /// split the Objective-C checks into a different routine; however, 2069 /// GCC seems to consider all of these conversions to be pointer 2070 /// conversions, so for now they live here. IncompatibleObjC will be 2071 /// set if the conversion is an allowed Objective-C conversion that 2072 /// should result in a warning. 2073 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2074 bool InOverloadResolution, 2075 QualType& ConvertedType, 2076 bool &IncompatibleObjC) { 2077 IncompatibleObjC = false; 2078 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2079 IncompatibleObjC)) 2080 return true; 2081 2082 // Conversion from a null pointer constant to any Objective-C pointer type. 2083 if (ToType->isObjCObjectPointerType() && 2084 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2085 ConvertedType = ToType; 2086 return true; 2087 } 2088 2089 // Blocks: Block pointers can be converted to void*. 2090 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2091 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2092 ConvertedType = ToType; 2093 return true; 2094 } 2095 // Blocks: A null pointer constant can be converted to a block 2096 // pointer type. 2097 if (ToType->isBlockPointerType() && 2098 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2099 ConvertedType = ToType; 2100 return true; 2101 } 2102 2103 // If the left-hand-side is nullptr_t, the right side can be a null 2104 // pointer constant. 2105 if (ToType->isNullPtrType() && 2106 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2107 ConvertedType = ToType; 2108 return true; 2109 } 2110 2111 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2112 if (!ToTypePtr) 2113 return false; 2114 2115 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2116 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2117 ConvertedType = ToType; 2118 return true; 2119 } 2120 2121 // Beyond this point, both types need to be pointers 2122 // , including objective-c pointers. 2123 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2124 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2125 !getLangOpts().ObjCAutoRefCount) { 2126 ConvertedType = BuildSimilarlyQualifiedPointerType( 2127 FromType->getAs<ObjCObjectPointerType>(), 2128 ToPointeeType, 2129 ToType, Context); 2130 return true; 2131 } 2132 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2133 if (!FromTypePtr) 2134 return false; 2135 2136 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2137 2138 // If the unqualified pointee types are the same, this can't be a 2139 // pointer conversion, so don't do all of the work below. 2140 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2141 return false; 2142 2143 // An rvalue of type "pointer to cv T," where T is an object type, 2144 // can be converted to an rvalue of type "pointer to cv void" (C++ 2145 // 4.10p2). 2146 if (FromPointeeType->isIncompleteOrObjectType() && 2147 ToPointeeType->isVoidType()) { 2148 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2149 ToPointeeType, 2150 ToType, Context, 2151 /*StripObjCLifetime=*/true); 2152 return true; 2153 } 2154 2155 // MSVC allows implicit function to void* type conversion. 2156 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2157 ToPointeeType->isVoidType()) { 2158 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2159 ToPointeeType, 2160 ToType, Context); 2161 return true; 2162 } 2163 2164 // When we're overloading in C, we allow a special kind of pointer 2165 // conversion for compatible-but-not-identical pointee types. 2166 if (!getLangOpts().CPlusPlus && 2167 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2169 ToPointeeType, 2170 ToType, Context); 2171 return true; 2172 } 2173 2174 // C++ [conv.ptr]p3: 2175 // 2176 // An rvalue of type "pointer to cv D," where D is a class type, 2177 // can be converted to an rvalue of type "pointer to cv B," where 2178 // B is a base class (clause 10) of D. If B is an inaccessible 2179 // (clause 11) or ambiguous (10.2) base class of D, a program that 2180 // necessitates this conversion is ill-formed. The result of the 2181 // conversion is a pointer to the base class sub-object of the 2182 // derived class object. The null pointer value is converted to 2183 // the null pointer value of the destination type. 2184 // 2185 // Note that we do not check for ambiguity or inaccessibility 2186 // here. That is handled by CheckPointerConversion. 2187 if (getLangOpts().CPlusPlus && 2188 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2189 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2190 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2191 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2192 ToPointeeType, 2193 ToType, Context); 2194 return true; 2195 } 2196 2197 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2198 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2200 ToPointeeType, 2201 ToType, Context); 2202 return true; 2203 } 2204 2205 return false; 2206 } 2207 2208 /// \brief Adopt the given qualifiers for the given type. 2209 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2210 Qualifiers TQs = T.getQualifiers(); 2211 2212 // Check whether qualifiers already match. 2213 if (TQs == Qs) 2214 return T; 2215 2216 if (Qs.compatiblyIncludes(TQs)) 2217 return Context.getQualifiedType(T, Qs); 2218 2219 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2220 } 2221 2222 /// isObjCPointerConversion - Determines whether this is an 2223 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2224 /// with the same arguments and return values. 2225 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2226 QualType& ConvertedType, 2227 bool &IncompatibleObjC) { 2228 if (!getLangOpts().ObjC1) 2229 return false; 2230 2231 // The set of qualifiers on the type we're converting from. 2232 Qualifiers FromQualifiers = FromType.getQualifiers(); 2233 2234 // First, we handle all conversions on ObjC object pointer types. 2235 const ObjCObjectPointerType* ToObjCPtr = 2236 ToType->getAs<ObjCObjectPointerType>(); 2237 const ObjCObjectPointerType *FromObjCPtr = 2238 FromType->getAs<ObjCObjectPointerType>(); 2239 2240 if (ToObjCPtr && FromObjCPtr) { 2241 // If the pointee types are the same (ignoring qualifications), 2242 // then this is not a pointer conversion. 2243 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2244 FromObjCPtr->getPointeeType())) 2245 return false; 2246 2247 // Conversion between Objective-C pointers. 2248 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2249 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2250 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2251 if (getLangOpts().CPlusPlus && LHS && RHS && 2252 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2253 FromObjCPtr->getPointeeType())) 2254 return false; 2255 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2256 ToObjCPtr->getPointeeType(), 2257 ToType, Context); 2258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2259 return true; 2260 } 2261 2262 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2263 // Okay: this is some kind of implicit downcast of Objective-C 2264 // interfaces, which is permitted. However, we're going to 2265 // complain about it. 2266 IncompatibleObjC = true; 2267 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2268 ToObjCPtr->getPointeeType(), 2269 ToType, Context); 2270 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2271 return true; 2272 } 2273 } 2274 // Beyond this point, both types need to be C pointers or block pointers. 2275 QualType ToPointeeType; 2276 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2277 ToPointeeType = ToCPtr->getPointeeType(); 2278 else if (const BlockPointerType *ToBlockPtr = 2279 ToType->getAs<BlockPointerType>()) { 2280 // Objective C++: We're able to convert from a pointer to any object 2281 // to a block pointer type. 2282 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2283 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2284 return true; 2285 } 2286 ToPointeeType = ToBlockPtr->getPointeeType(); 2287 } 2288 else if (FromType->getAs<BlockPointerType>() && 2289 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2290 // Objective C++: We're able to convert from a block pointer type to a 2291 // pointer to any object. 2292 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2293 return true; 2294 } 2295 else 2296 return false; 2297 2298 QualType FromPointeeType; 2299 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2300 FromPointeeType = FromCPtr->getPointeeType(); 2301 else if (const BlockPointerType *FromBlockPtr = 2302 FromType->getAs<BlockPointerType>()) 2303 FromPointeeType = FromBlockPtr->getPointeeType(); 2304 else 2305 return false; 2306 2307 // If we have pointers to pointers, recursively check whether this 2308 // is an Objective-C conversion. 2309 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2310 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2311 IncompatibleObjC)) { 2312 // We always complain about this conversion. 2313 IncompatibleObjC = true; 2314 ConvertedType = Context.getPointerType(ConvertedType); 2315 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2316 return true; 2317 } 2318 // Allow conversion of pointee being objective-c pointer to another one; 2319 // as in I* to id. 2320 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2321 ToPointeeType->getAs<ObjCObjectPointerType>() && 2322 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2323 IncompatibleObjC)) { 2324 2325 ConvertedType = Context.getPointerType(ConvertedType); 2326 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2327 return true; 2328 } 2329 2330 // If we have pointers to functions or blocks, check whether the only 2331 // differences in the argument and result types are in Objective-C 2332 // pointer conversions. If so, we permit the conversion (but 2333 // complain about it). 2334 const FunctionProtoType *FromFunctionType 2335 = FromPointeeType->getAs<FunctionProtoType>(); 2336 const FunctionProtoType *ToFunctionType 2337 = ToPointeeType->getAs<FunctionProtoType>(); 2338 if (FromFunctionType && ToFunctionType) { 2339 // If the function types are exactly the same, this isn't an 2340 // Objective-C pointer conversion. 2341 if (Context.getCanonicalType(FromPointeeType) 2342 == Context.getCanonicalType(ToPointeeType)) 2343 return false; 2344 2345 // Perform the quick checks that will tell us whether these 2346 // function types are obviously different. 2347 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2348 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2349 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2350 return false; 2351 2352 bool HasObjCConversion = false; 2353 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2354 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2355 // Okay, the types match exactly. Nothing to do. 2356 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2357 ToFunctionType->getReturnType(), 2358 ConvertedType, IncompatibleObjC)) { 2359 // Okay, we have an Objective-C pointer conversion. 2360 HasObjCConversion = true; 2361 } else { 2362 // Function types are too different. Abort. 2363 return false; 2364 } 2365 2366 // Check argument types. 2367 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2368 ArgIdx != NumArgs; ++ArgIdx) { 2369 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2370 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2371 if (Context.getCanonicalType(FromArgType) 2372 == Context.getCanonicalType(ToArgType)) { 2373 // Okay, the types match exactly. Nothing to do. 2374 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2375 ConvertedType, IncompatibleObjC)) { 2376 // Okay, we have an Objective-C pointer conversion. 2377 HasObjCConversion = true; 2378 } else { 2379 // Argument types are too different. Abort. 2380 return false; 2381 } 2382 } 2383 2384 if (HasObjCConversion) { 2385 // We had an Objective-C conversion. Allow this pointer 2386 // conversion, but complain about it. 2387 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2388 IncompatibleObjC = true; 2389 return true; 2390 } 2391 } 2392 2393 return false; 2394 } 2395 2396 /// \brief Determine whether this is an Objective-C writeback conversion, 2397 /// used for parameter passing when performing automatic reference counting. 2398 /// 2399 /// \param FromType The type we're converting form. 2400 /// 2401 /// \param ToType The type we're converting to. 2402 /// 2403 /// \param ConvertedType The type that will be produced after applying 2404 /// this conversion. 2405 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2406 QualType &ConvertedType) { 2407 if (!getLangOpts().ObjCAutoRefCount || 2408 Context.hasSameUnqualifiedType(FromType, ToType)) 2409 return false; 2410 2411 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2412 QualType ToPointee; 2413 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2414 ToPointee = ToPointer->getPointeeType(); 2415 else 2416 return false; 2417 2418 Qualifiers ToQuals = ToPointee.getQualifiers(); 2419 if (!ToPointee->isObjCLifetimeType() || 2420 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2421 !ToQuals.withoutObjCLifetime().empty()) 2422 return false; 2423 2424 // Argument must be a pointer to __strong to __weak. 2425 QualType FromPointee; 2426 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2427 FromPointee = FromPointer->getPointeeType(); 2428 else 2429 return false; 2430 2431 Qualifiers FromQuals = FromPointee.getQualifiers(); 2432 if (!FromPointee->isObjCLifetimeType() || 2433 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2434 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2435 return false; 2436 2437 // Make sure that we have compatible qualifiers. 2438 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2439 if (!ToQuals.compatiblyIncludes(FromQuals)) 2440 return false; 2441 2442 // Remove qualifiers from the pointee type we're converting from; they 2443 // aren't used in the compatibility check belong, and we'll be adding back 2444 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2445 FromPointee = FromPointee.getUnqualifiedType(); 2446 2447 // The unqualified form of the pointee types must be compatible. 2448 ToPointee = ToPointee.getUnqualifiedType(); 2449 bool IncompatibleObjC; 2450 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2451 FromPointee = ToPointee; 2452 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2453 IncompatibleObjC)) 2454 return false; 2455 2456 /// \brief Construct the type we're converting to, which is a pointer to 2457 /// __autoreleasing pointee. 2458 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2459 ConvertedType = Context.getPointerType(FromPointee); 2460 return true; 2461 } 2462 2463 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2464 QualType& ConvertedType) { 2465 QualType ToPointeeType; 2466 if (const BlockPointerType *ToBlockPtr = 2467 ToType->getAs<BlockPointerType>()) 2468 ToPointeeType = ToBlockPtr->getPointeeType(); 2469 else 2470 return false; 2471 2472 QualType FromPointeeType; 2473 if (const BlockPointerType *FromBlockPtr = 2474 FromType->getAs<BlockPointerType>()) 2475 FromPointeeType = FromBlockPtr->getPointeeType(); 2476 else 2477 return false; 2478 // We have pointer to blocks, check whether the only 2479 // differences in the argument and result types are in Objective-C 2480 // pointer conversions. If so, we permit the conversion. 2481 2482 const FunctionProtoType *FromFunctionType 2483 = FromPointeeType->getAs<FunctionProtoType>(); 2484 const FunctionProtoType *ToFunctionType 2485 = ToPointeeType->getAs<FunctionProtoType>(); 2486 2487 if (!FromFunctionType || !ToFunctionType) 2488 return false; 2489 2490 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2491 return true; 2492 2493 // Perform the quick checks that will tell us whether these 2494 // function types are obviously different. 2495 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2496 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2497 return false; 2498 2499 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2500 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2501 if (FromEInfo != ToEInfo) 2502 return false; 2503 2504 bool IncompatibleObjC = false; 2505 if (Context.hasSameType(FromFunctionType->getReturnType(), 2506 ToFunctionType->getReturnType())) { 2507 // Okay, the types match exactly. Nothing to do. 2508 } else { 2509 QualType RHS = FromFunctionType->getReturnType(); 2510 QualType LHS = ToFunctionType->getReturnType(); 2511 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2512 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2513 LHS = LHS.getUnqualifiedType(); 2514 2515 if (Context.hasSameType(RHS,LHS)) { 2516 // OK exact match. 2517 } else if (isObjCPointerConversion(RHS, LHS, 2518 ConvertedType, IncompatibleObjC)) { 2519 if (IncompatibleObjC) 2520 return false; 2521 // Okay, we have an Objective-C pointer conversion. 2522 } 2523 else 2524 return false; 2525 } 2526 2527 // Check argument types. 2528 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2529 ArgIdx != NumArgs; ++ArgIdx) { 2530 IncompatibleObjC = false; 2531 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2532 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2533 if (Context.hasSameType(FromArgType, ToArgType)) { 2534 // Okay, the types match exactly. Nothing to do. 2535 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2536 ConvertedType, IncompatibleObjC)) { 2537 if (IncompatibleObjC) 2538 return false; 2539 // Okay, we have an Objective-C pointer conversion. 2540 } else 2541 // Argument types are too different. Abort. 2542 return false; 2543 } 2544 if (LangOpts.ObjCAutoRefCount && 2545 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2546 ToFunctionType)) 2547 return false; 2548 2549 ConvertedType = ToType; 2550 return true; 2551 } 2552 2553 enum { 2554 ft_default, 2555 ft_different_class, 2556 ft_parameter_arity, 2557 ft_parameter_mismatch, 2558 ft_return_type, 2559 ft_qualifer_mismatch 2560 }; 2561 2562 /// Attempts to get the FunctionProtoType from a Type. Handles 2563 /// MemberFunctionPointers properly. 2564 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2565 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2566 return FPT; 2567 2568 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2569 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2570 2571 return nullptr; 2572 } 2573 2574 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2575 /// function types. Catches different number of parameter, mismatch in 2576 /// parameter types, and different return types. 2577 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2578 QualType FromType, QualType ToType) { 2579 // If either type is not valid, include no extra info. 2580 if (FromType.isNull() || ToType.isNull()) { 2581 PDiag << ft_default; 2582 return; 2583 } 2584 2585 // Get the function type from the pointers. 2586 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2587 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2588 *ToMember = ToType->getAs<MemberPointerType>(); 2589 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2590 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2591 << QualType(FromMember->getClass(), 0); 2592 return; 2593 } 2594 FromType = FromMember->getPointeeType(); 2595 ToType = ToMember->getPointeeType(); 2596 } 2597 2598 if (FromType->isPointerType()) 2599 FromType = FromType->getPointeeType(); 2600 if (ToType->isPointerType()) 2601 ToType = ToType->getPointeeType(); 2602 2603 // Remove references. 2604 FromType = FromType.getNonReferenceType(); 2605 ToType = ToType.getNonReferenceType(); 2606 2607 // Don't print extra info for non-specialized template functions. 2608 if (FromType->isInstantiationDependentType() && 2609 !FromType->getAs<TemplateSpecializationType>()) { 2610 PDiag << ft_default; 2611 return; 2612 } 2613 2614 // No extra info for same types. 2615 if (Context.hasSameType(FromType, ToType)) { 2616 PDiag << ft_default; 2617 return; 2618 } 2619 2620 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2621 *ToFunction = tryGetFunctionProtoType(ToType); 2622 2623 // Both types need to be function types. 2624 if (!FromFunction || !ToFunction) { 2625 PDiag << ft_default; 2626 return; 2627 } 2628 2629 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2630 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2631 << FromFunction->getNumParams(); 2632 return; 2633 } 2634 2635 // Handle different parameter types. 2636 unsigned ArgPos; 2637 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2638 PDiag << ft_parameter_mismatch << ArgPos + 1 2639 << ToFunction->getParamType(ArgPos) 2640 << FromFunction->getParamType(ArgPos); 2641 return; 2642 } 2643 2644 // Handle different return type. 2645 if (!Context.hasSameType(FromFunction->getReturnType(), 2646 ToFunction->getReturnType())) { 2647 PDiag << ft_return_type << ToFunction->getReturnType() 2648 << FromFunction->getReturnType(); 2649 return; 2650 } 2651 2652 unsigned FromQuals = FromFunction->getTypeQuals(), 2653 ToQuals = ToFunction->getTypeQuals(); 2654 if (FromQuals != ToQuals) { 2655 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2656 return; 2657 } 2658 2659 // Unable to find a difference, so add no extra info. 2660 PDiag << ft_default; 2661 } 2662 2663 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2664 /// for equality of their argument types. Caller has already checked that 2665 /// they have same number of arguments. If the parameters are different, 2666 /// ArgPos will have the parameter index of the first different parameter. 2667 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2668 const FunctionProtoType *NewType, 2669 unsigned *ArgPos) { 2670 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2671 N = NewType->param_type_begin(), 2672 E = OldType->param_type_end(); 2673 O && (O != E); ++O, ++N) { 2674 if (!Context.hasSameType(O->getUnqualifiedType(), 2675 N->getUnqualifiedType())) { 2676 if (ArgPos) 2677 *ArgPos = O - OldType->param_type_begin(); 2678 return false; 2679 } 2680 } 2681 return true; 2682 } 2683 2684 /// CheckPointerConversion - Check the pointer conversion from the 2685 /// expression From to the type ToType. This routine checks for 2686 /// ambiguous or inaccessible derived-to-base pointer 2687 /// conversions for which IsPointerConversion has already returned 2688 /// true. It returns true and produces a diagnostic if there was an 2689 /// error, or returns false otherwise. 2690 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2691 CastKind &Kind, 2692 CXXCastPath& BasePath, 2693 bool IgnoreBaseAccess, 2694 bool Diagnose) { 2695 QualType FromType = From->getType(); 2696 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2697 2698 Kind = CK_BitCast; 2699 2700 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2701 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2702 Expr::NPCK_ZeroExpression) { 2703 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2704 DiagRuntimeBehavior(From->getExprLoc(), From, 2705 PDiag(diag::warn_impcast_bool_to_null_pointer) 2706 << ToType << From->getSourceRange()); 2707 else if (!isUnevaluatedContext()) 2708 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2709 << ToType << From->getSourceRange(); 2710 } 2711 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2712 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2713 QualType FromPointeeType = FromPtrType->getPointeeType(), 2714 ToPointeeType = ToPtrType->getPointeeType(); 2715 2716 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2717 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2718 // We must have a derived-to-base conversion. Check an 2719 // ambiguous or inaccessible conversion. 2720 unsigned InaccessibleID = 0; 2721 unsigned AmbigiousID = 0; 2722 if (Diagnose) { 2723 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2724 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2725 } 2726 if (CheckDerivedToBaseConversion( 2727 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2728 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2729 &BasePath, IgnoreBaseAccess)) 2730 return true; 2731 2732 // The conversion was successful. 2733 Kind = CK_DerivedToBase; 2734 } 2735 2736 if (Diagnose && !IsCStyleOrFunctionalCast && 2737 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2738 assert(getLangOpts().MSVCCompat && 2739 "this should only be possible with MSVCCompat!"); 2740 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2741 << From->getSourceRange(); 2742 } 2743 } 2744 } else if (const ObjCObjectPointerType *ToPtrType = 2745 ToType->getAs<ObjCObjectPointerType>()) { 2746 if (const ObjCObjectPointerType *FromPtrType = 2747 FromType->getAs<ObjCObjectPointerType>()) { 2748 // Objective-C++ conversions are always okay. 2749 // FIXME: We should have a different class of conversions for the 2750 // Objective-C++ implicit conversions. 2751 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2752 return false; 2753 } else if (FromType->isBlockPointerType()) { 2754 Kind = CK_BlockPointerToObjCPointerCast; 2755 } else { 2756 Kind = CK_CPointerToObjCPointerCast; 2757 } 2758 } else if (ToType->isBlockPointerType()) { 2759 if (!FromType->isBlockPointerType()) 2760 Kind = CK_AnyPointerToBlockPointerCast; 2761 } 2762 2763 // We shouldn't fall into this case unless it's valid for other 2764 // reasons. 2765 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2766 Kind = CK_NullToPointer; 2767 2768 return false; 2769 } 2770 2771 /// IsMemberPointerConversion - Determines whether the conversion of the 2772 /// expression From, which has the (possibly adjusted) type FromType, can be 2773 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2774 /// If so, returns true and places the converted type (that might differ from 2775 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2776 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2777 QualType ToType, 2778 bool InOverloadResolution, 2779 QualType &ConvertedType) { 2780 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2781 if (!ToTypePtr) 2782 return false; 2783 2784 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2785 if (From->isNullPointerConstant(Context, 2786 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2787 : Expr::NPC_ValueDependentIsNull)) { 2788 ConvertedType = ToType; 2789 return true; 2790 } 2791 2792 // Otherwise, both types have to be member pointers. 2793 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2794 if (!FromTypePtr) 2795 return false; 2796 2797 // A pointer to member of B can be converted to a pointer to member of D, 2798 // where D is derived from B (C++ 4.11p2). 2799 QualType FromClass(FromTypePtr->getClass(), 0); 2800 QualType ToClass(ToTypePtr->getClass(), 0); 2801 2802 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2803 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2804 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2805 ToClass.getTypePtr()); 2806 return true; 2807 } 2808 2809 return false; 2810 } 2811 2812 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2813 /// expression From to the type ToType. This routine checks for ambiguous or 2814 /// virtual or inaccessible base-to-derived member pointer conversions 2815 /// for which IsMemberPointerConversion has already returned true. It returns 2816 /// true and produces a diagnostic if there was an error, or returns false 2817 /// otherwise. 2818 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2819 CastKind &Kind, 2820 CXXCastPath &BasePath, 2821 bool IgnoreBaseAccess) { 2822 QualType FromType = From->getType(); 2823 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2824 if (!FromPtrType) { 2825 // This must be a null pointer to member pointer conversion 2826 assert(From->isNullPointerConstant(Context, 2827 Expr::NPC_ValueDependentIsNull) && 2828 "Expr must be null pointer constant!"); 2829 Kind = CK_NullToMemberPointer; 2830 return false; 2831 } 2832 2833 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2834 assert(ToPtrType && "No member pointer cast has a target type " 2835 "that is not a member pointer."); 2836 2837 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2838 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2839 2840 // FIXME: What about dependent types? 2841 assert(FromClass->isRecordType() && "Pointer into non-class."); 2842 assert(ToClass->isRecordType() && "Pointer into non-class."); 2843 2844 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2845 /*DetectVirtual=*/true); 2846 bool DerivationOkay = 2847 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2848 assert(DerivationOkay && 2849 "Should not have been called if derivation isn't OK."); 2850 (void)DerivationOkay; 2851 2852 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2853 getUnqualifiedType())) { 2854 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2855 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2856 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2857 return true; 2858 } 2859 2860 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2861 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2862 << FromClass << ToClass << QualType(VBase, 0) 2863 << From->getSourceRange(); 2864 return true; 2865 } 2866 2867 if (!IgnoreBaseAccess) 2868 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2869 Paths.front(), 2870 diag::err_downcast_from_inaccessible_base); 2871 2872 // Must be a base to derived member conversion. 2873 BuildBasePathArray(Paths, BasePath); 2874 Kind = CK_BaseToDerivedMemberPointer; 2875 return false; 2876 } 2877 2878 /// Determine whether the lifetime conversion between the two given 2879 /// qualifiers sets is nontrivial. 2880 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2881 Qualifiers ToQuals) { 2882 // Converting anything to const __unsafe_unretained is trivial. 2883 if (ToQuals.hasConst() && 2884 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2885 return false; 2886 2887 return true; 2888 } 2889 2890 /// IsQualificationConversion - Determines whether the conversion from 2891 /// an rvalue of type FromType to ToType is a qualification conversion 2892 /// (C++ 4.4). 2893 /// 2894 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2895 /// when the qualification conversion involves a change in the Objective-C 2896 /// object lifetime. 2897 bool 2898 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2899 bool CStyle, bool &ObjCLifetimeConversion) { 2900 FromType = Context.getCanonicalType(FromType); 2901 ToType = Context.getCanonicalType(ToType); 2902 ObjCLifetimeConversion = false; 2903 2904 // If FromType and ToType are the same type, this is not a 2905 // qualification conversion. 2906 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2907 return false; 2908 2909 // (C++ 4.4p4): 2910 // A conversion can add cv-qualifiers at levels other than the first 2911 // in multi-level pointers, subject to the following rules: [...] 2912 bool PreviousToQualsIncludeConst = true; 2913 bool UnwrappedAnyPointer = false; 2914 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2915 // Within each iteration of the loop, we check the qualifiers to 2916 // determine if this still looks like a qualification 2917 // conversion. Then, if all is well, we unwrap one more level of 2918 // pointers or pointers-to-members and do it all again 2919 // until there are no more pointers or pointers-to-members left to 2920 // unwrap. 2921 UnwrappedAnyPointer = true; 2922 2923 Qualifiers FromQuals = FromType.getQualifiers(); 2924 Qualifiers ToQuals = ToType.getQualifiers(); 2925 2926 // Objective-C ARC: 2927 // Check Objective-C lifetime conversions. 2928 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2929 UnwrappedAnyPointer) { 2930 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2931 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2932 ObjCLifetimeConversion = true; 2933 FromQuals.removeObjCLifetime(); 2934 ToQuals.removeObjCLifetime(); 2935 } else { 2936 // Qualification conversions cannot cast between different 2937 // Objective-C lifetime qualifiers. 2938 return false; 2939 } 2940 } 2941 2942 // Allow addition/removal of GC attributes but not changing GC attributes. 2943 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2944 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2945 FromQuals.removeObjCGCAttr(); 2946 ToQuals.removeObjCGCAttr(); 2947 } 2948 2949 // -- for every j > 0, if const is in cv 1,j then const is in cv 2950 // 2,j, and similarly for volatile. 2951 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2952 return false; 2953 2954 // -- if the cv 1,j and cv 2,j are different, then const is in 2955 // every cv for 0 < k < j. 2956 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2957 && !PreviousToQualsIncludeConst) 2958 return false; 2959 2960 // Keep track of whether all prior cv-qualifiers in the "to" type 2961 // include const. 2962 PreviousToQualsIncludeConst 2963 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2964 } 2965 2966 // We are left with FromType and ToType being the pointee types 2967 // after unwrapping the original FromType and ToType the same number 2968 // of types. If we unwrapped any pointers, and if FromType and 2969 // ToType have the same unqualified type (since we checked 2970 // qualifiers above), then this is a qualification conversion. 2971 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2972 } 2973 2974 /// \brief - Determine whether this is a conversion from a scalar type to an 2975 /// atomic type. 2976 /// 2977 /// If successful, updates \c SCS's second and third steps in the conversion 2978 /// sequence to finish the conversion. 2979 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2980 bool InOverloadResolution, 2981 StandardConversionSequence &SCS, 2982 bool CStyle) { 2983 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2984 if (!ToAtomic) 2985 return false; 2986 2987 StandardConversionSequence InnerSCS; 2988 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2989 InOverloadResolution, InnerSCS, 2990 CStyle, /*AllowObjCWritebackConversion=*/false)) 2991 return false; 2992 2993 SCS.Second = InnerSCS.Second; 2994 SCS.setToType(1, InnerSCS.getToType(1)); 2995 SCS.Third = InnerSCS.Third; 2996 SCS.QualificationIncludesObjCLifetime 2997 = InnerSCS.QualificationIncludesObjCLifetime; 2998 SCS.setToType(2, InnerSCS.getToType(2)); 2999 return true; 3000 } 3001 3002 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3003 CXXConstructorDecl *Constructor, 3004 QualType Type) { 3005 const FunctionProtoType *CtorType = 3006 Constructor->getType()->getAs<FunctionProtoType>(); 3007 if (CtorType->getNumParams() > 0) { 3008 QualType FirstArg = CtorType->getParamType(0); 3009 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3010 return true; 3011 } 3012 return false; 3013 } 3014 3015 static OverloadingResult 3016 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3017 CXXRecordDecl *To, 3018 UserDefinedConversionSequence &User, 3019 OverloadCandidateSet &CandidateSet, 3020 bool AllowExplicit) { 3021 DeclContext::lookup_result R = S.LookupConstructors(To); 3022 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3023 Con != ConEnd; ++Con) { 3024 NamedDecl *D = *Con; 3025 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3026 3027 // Find the constructor (which may be a template). 3028 CXXConstructorDecl *Constructor = nullptr; 3029 FunctionTemplateDecl *ConstructorTmpl 3030 = dyn_cast<FunctionTemplateDecl>(D); 3031 if (ConstructorTmpl) 3032 Constructor 3033 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3034 else 3035 Constructor = cast<CXXConstructorDecl>(D); 3036 3037 bool Usable = !Constructor->isInvalidDecl() && 3038 S.isInitListConstructor(Constructor) && 3039 (AllowExplicit || !Constructor->isExplicit()); 3040 if (Usable) { 3041 // If the first argument is (a reference to) the target type, 3042 // suppress conversions. 3043 bool SuppressUserConversions = 3044 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 3045 if (ConstructorTmpl) 3046 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3047 /*ExplicitArgs*/ nullptr, 3048 From, CandidateSet, 3049 SuppressUserConversions); 3050 else 3051 S.AddOverloadCandidate(Constructor, FoundDecl, 3052 From, CandidateSet, 3053 SuppressUserConversions); 3054 } 3055 } 3056 3057 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3058 3059 OverloadCandidateSet::iterator Best; 3060 switch (auto Result = 3061 CandidateSet.BestViableFunction(S, From->getLocStart(), 3062 Best, true)) { 3063 case OR_Deleted: 3064 case OR_Success: { 3065 // Record the standard conversion we used and the conversion function. 3066 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3067 QualType ThisType = Constructor->getThisType(S.Context); 3068 // Initializer lists don't have conversions as such. 3069 User.Before.setAsIdentityConversion(); 3070 User.HadMultipleCandidates = HadMultipleCandidates; 3071 User.ConversionFunction = Constructor; 3072 User.FoundConversionFunction = Best->FoundDecl; 3073 User.After.setAsIdentityConversion(); 3074 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3075 User.After.setAllToTypes(ToType); 3076 return Result; 3077 } 3078 3079 case OR_No_Viable_Function: 3080 return OR_No_Viable_Function; 3081 case OR_Ambiguous: 3082 return OR_Ambiguous; 3083 } 3084 3085 llvm_unreachable("Invalid OverloadResult!"); 3086 } 3087 3088 /// Determines whether there is a user-defined conversion sequence 3089 /// (C++ [over.ics.user]) that converts expression From to the type 3090 /// ToType. If such a conversion exists, User will contain the 3091 /// user-defined conversion sequence that performs such a conversion 3092 /// and this routine will return true. Otherwise, this routine returns 3093 /// false and User is unspecified. 3094 /// 3095 /// \param AllowExplicit true if the conversion should consider C++0x 3096 /// "explicit" conversion functions as well as non-explicit conversion 3097 /// functions (C++0x [class.conv.fct]p2). 3098 /// 3099 /// \param AllowObjCConversionOnExplicit true if the conversion should 3100 /// allow an extra Objective-C pointer conversion on uses of explicit 3101 /// constructors. Requires \c AllowExplicit to also be set. 3102 static OverloadingResult 3103 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3104 UserDefinedConversionSequence &User, 3105 OverloadCandidateSet &CandidateSet, 3106 bool AllowExplicit, 3107 bool AllowObjCConversionOnExplicit) { 3108 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3109 3110 // Whether we will only visit constructors. 3111 bool ConstructorsOnly = false; 3112 3113 // If the type we are conversion to is a class type, enumerate its 3114 // constructors. 3115 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3116 // C++ [over.match.ctor]p1: 3117 // When objects of class type are direct-initialized (8.5), or 3118 // copy-initialized from an expression of the same or a 3119 // derived class type (8.5), overload resolution selects the 3120 // constructor. [...] For copy-initialization, the candidate 3121 // functions are all the converting constructors (12.3.1) of 3122 // that class. The argument list is the expression-list within 3123 // the parentheses of the initializer. 3124 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3125 (From->getType()->getAs<RecordType>() && 3126 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3127 ConstructorsOnly = true; 3128 3129 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3130 // We're not going to find any constructors. 3131 } else if (CXXRecordDecl *ToRecordDecl 3132 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3133 3134 Expr **Args = &From; 3135 unsigned NumArgs = 1; 3136 bool ListInitializing = false; 3137 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3138 // But first, see if there is an init-list-constructor that will work. 3139 OverloadingResult Result = IsInitializerListConstructorConversion( 3140 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3141 if (Result != OR_No_Viable_Function) 3142 return Result; 3143 // Never mind. 3144 CandidateSet.clear(); 3145 3146 // If we're list-initializing, we pass the individual elements as 3147 // arguments, not the entire list. 3148 Args = InitList->getInits(); 3149 NumArgs = InitList->getNumInits(); 3150 ListInitializing = true; 3151 } 3152 3153 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3154 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3155 Con != ConEnd; ++Con) { 3156 NamedDecl *D = *Con; 3157 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3158 3159 // Find the constructor (which may be a template). 3160 CXXConstructorDecl *Constructor = nullptr; 3161 FunctionTemplateDecl *ConstructorTmpl 3162 = dyn_cast<FunctionTemplateDecl>(D); 3163 if (ConstructorTmpl) 3164 Constructor 3165 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3166 else 3167 Constructor = cast<CXXConstructorDecl>(D); 3168 3169 bool Usable = !Constructor->isInvalidDecl(); 3170 if (ListInitializing) 3171 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3172 else 3173 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3174 if (Usable) { 3175 bool SuppressUserConversions = !ConstructorsOnly; 3176 if (SuppressUserConversions && ListInitializing) { 3177 SuppressUserConversions = false; 3178 if (NumArgs == 1) { 3179 // If the first argument is (a reference to) the target type, 3180 // suppress conversions. 3181 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3182 S.Context, Constructor, ToType); 3183 } 3184 } 3185 if (ConstructorTmpl) 3186 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3187 /*ExplicitArgs*/ nullptr, 3188 llvm::makeArrayRef(Args, NumArgs), 3189 CandidateSet, SuppressUserConversions); 3190 else 3191 // Allow one user-defined conversion when user specifies a 3192 // From->ToType conversion via an static cast (c-style, etc). 3193 S.AddOverloadCandidate(Constructor, FoundDecl, 3194 llvm::makeArrayRef(Args, NumArgs), 3195 CandidateSet, SuppressUserConversions); 3196 } 3197 } 3198 } 3199 } 3200 3201 // Enumerate conversion functions, if we're allowed to. 3202 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3203 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3204 // No conversion functions from incomplete types. 3205 } else if (const RecordType *FromRecordType 3206 = From->getType()->getAs<RecordType>()) { 3207 if (CXXRecordDecl *FromRecordDecl 3208 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3209 // Add all of the conversion functions as candidates. 3210 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3211 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3212 DeclAccessPair FoundDecl = I.getPair(); 3213 NamedDecl *D = FoundDecl.getDecl(); 3214 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3215 if (isa<UsingShadowDecl>(D)) 3216 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3217 3218 CXXConversionDecl *Conv; 3219 FunctionTemplateDecl *ConvTemplate; 3220 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3221 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3222 else 3223 Conv = cast<CXXConversionDecl>(D); 3224 3225 if (AllowExplicit || !Conv->isExplicit()) { 3226 if (ConvTemplate) 3227 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3228 ActingContext, From, ToType, 3229 CandidateSet, 3230 AllowObjCConversionOnExplicit); 3231 else 3232 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3233 From, ToType, CandidateSet, 3234 AllowObjCConversionOnExplicit); 3235 } 3236 } 3237 } 3238 } 3239 3240 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3241 3242 OverloadCandidateSet::iterator Best; 3243 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3244 Best, true)) { 3245 case OR_Success: 3246 case OR_Deleted: 3247 // Record the standard conversion we used and the conversion function. 3248 if (CXXConstructorDecl *Constructor 3249 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3250 // C++ [over.ics.user]p1: 3251 // If the user-defined conversion is specified by a 3252 // constructor (12.3.1), the initial standard conversion 3253 // sequence converts the source type to the type required by 3254 // the argument of the constructor. 3255 // 3256 QualType ThisType = Constructor->getThisType(S.Context); 3257 if (isa<InitListExpr>(From)) { 3258 // Initializer lists don't have conversions as such. 3259 User.Before.setAsIdentityConversion(); 3260 } else { 3261 if (Best->Conversions[0].isEllipsis()) 3262 User.EllipsisConversion = true; 3263 else { 3264 User.Before = Best->Conversions[0].Standard; 3265 User.EllipsisConversion = false; 3266 } 3267 } 3268 User.HadMultipleCandidates = HadMultipleCandidates; 3269 User.ConversionFunction = Constructor; 3270 User.FoundConversionFunction = Best->FoundDecl; 3271 User.After.setAsIdentityConversion(); 3272 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3273 User.After.setAllToTypes(ToType); 3274 return Result; 3275 } 3276 if (CXXConversionDecl *Conversion 3277 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3278 // C++ [over.ics.user]p1: 3279 // 3280 // [...] If the user-defined conversion is specified by a 3281 // conversion function (12.3.2), the initial standard 3282 // conversion sequence converts the source type to the 3283 // implicit object parameter of the conversion function. 3284 User.Before = Best->Conversions[0].Standard; 3285 User.HadMultipleCandidates = HadMultipleCandidates; 3286 User.ConversionFunction = Conversion; 3287 User.FoundConversionFunction = Best->FoundDecl; 3288 User.EllipsisConversion = false; 3289 3290 // C++ [over.ics.user]p2: 3291 // The second standard conversion sequence converts the 3292 // result of the user-defined conversion to the target type 3293 // for the sequence. Since an implicit conversion sequence 3294 // is an initialization, the special rules for 3295 // initialization by user-defined conversion apply when 3296 // selecting the best user-defined conversion for a 3297 // user-defined conversion sequence (see 13.3.3 and 3298 // 13.3.3.1). 3299 User.After = Best->FinalConversion; 3300 return Result; 3301 } 3302 llvm_unreachable("Not a constructor or conversion function?"); 3303 3304 case OR_No_Viable_Function: 3305 return OR_No_Viable_Function; 3306 3307 case OR_Ambiguous: 3308 return OR_Ambiguous; 3309 } 3310 3311 llvm_unreachable("Invalid OverloadResult!"); 3312 } 3313 3314 bool 3315 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3316 ImplicitConversionSequence ICS; 3317 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3318 OverloadCandidateSet::CSK_Normal); 3319 OverloadingResult OvResult = 3320 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3321 CandidateSet, false, false); 3322 if (OvResult == OR_Ambiguous) 3323 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3324 << From->getType() << ToType << From->getSourceRange(); 3325 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3326 if (!RequireCompleteType(From->getLocStart(), ToType, 3327 diag::err_typecheck_nonviable_condition_incomplete, 3328 From->getType(), From->getSourceRange())) 3329 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3330 << false << From->getType() << From->getSourceRange() << ToType; 3331 } else 3332 return false; 3333 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3334 return true; 3335 } 3336 3337 /// \brief Compare the user-defined conversion functions or constructors 3338 /// of two user-defined conversion sequences to determine whether any ordering 3339 /// is possible. 3340 static ImplicitConversionSequence::CompareKind 3341 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3342 FunctionDecl *Function2) { 3343 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3344 return ImplicitConversionSequence::Indistinguishable; 3345 3346 // Objective-C++: 3347 // If both conversion functions are implicitly-declared conversions from 3348 // a lambda closure type to a function pointer and a block pointer, 3349 // respectively, always prefer the conversion to a function pointer, 3350 // because the function pointer is more lightweight and is more likely 3351 // to keep code working. 3352 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3353 if (!Conv1) 3354 return ImplicitConversionSequence::Indistinguishable; 3355 3356 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3357 if (!Conv2) 3358 return ImplicitConversionSequence::Indistinguishable; 3359 3360 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3361 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3362 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3363 if (Block1 != Block2) 3364 return Block1 ? ImplicitConversionSequence::Worse 3365 : ImplicitConversionSequence::Better; 3366 } 3367 3368 return ImplicitConversionSequence::Indistinguishable; 3369 } 3370 3371 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3372 const ImplicitConversionSequence &ICS) { 3373 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3374 (ICS.isUserDefined() && 3375 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3376 } 3377 3378 /// CompareImplicitConversionSequences - Compare two implicit 3379 /// conversion sequences to determine whether one is better than the 3380 /// other or if they are indistinguishable (C++ 13.3.3.2). 3381 static ImplicitConversionSequence::CompareKind 3382 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3383 const ImplicitConversionSequence& ICS1, 3384 const ImplicitConversionSequence& ICS2) 3385 { 3386 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3387 // conversion sequences (as defined in 13.3.3.1) 3388 // -- a standard conversion sequence (13.3.3.1.1) is a better 3389 // conversion sequence than a user-defined conversion sequence or 3390 // an ellipsis conversion sequence, and 3391 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3392 // conversion sequence than an ellipsis conversion sequence 3393 // (13.3.3.1.3). 3394 // 3395 // C++0x [over.best.ics]p10: 3396 // For the purpose of ranking implicit conversion sequences as 3397 // described in 13.3.3.2, the ambiguous conversion sequence is 3398 // treated as a user-defined sequence that is indistinguishable 3399 // from any other user-defined conversion sequence. 3400 3401 // String literal to 'char *' conversion has been deprecated in C++03. It has 3402 // been removed from C++11. We still accept this conversion, if it happens at 3403 // the best viable function. Otherwise, this conversion is considered worse 3404 // than ellipsis conversion. Consider this as an extension; this is not in the 3405 // standard. For example: 3406 // 3407 // int &f(...); // #1 3408 // void f(char*); // #2 3409 // void g() { int &r = f("foo"); } 3410 // 3411 // In C++03, we pick #2 as the best viable function. 3412 // In C++11, we pick #1 as the best viable function, because ellipsis 3413 // conversion is better than string-literal to char* conversion (since there 3414 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3415 // convert arguments, #2 would be the best viable function in C++11. 3416 // If the best viable function has this conversion, a warning will be issued 3417 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3418 3419 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3420 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3421 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3422 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3423 ? ImplicitConversionSequence::Worse 3424 : ImplicitConversionSequence::Better; 3425 3426 if (ICS1.getKindRank() < ICS2.getKindRank()) 3427 return ImplicitConversionSequence::Better; 3428 if (ICS2.getKindRank() < ICS1.getKindRank()) 3429 return ImplicitConversionSequence::Worse; 3430 3431 // The following checks require both conversion sequences to be of 3432 // the same kind. 3433 if (ICS1.getKind() != ICS2.getKind()) 3434 return ImplicitConversionSequence::Indistinguishable; 3435 3436 ImplicitConversionSequence::CompareKind Result = 3437 ImplicitConversionSequence::Indistinguishable; 3438 3439 // Two implicit conversion sequences of the same form are 3440 // indistinguishable conversion sequences unless one of the 3441 // following rules apply: (C++ 13.3.3.2p3): 3442 3443 // List-initialization sequence L1 is a better conversion sequence than 3444 // list-initialization sequence L2 if: 3445 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3446 // if not that, 3447 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3448 // and N1 is smaller than N2., 3449 // even if one of the other rules in this paragraph would otherwise apply. 3450 if (!ICS1.isBad()) { 3451 if (ICS1.isStdInitializerListElement() && 3452 !ICS2.isStdInitializerListElement()) 3453 return ImplicitConversionSequence::Better; 3454 if (!ICS1.isStdInitializerListElement() && 3455 ICS2.isStdInitializerListElement()) 3456 return ImplicitConversionSequence::Worse; 3457 } 3458 3459 if (ICS1.isStandard()) 3460 // Standard conversion sequence S1 is a better conversion sequence than 3461 // standard conversion sequence S2 if [...] 3462 Result = CompareStandardConversionSequences(S, Loc, 3463 ICS1.Standard, ICS2.Standard); 3464 else if (ICS1.isUserDefined()) { 3465 // User-defined conversion sequence U1 is a better conversion 3466 // sequence than another user-defined conversion sequence U2 if 3467 // they contain the same user-defined conversion function or 3468 // constructor and if the second standard conversion sequence of 3469 // U1 is better than the second standard conversion sequence of 3470 // U2 (C++ 13.3.3.2p3). 3471 if (ICS1.UserDefined.ConversionFunction == 3472 ICS2.UserDefined.ConversionFunction) 3473 Result = CompareStandardConversionSequences(S, Loc, 3474 ICS1.UserDefined.After, 3475 ICS2.UserDefined.After); 3476 else 3477 Result = compareConversionFunctions(S, 3478 ICS1.UserDefined.ConversionFunction, 3479 ICS2.UserDefined.ConversionFunction); 3480 } 3481 3482 return Result; 3483 } 3484 3485 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3486 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3487 Qualifiers Quals; 3488 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3489 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3490 } 3491 3492 return Context.hasSameUnqualifiedType(T1, T2); 3493 } 3494 3495 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3496 // determine if one is a proper subset of the other. 3497 static ImplicitConversionSequence::CompareKind 3498 compareStandardConversionSubsets(ASTContext &Context, 3499 const StandardConversionSequence& SCS1, 3500 const StandardConversionSequence& SCS2) { 3501 ImplicitConversionSequence::CompareKind Result 3502 = ImplicitConversionSequence::Indistinguishable; 3503 3504 // the identity conversion sequence is considered to be a subsequence of 3505 // any non-identity conversion sequence 3506 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3507 return ImplicitConversionSequence::Better; 3508 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3509 return ImplicitConversionSequence::Worse; 3510 3511 if (SCS1.Second != SCS2.Second) { 3512 if (SCS1.Second == ICK_Identity) 3513 Result = ImplicitConversionSequence::Better; 3514 else if (SCS2.Second == ICK_Identity) 3515 Result = ImplicitConversionSequence::Worse; 3516 else 3517 return ImplicitConversionSequence::Indistinguishable; 3518 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3519 return ImplicitConversionSequence::Indistinguishable; 3520 3521 if (SCS1.Third == SCS2.Third) { 3522 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3523 : ImplicitConversionSequence::Indistinguishable; 3524 } 3525 3526 if (SCS1.Third == ICK_Identity) 3527 return Result == ImplicitConversionSequence::Worse 3528 ? ImplicitConversionSequence::Indistinguishable 3529 : ImplicitConversionSequence::Better; 3530 3531 if (SCS2.Third == ICK_Identity) 3532 return Result == ImplicitConversionSequence::Better 3533 ? ImplicitConversionSequence::Indistinguishable 3534 : ImplicitConversionSequence::Worse; 3535 3536 return ImplicitConversionSequence::Indistinguishable; 3537 } 3538 3539 /// \brief Determine whether one of the given reference bindings is better 3540 /// than the other based on what kind of bindings they are. 3541 static bool 3542 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3543 const StandardConversionSequence &SCS2) { 3544 // C++0x [over.ics.rank]p3b4: 3545 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3546 // implicit object parameter of a non-static member function declared 3547 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3548 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3549 // lvalue reference to a function lvalue and S2 binds an rvalue 3550 // reference*. 3551 // 3552 // FIXME: Rvalue references. We're going rogue with the above edits, 3553 // because the semantics in the current C++0x working paper (N3225 at the 3554 // time of this writing) break the standard definition of std::forward 3555 // and std::reference_wrapper when dealing with references to functions. 3556 // Proposed wording changes submitted to CWG for consideration. 3557 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3558 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3559 return false; 3560 3561 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3562 SCS2.IsLvalueReference) || 3563 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3564 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3565 } 3566 3567 /// CompareStandardConversionSequences - Compare two standard 3568 /// conversion sequences to determine whether one is better than the 3569 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3570 static ImplicitConversionSequence::CompareKind 3571 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3572 const StandardConversionSequence& SCS1, 3573 const StandardConversionSequence& SCS2) 3574 { 3575 // Standard conversion sequence S1 is a better conversion sequence 3576 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3577 3578 // -- S1 is a proper subsequence of S2 (comparing the conversion 3579 // sequences in the canonical form defined by 13.3.3.1.1, 3580 // excluding any Lvalue Transformation; the identity conversion 3581 // sequence is considered to be a subsequence of any 3582 // non-identity conversion sequence) or, if not that, 3583 if (ImplicitConversionSequence::CompareKind CK 3584 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3585 return CK; 3586 3587 // -- the rank of S1 is better than the rank of S2 (by the rules 3588 // defined below), or, if not that, 3589 ImplicitConversionRank Rank1 = SCS1.getRank(); 3590 ImplicitConversionRank Rank2 = SCS2.getRank(); 3591 if (Rank1 < Rank2) 3592 return ImplicitConversionSequence::Better; 3593 else if (Rank2 < Rank1) 3594 return ImplicitConversionSequence::Worse; 3595 3596 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3597 // are indistinguishable unless one of the following rules 3598 // applies: 3599 3600 // A conversion that is not a conversion of a pointer, or 3601 // pointer to member, to bool is better than another conversion 3602 // that is such a conversion. 3603 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3604 return SCS2.isPointerConversionToBool() 3605 ? ImplicitConversionSequence::Better 3606 : ImplicitConversionSequence::Worse; 3607 3608 // C++ [over.ics.rank]p4b2: 3609 // 3610 // If class B is derived directly or indirectly from class A, 3611 // conversion of B* to A* is better than conversion of B* to 3612 // void*, and conversion of A* to void* is better than conversion 3613 // of B* to void*. 3614 bool SCS1ConvertsToVoid 3615 = SCS1.isPointerConversionToVoidPointer(S.Context); 3616 bool SCS2ConvertsToVoid 3617 = SCS2.isPointerConversionToVoidPointer(S.Context); 3618 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3619 // Exactly one of the conversion sequences is a conversion to 3620 // a void pointer; it's the worse conversion. 3621 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3622 : ImplicitConversionSequence::Worse; 3623 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3624 // Neither conversion sequence converts to a void pointer; compare 3625 // their derived-to-base conversions. 3626 if (ImplicitConversionSequence::CompareKind DerivedCK 3627 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3628 return DerivedCK; 3629 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3630 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3631 // Both conversion sequences are conversions to void 3632 // pointers. Compare the source types to determine if there's an 3633 // inheritance relationship in their sources. 3634 QualType FromType1 = SCS1.getFromType(); 3635 QualType FromType2 = SCS2.getFromType(); 3636 3637 // Adjust the types we're converting from via the array-to-pointer 3638 // conversion, if we need to. 3639 if (SCS1.First == ICK_Array_To_Pointer) 3640 FromType1 = S.Context.getArrayDecayedType(FromType1); 3641 if (SCS2.First == ICK_Array_To_Pointer) 3642 FromType2 = S.Context.getArrayDecayedType(FromType2); 3643 3644 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3645 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3646 3647 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3648 return ImplicitConversionSequence::Better; 3649 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3650 return ImplicitConversionSequence::Worse; 3651 3652 // Objective-C++: If one interface is more specific than the 3653 // other, it is the better one. 3654 const ObjCObjectPointerType* FromObjCPtr1 3655 = FromType1->getAs<ObjCObjectPointerType>(); 3656 const ObjCObjectPointerType* FromObjCPtr2 3657 = FromType2->getAs<ObjCObjectPointerType>(); 3658 if (FromObjCPtr1 && FromObjCPtr2) { 3659 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3660 FromObjCPtr2); 3661 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3662 FromObjCPtr1); 3663 if (AssignLeft != AssignRight) { 3664 return AssignLeft? ImplicitConversionSequence::Better 3665 : ImplicitConversionSequence::Worse; 3666 } 3667 } 3668 } 3669 3670 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3671 // bullet 3). 3672 if (ImplicitConversionSequence::CompareKind QualCK 3673 = CompareQualificationConversions(S, SCS1, SCS2)) 3674 return QualCK; 3675 3676 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3677 // Check for a better reference binding based on the kind of bindings. 3678 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3679 return ImplicitConversionSequence::Better; 3680 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3681 return ImplicitConversionSequence::Worse; 3682 3683 // C++ [over.ics.rank]p3b4: 3684 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3685 // which the references refer are the same type except for 3686 // top-level cv-qualifiers, and the type to which the reference 3687 // initialized by S2 refers is more cv-qualified than the type 3688 // to which the reference initialized by S1 refers. 3689 QualType T1 = SCS1.getToType(2); 3690 QualType T2 = SCS2.getToType(2); 3691 T1 = S.Context.getCanonicalType(T1); 3692 T2 = S.Context.getCanonicalType(T2); 3693 Qualifiers T1Quals, T2Quals; 3694 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3695 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3696 if (UnqualT1 == UnqualT2) { 3697 // Objective-C++ ARC: If the references refer to objects with different 3698 // lifetimes, prefer bindings that don't change lifetime. 3699 if (SCS1.ObjCLifetimeConversionBinding != 3700 SCS2.ObjCLifetimeConversionBinding) { 3701 return SCS1.ObjCLifetimeConversionBinding 3702 ? ImplicitConversionSequence::Worse 3703 : ImplicitConversionSequence::Better; 3704 } 3705 3706 // If the type is an array type, promote the element qualifiers to the 3707 // type for comparison. 3708 if (isa<ArrayType>(T1) && T1Quals) 3709 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3710 if (isa<ArrayType>(T2) && T2Quals) 3711 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3712 if (T2.isMoreQualifiedThan(T1)) 3713 return ImplicitConversionSequence::Better; 3714 else if (T1.isMoreQualifiedThan(T2)) 3715 return ImplicitConversionSequence::Worse; 3716 } 3717 } 3718 3719 // In Microsoft mode, prefer an integral conversion to a 3720 // floating-to-integral conversion if the integral conversion 3721 // is between types of the same size. 3722 // For example: 3723 // void f(float); 3724 // void f(int); 3725 // int main { 3726 // long a; 3727 // f(a); 3728 // } 3729 // Here, MSVC will call f(int) instead of generating a compile error 3730 // as clang will do in standard mode. 3731 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3732 SCS2.Second == ICK_Floating_Integral && 3733 S.Context.getTypeSize(SCS1.getFromType()) == 3734 S.Context.getTypeSize(SCS1.getToType(2))) 3735 return ImplicitConversionSequence::Better; 3736 3737 return ImplicitConversionSequence::Indistinguishable; 3738 } 3739 3740 /// CompareQualificationConversions - Compares two standard conversion 3741 /// sequences to determine whether they can be ranked based on their 3742 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3743 static ImplicitConversionSequence::CompareKind 3744 CompareQualificationConversions(Sema &S, 3745 const StandardConversionSequence& SCS1, 3746 const StandardConversionSequence& SCS2) { 3747 // C++ 13.3.3.2p3: 3748 // -- S1 and S2 differ only in their qualification conversion and 3749 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3750 // cv-qualification signature of type T1 is a proper subset of 3751 // the cv-qualification signature of type T2, and S1 is not the 3752 // deprecated string literal array-to-pointer conversion (4.2). 3753 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3754 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3755 return ImplicitConversionSequence::Indistinguishable; 3756 3757 // FIXME: the example in the standard doesn't use a qualification 3758 // conversion (!) 3759 QualType T1 = SCS1.getToType(2); 3760 QualType T2 = SCS2.getToType(2); 3761 T1 = S.Context.getCanonicalType(T1); 3762 T2 = S.Context.getCanonicalType(T2); 3763 Qualifiers T1Quals, T2Quals; 3764 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3765 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3766 3767 // If the types are the same, we won't learn anything by unwrapped 3768 // them. 3769 if (UnqualT1 == UnqualT2) 3770 return ImplicitConversionSequence::Indistinguishable; 3771 3772 // If the type is an array type, promote the element qualifiers to the type 3773 // for comparison. 3774 if (isa<ArrayType>(T1) && T1Quals) 3775 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3776 if (isa<ArrayType>(T2) && T2Quals) 3777 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3778 3779 ImplicitConversionSequence::CompareKind Result 3780 = ImplicitConversionSequence::Indistinguishable; 3781 3782 // Objective-C++ ARC: 3783 // Prefer qualification conversions not involving a change in lifetime 3784 // to qualification conversions that do not change lifetime. 3785 if (SCS1.QualificationIncludesObjCLifetime != 3786 SCS2.QualificationIncludesObjCLifetime) { 3787 Result = SCS1.QualificationIncludesObjCLifetime 3788 ? ImplicitConversionSequence::Worse 3789 : ImplicitConversionSequence::Better; 3790 } 3791 3792 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3793 // Within each iteration of the loop, we check the qualifiers to 3794 // determine if this still looks like a qualification 3795 // conversion. Then, if all is well, we unwrap one more level of 3796 // pointers or pointers-to-members and do it all again 3797 // until there are no more pointers or pointers-to-members left 3798 // to unwrap. This essentially mimics what 3799 // IsQualificationConversion does, but here we're checking for a 3800 // strict subset of qualifiers. 3801 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3802 // The qualifiers are the same, so this doesn't tell us anything 3803 // about how the sequences rank. 3804 ; 3805 else if (T2.isMoreQualifiedThan(T1)) { 3806 // T1 has fewer qualifiers, so it could be the better sequence. 3807 if (Result == ImplicitConversionSequence::Worse) 3808 // Neither has qualifiers that are a subset of the other's 3809 // qualifiers. 3810 return ImplicitConversionSequence::Indistinguishable; 3811 3812 Result = ImplicitConversionSequence::Better; 3813 } else if (T1.isMoreQualifiedThan(T2)) { 3814 // T2 has fewer qualifiers, so it could be the better sequence. 3815 if (Result == ImplicitConversionSequence::Better) 3816 // Neither has qualifiers that are a subset of the other's 3817 // qualifiers. 3818 return ImplicitConversionSequence::Indistinguishable; 3819 3820 Result = ImplicitConversionSequence::Worse; 3821 } else { 3822 // Qualifiers are disjoint. 3823 return ImplicitConversionSequence::Indistinguishable; 3824 } 3825 3826 // If the types after this point are equivalent, we're done. 3827 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3828 break; 3829 } 3830 3831 // Check that the winning standard conversion sequence isn't using 3832 // the deprecated string literal array to pointer conversion. 3833 switch (Result) { 3834 case ImplicitConversionSequence::Better: 3835 if (SCS1.DeprecatedStringLiteralToCharPtr) 3836 Result = ImplicitConversionSequence::Indistinguishable; 3837 break; 3838 3839 case ImplicitConversionSequence::Indistinguishable: 3840 break; 3841 3842 case ImplicitConversionSequence::Worse: 3843 if (SCS2.DeprecatedStringLiteralToCharPtr) 3844 Result = ImplicitConversionSequence::Indistinguishable; 3845 break; 3846 } 3847 3848 return Result; 3849 } 3850 3851 /// CompareDerivedToBaseConversions - Compares two standard conversion 3852 /// sequences to determine whether they can be ranked based on their 3853 /// various kinds of derived-to-base conversions (C++ 3854 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3855 /// conversions between Objective-C interface types. 3856 static ImplicitConversionSequence::CompareKind 3857 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3858 const StandardConversionSequence& SCS1, 3859 const StandardConversionSequence& SCS2) { 3860 QualType FromType1 = SCS1.getFromType(); 3861 QualType ToType1 = SCS1.getToType(1); 3862 QualType FromType2 = SCS2.getFromType(); 3863 QualType ToType2 = SCS2.getToType(1); 3864 3865 // Adjust the types we're converting from via the array-to-pointer 3866 // conversion, if we need to. 3867 if (SCS1.First == ICK_Array_To_Pointer) 3868 FromType1 = S.Context.getArrayDecayedType(FromType1); 3869 if (SCS2.First == ICK_Array_To_Pointer) 3870 FromType2 = S.Context.getArrayDecayedType(FromType2); 3871 3872 // Canonicalize all of the types. 3873 FromType1 = S.Context.getCanonicalType(FromType1); 3874 ToType1 = S.Context.getCanonicalType(ToType1); 3875 FromType2 = S.Context.getCanonicalType(FromType2); 3876 ToType2 = S.Context.getCanonicalType(ToType2); 3877 3878 // C++ [over.ics.rank]p4b3: 3879 // 3880 // If class B is derived directly or indirectly from class A and 3881 // class C is derived directly or indirectly from B, 3882 // 3883 // Compare based on pointer conversions. 3884 if (SCS1.Second == ICK_Pointer_Conversion && 3885 SCS2.Second == ICK_Pointer_Conversion && 3886 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3887 FromType1->isPointerType() && FromType2->isPointerType() && 3888 ToType1->isPointerType() && ToType2->isPointerType()) { 3889 QualType FromPointee1 3890 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3891 QualType ToPointee1 3892 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3893 QualType FromPointee2 3894 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3895 QualType ToPointee2 3896 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3897 3898 // -- conversion of C* to B* is better than conversion of C* to A*, 3899 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3900 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3901 return ImplicitConversionSequence::Better; 3902 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3903 return ImplicitConversionSequence::Worse; 3904 } 3905 3906 // -- conversion of B* to A* is better than conversion of C* to A*, 3907 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3908 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3909 return ImplicitConversionSequence::Better; 3910 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3911 return ImplicitConversionSequence::Worse; 3912 } 3913 } else if (SCS1.Second == ICK_Pointer_Conversion && 3914 SCS2.Second == ICK_Pointer_Conversion) { 3915 const ObjCObjectPointerType *FromPtr1 3916 = FromType1->getAs<ObjCObjectPointerType>(); 3917 const ObjCObjectPointerType *FromPtr2 3918 = FromType2->getAs<ObjCObjectPointerType>(); 3919 const ObjCObjectPointerType *ToPtr1 3920 = ToType1->getAs<ObjCObjectPointerType>(); 3921 const ObjCObjectPointerType *ToPtr2 3922 = ToType2->getAs<ObjCObjectPointerType>(); 3923 3924 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3925 // Apply the same conversion ranking rules for Objective-C pointer types 3926 // that we do for C++ pointers to class types. However, we employ the 3927 // Objective-C pseudo-subtyping relationship used for assignment of 3928 // Objective-C pointer types. 3929 bool FromAssignLeft 3930 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3931 bool FromAssignRight 3932 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3933 bool ToAssignLeft 3934 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3935 bool ToAssignRight 3936 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3937 3938 // A conversion to an a non-id object pointer type or qualified 'id' 3939 // type is better than a conversion to 'id'. 3940 if (ToPtr1->isObjCIdType() && 3941 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3942 return ImplicitConversionSequence::Worse; 3943 if (ToPtr2->isObjCIdType() && 3944 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3945 return ImplicitConversionSequence::Better; 3946 3947 // A conversion to a non-id object pointer type is better than a 3948 // conversion to a qualified 'id' type 3949 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3950 return ImplicitConversionSequence::Worse; 3951 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3952 return ImplicitConversionSequence::Better; 3953 3954 // A conversion to an a non-Class object pointer type or qualified 'Class' 3955 // type is better than a conversion to 'Class'. 3956 if (ToPtr1->isObjCClassType() && 3957 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3958 return ImplicitConversionSequence::Worse; 3959 if (ToPtr2->isObjCClassType() && 3960 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3961 return ImplicitConversionSequence::Better; 3962 3963 // A conversion to a non-Class object pointer type is better than a 3964 // conversion to a qualified 'Class' type. 3965 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3966 return ImplicitConversionSequence::Worse; 3967 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3968 return ImplicitConversionSequence::Better; 3969 3970 // -- "conversion of C* to B* is better than conversion of C* to A*," 3971 if (S.Context.hasSameType(FromType1, FromType2) && 3972 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3973 (ToAssignLeft != ToAssignRight)) 3974 return ToAssignLeft? ImplicitConversionSequence::Worse 3975 : ImplicitConversionSequence::Better; 3976 3977 // -- "conversion of B* to A* is better than conversion of C* to A*," 3978 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3979 (FromAssignLeft != FromAssignRight)) 3980 return FromAssignLeft? ImplicitConversionSequence::Better 3981 : ImplicitConversionSequence::Worse; 3982 } 3983 } 3984 3985 // Ranking of member-pointer types. 3986 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3987 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3988 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3989 const MemberPointerType * FromMemPointer1 = 3990 FromType1->getAs<MemberPointerType>(); 3991 const MemberPointerType * ToMemPointer1 = 3992 ToType1->getAs<MemberPointerType>(); 3993 const MemberPointerType * FromMemPointer2 = 3994 FromType2->getAs<MemberPointerType>(); 3995 const MemberPointerType * ToMemPointer2 = 3996 ToType2->getAs<MemberPointerType>(); 3997 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3998 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3999 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4000 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4001 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4002 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4003 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4004 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4005 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4006 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4007 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4008 return ImplicitConversionSequence::Worse; 4009 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4010 return ImplicitConversionSequence::Better; 4011 } 4012 // conversion of B::* to C::* is better than conversion of A::* to C::* 4013 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4014 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4015 return ImplicitConversionSequence::Better; 4016 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4017 return ImplicitConversionSequence::Worse; 4018 } 4019 } 4020 4021 if (SCS1.Second == ICK_Derived_To_Base) { 4022 // -- conversion of C to B is better than conversion of C to A, 4023 // -- binding of an expression of type C to a reference of type 4024 // B& is better than binding an expression of type C to a 4025 // reference of type A&, 4026 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4027 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4028 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4029 return ImplicitConversionSequence::Better; 4030 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4031 return ImplicitConversionSequence::Worse; 4032 } 4033 4034 // -- conversion of B to A is better than conversion of C to A. 4035 // -- binding of an expression of type B to a reference of type 4036 // A& is better than binding an expression of type C to a 4037 // reference of type A&, 4038 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4039 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4040 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4041 return ImplicitConversionSequence::Better; 4042 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4043 return ImplicitConversionSequence::Worse; 4044 } 4045 } 4046 4047 return ImplicitConversionSequence::Indistinguishable; 4048 } 4049 4050 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4051 /// C++ class. 4052 static bool isTypeValid(QualType T) { 4053 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4054 return !Record->isInvalidDecl(); 4055 4056 return true; 4057 } 4058 4059 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4060 /// determine whether they are reference-related, 4061 /// reference-compatible, reference-compatible with added 4062 /// qualification, or incompatible, for use in C++ initialization by 4063 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4064 /// type, and the first type (T1) is the pointee type of the reference 4065 /// type being initialized. 4066 Sema::ReferenceCompareResult 4067 Sema::CompareReferenceRelationship(SourceLocation Loc, 4068 QualType OrigT1, QualType OrigT2, 4069 bool &DerivedToBase, 4070 bool &ObjCConversion, 4071 bool &ObjCLifetimeConversion) { 4072 assert(!OrigT1->isReferenceType() && 4073 "T1 must be the pointee type of the reference type"); 4074 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4075 4076 QualType T1 = Context.getCanonicalType(OrigT1); 4077 QualType T2 = Context.getCanonicalType(OrigT2); 4078 Qualifiers T1Quals, T2Quals; 4079 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4080 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4081 4082 // C++ [dcl.init.ref]p4: 4083 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4084 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4085 // T1 is a base class of T2. 4086 DerivedToBase = false; 4087 ObjCConversion = false; 4088 ObjCLifetimeConversion = false; 4089 if (UnqualT1 == UnqualT2) { 4090 // Nothing to do. 4091 } else if (isCompleteType(Loc, OrigT2) && 4092 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4093 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4094 DerivedToBase = true; 4095 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4096 UnqualT2->isObjCObjectOrInterfaceType() && 4097 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4098 ObjCConversion = true; 4099 else 4100 return Ref_Incompatible; 4101 4102 // At this point, we know that T1 and T2 are reference-related (at 4103 // least). 4104 4105 // If the type is an array type, promote the element qualifiers to the type 4106 // for comparison. 4107 if (isa<ArrayType>(T1) && T1Quals) 4108 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4109 if (isa<ArrayType>(T2) && T2Quals) 4110 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4111 4112 // C++ [dcl.init.ref]p4: 4113 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4114 // reference-related to T2 and cv1 is the same cv-qualification 4115 // as, or greater cv-qualification than, cv2. For purposes of 4116 // overload resolution, cases for which cv1 is greater 4117 // cv-qualification than cv2 are identified as 4118 // reference-compatible with added qualification (see 13.3.3.2). 4119 // 4120 // Note that we also require equivalence of Objective-C GC and address-space 4121 // qualifiers when performing these computations, so that e.g., an int in 4122 // address space 1 is not reference-compatible with an int in address 4123 // space 2. 4124 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4125 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4126 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4127 ObjCLifetimeConversion = true; 4128 4129 T1Quals.removeObjCLifetime(); 4130 T2Quals.removeObjCLifetime(); 4131 } 4132 4133 if (T1Quals == T2Quals) 4134 return Ref_Compatible; 4135 else if (T1Quals.compatiblyIncludes(T2Quals)) 4136 return Ref_Compatible_With_Added_Qualification; 4137 else 4138 return Ref_Related; 4139 } 4140 4141 /// \brief Look for a user-defined conversion to an value reference-compatible 4142 /// with DeclType. Return true if something definite is found. 4143 static bool 4144 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4145 QualType DeclType, SourceLocation DeclLoc, 4146 Expr *Init, QualType T2, bool AllowRvalues, 4147 bool AllowExplicit) { 4148 assert(T2->isRecordType() && "Can only find conversions of record types."); 4149 CXXRecordDecl *T2RecordDecl 4150 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4151 4152 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4153 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4154 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4155 NamedDecl *D = *I; 4156 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4157 if (isa<UsingShadowDecl>(D)) 4158 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4159 4160 FunctionTemplateDecl *ConvTemplate 4161 = dyn_cast<FunctionTemplateDecl>(D); 4162 CXXConversionDecl *Conv; 4163 if (ConvTemplate) 4164 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4165 else 4166 Conv = cast<CXXConversionDecl>(D); 4167 4168 // If this is an explicit conversion, and we're not allowed to consider 4169 // explicit conversions, skip it. 4170 if (!AllowExplicit && Conv->isExplicit()) 4171 continue; 4172 4173 if (AllowRvalues) { 4174 bool DerivedToBase = false; 4175 bool ObjCConversion = false; 4176 bool ObjCLifetimeConversion = false; 4177 4178 // If we are initializing an rvalue reference, don't permit conversion 4179 // functions that return lvalues. 4180 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4181 const ReferenceType *RefType 4182 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4183 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4184 continue; 4185 } 4186 4187 if (!ConvTemplate && 4188 S.CompareReferenceRelationship( 4189 DeclLoc, 4190 Conv->getConversionType().getNonReferenceType() 4191 .getUnqualifiedType(), 4192 DeclType.getNonReferenceType().getUnqualifiedType(), 4193 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4194 Sema::Ref_Incompatible) 4195 continue; 4196 } else { 4197 // If the conversion function doesn't return a reference type, 4198 // it can't be considered for this conversion. An rvalue reference 4199 // is only acceptable if its referencee is a function type. 4200 4201 const ReferenceType *RefType = 4202 Conv->getConversionType()->getAs<ReferenceType>(); 4203 if (!RefType || 4204 (!RefType->isLValueReferenceType() && 4205 !RefType->getPointeeType()->isFunctionType())) 4206 continue; 4207 } 4208 4209 if (ConvTemplate) 4210 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4211 Init, DeclType, CandidateSet, 4212 /*AllowObjCConversionOnExplicit=*/false); 4213 else 4214 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4215 DeclType, CandidateSet, 4216 /*AllowObjCConversionOnExplicit=*/false); 4217 } 4218 4219 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4220 4221 OverloadCandidateSet::iterator Best; 4222 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4223 case OR_Success: 4224 // C++ [over.ics.ref]p1: 4225 // 4226 // [...] If the parameter binds directly to the result of 4227 // applying a conversion function to the argument 4228 // expression, the implicit conversion sequence is a 4229 // user-defined conversion sequence (13.3.3.1.2), with the 4230 // second standard conversion sequence either an identity 4231 // conversion or, if the conversion function returns an 4232 // entity of a type that is a derived class of the parameter 4233 // type, a derived-to-base Conversion. 4234 if (!Best->FinalConversion.DirectBinding) 4235 return false; 4236 4237 ICS.setUserDefined(); 4238 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4239 ICS.UserDefined.After = Best->FinalConversion; 4240 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4241 ICS.UserDefined.ConversionFunction = Best->Function; 4242 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4243 ICS.UserDefined.EllipsisConversion = false; 4244 assert(ICS.UserDefined.After.ReferenceBinding && 4245 ICS.UserDefined.After.DirectBinding && 4246 "Expected a direct reference binding!"); 4247 return true; 4248 4249 case OR_Ambiguous: 4250 ICS.setAmbiguous(); 4251 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4252 Cand != CandidateSet.end(); ++Cand) 4253 if (Cand->Viable) 4254 ICS.Ambiguous.addConversion(Cand->Function); 4255 return true; 4256 4257 case OR_No_Viable_Function: 4258 case OR_Deleted: 4259 // There was no suitable conversion, or we found a deleted 4260 // conversion; continue with other checks. 4261 return false; 4262 } 4263 4264 llvm_unreachable("Invalid OverloadResult!"); 4265 } 4266 4267 /// \brief Compute an implicit conversion sequence for reference 4268 /// initialization. 4269 static ImplicitConversionSequence 4270 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4271 SourceLocation DeclLoc, 4272 bool SuppressUserConversions, 4273 bool AllowExplicit) { 4274 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4275 4276 // Most paths end in a failed conversion. 4277 ImplicitConversionSequence ICS; 4278 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4279 4280 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4281 QualType T2 = Init->getType(); 4282 4283 // If the initializer is the address of an overloaded function, try 4284 // to resolve the overloaded function. If all goes well, T2 is the 4285 // type of the resulting function. 4286 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4287 DeclAccessPair Found; 4288 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4289 false, Found)) 4290 T2 = Fn->getType(); 4291 } 4292 4293 // Compute some basic properties of the types and the initializer. 4294 bool isRValRef = DeclType->isRValueReferenceType(); 4295 bool DerivedToBase = false; 4296 bool ObjCConversion = false; 4297 bool ObjCLifetimeConversion = false; 4298 Expr::Classification InitCategory = Init->Classify(S.Context); 4299 Sema::ReferenceCompareResult RefRelationship 4300 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4301 ObjCConversion, ObjCLifetimeConversion); 4302 4303 4304 // C++0x [dcl.init.ref]p5: 4305 // A reference to type "cv1 T1" is initialized by an expression 4306 // of type "cv2 T2" as follows: 4307 4308 // -- If reference is an lvalue reference and the initializer expression 4309 if (!isRValRef) { 4310 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4311 // reference-compatible with "cv2 T2," or 4312 // 4313 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4314 if (InitCategory.isLValue() && 4315 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4316 // C++ [over.ics.ref]p1: 4317 // When a parameter of reference type binds directly (8.5.3) 4318 // to an argument expression, the implicit conversion sequence 4319 // is the identity conversion, unless the argument expression 4320 // has a type that is a derived class of the parameter type, 4321 // in which case the implicit conversion sequence is a 4322 // derived-to-base Conversion (13.3.3.1). 4323 ICS.setStandard(); 4324 ICS.Standard.First = ICK_Identity; 4325 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4326 : ObjCConversion? ICK_Compatible_Conversion 4327 : ICK_Identity; 4328 ICS.Standard.Third = ICK_Identity; 4329 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4330 ICS.Standard.setToType(0, T2); 4331 ICS.Standard.setToType(1, T1); 4332 ICS.Standard.setToType(2, T1); 4333 ICS.Standard.ReferenceBinding = true; 4334 ICS.Standard.DirectBinding = true; 4335 ICS.Standard.IsLvalueReference = !isRValRef; 4336 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4337 ICS.Standard.BindsToRvalue = false; 4338 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4339 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4340 ICS.Standard.CopyConstructor = nullptr; 4341 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4342 4343 // Nothing more to do: the inaccessibility/ambiguity check for 4344 // derived-to-base conversions is suppressed when we're 4345 // computing the implicit conversion sequence (C++ 4346 // [over.best.ics]p2). 4347 return ICS; 4348 } 4349 4350 // -- has a class type (i.e., T2 is a class type), where T1 is 4351 // not reference-related to T2, and can be implicitly 4352 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4353 // is reference-compatible with "cv3 T3" 92) (this 4354 // conversion is selected by enumerating the applicable 4355 // conversion functions (13.3.1.6) and choosing the best 4356 // one through overload resolution (13.3)), 4357 if (!SuppressUserConversions && T2->isRecordType() && 4358 S.isCompleteType(DeclLoc, T2) && 4359 RefRelationship == Sema::Ref_Incompatible) { 4360 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4361 Init, T2, /*AllowRvalues=*/false, 4362 AllowExplicit)) 4363 return ICS; 4364 } 4365 } 4366 4367 // -- Otherwise, the reference shall be an lvalue reference to a 4368 // non-volatile const type (i.e., cv1 shall be const), or the reference 4369 // shall be an rvalue reference. 4370 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4371 return ICS; 4372 4373 // -- If the initializer expression 4374 // 4375 // -- is an xvalue, class prvalue, array prvalue or function 4376 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4377 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4378 (InitCategory.isXValue() || 4379 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4380 (InitCategory.isLValue() && T2->isFunctionType()))) { 4381 ICS.setStandard(); 4382 ICS.Standard.First = ICK_Identity; 4383 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4384 : ObjCConversion? ICK_Compatible_Conversion 4385 : ICK_Identity; 4386 ICS.Standard.Third = ICK_Identity; 4387 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4388 ICS.Standard.setToType(0, T2); 4389 ICS.Standard.setToType(1, T1); 4390 ICS.Standard.setToType(2, T1); 4391 ICS.Standard.ReferenceBinding = true; 4392 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4393 // binding unless we're binding to a class prvalue. 4394 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4395 // allow the use of rvalue references in C++98/03 for the benefit of 4396 // standard library implementors; therefore, we need the xvalue check here. 4397 ICS.Standard.DirectBinding = 4398 S.getLangOpts().CPlusPlus11 || 4399 !(InitCategory.isPRValue() || T2->isRecordType()); 4400 ICS.Standard.IsLvalueReference = !isRValRef; 4401 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4402 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4403 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4404 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4405 ICS.Standard.CopyConstructor = nullptr; 4406 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4407 return ICS; 4408 } 4409 4410 // -- has a class type (i.e., T2 is a class type), where T1 is not 4411 // reference-related to T2, and can be implicitly converted to 4412 // an xvalue, class prvalue, or function lvalue of type 4413 // "cv3 T3", where "cv1 T1" is reference-compatible with 4414 // "cv3 T3", 4415 // 4416 // then the reference is bound to the value of the initializer 4417 // expression in the first case and to the result of the conversion 4418 // in the second case (or, in either case, to an appropriate base 4419 // class subobject). 4420 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4421 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4422 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4423 Init, T2, /*AllowRvalues=*/true, 4424 AllowExplicit)) { 4425 // In the second case, if the reference is an rvalue reference 4426 // and the second standard conversion sequence of the 4427 // user-defined conversion sequence includes an lvalue-to-rvalue 4428 // conversion, the program is ill-formed. 4429 if (ICS.isUserDefined() && isRValRef && 4430 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4431 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4432 4433 return ICS; 4434 } 4435 4436 // A temporary of function type cannot be created; don't even try. 4437 if (T1->isFunctionType()) 4438 return ICS; 4439 4440 // -- Otherwise, a temporary of type "cv1 T1" is created and 4441 // initialized from the initializer expression using the 4442 // rules for a non-reference copy initialization (8.5). The 4443 // reference is then bound to the temporary. If T1 is 4444 // reference-related to T2, cv1 must be the same 4445 // cv-qualification as, or greater cv-qualification than, 4446 // cv2; otherwise, the program is ill-formed. 4447 if (RefRelationship == Sema::Ref_Related) { 4448 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4449 // we would be reference-compatible or reference-compatible with 4450 // added qualification. But that wasn't the case, so the reference 4451 // initialization fails. 4452 // 4453 // Note that we only want to check address spaces and cvr-qualifiers here. 4454 // ObjC GC and lifetime qualifiers aren't important. 4455 Qualifiers T1Quals = T1.getQualifiers(); 4456 Qualifiers T2Quals = T2.getQualifiers(); 4457 T1Quals.removeObjCGCAttr(); 4458 T1Quals.removeObjCLifetime(); 4459 T2Quals.removeObjCGCAttr(); 4460 T2Quals.removeObjCLifetime(); 4461 if (!T1Quals.compatiblyIncludes(T2Quals)) 4462 return ICS; 4463 } 4464 4465 // If at least one of the types is a class type, the types are not 4466 // related, and we aren't allowed any user conversions, the 4467 // reference binding fails. This case is important for breaking 4468 // recursion, since TryImplicitConversion below will attempt to 4469 // create a temporary through the use of a copy constructor. 4470 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4471 (T1->isRecordType() || T2->isRecordType())) 4472 return ICS; 4473 4474 // If T1 is reference-related to T2 and the reference is an rvalue 4475 // reference, the initializer expression shall not be an lvalue. 4476 if (RefRelationship >= Sema::Ref_Related && 4477 isRValRef && Init->Classify(S.Context).isLValue()) 4478 return ICS; 4479 4480 // C++ [over.ics.ref]p2: 4481 // When a parameter of reference type is not bound directly to 4482 // an argument expression, the conversion sequence is the one 4483 // required to convert the argument expression to the 4484 // underlying type of the reference according to 4485 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4486 // to copy-initializing a temporary of the underlying type with 4487 // the argument expression. Any difference in top-level 4488 // cv-qualification is subsumed by the initialization itself 4489 // and does not constitute a conversion. 4490 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4491 /*AllowExplicit=*/false, 4492 /*InOverloadResolution=*/false, 4493 /*CStyle=*/false, 4494 /*AllowObjCWritebackConversion=*/false, 4495 /*AllowObjCConversionOnExplicit=*/false); 4496 4497 // Of course, that's still a reference binding. 4498 if (ICS.isStandard()) { 4499 ICS.Standard.ReferenceBinding = true; 4500 ICS.Standard.IsLvalueReference = !isRValRef; 4501 ICS.Standard.BindsToFunctionLvalue = false; 4502 ICS.Standard.BindsToRvalue = true; 4503 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4504 ICS.Standard.ObjCLifetimeConversionBinding = false; 4505 } else if (ICS.isUserDefined()) { 4506 const ReferenceType *LValRefType = 4507 ICS.UserDefined.ConversionFunction->getReturnType() 4508 ->getAs<LValueReferenceType>(); 4509 4510 // C++ [over.ics.ref]p3: 4511 // Except for an implicit object parameter, for which see 13.3.1, a 4512 // standard conversion sequence cannot be formed if it requires [...] 4513 // binding an rvalue reference to an lvalue other than a function 4514 // lvalue. 4515 // Note that the function case is not possible here. 4516 if (DeclType->isRValueReferenceType() && LValRefType) { 4517 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4518 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4519 // reference to an rvalue! 4520 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4521 return ICS; 4522 } 4523 4524 ICS.UserDefined.Before.setAsIdentityConversion(); 4525 ICS.UserDefined.After.ReferenceBinding = true; 4526 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4527 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4528 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4529 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4530 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4531 } 4532 4533 return ICS; 4534 } 4535 4536 static ImplicitConversionSequence 4537 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4538 bool SuppressUserConversions, 4539 bool InOverloadResolution, 4540 bool AllowObjCWritebackConversion, 4541 bool AllowExplicit = false); 4542 4543 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4544 /// initializer list From. 4545 static ImplicitConversionSequence 4546 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4547 bool SuppressUserConversions, 4548 bool InOverloadResolution, 4549 bool AllowObjCWritebackConversion) { 4550 // C++11 [over.ics.list]p1: 4551 // When an argument is an initializer list, it is not an expression and 4552 // special rules apply for converting it to a parameter type. 4553 4554 ImplicitConversionSequence Result; 4555 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4556 4557 // We need a complete type for what follows. Incomplete types can never be 4558 // initialized from init lists. 4559 if (!S.isCompleteType(From->getLocStart(), ToType)) 4560 return Result; 4561 4562 // Per DR1467: 4563 // If the parameter type is a class X and the initializer list has a single 4564 // element of type cv U, where U is X or a class derived from X, the 4565 // implicit conversion sequence is the one required to convert the element 4566 // to the parameter type. 4567 // 4568 // Otherwise, if the parameter type is a character array [... ] 4569 // and the initializer list has a single element that is an 4570 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4571 // implicit conversion sequence is the identity conversion. 4572 if (From->getNumInits() == 1) { 4573 if (ToType->isRecordType()) { 4574 QualType InitType = From->getInit(0)->getType(); 4575 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4576 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4577 return TryCopyInitialization(S, From->getInit(0), ToType, 4578 SuppressUserConversions, 4579 InOverloadResolution, 4580 AllowObjCWritebackConversion); 4581 } 4582 // FIXME: Check the other conditions here: array of character type, 4583 // initializer is a string literal. 4584 if (ToType->isArrayType()) { 4585 InitializedEntity Entity = 4586 InitializedEntity::InitializeParameter(S.Context, ToType, 4587 /*Consumed=*/false); 4588 if (S.CanPerformCopyInitialization(Entity, From)) { 4589 Result.setStandard(); 4590 Result.Standard.setAsIdentityConversion(); 4591 Result.Standard.setFromType(ToType); 4592 Result.Standard.setAllToTypes(ToType); 4593 return Result; 4594 } 4595 } 4596 } 4597 4598 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4599 // C++11 [over.ics.list]p2: 4600 // If the parameter type is std::initializer_list<X> or "array of X" and 4601 // all the elements can be implicitly converted to X, the implicit 4602 // conversion sequence is the worst conversion necessary to convert an 4603 // element of the list to X. 4604 // 4605 // C++14 [over.ics.list]p3: 4606 // Otherwise, if the parameter type is "array of N X", if the initializer 4607 // list has exactly N elements or if it has fewer than N elements and X is 4608 // default-constructible, and if all the elements of the initializer list 4609 // can be implicitly converted to X, the implicit conversion sequence is 4610 // the worst conversion necessary to convert an element of the list to X. 4611 // 4612 // FIXME: We're missing a lot of these checks. 4613 bool toStdInitializerList = false; 4614 QualType X; 4615 if (ToType->isArrayType()) 4616 X = S.Context.getAsArrayType(ToType)->getElementType(); 4617 else 4618 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4619 if (!X.isNull()) { 4620 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4621 Expr *Init = From->getInit(i); 4622 ImplicitConversionSequence ICS = 4623 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4624 InOverloadResolution, 4625 AllowObjCWritebackConversion); 4626 // If a single element isn't convertible, fail. 4627 if (ICS.isBad()) { 4628 Result = ICS; 4629 break; 4630 } 4631 // Otherwise, look for the worst conversion. 4632 if (Result.isBad() || 4633 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4634 Result) == 4635 ImplicitConversionSequence::Worse) 4636 Result = ICS; 4637 } 4638 4639 // For an empty list, we won't have computed any conversion sequence. 4640 // Introduce the identity conversion sequence. 4641 if (From->getNumInits() == 0) { 4642 Result.setStandard(); 4643 Result.Standard.setAsIdentityConversion(); 4644 Result.Standard.setFromType(ToType); 4645 Result.Standard.setAllToTypes(ToType); 4646 } 4647 4648 Result.setStdInitializerListElement(toStdInitializerList); 4649 return Result; 4650 } 4651 4652 // C++14 [over.ics.list]p4: 4653 // C++11 [over.ics.list]p3: 4654 // Otherwise, if the parameter is a non-aggregate class X and overload 4655 // resolution chooses a single best constructor [...] the implicit 4656 // conversion sequence is a user-defined conversion sequence. If multiple 4657 // constructors are viable but none is better than the others, the 4658 // implicit conversion sequence is a user-defined conversion sequence. 4659 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4660 // This function can deal with initializer lists. 4661 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4662 /*AllowExplicit=*/false, 4663 InOverloadResolution, /*CStyle=*/false, 4664 AllowObjCWritebackConversion, 4665 /*AllowObjCConversionOnExplicit=*/false); 4666 } 4667 4668 // C++14 [over.ics.list]p5: 4669 // C++11 [over.ics.list]p4: 4670 // Otherwise, if the parameter has an aggregate type which can be 4671 // initialized from the initializer list [...] the implicit conversion 4672 // sequence is a user-defined conversion sequence. 4673 if (ToType->isAggregateType()) { 4674 // Type is an aggregate, argument is an init list. At this point it comes 4675 // down to checking whether the initialization works. 4676 // FIXME: Find out whether this parameter is consumed or not. 4677 InitializedEntity Entity = 4678 InitializedEntity::InitializeParameter(S.Context, ToType, 4679 /*Consumed=*/false); 4680 if (S.CanPerformCopyInitialization(Entity, From)) { 4681 Result.setUserDefined(); 4682 Result.UserDefined.Before.setAsIdentityConversion(); 4683 // Initializer lists don't have a type. 4684 Result.UserDefined.Before.setFromType(QualType()); 4685 Result.UserDefined.Before.setAllToTypes(QualType()); 4686 4687 Result.UserDefined.After.setAsIdentityConversion(); 4688 Result.UserDefined.After.setFromType(ToType); 4689 Result.UserDefined.After.setAllToTypes(ToType); 4690 Result.UserDefined.ConversionFunction = nullptr; 4691 } 4692 return Result; 4693 } 4694 4695 // C++14 [over.ics.list]p6: 4696 // C++11 [over.ics.list]p5: 4697 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4698 if (ToType->isReferenceType()) { 4699 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4700 // mention initializer lists in any way. So we go by what list- 4701 // initialization would do and try to extrapolate from that. 4702 4703 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4704 4705 // If the initializer list has a single element that is reference-related 4706 // to the parameter type, we initialize the reference from that. 4707 if (From->getNumInits() == 1) { 4708 Expr *Init = From->getInit(0); 4709 4710 QualType T2 = Init->getType(); 4711 4712 // If the initializer is the address of an overloaded function, try 4713 // to resolve the overloaded function. If all goes well, T2 is the 4714 // type of the resulting function. 4715 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4716 DeclAccessPair Found; 4717 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4718 Init, ToType, false, Found)) 4719 T2 = Fn->getType(); 4720 } 4721 4722 // Compute some basic properties of the types and the initializer. 4723 bool dummy1 = false; 4724 bool dummy2 = false; 4725 bool dummy3 = false; 4726 Sema::ReferenceCompareResult RefRelationship 4727 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4728 dummy2, dummy3); 4729 4730 if (RefRelationship >= Sema::Ref_Related) { 4731 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4732 SuppressUserConversions, 4733 /*AllowExplicit=*/false); 4734 } 4735 } 4736 4737 // Otherwise, we bind the reference to a temporary created from the 4738 // initializer list. 4739 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4740 InOverloadResolution, 4741 AllowObjCWritebackConversion); 4742 if (Result.isFailure()) 4743 return Result; 4744 assert(!Result.isEllipsis() && 4745 "Sub-initialization cannot result in ellipsis conversion."); 4746 4747 // Can we even bind to a temporary? 4748 if (ToType->isRValueReferenceType() || 4749 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4750 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4751 Result.UserDefined.After; 4752 SCS.ReferenceBinding = true; 4753 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4754 SCS.BindsToRvalue = true; 4755 SCS.BindsToFunctionLvalue = false; 4756 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4757 SCS.ObjCLifetimeConversionBinding = false; 4758 } else 4759 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4760 From, ToType); 4761 return Result; 4762 } 4763 4764 // C++14 [over.ics.list]p7: 4765 // C++11 [over.ics.list]p6: 4766 // Otherwise, if the parameter type is not a class: 4767 if (!ToType->isRecordType()) { 4768 // - if the initializer list has one element that is not itself an 4769 // initializer list, the implicit conversion sequence is the one 4770 // required to convert the element to the parameter type. 4771 unsigned NumInits = From->getNumInits(); 4772 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4773 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4774 SuppressUserConversions, 4775 InOverloadResolution, 4776 AllowObjCWritebackConversion); 4777 // - if the initializer list has no elements, the implicit conversion 4778 // sequence is the identity conversion. 4779 else if (NumInits == 0) { 4780 Result.setStandard(); 4781 Result.Standard.setAsIdentityConversion(); 4782 Result.Standard.setFromType(ToType); 4783 Result.Standard.setAllToTypes(ToType); 4784 } 4785 return Result; 4786 } 4787 4788 // C++14 [over.ics.list]p8: 4789 // C++11 [over.ics.list]p7: 4790 // In all cases other than those enumerated above, no conversion is possible 4791 return Result; 4792 } 4793 4794 /// TryCopyInitialization - Try to copy-initialize a value of type 4795 /// ToType from the expression From. Return the implicit conversion 4796 /// sequence required to pass this argument, which may be a bad 4797 /// conversion sequence (meaning that the argument cannot be passed to 4798 /// a parameter of this type). If @p SuppressUserConversions, then we 4799 /// do not permit any user-defined conversion sequences. 4800 static ImplicitConversionSequence 4801 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4802 bool SuppressUserConversions, 4803 bool InOverloadResolution, 4804 bool AllowObjCWritebackConversion, 4805 bool AllowExplicit) { 4806 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4807 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4808 InOverloadResolution,AllowObjCWritebackConversion); 4809 4810 if (ToType->isReferenceType()) 4811 return TryReferenceInit(S, From, ToType, 4812 /*FIXME:*/From->getLocStart(), 4813 SuppressUserConversions, 4814 AllowExplicit); 4815 4816 return TryImplicitConversion(S, From, ToType, 4817 SuppressUserConversions, 4818 /*AllowExplicit=*/false, 4819 InOverloadResolution, 4820 /*CStyle=*/false, 4821 AllowObjCWritebackConversion, 4822 /*AllowObjCConversionOnExplicit=*/false); 4823 } 4824 4825 static bool TryCopyInitialization(const CanQualType FromQTy, 4826 const CanQualType ToQTy, 4827 Sema &S, 4828 SourceLocation Loc, 4829 ExprValueKind FromVK) { 4830 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4831 ImplicitConversionSequence ICS = 4832 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4833 4834 return !ICS.isBad(); 4835 } 4836 4837 /// TryObjectArgumentInitialization - Try to initialize the object 4838 /// parameter of the given member function (@c Method) from the 4839 /// expression @p From. 4840 static ImplicitConversionSequence 4841 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4842 Expr::Classification FromClassification, 4843 CXXMethodDecl *Method, 4844 CXXRecordDecl *ActingContext) { 4845 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4846 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4847 // const volatile object. 4848 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4849 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4850 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4851 4852 // Set up the conversion sequence as a "bad" conversion, to allow us 4853 // to exit early. 4854 ImplicitConversionSequence ICS; 4855 4856 // We need to have an object of class type. 4857 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4858 FromType = PT->getPointeeType(); 4859 4860 // When we had a pointer, it's implicitly dereferenced, so we 4861 // better have an lvalue. 4862 assert(FromClassification.isLValue()); 4863 } 4864 4865 assert(FromType->isRecordType()); 4866 4867 // C++0x [over.match.funcs]p4: 4868 // For non-static member functions, the type of the implicit object 4869 // parameter is 4870 // 4871 // - "lvalue reference to cv X" for functions declared without a 4872 // ref-qualifier or with the & ref-qualifier 4873 // - "rvalue reference to cv X" for functions declared with the && 4874 // ref-qualifier 4875 // 4876 // where X is the class of which the function is a member and cv is the 4877 // cv-qualification on the member function declaration. 4878 // 4879 // However, when finding an implicit conversion sequence for the argument, we 4880 // are not allowed to create temporaries or perform user-defined conversions 4881 // (C++ [over.match.funcs]p5). We perform a simplified version of 4882 // reference binding here, that allows class rvalues to bind to 4883 // non-constant references. 4884 4885 // First check the qualifiers. 4886 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4887 if (ImplicitParamType.getCVRQualifiers() 4888 != FromTypeCanon.getLocalCVRQualifiers() && 4889 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4890 ICS.setBad(BadConversionSequence::bad_qualifiers, 4891 FromType, ImplicitParamType); 4892 return ICS; 4893 } 4894 4895 // Check that we have either the same type or a derived type. It 4896 // affects the conversion rank. 4897 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4898 ImplicitConversionKind SecondKind; 4899 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4900 SecondKind = ICK_Identity; 4901 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4902 SecondKind = ICK_Derived_To_Base; 4903 else { 4904 ICS.setBad(BadConversionSequence::unrelated_class, 4905 FromType, ImplicitParamType); 4906 return ICS; 4907 } 4908 4909 // Check the ref-qualifier. 4910 switch (Method->getRefQualifier()) { 4911 case RQ_None: 4912 // Do nothing; we don't care about lvalueness or rvalueness. 4913 break; 4914 4915 case RQ_LValue: 4916 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4917 // non-const lvalue reference cannot bind to an rvalue 4918 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4919 ImplicitParamType); 4920 return ICS; 4921 } 4922 break; 4923 4924 case RQ_RValue: 4925 if (!FromClassification.isRValue()) { 4926 // rvalue reference cannot bind to an lvalue 4927 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4928 ImplicitParamType); 4929 return ICS; 4930 } 4931 break; 4932 } 4933 4934 // Success. Mark this as a reference binding. 4935 ICS.setStandard(); 4936 ICS.Standard.setAsIdentityConversion(); 4937 ICS.Standard.Second = SecondKind; 4938 ICS.Standard.setFromType(FromType); 4939 ICS.Standard.setAllToTypes(ImplicitParamType); 4940 ICS.Standard.ReferenceBinding = true; 4941 ICS.Standard.DirectBinding = true; 4942 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4943 ICS.Standard.BindsToFunctionLvalue = false; 4944 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4945 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4946 = (Method->getRefQualifier() == RQ_None); 4947 return ICS; 4948 } 4949 4950 /// PerformObjectArgumentInitialization - Perform initialization of 4951 /// the implicit object parameter for the given Method with the given 4952 /// expression. 4953 ExprResult 4954 Sema::PerformObjectArgumentInitialization(Expr *From, 4955 NestedNameSpecifier *Qualifier, 4956 NamedDecl *FoundDecl, 4957 CXXMethodDecl *Method) { 4958 QualType FromRecordType, DestType; 4959 QualType ImplicitParamRecordType = 4960 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4961 4962 Expr::Classification FromClassification; 4963 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4964 FromRecordType = PT->getPointeeType(); 4965 DestType = Method->getThisType(Context); 4966 FromClassification = Expr::Classification::makeSimpleLValue(); 4967 } else { 4968 FromRecordType = From->getType(); 4969 DestType = ImplicitParamRecordType; 4970 FromClassification = From->Classify(Context); 4971 } 4972 4973 // Note that we always use the true parent context when performing 4974 // the actual argument initialization. 4975 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4976 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4977 Method->getParent()); 4978 if (ICS.isBad()) { 4979 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4980 Qualifiers FromQs = FromRecordType.getQualifiers(); 4981 Qualifiers ToQs = DestType.getQualifiers(); 4982 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4983 if (CVR) { 4984 Diag(From->getLocStart(), 4985 diag::err_member_function_call_bad_cvr) 4986 << Method->getDeclName() << FromRecordType << (CVR - 1) 4987 << From->getSourceRange(); 4988 Diag(Method->getLocation(), diag::note_previous_decl) 4989 << Method->getDeclName(); 4990 return ExprError(); 4991 } 4992 } 4993 4994 return Diag(From->getLocStart(), 4995 diag::err_implicit_object_parameter_init) 4996 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4997 } 4998 4999 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5000 ExprResult FromRes = 5001 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5002 if (FromRes.isInvalid()) 5003 return ExprError(); 5004 From = FromRes.get(); 5005 } 5006 5007 if (!Context.hasSameType(From->getType(), DestType)) 5008 From = ImpCastExprToType(From, DestType, CK_NoOp, 5009 From->getValueKind()).get(); 5010 return From; 5011 } 5012 5013 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5014 /// expression From to bool (C++0x [conv]p3). 5015 static ImplicitConversionSequence 5016 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5017 return TryImplicitConversion(S, From, S.Context.BoolTy, 5018 /*SuppressUserConversions=*/false, 5019 /*AllowExplicit=*/true, 5020 /*InOverloadResolution=*/false, 5021 /*CStyle=*/false, 5022 /*AllowObjCWritebackConversion=*/false, 5023 /*AllowObjCConversionOnExplicit=*/false); 5024 } 5025 5026 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5027 /// of the expression From to bool (C++0x [conv]p3). 5028 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5029 if (checkPlaceholderForOverload(*this, From)) 5030 return ExprError(); 5031 5032 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5033 if (!ICS.isBad()) 5034 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5035 5036 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5037 return Diag(From->getLocStart(), 5038 diag::err_typecheck_bool_condition) 5039 << From->getType() << From->getSourceRange(); 5040 return ExprError(); 5041 } 5042 5043 /// Check that the specified conversion is permitted in a converted constant 5044 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5045 /// is acceptable. 5046 static bool CheckConvertedConstantConversions(Sema &S, 5047 StandardConversionSequence &SCS) { 5048 // Since we know that the target type is an integral or unscoped enumeration 5049 // type, most conversion kinds are impossible. All possible First and Third 5050 // conversions are fine. 5051 switch (SCS.Second) { 5052 case ICK_Identity: 5053 case ICK_NoReturn_Adjustment: 5054 case ICK_Integral_Promotion: 5055 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5056 return true; 5057 5058 case ICK_Boolean_Conversion: 5059 // Conversion from an integral or unscoped enumeration type to bool is 5060 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5061 // conversion, so we allow it in a converted constant expression. 5062 // 5063 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5064 // a lot of popular code. We should at least add a warning for this 5065 // (non-conforming) extension. 5066 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5067 SCS.getToType(2)->isBooleanType(); 5068 5069 case ICK_Pointer_Conversion: 5070 case ICK_Pointer_Member: 5071 // C++1z: null pointer conversions and null member pointer conversions are 5072 // only permitted if the source type is std::nullptr_t. 5073 return SCS.getFromType()->isNullPtrType(); 5074 5075 case ICK_Floating_Promotion: 5076 case ICK_Complex_Promotion: 5077 case ICK_Floating_Conversion: 5078 case ICK_Complex_Conversion: 5079 case ICK_Floating_Integral: 5080 case ICK_Compatible_Conversion: 5081 case ICK_Derived_To_Base: 5082 case ICK_Vector_Conversion: 5083 case ICK_Vector_Splat: 5084 case ICK_Complex_Real: 5085 case ICK_Block_Pointer_Conversion: 5086 case ICK_TransparentUnionConversion: 5087 case ICK_Writeback_Conversion: 5088 case ICK_Zero_Event_Conversion: 5089 case ICK_C_Only_Conversion: 5090 return false; 5091 5092 case ICK_Lvalue_To_Rvalue: 5093 case ICK_Array_To_Pointer: 5094 case ICK_Function_To_Pointer: 5095 llvm_unreachable("found a first conversion kind in Second"); 5096 5097 case ICK_Qualification: 5098 llvm_unreachable("found a third conversion kind in Second"); 5099 5100 case ICK_Num_Conversion_Kinds: 5101 break; 5102 } 5103 5104 llvm_unreachable("unknown conversion kind"); 5105 } 5106 5107 /// CheckConvertedConstantExpression - Check that the expression From is a 5108 /// converted constant expression of type T, perform the conversion and produce 5109 /// the converted expression, per C++11 [expr.const]p3. 5110 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5111 QualType T, APValue &Value, 5112 Sema::CCEKind CCE, 5113 bool RequireInt) { 5114 assert(S.getLangOpts().CPlusPlus11 && 5115 "converted constant expression outside C++11"); 5116 5117 if (checkPlaceholderForOverload(S, From)) 5118 return ExprError(); 5119 5120 // C++1z [expr.const]p3: 5121 // A converted constant expression of type T is an expression, 5122 // implicitly converted to type T, where the converted 5123 // expression is a constant expression and the implicit conversion 5124 // sequence contains only [... list of conversions ...]. 5125 ImplicitConversionSequence ICS = 5126 TryCopyInitialization(S, From, T, 5127 /*SuppressUserConversions=*/false, 5128 /*InOverloadResolution=*/false, 5129 /*AllowObjcWritebackConversion=*/false, 5130 /*AllowExplicit=*/false); 5131 StandardConversionSequence *SCS = nullptr; 5132 switch (ICS.getKind()) { 5133 case ImplicitConversionSequence::StandardConversion: 5134 SCS = &ICS.Standard; 5135 break; 5136 case ImplicitConversionSequence::UserDefinedConversion: 5137 // We are converting to a non-class type, so the Before sequence 5138 // must be trivial. 5139 SCS = &ICS.UserDefined.After; 5140 break; 5141 case ImplicitConversionSequence::AmbiguousConversion: 5142 case ImplicitConversionSequence::BadConversion: 5143 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5144 return S.Diag(From->getLocStart(), 5145 diag::err_typecheck_converted_constant_expression) 5146 << From->getType() << From->getSourceRange() << T; 5147 return ExprError(); 5148 5149 case ImplicitConversionSequence::EllipsisConversion: 5150 llvm_unreachable("ellipsis conversion in converted constant expression"); 5151 } 5152 5153 // Check that we would only use permitted conversions. 5154 if (!CheckConvertedConstantConversions(S, *SCS)) { 5155 return S.Diag(From->getLocStart(), 5156 diag::err_typecheck_converted_constant_expression_disallowed) 5157 << From->getType() << From->getSourceRange() << T; 5158 } 5159 // [...] and where the reference binding (if any) binds directly. 5160 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5161 return S.Diag(From->getLocStart(), 5162 diag::err_typecheck_converted_constant_expression_indirect) 5163 << From->getType() << From->getSourceRange() << T; 5164 } 5165 5166 ExprResult Result = 5167 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5168 if (Result.isInvalid()) 5169 return Result; 5170 5171 // Check for a narrowing implicit conversion. 5172 APValue PreNarrowingValue; 5173 QualType PreNarrowingType; 5174 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5175 PreNarrowingType)) { 5176 case NK_Variable_Narrowing: 5177 // Implicit conversion to a narrower type, and the value is not a constant 5178 // expression. We'll diagnose this in a moment. 5179 case NK_Not_Narrowing: 5180 break; 5181 5182 case NK_Constant_Narrowing: 5183 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5184 << CCE << /*Constant*/1 5185 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5186 break; 5187 5188 case NK_Type_Narrowing: 5189 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5190 << CCE << /*Constant*/0 << From->getType() << T; 5191 break; 5192 } 5193 5194 // Check the expression is a constant expression. 5195 SmallVector<PartialDiagnosticAt, 8> Notes; 5196 Expr::EvalResult Eval; 5197 Eval.Diag = &Notes; 5198 5199 if ((T->isReferenceType() 5200 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5201 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5202 (RequireInt && !Eval.Val.isInt())) { 5203 // The expression can't be folded, so we can't keep it at this position in 5204 // the AST. 5205 Result = ExprError(); 5206 } else { 5207 Value = Eval.Val; 5208 5209 if (Notes.empty()) { 5210 // It's a constant expression. 5211 return Result; 5212 } 5213 } 5214 5215 // It's not a constant expression. Produce an appropriate diagnostic. 5216 if (Notes.size() == 1 && 5217 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5218 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5219 else { 5220 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5221 << CCE << From->getSourceRange(); 5222 for (unsigned I = 0; I < Notes.size(); ++I) 5223 S.Diag(Notes[I].first, Notes[I].second); 5224 } 5225 return ExprError(); 5226 } 5227 5228 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5229 APValue &Value, CCEKind CCE) { 5230 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5231 } 5232 5233 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5234 llvm::APSInt &Value, 5235 CCEKind CCE) { 5236 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5237 5238 APValue V; 5239 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5240 if (!R.isInvalid()) 5241 Value = V.getInt(); 5242 return R; 5243 } 5244 5245 5246 /// dropPointerConversions - If the given standard conversion sequence 5247 /// involves any pointer conversions, remove them. This may change 5248 /// the result type of the conversion sequence. 5249 static void dropPointerConversion(StandardConversionSequence &SCS) { 5250 if (SCS.Second == ICK_Pointer_Conversion) { 5251 SCS.Second = ICK_Identity; 5252 SCS.Third = ICK_Identity; 5253 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5254 } 5255 } 5256 5257 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5258 /// convert the expression From to an Objective-C pointer type. 5259 static ImplicitConversionSequence 5260 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5261 // Do an implicit conversion to 'id'. 5262 QualType Ty = S.Context.getObjCIdType(); 5263 ImplicitConversionSequence ICS 5264 = TryImplicitConversion(S, From, Ty, 5265 // FIXME: Are these flags correct? 5266 /*SuppressUserConversions=*/false, 5267 /*AllowExplicit=*/true, 5268 /*InOverloadResolution=*/false, 5269 /*CStyle=*/false, 5270 /*AllowObjCWritebackConversion=*/false, 5271 /*AllowObjCConversionOnExplicit=*/true); 5272 5273 // Strip off any final conversions to 'id'. 5274 switch (ICS.getKind()) { 5275 case ImplicitConversionSequence::BadConversion: 5276 case ImplicitConversionSequence::AmbiguousConversion: 5277 case ImplicitConversionSequence::EllipsisConversion: 5278 break; 5279 5280 case ImplicitConversionSequence::UserDefinedConversion: 5281 dropPointerConversion(ICS.UserDefined.After); 5282 break; 5283 5284 case ImplicitConversionSequence::StandardConversion: 5285 dropPointerConversion(ICS.Standard); 5286 break; 5287 } 5288 5289 return ICS; 5290 } 5291 5292 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5293 /// conversion of the expression From to an Objective-C pointer type. 5294 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5295 if (checkPlaceholderForOverload(*this, From)) 5296 return ExprError(); 5297 5298 QualType Ty = Context.getObjCIdType(); 5299 ImplicitConversionSequence ICS = 5300 TryContextuallyConvertToObjCPointer(*this, From); 5301 if (!ICS.isBad()) 5302 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5303 return ExprError(); 5304 } 5305 5306 /// Determine whether the provided type is an integral type, or an enumeration 5307 /// type of a permitted flavor. 5308 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5309 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5310 : T->isIntegralOrUnscopedEnumerationType(); 5311 } 5312 5313 static ExprResult 5314 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5315 Sema::ContextualImplicitConverter &Converter, 5316 QualType T, UnresolvedSetImpl &ViableConversions) { 5317 5318 if (Converter.Suppress) 5319 return ExprError(); 5320 5321 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5322 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5323 CXXConversionDecl *Conv = 5324 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5325 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5326 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5327 } 5328 return From; 5329 } 5330 5331 static bool 5332 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5333 Sema::ContextualImplicitConverter &Converter, 5334 QualType T, bool HadMultipleCandidates, 5335 UnresolvedSetImpl &ExplicitConversions) { 5336 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5337 DeclAccessPair Found = ExplicitConversions[0]; 5338 CXXConversionDecl *Conversion = 5339 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5340 5341 // The user probably meant to invoke the given explicit 5342 // conversion; use it. 5343 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5344 std::string TypeStr; 5345 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5346 5347 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5348 << FixItHint::CreateInsertion(From->getLocStart(), 5349 "static_cast<" + TypeStr + ">(") 5350 << FixItHint::CreateInsertion( 5351 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5352 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5353 5354 // If we aren't in a SFINAE context, build a call to the 5355 // explicit conversion function. 5356 if (SemaRef.isSFINAEContext()) 5357 return true; 5358 5359 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5360 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5361 HadMultipleCandidates); 5362 if (Result.isInvalid()) 5363 return true; 5364 // Record usage of conversion in an implicit cast. 5365 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5366 CK_UserDefinedConversion, Result.get(), 5367 nullptr, Result.get()->getValueKind()); 5368 } 5369 return false; 5370 } 5371 5372 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5373 Sema::ContextualImplicitConverter &Converter, 5374 QualType T, bool HadMultipleCandidates, 5375 DeclAccessPair &Found) { 5376 CXXConversionDecl *Conversion = 5377 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5378 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5379 5380 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5381 if (!Converter.SuppressConversion) { 5382 if (SemaRef.isSFINAEContext()) 5383 return true; 5384 5385 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5386 << From->getSourceRange(); 5387 } 5388 5389 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5390 HadMultipleCandidates); 5391 if (Result.isInvalid()) 5392 return true; 5393 // Record usage of conversion in an implicit cast. 5394 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5395 CK_UserDefinedConversion, Result.get(), 5396 nullptr, Result.get()->getValueKind()); 5397 return false; 5398 } 5399 5400 static ExprResult finishContextualImplicitConversion( 5401 Sema &SemaRef, SourceLocation Loc, Expr *From, 5402 Sema::ContextualImplicitConverter &Converter) { 5403 if (!Converter.match(From->getType()) && !Converter.Suppress) 5404 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5405 << From->getSourceRange(); 5406 5407 return SemaRef.DefaultLvalueConversion(From); 5408 } 5409 5410 static void 5411 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5412 UnresolvedSetImpl &ViableConversions, 5413 OverloadCandidateSet &CandidateSet) { 5414 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5415 DeclAccessPair FoundDecl = ViableConversions[I]; 5416 NamedDecl *D = FoundDecl.getDecl(); 5417 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5418 if (isa<UsingShadowDecl>(D)) 5419 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5420 5421 CXXConversionDecl *Conv; 5422 FunctionTemplateDecl *ConvTemplate; 5423 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5424 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5425 else 5426 Conv = cast<CXXConversionDecl>(D); 5427 5428 if (ConvTemplate) 5429 SemaRef.AddTemplateConversionCandidate( 5430 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5431 /*AllowObjCConversionOnExplicit=*/false); 5432 else 5433 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5434 ToType, CandidateSet, 5435 /*AllowObjCConversionOnExplicit=*/false); 5436 } 5437 } 5438 5439 /// \brief Attempt to convert the given expression to a type which is accepted 5440 /// by the given converter. 5441 /// 5442 /// This routine will attempt to convert an expression of class type to a 5443 /// type accepted by the specified converter. In C++11 and before, the class 5444 /// must have a single non-explicit conversion function converting to a matching 5445 /// type. In C++1y, there can be multiple such conversion functions, but only 5446 /// one target type. 5447 /// 5448 /// \param Loc The source location of the construct that requires the 5449 /// conversion. 5450 /// 5451 /// \param From The expression we're converting from. 5452 /// 5453 /// \param Converter Used to control and diagnose the conversion process. 5454 /// 5455 /// \returns The expression, converted to an integral or enumeration type if 5456 /// successful. 5457 ExprResult Sema::PerformContextualImplicitConversion( 5458 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5459 // We can't perform any more checking for type-dependent expressions. 5460 if (From->isTypeDependent()) 5461 return From; 5462 5463 // Process placeholders immediately. 5464 if (From->hasPlaceholderType()) { 5465 ExprResult result = CheckPlaceholderExpr(From); 5466 if (result.isInvalid()) 5467 return result; 5468 From = result.get(); 5469 } 5470 5471 // If the expression already has a matching type, we're golden. 5472 QualType T = From->getType(); 5473 if (Converter.match(T)) 5474 return DefaultLvalueConversion(From); 5475 5476 // FIXME: Check for missing '()' if T is a function type? 5477 5478 // We can only perform contextual implicit conversions on objects of class 5479 // type. 5480 const RecordType *RecordTy = T->getAs<RecordType>(); 5481 if (!RecordTy || !getLangOpts().CPlusPlus) { 5482 if (!Converter.Suppress) 5483 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5484 return From; 5485 } 5486 5487 // We must have a complete class type. 5488 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5489 ContextualImplicitConverter &Converter; 5490 Expr *From; 5491 5492 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5493 : Converter(Converter), From(From) {} 5494 5495 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5496 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5497 } 5498 } IncompleteDiagnoser(Converter, From); 5499 5500 if (Converter.Suppress ? !isCompleteType(Loc, T) 5501 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5502 return From; 5503 5504 // Look for a conversion to an integral or enumeration type. 5505 UnresolvedSet<4> 5506 ViableConversions; // These are *potentially* viable in C++1y. 5507 UnresolvedSet<4> ExplicitConversions; 5508 const auto &Conversions = 5509 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5510 5511 bool HadMultipleCandidates = 5512 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5513 5514 // To check that there is only one target type, in C++1y: 5515 QualType ToType; 5516 bool HasUniqueTargetType = true; 5517 5518 // Collect explicit or viable (potentially in C++1y) conversions. 5519 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5520 NamedDecl *D = (*I)->getUnderlyingDecl(); 5521 CXXConversionDecl *Conversion; 5522 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5523 if (ConvTemplate) { 5524 if (getLangOpts().CPlusPlus14) 5525 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5526 else 5527 continue; // C++11 does not consider conversion operator templates(?). 5528 } else 5529 Conversion = cast<CXXConversionDecl>(D); 5530 5531 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5532 "Conversion operator templates are considered potentially " 5533 "viable in C++1y"); 5534 5535 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5536 if (Converter.match(CurToType) || ConvTemplate) { 5537 5538 if (Conversion->isExplicit()) { 5539 // FIXME: For C++1y, do we need this restriction? 5540 // cf. diagnoseNoViableConversion() 5541 if (!ConvTemplate) 5542 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5543 } else { 5544 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5545 if (ToType.isNull()) 5546 ToType = CurToType.getUnqualifiedType(); 5547 else if (HasUniqueTargetType && 5548 (CurToType.getUnqualifiedType() != ToType)) 5549 HasUniqueTargetType = false; 5550 } 5551 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5552 } 5553 } 5554 } 5555 5556 if (getLangOpts().CPlusPlus14) { 5557 // C++1y [conv]p6: 5558 // ... An expression e of class type E appearing in such a context 5559 // is said to be contextually implicitly converted to a specified 5560 // type T and is well-formed if and only if e can be implicitly 5561 // converted to a type T that is determined as follows: E is searched 5562 // for conversion functions whose return type is cv T or reference to 5563 // cv T such that T is allowed by the context. There shall be 5564 // exactly one such T. 5565 5566 // If no unique T is found: 5567 if (ToType.isNull()) { 5568 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5569 HadMultipleCandidates, 5570 ExplicitConversions)) 5571 return ExprError(); 5572 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5573 } 5574 5575 // If more than one unique Ts are found: 5576 if (!HasUniqueTargetType) 5577 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5578 ViableConversions); 5579 5580 // If one unique T is found: 5581 // First, build a candidate set from the previously recorded 5582 // potentially viable conversions. 5583 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5584 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5585 CandidateSet); 5586 5587 // Then, perform overload resolution over the candidate set. 5588 OverloadCandidateSet::iterator Best; 5589 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5590 case OR_Success: { 5591 // Apply this conversion. 5592 DeclAccessPair Found = 5593 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5594 if (recordConversion(*this, Loc, From, Converter, T, 5595 HadMultipleCandidates, Found)) 5596 return ExprError(); 5597 break; 5598 } 5599 case OR_Ambiguous: 5600 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5601 ViableConversions); 5602 case OR_No_Viable_Function: 5603 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5604 HadMultipleCandidates, 5605 ExplicitConversions)) 5606 return ExprError(); 5607 // fall through 'OR_Deleted' case. 5608 case OR_Deleted: 5609 // We'll complain below about a non-integral condition type. 5610 break; 5611 } 5612 } else { 5613 switch (ViableConversions.size()) { 5614 case 0: { 5615 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5616 HadMultipleCandidates, 5617 ExplicitConversions)) 5618 return ExprError(); 5619 5620 // We'll complain below about a non-integral condition type. 5621 break; 5622 } 5623 case 1: { 5624 // Apply this conversion. 5625 DeclAccessPair Found = ViableConversions[0]; 5626 if (recordConversion(*this, Loc, From, Converter, T, 5627 HadMultipleCandidates, Found)) 5628 return ExprError(); 5629 break; 5630 } 5631 default: 5632 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5633 ViableConversions); 5634 } 5635 } 5636 5637 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5638 } 5639 5640 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5641 /// an acceptable non-member overloaded operator for a call whose 5642 /// arguments have types T1 (and, if non-empty, T2). This routine 5643 /// implements the check in C++ [over.match.oper]p3b2 concerning 5644 /// enumeration types. 5645 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5646 FunctionDecl *Fn, 5647 ArrayRef<Expr *> Args) { 5648 QualType T1 = Args[0]->getType(); 5649 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5650 5651 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5652 return true; 5653 5654 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5655 return true; 5656 5657 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5658 if (Proto->getNumParams() < 1) 5659 return false; 5660 5661 if (T1->isEnumeralType()) { 5662 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5663 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5664 return true; 5665 } 5666 5667 if (Proto->getNumParams() < 2) 5668 return false; 5669 5670 if (!T2.isNull() && T2->isEnumeralType()) { 5671 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5672 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5673 return true; 5674 } 5675 5676 return false; 5677 } 5678 5679 /// AddOverloadCandidate - Adds the given function to the set of 5680 /// candidate functions, using the given function call arguments. If 5681 /// @p SuppressUserConversions, then don't allow user-defined 5682 /// conversions via constructors or conversion operators. 5683 /// 5684 /// \param PartialOverloading true if we are performing "partial" overloading 5685 /// based on an incomplete set of function arguments. This feature is used by 5686 /// code completion. 5687 void 5688 Sema::AddOverloadCandidate(FunctionDecl *Function, 5689 DeclAccessPair FoundDecl, 5690 ArrayRef<Expr *> Args, 5691 OverloadCandidateSet &CandidateSet, 5692 bool SuppressUserConversions, 5693 bool PartialOverloading, 5694 bool AllowExplicit) { 5695 const FunctionProtoType *Proto 5696 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5697 assert(Proto && "Functions without a prototype cannot be overloaded"); 5698 assert(!Function->getDescribedFunctionTemplate() && 5699 "Use AddTemplateOverloadCandidate for function templates"); 5700 5701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5702 if (!isa<CXXConstructorDecl>(Method)) { 5703 // If we get here, it's because we're calling a member function 5704 // that is named without a member access expression (e.g., 5705 // "this->f") that was either written explicitly or created 5706 // implicitly. This can happen with a qualified call to a member 5707 // function, e.g., X::f(). We use an empty type for the implied 5708 // object argument (C++ [over.call.func]p3), and the acting context 5709 // is irrelevant. 5710 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5711 QualType(), Expr::Classification::makeSimpleLValue(), 5712 Args, CandidateSet, SuppressUserConversions, 5713 PartialOverloading); 5714 return; 5715 } 5716 // We treat a constructor like a non-member function, since its object 5717 // argument doesn't participate in overload resolution. 5718 } 5719 5720 if (!CandidateSet.isNewCandidate(Function)) 5721 return; 5722 5723 // C++ [over.match.oper]p3: 5724 // if no operand has a class type, only those non-member functions in the 5725 // lookup set that have a first parameter of type T1 or "reference to 5726 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5727 // is a right operand) a second parameter of type T2 or "reference to 5728 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5729 // candidate functions. 5730 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5731 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5732 return; 5733 5734 // C++11 [class.copy]p11: [DR1402] 5735 // A defaulted move constructor that is defined as deleted is ignored by 5736 // overload resolution. 5737 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5738 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5739 Constructor->isMoveConstructor()) 5740 return; 5741 5742 // Overload resolution is always an unevaluated context. 5743 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5744 5745 // Add this candidate 5746 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5747 Candidate.FoundDecl = FoundDecl; 5748 Candidate.Function = Function; 5749 Candidate.Viable = true; 5750 Candidate.IsSurrogate = false; 5751 Candidate.IgnoreObjectArgument = false; 5752 Candidate.ExplicitCallArguments = Args.size(); 5753 5754 if (Constructor) { 5755 // C++ [class.copy]p3: 5756 // A member function template is never instantiated to perform the copy 5757 // of a class object to an object of its class type. 5758 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5759 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5760 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5761 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5762 ClassType))) { 5763 Candidate.Viable = false; 5764 Candidate.FailureKind = ovl_fail_illegal_constructor; 5765 return; 5766 } 5767 } 5768 5769 unsigned NumParams = Proto->getNumParams(); 5770 5771 // (C++ 13.3.2p2): A candidate function having fewer than m 5772 // parameters is viable only if it has an ellipsis in its parameter 5773 // list (8.3.5). 5774 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5775 !Proto->isVariadic()) { 5776 Candidate.Viable = false; 5777 Candidate.FailureKind = ovl_fail_too_many_arguments; 5778 return; 5779 } 5780 5781 // (C++ 13.3.2p2): A candidate function having more than m parameters 5782 // is viable only if the (m+1)st parameter has a default argument 5783 // (8.3.6). For the purposes of overload resolution, the 5784 // parameter list is truncated on the right, so that there are 5785 // exactly m parameters. 5786 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5787 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5788 // Not enough arguments. 5789 Candidate.Viable = false; 5790 Candidate.FailureKind = ovl_fail_too_few_arguments; 5791 return; 5792 } 5793 5794 // (CUDA B.1): Check for invalid calls between targets. 5795 if (getLangOpts().CUDA) 5796 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5797 // Skip the check for callers that are implicit members, because in this 5798 // case we may not yet know what the member's target is; the target is 5799 // inferred for the member automatically, based on the bases and fields of 5800 // the class. 5801 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5802 Candidate.Viable = false; 5803 Candidate.FailureKind = ovl_fail_bad_target; 5804 return; 5805 } 5806 5807 // Determine the implicit conversion sequences for each of the 5808 // arguments. 5809 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5810 if (ArgIdx < NumParams) { 5811 // (C++ 13.3.2p3): for F to be a viable function, there shall 5812 // exist for each argument an implicit conversion sequence 5813 // (13.3.3.1) that converts that argument to the corresponding 5814 // parameter of F. 5815 QualType ParamType = Proto->getParamType(ArgIdx); 5816 Candidate.Conversions[ArgIdx] 5817 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5818 SuppressUserConversions, 5819 /*InOverloadResolution=*/true, 5820 /*AllowObjCWritebackConversion=*/ 5821 getLangOpts().ObjCAutoRefCount, 5822 AllowExplicit); 5823 if (Candidate.Conversions[ArgIdx].isBad()) { 5824 Candidate.Viable = false; 5825 Candidate.FailureKind = ovl_fail_bad_conversion; 5826 return; 5827 } 5828 } else { 5829 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5830 // argument for which there is no corresponding parameter is 5831 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5832 Candidate.Conversions[ArgIdx].setEllipsis(); 5833 } 5834 } 5835 5836 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5837 Candidate.Viable = false; 5838 Candidate.FailureKind = ovl_fail_enable_if; 5839 Candidate.DeductionFailure.Data = FailedAttr; 5840 return; 5841 } 5842 } 5843 5844 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5845 bool IsInstance) { 5846 SmallVector<ObjCMethodDecl*, 4> Methods; 5847 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5848 return nullptr; 5849 5850 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5851 bool Match = true; 5852 ObjCMethodDecl *Method = Methods[b]; 5853 unsigned NumNamedArgs = Sel.getNumArgs(); 5854 // Method might have more arguments than selector indicates. This is due 5855 // to addition of c-style arguments in method. 5856 if (Method->param_size() > NumNamedArgs) 5857 NumNamedArgs = Method->param_size(); 5858 if (Args.size() < NumNamedArgs) 5859 continue; 5860 5861 for (unsigned i = 0; i < NumNamedArgs; i++) { 5862 // We can't do any type-checking on a type-dependent argument. 5863 if (Args[i]->isTypeDependent()) { 5864 Match = false; 5865 break; 5866 } 5867 5868 ParmVarDecl *param = Method->parameters()[i]; 5869 Expr *argExpr = Args[i]; 5870 assert(argExpr && "SelectBestMethod(): missing expression"); 5871 5872 // Strip the unbridged-cast placeholder expression off unless it's 5873 // a consumed argument. 5874 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5875 !param->hasAttr<CFConsumedAttr>()) 5876 argExpr = stripARCUnbridgedCast(argExpr); 5877 5878 // If the parameter is __unknown_anytype, move on to the next method. 5879 if (param->getType() == Context.UnknownAnyTy) { 5880 Match = false; 5881 break; 5882 } 5883 5884 ImplicitConversionSequence ConversionState 5885 = TryCopyInitialization(*this, argExpr, param->getType(), 5886 /*SuppressUserConversions*/false, 5887 /*InOverloadResolution=*/true, 5888 /*AllowObjCWritebackConversion=*/ 5889 getLangOpts().ObjCAutoRefCount, 5890 /*AllowExplicit*/false); 5891 if (ConversionState.isBad()) { 5892 Match = false; 5893 break; 5894 } 5895 } 5896 // Promote additional arguments to variadic methods. 5897 if (Match && Method->isVariadic()) { 5898 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5899 if (Args[i]->isTypeDependent()) { 5900 Match = false; 5901 break; 5902 } 5903 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5904 nullptr); 5905 if (Arg.isInvalid()) { 5906 Match = false; 5907 break; 5908 } 5909 } 5910 } else { 5911 // Check for extra arguments to non-variadic methods. 5912 if (Args.size() != NumNamedArgs) 5913 Match = false; 5914 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5915 // Special case when selectors have no argument. In this case, select 5916 // one with the most general result type of 'id'. 5917 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5918 QualType ReturnT = Methods[b]->getReturnType(); 5919 if (ReturnT->isObjCIdType()) 5920 return Methods[b]; 5921 } 5922 } 5923 } 5924 5925 if (Match) 5926 return Method; 5927 } 5928 return nullptr; 5929 } 5930 5931 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5932 // enable_if is order-sensitive. As a result, we need to reverse things 5933 // sometimes. Size of 4 elements is arbitrary. 5934 static SmallVector<EnableIfAttr *, 4> 5935 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5936 SmallVector<EnableIfAttr *, 4> Result; 5937 if (!Function->hasAttrs()) 5938 return Result; 5939 5940 const auto &FuncAttrs = Function->getAttrs(); 5941 for (Attr *Attr : FuncAttrs) 5942 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5943 Result.push_back(EnableIf); 5944 5945 std::reverse(Result.begin(), Result.end()); 5946 return Result; 5947 } 5948 5949 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5950 bool MissingImplicitThis) { 5951 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5952 if (EnableIfAttrs.empty()) 5953 return nullptr; 5954 5955 SFINAETrap Trap(*this); 5956 SmallVector<Expr *, 16> ConvertedArgs; 5957 bool InitializationFailed = false; 5958 bool ContainsValueDependentExpr = false; 5959 5960 // Convert the arguments. 5961 for (unsigned I = 0, E = Args.size(); I != E; ++I) { 5962 ExprResult R; 5963 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5964 !cast<CXXMethodDecl>(Function)->isStatic() && 5965 !isa<CXXConstructorDecl>(Function)) { 5966 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5967 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5968 Method, Method); 5969 } else { 5970 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 5971 Context, Function->getParamDecl(I)), 5972 SourceLocation(), Args[I]); 5973 } 5974 5975 if (R.isInvalid()) { 5976 InitializationFailed = true; 5977 break; 5978 } 5979 5980 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5981 ConvertedArgs.push_back(R.get()); 5982 } 5983 5984 if (InitializationFailed || Trap.hasErrorOccurred()) 5985 return EnableIfAttrs[0]; 5986 5987 // Push default arguments if needed. 5988 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5989 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5990 ParmVarDecl *P = Function->getParamDecl(i); 5991 ExprResult R = PerformCopyInitialization( 5992 InitializedEntity::InitializeParameter(Context, 5993 Function->getParamDecl(i)), 5994 SourceLocation(), 5995 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5996 : P->getDefaultArg()); 5997 if (R.isInvalid()) { 5998 InitializationFailed = true; 5999 break; 6000 } 6001 ContainsValueDependentExpr |= R.get()->isValueDependent(); 6002 ConvertedArgs.push_back(R.get()); 6003 } 6004 6005 if (InitializationFailed || Trap.hasErrorOccurred()) 6006 return EnableIfAttrs[0]; 6007 } 6008 6009 for (auto *EIA : EnableIfAttrs) { 6010 APValue Result; 6011 if (EIA->getCond()->isValueDependent()) { 6012 // Don't even try now, we'll examine it after instantiation. 6013 continue; 6014 } 6015 6016 if (!EIA->getCond()->EvaluateWithSubstitution( 6017 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 6018 if (!ContainsValueDependentExpr) 6019 return EIA; 6020 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 6021 return EIA; 6022 } 6023 } 6024 return nullptr; 6025 } 6026 6027 /// \brief Add all of the function declarations in the given function set to 6028 /// the overload candidate set. 6029 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6030 ArrayRef<Expr *> Args, 6031 OverloadCandidateSet& CandidateSet, 6032 TemplateArgumentListInfo *ExplicitTemplateArgs, 6033 bool SuppressUserConversions, 6034 bool PartialOverloading) { 6035 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6036 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6037 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6038 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6039 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6040 cast<CXXMethodDecl>(FD)->getParent(), 6041 Args[0]->getType(), Args[0]->Classify(Context), 6042 Args.slice(1), CandidateSet, 6043 SuppressUserConversions, PartialOverloading); 6044 else 6045 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6046 SuppressUserConversions, PartialOverloading); 6047 } else { 6048 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6049 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6050 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6051 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6052 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6053 ExplicitTemplateArgs, 6054 Args[0]->getType(), 6055 Args[0]->Classify(Context), Args.slice(1), 6056 CandidateSet, SuppressUserConversions, 6057 PartialOverloading); 6058 else 6059 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6060 ExplicitTemplateArgs, Args, 6061 CandidateSet, SuppressUserConversions, 6062 PartialOverloading); 6063 } 6064 } 6065 } 6066 6067 /// AddMethodCandidate - Adds a named decl (which is some kind of 6068 /// method) as a method candidate to the given overload set. 6069 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6070 QualType ObjectType, 6071 Expr::Classification ObjectClassification, 6072 ArrayRef<Expr *> Args, 6073 OverloadCandidateSet& CandidateSet, 6074 bool SuppressUserConversions) { 6075 NamedDecl *Decl = FoundDecl.getDecl(); 6076 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6077 6078 if (isa<UsingShadowDecl>(Decl)) 6079 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6080 6081 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6082 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6083 "Expected a member function template"); 6084 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6085 /*ExplicitArgs*/ nullptr, 6086 ObjectType, ObjectClassification, 6087 Args, CandidateSet, 6088 SuppressUserConversions); 6089 } else { 6090 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6091 ObjectType, ObjectClassification, 6092 Args, 6093 CandidateSet, SuppressUserConversions); 6094 } 6095 } 6096 6097 /// AddMethodCandidate - Adds the given C++ member function to the set 6098 /// of candidate functions, using the given function call arguments 6099 /// and the object argument (@c Object). For example, in a call 6100 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6101 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6102 /// allow user-defined conversions via constructors or conversion 6103 /// operators. 6104 void 6105 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6106 CXXRecordDecl *ActingContext, QualType ObjectType, 6107 Expr::Classification ObjectClassification, 6108 ArrayRef<Expr *> Args, 6109 OverloadCandidateSet &CandidateSet, 6110 bool SuppressUserConversions, 6111 bool PartialOverloading) { 6112 const FunctionProtoType *Proto 6113 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6114 assert(Proto && "Methods without a prototype cannot be overloaded"); 6115 assert(!isa<CXXConstructorDecl>(Method) && 6116 "Use AddOverloadCandidate for constructors"); 6117 6118 if (!CandidateSet.isNewCandidate(Method)) 6119 return; 6120 6121 // C++11 [class.copy]p23: [DR1402] 6122 // A defaulted move assignment operator that is defined as deleted is 6123 // ignored by overload resolution. 6124 if (Method->isDefaulted() && Method->isDeleted() && 6125 Method->isMoveAssignmentOperator()) 6126 return; 6127 6128 // Overload resolution is always an unevaluated context. 6129 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6130 6131 // Add this candidate 6132 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6133 Candidate.FoundDecl = FoundDecl; 6134 Candidate.Function = Method; 6135 Candidate.IsSurrogate = false; 6136 Candidate.IgnoreObjectArgument = false; 6137 Candidate.ExplicitCallArguments = Args.size(); 6138 6139 unsigned NumParams = Proto->getNumParams(); 6140 6141 // (C++ 13.3.2p2): A candidate function having fewer than m 6142 // parameters is viable only if it has an ellipsis in its parameter 6143 // list (8.3.5). 6144 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6145 !Proto->isVariadic()) { 6146 Candidate.Viable = false; 6147 Candidate.FailureKind = ovl_fail_too_many_arguments; 6148 return; 6149 } 6150 6151 // (C++ 13.3.2p2): A candidate function having more than m parameters 6152 // is viable only if the (m+1)st parameter has a default argument 6153 // (8.3.6). For the purposes of overload resolution, the 6154 // parameter list is truncated on the right, so that there are 6155 // exactly m parameters. 6156 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6157 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6158 // Not enough arguments. 6159 Candidate.Viable = false; 6160 Candidate.FailureKind = ovl_fail_too_few_arguments; 6161 return; 6162 } 6163 6164 Candidate.Viable = true; 6165 6166 if (Method->isStatic() || ObjectType.isNull()) 6167 // The implicit object argument is ignored. 6168 Candidate.IgnoreObjectArgument = true; 6169 else { 6170 // Determine the implicit conversion sequence for the object 6171 // parameter. 6172 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6173 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6174 Method, ActingContext); 6175 if (Candidate.Conversions[0].isBad()) { 6176 Candidate.Viable = false; 6177 Candidate.FailureKind = ovl_fail_bad_conversion; 6178 return; 6179 } 6180 } 6181 6182 // (CUDA B.1): Check for invalid calls between targets. 6183 if (getLangOpts().CUDA) 6184 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6185 if (CheckCUDATarget(Caller, Method)) { 6186 Candidate.Viable = false; 6187 Candidate.FailureKind = ovl_fail_bad_target; 6188 return; 6189 } 6190 6191 // Determine the implicit conversion sequences for each of the 6192 // arguments. 6193 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6194 if (ArgIdx < NumParams) { 6195 // (C++ 13.3.2p3): for F to be a viable function, there shall 6196 // exist for each argument an implicit conversion sequence 6197 // (13.3.3.1) that converts that argument to the corresponding 6198 // parameter of F. 6199 QualType ParamType = Proto->getParamType(ArgIdx); 6200 Candidate.Conversions[ArgIdx + 1] 6201 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6202 SuppressUserConversions, 6203 /*InOverloadResolution=*/true, 6204 /*AllowObjCWritebackConversion=*/ 6205 getLangOpts().ObjCAutoRefCount); 6206 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6207 Candidate.Viable = false; 6208 Candidate.FailureKind = ovl_fail_bad_conversion; 6209 return; 6210 } 6211 } else { 6212 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6213 // argument for which there is no corresponding parameter is 6214 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6215 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6216 } 6217 } 6218 6219 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6220 Candidate.Viable = false; 6221 Candidate.FailureKind = ovl_fail_enable_if; 6222 Candidate.DeductionFailure.Data = FailedAttr; 6223 return; 6224 } 6225 } 6226 6227 /// \brief Add a C++ member function template as a candidate to the candidate 6228 /// set, using template argument deduction to produce an appropriate member 6229 /// function template specialization. 6230 void 6231 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6232 DeclAccessPair FoundDecl, 6233 CXXRecordDecl *ActingContext, 6234 TemplateArgumentListInfo *ExplicitTemplateArgs, 6235 QualType ObjectType, 6236 Expr::Classification ObjectClassification, 6237 ArrayRef<Expr *> Args, 6238 OverloadCandidateSet& CandidateSet, 6239 bool SuppressUserConversions, 6240 bool PartialOverloading) { 6241 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6242 return; 6243 6244 // C++ [over.match.funcs]p7: 6245 // In each case where a candidate is a function template, candidate 6246 // function template specializations are generated using template argument 6247 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6248 // candidate functions in the usual way.113) A given name can refer to one 6249 // or more function templates and also to a set of overloaded non-template 6250 // functions. In such a case, the candidate functions generated from each 6251 // function template are combined with the set of non-template candidate 6252 // functions. 6253 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6254 FunctionDecl *Specialization = nullptr; 6255 if (TemplateDeductionResult Result 6256 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6257 Specialization, Info, PartialOverloading)) { 6258 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6259 Candidate.FoundDecl = FoundDecl; 6260 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6261 Candidate.Viable = false; 6262 Candidate.FailureKind = ovl_fail_bad_deduction; 6263 Candidate.IsSurrogate = false; 6264 Candidate.IgnoreObjectArgument = false; 6265 Candidate.ExplicitCallArguments = Args.size(); 6266 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6267 Info); 6268 return; 6269 } 6270 6271 // Add the function template specialization produced by template argument 6272 // deduction as a candidate. 6273 assert(Specialization && "Missing member function template specialization?"); 6274 assert(isa<CXXMethodDecl>(Specialization) && 6275 "Specialization is not a member function?"); 6276 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6277 ActingContext, ObjectType, ObjectClassification, Args, 6278 CandidateSet, SuppressUserConversions, PartialOverloading); 6279 } 6280 6281 /// \brief Add a C++ function template specialization as a candidate 6282 /// in the candidate set, using template argument deduction to produce 6283 /// an appropriate function template specialization. 6284 void 6285 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6286 DeclAccessPair FoundDecl, 6287 TemplateArgumentListInfo *ExplicitTemplateArgs, 6288 ArrayRef<Expr *> Args, 6289 OverloadCandidateSet& CandidateSet, 6290 bool SuppressUserConversions, 6291 bool PartialOverloading) { 6292 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6293 return; 6294 6295 // C++ [over.match.funcs]p7: 6296 // In each case where a candidate is a function template, candidate 6297 // function template specializations are generated using template argument 6298 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6299 // candidate functions in the usual way.113) A given name can refer to one 6300 // or more function templates and also to a set of overloaded non-template 6301 // functions. In such a case, the candidate functions generated from each 6302 // function template are combined with the set of non-template candidate 6303 // functions. 6304 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6305 FunctionDecl *Specialization = nullptr; 6306 if (TemplateDeductionResult Result 6307 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6308 Specialization, Info, PartialOverloading)) { 6309 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6310 Candidate.FoundDecl = FoundDecl; 6311 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6312 Candidate.Viable = false; 6313 Candidate.FailureKind = ovl_fail_bad_deduction; 6314 Candidate.IsSurrogate = false; 6315 Candidate.IgnoreObjectArgument = false; 6316 Candidate.ExplicitCallArguments = Args.size(); 6317 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6318 Info); 6319 return; 6320 } 6321 6322 // Add the function template specialization produced by template argument 6323 // deduction as a candidate. 6324 assert(Specialization && "Missing function template specialization?"); 6325 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6326 SuppressUserConversions, PartialOverloading); 6327 } 6328 6329 /// Determine whether this is an allowable conversion from the result 6330 /// of an explicit conversion operator to the expected type, per C++ 6331 /// [over.match.conv]p1 and [over.match.ref]p1. 6332 /// 6333 /// \param ConvType The return type of the conversion function. 6334 /// 6335 /// \param ToType The type we are converting to. 6336 /// 6337 /// \param AllowObjCPointerConversion Allow a conversion from one 6338 /// Objective-C pointer to another. 6339 /// 6340 /// \returns true if the conversion is allowable, false otherwise. 6341 static bool isAllowableExplicitConversion(Sema &S, 6342 QualType ConvType, QualType ToType, 6343 bool AllowObjCPointerConversion) { 6344 QualType ToNonRefType = ToType.getNonReferenceType(); 6345 6346 // Easy case: the types are the same. 6347 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6348 return true; 6349 6350 // Allow qualification conversions. 6351 bool ObjCLifetimeConversion; 6352 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6353 ObjCLifetimeConversion)) 6354 return true; 6355 6356 // If we're not allowed to consider Objective-C pointer conversions, 6357 // we're done. 6358 if (!AllowObjCPointerConversion) 6359 return false; 6360 6361 // Is this an Objective-C pointer conversion? 6362 bool IncompatibleObjC = false; 6363 QualType ConvertedType; 6364 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6365 IncompatibleObjC); 6366 } 6367 6368 /// AddConversionCandidate - Add a C++ conversion function as a 6369 /// candidate in the candidate set (C++ [over.match.conv], 6370 /// C++ [over.match.copy]). From is the expression we're converting from, 6371 /// and ToType is the type that we're eventually trying to convert to 6372 /// (which may or may not be the same type as the type that the 6373 /// conversion function produces). 6374 void 6375 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6376 DeclAccessPair FoundDecl, 6377 CXXRecordDecl *ActingContext, 6378 Expr *From, QualType ToType, 6379 OverloadCandidateSet& CandidateSet, 6380 bool AllowObjCConversionOnExplicit) { 6381 assert(!Conversion->getDescribedFunctionTemplate() && 6382 "Conversion function templates use AddTemplateConversionCandidate"); 6383 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6384 if (!CandidateSet.isNewCandidate(Conversion)) 6385 return; 6386 6387 // If the conversion function has an undeduced return type, trigger its 6388 // deduction now. 6389 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6390 if (DeduceReturnType(Conversion, From->getExprLoc())) 6391 return; 6392 ConvType = Conversion->getConversionType().getNonReferenceType(); 6393 } 6394 6395 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6396 // operator is only a candidate if its return type is the target type or 6397 // can be converted to the target type with a qualification conversion. 6398 if (Conversion->isExplicit() && 6399 !isAllowableExplicitConversion(*this, ConvType, ToType, 6400 AllowObjCConversionOnExplicit)) 6401 return; 6402 6403 // Overload resolution is always an unevaluated context. 6404 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6405 6406 // Add this candidate 6407 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6408 Candidate.FoundDecl = FoundDecl; 6409 Candidate.Function = Conversion; 6410 Candidate.IsSurrogate = false; 6411 Candidate.IgnoreObjectArgument = false; 6412 Candidate.FinalConversion.setAsIdentityConversion(); 6413 Candidate.FinalConversion.setFromType(ConvType); 6414 Candidate.FinalConversion.setAllToTypes(ToType); 6415 Candidate.Viable = true; 6416 Candidate.ExplicitCallArguments = 1; 6417 6418 // C++ [over.match.funcs]p4: 6419 // For conversion functions, the function is considered to be a member of 6420 // the class of the implicit implied object argument for the purpose of 6421 // defining the type of the implicit object parameter. 6422 // 6423 // Determine the implicit conversion sequence for the implicit 6424 // object parameter. 6425 QualType ImplicitParamType = From->getType(); 6426 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6427 ImplicitParamType = FromPtrType->getPointeeType(); 6428 CXXRecordDecl *ConversionContext 6429 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6430 6431 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6432 *this, CandidateSet.getLocation(), From->getType(), 6433 From->Classify(Context), Conversion, ConversionContext); 6434 6435 if (Candidate.Conversions[0].isBad()) { 6436 Candidate.Viable = false; 6437 Candidate.FailureKind = ovl_fail_bad_conversion; 6438 return; 6439 } 6440 6441 // We won't go through a user-defined type conversion function to convert a 6442 // derived to base as such conversions are given Conversion Rank. They only 6443 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6444 QualType FromCanon 6445 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6446 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6447 if (FromCanon == ToCanon || 6448 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6449 Candidate.Viable = false; 6450 Candidate.FailureKind = ovl_fail_trivial_conversion; 6451 return; 6452 } 6453 6454 // To determine what the conversion from the result of calling the 6455 // conversion function to the type we're eventually trying to 6456 // convert to (ToType), we need to synthesize a call to the 6457 // conversion function and attempt copy initialization from it. This 6458 // makes sure that we get the right semantics with respect to 6459 // lvalues/rvalues and the type. Fortunately, we can allocate this 6460 // call on the stack and we don't need its arguments to be 6461 // well-formed. 6462 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6463 VK_LValue, From->getLocStart()); 6464 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6465 Context.getPointerType(Conversion->getType()), 6466 CK_FunctionToPointerDecay, 6467 &ConversionRef, VK_RValue); 6468 6469 QualType ConversionType = Conversion->getConversionType(); 6470 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6471 Candidate.Viable = false; 6472 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6473 return; 6474 } 6475 6476 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6477 6478 // Note that it is safe to allocate CallExpr on the stack here because 6479 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6480 // allocator). 6481 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6482 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6483 From->getLocStart()); 6484 ImplicitConversionSequence ICS = 6485 TryCopyInitialization(*this, &Call, ToType, 6486 /*SuppressUserConversions=*/true, 6487 /*InOverloadResolution=*/false, 6488 /*AllowObjCWritebackConversion=*/false); 6489 6490 switch (ICS.getKind()) { 6491 case ImplicitConversionSequence::StandardConversion: 6492 Candidate.FinalConversion = ICS.Standard; 6493 6494 // C++ [over.ics.user]p3: 6495 // If the user-defined conversion is specified by a specialization of a 6496 // conversion function template, the second standard conversion sequence 6497 // shall have exact match rank. 6498 if (Conversion->getPrimaryTemplate() && 6499 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6500 Candidate.Viable = false; 6501 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6502 return; 6503 } 6504 6505 // C++0x [dcl.init.ref]p5: 6506 // In the second case, if the reference is an rvalue reference and 6507 // the second standard conversion sequence of the user-defined 6508 // conversion sequence includes an lvalue-to-rvalue conversion, the 6509 // program is ill-formed. 6510 if (ToType->isRValueReferenceType() && 6511 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6512 Candidate.Viable = false; 6513 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6514 return; 6515 } 6516 break; 6517 6518 case ImplicitConversionSequence::BadConversion: 6519 Candidate.Viable = false; 6520 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6521 return; 6522 6523 default: 6524 llvm_unreachable( 6525 "Can only end up with a standard conversion sequence or failure"); 6526 } 6527 6528 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6529 Candidate.Viable = false; 6530 Candidate.FailureKind = ovl_fail_enable_if; 6531 Candidate.DeductionFailure.Data = FailedAttr; 6532 return; 6533 } 6534 } 6535 6536 /// \brief Adds a conversion function template specialization 6537 /// candidate to the overload set, using template argument deduction 6538 /// to deduce the template arguments of the conversion function 6539 /// template from the type that we are converting to (C++ 6540 /// [temp.deduct.conv]). 6541 void 6542 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6543 DeclAccessPair FoundDecl, 6544 CXXRecordDecl *ActingDC, 6545 Expr *From, QualType ToType, 6546 OverloadCandidateSet &CandidateSet, 6547 bool AllowObjCConversionOnExplicit) { 6548 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6549 "Only conversion function templates permitted here"); 6550 6551 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6552 return; 6553 6554 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6555 CXXConversionDecl *Specialization = nullptr; 6556 if (TemplateDeductionResult Result 6557 = DeduceTemplateArguments(FunctionTemplate, ToType, 6558 Specialization, Info)) { 6559 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6560 Candidate.FoundDecl = FoundDecl; 6561 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6562 Candidate.Viable = false; 6563 Candidate.FailureKind = ovl_fail_bad_deduction; 6564 Candidate.IsSurrogate = false; 6565 Candidate.IgnoreObjectArgument = false; 6566 Candidate.ExplicitCallArguments = 1; 6567 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6568 Info); 6569 return; 6570 } 6571 6572 // Add the conversion function template specialization produced by 6573 // template argument deduction as a candidate. 6574 assert(Specialization && "Missing function template specialization?"); 6575 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6576 CandidateSet, AllowObjCConversionOnExplicit); 6577 } 6578 6579 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6580 /// converts the given @c Object to a function pointer via the 6581 /// conversion function @c Conversion, and then attempts to call it 6582 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6583 /// the type of function that we'll eventually be calling. 6584 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6585 DeclAccessPair FoundDecl, 6586 CXXRecordDecl *ActingContext, 6587 const FunctionProtoType *Proto, 6588 Expr *Object, 6589 ArrayRef<Expr *> Args, 6590 OverloadCandidateSet& CandidateSet) { 6591 if (!CandidateSet.isNewCandidate(Conversion)) 6592 return; 6593 6594 // Overload resolution is always an unevaluated context. 6595 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6596 6597 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6598 Candidate.FoundDecl = FoundDecl; 6599 Candidate.Function = nullptr; 6600 Candidate.Surrogate = Conversion; 6601 Candidate.Viable = true; 6602 Candidate.IsSurrogate = true; 6603 Candidate.IgnoreObjectArgument = false; 6604 Candidate.ExplicitCallArguments = Args.size(); 6605 6606 // Determine the implicit conversion sequence for the implicit 6607 // object parameter. 6608 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6609 *this, CandidateSet.getLocation(), Object->getType(), 6610 Object->Classify(Context), Conversion, ActingContext); 6611 if (ObjectInit.isBad()) { 6612 Candidate.Viable = false; 6613 Candidate.FailureKind = ovl_fail_bad_conversion; 6614 Candidate.Conversions[0] = ObjectInit; 6615 return; 6616 } 6617 6618 // The first conversion is actually a user-defined conversion whose 6619 // first conversion is ObjectInit's standard conversion (which is 6620 // effectively a reference binding). Record it as such. 6621 Candidate.Conversions[0].setUserDefined(); 6622 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6623 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6624 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6625 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6626 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6627 Candidate.Conversions[0].UserDefined.After 6628 = Candidate.Conversions[0].UserDefined.Before; 6629 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6630 6631 // Find the 6632 unsigned NumParams = Proto->getNumParams(); 6633 6634 // (C++ 13.3.2p2): A candidate function having fewer than m 6635 // parameters is viable only if it has an ellipsis in its parameter 6636 // list (8.3.5). 6637 if (Args.size() > NumParams && !Proto->isVariadic()) { 6638 Candidate.Viable = false; 6639 Candidate.FailureKind = ovl_fail_too_many_arguments; 6640 return; 6641 } 6642 6643 // Function types don't have any default arguments, so just check if 6644 // we have enough arguments. 6645 if (Args.size() < NumParams) { 6646 // Not enough arguments. 6647 Candidate.Viable = false; 6648 Candidate.FailureKind = ovl_fail_too_few_arguments; 6649 return; 6650 } 6651 6652 // Determine the implicit conversion sequences for each of the 6653 // arguments. 6654 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6655 if (ArgIdx < NumParams) { 6656 // (C++ 13.3.2p3): for F to be a viable function, there shall 6657 // exist for each argument an implicit conversion sequence 6658 // (13.3.3.1) that converts that argument to the corresponding 6659 // parameter of F. 6660 QualType ParamType = Proto->getParamType(ArgIdx); 6661 Candidate.Conversions[ArgIdx + 1] 6662 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6663 /*SuppressUserConversions=*/false, 6664 /*InOverloadResolution=*/false, 6665 /*AllowObjCWritebackConversion=*/ 6666 getLangOpts().ObjCAutoRefCount); 6667 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6668 Candidate.Viable = false; 6669 Candidate.FailureKind = ovl_fail_bad_conversion; 6670 return; 6671 } 6672 } else { 6673 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6674 // argument for which there is no corresponding parameter is 6675 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6676 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6677 } 6678 } 6679 6680 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6681 Candidate.Viable = false; 6682 Candidate.FailureKind = ovl_fail_enable_if; 6683 Candidate.DeductionFailure.Data = FailedAttr; 6684 return; 6685 } 6686 } 6687 6688 /// \brief Add overload candidates for overloaded operators that are 6689 /// member functions. 6690 /// 6691 /// Add the overloaded operator candidates that are member functions 6692 /// for the operator Op that was used in an operator expression such 6693 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6694 /// CandidateSet will store the added overload candidates. (C++ 6695 /// [over.match.oper]). 6696 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6697 SourceLocation OpLoc, 6698 ArrayRef<Expr *> Args, 6699 OverloadCandidateSet& CandidateSet, 6700 SourceRange OpRange) { 6701 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6702 6703 // C++ [over.match.oper]p3: 6704 // For a unary operator @ with an operand of a type whose 6705 // cv-unqualified version is T1, and for a binary operator @ with 6706 // a left operand of a type whose cv-unqualified version is T1 and 6707 // a right operand of a type whose cv-unqualified version is T2, 6708 // three sets of candidate functions, designated member 6709 // candidates, non-member candidates and built-in candidates, are 6710 // constructed as follows: 6711 QualType T1 = Args[0]->getType(); 6712 6713 // -- If T1 is a complete class type or a class currently being 6714 // defined, the set of member candidates is the result of the 6715 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6716 // the set of member candidates is empty. 6717 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6718 // Complete the type if it can be completed. 6719 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6720 return; 6721 // If the type is neither complete nor being defined, bail out now. 6722 if (!T1Rec->getDecl()->getDefinition()) 6723 return; 6724 6725 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6726 LookupQualifiedName(Operators, T1Rec->getDecl()); 6727 Operators.suppressDiagnostics(); 6728 6729 for (LookupResult::iterator Oper = Operators.begin(), 6730 OperEnd = Operators.end(); 6731 Oper != OperEnd; 6732 ++Oper) 6733 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6734 Args[0]->Classify(Context), 6735 Args.slice(1), 6736 CandidateSet, 6737 /* SuppressUserConversions = */ false); 6738 } 6739 } 6740 6741 /// AddBuiltinCandidate - Add a candidate for a built-in 6742 /// operator. ResultTy and ParamTys are the result and parameter types 6743 /// of the built-in candidate, respectively. Args and NumArgs are the 6744 /// arguments being passed to the candidate. IsAssignmentOperator 6745 /// should be true when this built-in candidate is an assignment 6746 /// operator. NumContextualBoolArguments is the number of arguments 6747 /// (at the beginning of the argument list) that will be contextually 6748 /// converted to bool. 6749 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6750 ArrayRef<Expr *> Args, 6751 OverloadCandidateSet& CandidateSet, 6752 bool IsAssignmentOperator, 6753 unsigned NumContextualBoolArguments) { 6754 // Overload resolution is always an unevaluated context. 6755 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6756 6757 // Add this candidate 6758 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6759 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6760 Candidate.Function = nullptr; 6761 Candidate.IsSurrogate = false; 6762 Candidate.IgnoreObjectArgument = false; 6763 Candidate.BuiltinTypes.ResultTy = ResultTy; 6764 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6765 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6766 6767 // Determine the implicit conversion sequences for each of the 6768 // arguments. 6769 Candidate.Viable = true; 6770 Candidate.ExplicitCallArguments = Args.size(); 6771 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6772 // C++ [over.match.oper]p4: 6773 // For the built-in assignment operators, conversions of the 6774 // left operand are restricted as follows: 6775 // -- no temporaries are introduced to hold the left operand, and 6776 // -- no user-defined conversions are applied to the left 6777 // operand to achieve a type match with the left-most 6778 // parameter of a built-in candidate. 6779 // 6780 // We block these conversions by turning off user-defined 6781 // conversions, since that is the only way that initialization of 6782 // a reference to a non-class type can occur from something that 6783 // is not of the same type. 6784 if (ArgIdx < NumContextualBoolArguments) { 6785 assert(ParamTys[ArgIdx] == Context.BoolTy && 6786 "Contextual conversion to bool requires bool type"); 6787 Candidate.Conversions[ArgIdx] 6788 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6789 } else { 6790 Candidate.Conversions[ArgIdx] 6791 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6792 ArgIdx == 0 && IsAssignmentOperator, 6793 /*InOverloadResolution=*/false, 6794 /*AllowObjCWritebackConversion=*/ 6795 getLangOpts().ObjCAutoRefCount); 6796 } 6797 if (Candidate.Conversions[ArgIdx].isBad()) { 6798 Candidate.Viable = false; 6799 Candidate.FailureKind = ovl_fail_bad_conversion; 6800 break; 6801 } 6802 } 6803 } 6804 6805 namespace { 6806 6807 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6808 /// candidate operator functions for built-in operators (C++ 6809 /// [over.built]). The types are separated into pointer types and 6810 /// enumeration types. 6811 class BuiltinCandidateTypeSet { 6812 /// TypeSet - A set of types. 6813 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6814 6815 /// PointerTypes - The set of pointer types that will be used in the 6816 /// built-in candidates. 6817 TypeSet PointerTypes; 6818 6819 /// MemberPointerTypes - The set of member pointer types that will be 6820 /// used in the built-in candidates. 6821 TypeSet MemberPointerTypes; 6822 6823 /// EnumerationTypes - The set of enumeration types that will be 6824 /// used in the built-in candidates. 6825 TypeSet EnumerationTypes; 6826 6827 /// \brief The set of vector types that will be used in the built-in 6828 /// candidates. 6829 TypeSet VectorTypes; 6830 6831 /// \brief A flag indicating non-record types are viable candidates 6832 bool HasNonRecordTypes; 6833 6834 /// \brief A flag indicating whether either arithmetic or enumeration types 6835 /// were present in the candidate set. 6836 bool HasArithmeticOrEnumeralTypes; 6837 6838 /// \brief A flag indicating whether the nullptr type was present in the 6839 /// candidate set. 6840 bool HasNullPtrType; 6841 6842 /// Sema - The semantic analysis instance where we are building the 6843 /// candidate type set. 6844 Sema &SemaRef; 6845 6846 /// Context - The AST context in which we will build the type sets. 6847 ASTContext &Context; 6848 6849 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6850 const Qualifiers &VisibleQuals); 6851 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6852 6853 public: 6854 /// iterator - Iterates through the types that are part of the set. 6855 typedef TypeSet::iterator iterator; 6856 6857 BuiltinCandidateTypeSet(Sema &SemaRef) 6858 : HasNonRecordTypes(false), 6859 HasArithmeticOrEnumeralTypes(false), 6860 HasNullPtrType(false), 6861 SemaRef(SemaRef), 6862 Context(SemaRef.Context) { } 6863 6864 void AddTypesConvertedFrom(QualType Ty, 6865 SourceLocation Loc, 6866 bool AllowUserConversions, 6867 bool AllowExplicitConversions, 6868 const Qualifiers &VisibleTypeConversionsQuals); 6869 6870 /// pointer_begin - First pointer type found; 6871 iterator pointer_begin() { return PointerTypes.begin(); } 6872 6873 /// pointer_end - Past the last pointer type found; 6874 iterator pointer_end() { return PointerTypes.end(); } 6875 6876 /// member_pointer_begin - First member pointer type found; 6877 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6878 6879 /// member_pointer_end - Past the last member pointer type found; 6880 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6881 6882 /// enumeration_begin - First enumeration type found; 6883 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6884 6885 /// enumeration_end - Past the last enumeration type found; 6886 iterator enumeration_end() { return EnumerationTypes.end(); } 6887 6888 iterator vector_begin() { return VectorTypes.begin(); } 6889 iterator vector_end() { return VectorTypes.end(); } 6890 6891 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6892 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6893 bool hasNullPtrType() const { return HasNullPtrType; } 6894 }; 6895 6896 } // end anonymous namespace 6897 6898 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6899 /// the set of pointer types along with any more-qualified variants of 6900 /// that type. For example, if @p Ty is "int const *", this routine 6901 /// will add "int const *", "int const volatile *", "int const 6902 /// restrict *", and "int const volatile restrict *" to the set of 6903 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6904 /// false otherwise. 6905 /// 6906 /// FIXME: what to do about extended qualifiers? 6907 bool 6908 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6909 const Qualifiers &VisibleQuals) { 6910 6911 // Insert this type. 6912 if (!PointerTypes.insert(Ty).second) 6913 return false; 6914 6915 QualType PointeeTy; 6916 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6917 bool buildObjCPtr = false; 6918 if (!PointerTy) { 6919 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6920 PointeeTy = PTy->getPointeeType(); 6921 buildObjCPtr = true; 6922 } else { 6923 PointeeTy = PointerTy->getPointeeType(); 6924 } 6925 6926 // Don't add qualified variants of arrays. For one, they're not allowed 6927 // (the qualifier would sink to the element type), and for another, the 6928 // only overload situation where it matters is subscript or pointer +- int, 6929 // and those shouldn't have qualifier variants anyway. 6930 if (PointeeTy->isArrayType()) 6931 return true; 6932 6933 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6934 bool hasVolatile = VisibleQuals.hasVolatile(); 6935 bool hasRestrict = VisibleQuals.hasRestrict(); 6936 6937 // Iterate through all strict supersets of BaseCVR. 6938 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6939 if ((CVR | BaseCVR) != CVR) continue; 6940 // Skip over volatile if no volatile found anywhere in the types. 6941 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6942 6943 // Skip over restrict if no restrict found anywhere in the types, or if 6944 // the type cannot be restrict-qualified. 6945 if ((CVR & Qualifiers::Restrict) && 6946 (!hasRestrict || 6947 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6948 continue; 6949 6950 // Build qualified pointee type. 6951 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6952 6953 // Build qualified pointer type. 6954 QualType QPointerTy; 6955 if (!buildObjCPtr) 6956 QPointerTy = Context.getPointerType(QPointeeTy); 6957 else 6958 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6959 6960 // Insert qualified pointer type. 6961 PointerTypes.insert(QPointerTy); 6962 } 6963 6964 return true; 6965 } 6966 6967 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6968 /// to the set of pointer types along with any more-qualified variants of 6969 /// that type. For example, if @p Ty is "int const *", this routine 6970 /// will add "int const *", "int const volatile *", "int const 6971 /// restrict *", and "int const volatile restrict *" to the set of 6972 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6973 /// false otherwise. 6974 /// 6975 /// FIXME: what to do about extended qualifiers? 6976 bool 6977 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6978 QualType Ty) { 6979 // Insert this type. 6980 if (!MemberPointerTypes.insert(Ty).second) 6981 return false; 6982 6983 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6984 assert(PointerTy && "type was not a member pointer type!"); 6985 6986 QualType PointeeTy = PointerTy->getPointeeType(); 6987 // Don't add qualified variants of arrays. For one, they're not allowed 6988 // (the qualifier would sink to the element type), and for another, the 6989 // only overload situation where it matters is subscript or pointer +- int, 6990 // and those shouldn't have qualifier variants anyway. 6991 if (PointeeTy->isArrayType()) 6992 return true; 6993 const Type *ClassTy = PointerTy->getClass(); 6994 6995 // Iterate through all strict supersets of the pointee type's CVR 6996 // qualifiers. 6997 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6998 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6999 if ((CVR | BaseCVR) != CVR) continue; 7000 7001 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7002 MemberPointerTypes.insert( 7003 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7004 } 7005 7006 return true; 7007 } 7008 7009 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7010 /// Ty can be implicit converted to the given set of @p Types. We're 7011 /// primarily interested in pointer types and enumeration types. We also 7012 /// take member pointer types, for the conditional operator. 7013 /// AllowUserConversions is true if we should look at the conversion 7014 /// functions of a class type, and AllowExplicitConversions if we 7015 /// should also include the explicit conversion functions of a class 7016 /// type. 7017 void 7018 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7019 SourceLocation Loc, 7020 bool AllowUserConversions, 7021 bool AllowExplicitConversions, 7022 const Qualifiers &VisibleQuals) { 7023 // Only deal with canonical types. 7024 Ty = Context.getCanonicalType(Ty); 7025 7026 // Look through reference types; they aren't part of the type of an 7027 // expression for the purposes of conversions. 7028 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7029 Ty = RefTy->getPointeeType(); 7030 7031 // If we're dealing with an array type, decay to the pointer. 7032 if (Ty->isArrayType()) 7033 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7034 7035 // Otherwise, we don't care about qualifiers on the type. 7036 Ty = Ty.getLocalUnqualifiedType(); 7037 7038 // Flag if we ever add a non-record type. 7039 const RecordType *TyRec = Ty->getAs<RecordType>(); 7040 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7041 7042 // Flag if we encounter an arithmetic type. 7043 HasArithmeticOrEnumeralTypes = 7044 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7045 7046 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7047 PointerTypes.insert(Ty); 7048 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7049 // Insert our type, and its more-qualified variants, into the set 7050 // of types. 7051 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7052 return; 7053 } else if (Ty->isMemberPointerType()) { 7054 // Member pointers are far easier, since the pointee can't be converted. 7055 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7056 return; 7057 } else if (Ty->isEnumeralType()) { 7058 HasArithmeticOrEnumeralTypes = true; 7059 EnumerationTypes.insert(Ty); 7060 } else if (Ty->isVectorType()) { 7061 // We treat vector types as arithmetic types in many contexts as an 7062 // extension. 7063 HasArithmeticOrEnumeralTypes = true; 7064 VectorTypes.insert(Ty); 7065 } else if (Ty->isNullPtrType()) { 7066 HasNullPtrType = true; 7067 } else if (AllowUserConversions && TyRec) { 7068 // No conversion functions in incomplete types. 7069 if (!SemaRef.isCompleteType(Loc, Ty)) 7070 return; 7071 7072 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7073 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7074 if (isa<UsingShadowDecl>(D)) 7075 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7076 7077 // Skip conversion function templates; they don't tell us anything 7078 // about which builtin types we can convert to. 7079 if (isa<FunctionTemplateDecl>(D)) 7080 continue; 7081 7082 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7083 if (AllowExplicitConversions || !Conv->isExplicit()) { 7084 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7085 VisibleQuals); 7086 } 7087 } 7088 } 7089 } 7090 7091 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7092 /// the volatile- and non-volatile-qualified assignment operators for the 7093 /// given type to the candidate set. 7094 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7095 QualType T, 7096 ArrayRef<Expr *> Args, 7097 OverloadCandidateSet &CandidateSet) { 7098 QualType ParamTypes[2]; 7099 7100 // T& operator=(T&, T) 7101 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7102 ParamTypes[1] = T; 7103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7104 /*IsAssignmentOperator=*/true); 7105 7106 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7107 // volatile T& operator=(volatile T&, T) 7108 ParamTypes[0] 7109 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7110 ParamTypes[1] = T; 7111 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7112 /*IsAssignmentOperator=*/true); 7113 } 7114 } 7115 7116 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7117 /// if any, found in visible type conversion functions found in ArgExpr's type. 7118 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7119 Qualifiers VRQuals; 7120 const RecordType *TyRec; 7121 if (const MemberPointerType *RHSMPType = 7122 ArgExpr->getType()->getAs<MemberPointerType>()) 7123 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7124 else 7125 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7126 if (!TyRec) { 7127 // Just to be safe, assume the worst case. 7128 VRQuals.addVolatile(); 7129 VRQuals.addRestrict(); 7130 return VRQuals; 7131 } 7132 7133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7134 if (!ClassDecl->hasDefinition()) 7135 return VRQuals; 7136 7137 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7138 if (isa<UsingShadowDecl>(D)) 7139 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7140 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7141 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7142 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7143 CanTy = ResTypeRef->getPointeeType(); 7144 // Need to go down the pointer/mempointer chain and add qualifiers 7145 // as see them. 7146 bool done = false; 7147 while (!done) { 7148 if (CanTy.isRestrictQualified()) 7149 VRQuals.addRestrict(); 7150 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7151 CanTy = ResTypePtr->getPointeeType(); 7152 else if (const MemberPointerType *ResTypeMPtr = 7153 CanTy->getAs<MemberPointerType>()) 7154 CanTy = ResTypeMPtr->getPointeeType(); 7155 else 7156 done = true; 7157 if (CanTy.isVolatileQualified()) 7158 VRQuals.addVolatile(); 7159 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7160 return VRQuals; 7161 } 7162 } 7163 } 7164 return VRQuals; 7165 } 7166 7167 namespace { 7168 7169 /// \brief Helper class to manage the addition of builtin operator overload 7170 /// candidates. It provides shared state and utility methods used throughout 7171 /// the process, as well as a helper method to add each group of builtin 7172 /// operator overloads from the standard to a candidate set. 7173 class BuiltinOperatorOverloadBuilder { 7174 // Common instance state available to all overload candidate addition methods. 7175 Sema &S; 7176 ArrayRef<Expr *> Args; 7177 Qualifiers VisibleTypeConversionsQuals; 7178 bool HasArithmeticOrEnumeralCandidateType; 7179 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7180 OverloadCandidateSet &CandidateSet; 7181 7182 // Define some constants used to index and iterate over the arithemetic types 7183 // provided via the getArithmeticType() method below. 7184 // The "promoted arithmetic types" are the arithmetic 7185 // types are that preserved by promotion (C++ [over.built]p2). 7186 static const unsigned FirstIntegralType = 3; 7187 static const unsigned LastIntegralType = 20; 7188 static const unsigned FirstPromotedIntegralType = 3, 7189 LastPromotedIntegralType = 11; 7190 static const unsigned FirstPromotedArithmeticType = 0, 7191 LastPromotedArithmeticType = 11; 7192 static const unsigned NumArithmeticTypes = 20; 7193 7194 /// \brief Get the canonical type for a given arithmetic type index. 7195 CanQualType getArithmeticType(unsigned index) { 7196 assert(index < NumArithmeticTypes); 7197 static CanQualType ASTContext::* const 7198 ArithmeticTypes[NumArithmeticTypes] = { 7199 // Start of promoted types. 7200 &ASTContext::FloatTy, 7201 &ASTContext::DoubleTy, 7202 &ASTContext::LongDoubleTy, 7203 7204 // Start of integral types. 7205 &ASTContext::IntTy, 7206 &ASTContext::LongTy, 7207 &ASTContext::LongLongTy, 7208 &ASTContext::Int128Ty, 7209 &ASTContext::UnsignedIntTy, 7210 &ASTContext::UnsignedLongTy, 7211 &ASTContext::UnsignedLongLongTy, 7212 &ASTContext::UnsignedInt128Ty, 7213 // End of promoted types. 7214 7215 &ASTContext::BoolTy, 7216 &ASTContext::CharTy, 7217 &ASTContext::WCharTy, 7218 &ASTContext::Char16Ty, 7219 &ASTContext::Char32Ty, 7220 &ASTContext::SignedCharTy, 7221 &ASTContext::ShortTy, 7222 &ASTContext::UnsignedCharTy, 7223 &ASTContext::UnsignedShortTy, 7224 // End of integral types. 7225 // FIXME: What about complex? What about half? 7226 }; 7227 return S.Context.*ArithmeticTypes[index]; 7228 } 7229 7230 /// \brief Gets the canonical type resulting from the usual arithemetic 7231 /// converions for the given arithmetic types. 7232 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7233 // Accelerator table for performing the usual arithmetic conversions. 7234 // The rules are basically: 7235 // - if either is floating-point, use the wider floating-point 7236 // - if same signedness, use the higher rank 7237 // - if same size, use unsigned of the higher rank 7238 // - use the larger type 7239 // These rules, together with the axiom that higher ranks are 7240 // never smaller, are sufficient to precompute all of these results 7241 // *except* when dealing with signed types of higher rank. 7242 // (we could precompute SLL x UI for all known platforms, but it's 7243 // better not to make any assumptions). 7244 // We assume that int128 has a higher rank than long long on all platforms. 7245 enum PromotedType { 7246 Dep=-1, 7247 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7248 }; 7249 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7250 [LastPromotedArithmeticType] = { 7251 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7252 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7253 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7254 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7255 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7256 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7257 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7258 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7259 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7260 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7261 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7262 }; 7263 7264 assert(L < LastPromotedArithmeticType); 7265 assert(R < LastPromotedArithmeticType); 7266 int Idx = ConversionsTable[L][R]; 7267 7268 // Fast path: the table gives us a concrete answer. 7269 if (Idx != Dep) return getArithmeticType(Idx); 7270 7271 // Slow path: we need to compare widths. 7272 // An invariant is that the signed type has higher rank. 7273 CanQualType LT = getArithmeticType(L), 7274 RT = getArithmeticType(R); 7275 unsigned LW = S.Context.getIntWidth(LT), 7276 RW = S.Context.getIntWidth(RT); 7277 7278 // If they're different widths, use the signed type. 7279 if (LW > RW) return LT; 7280 else if (LW < RW) return RT; 7281 7282 // Otherwise, use the unsigned type of the signed type's rank. 7283 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7284 assert(L == SLL || R == SLL); 7285 return S.Context.UnsignedLongLongTy; 7286 } 7287 7288 /// \brief Helper method to factor out the common pattern of adding overloads 7289 /// for '++' and '--' builtin operators. 7290 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7291 bool HasVolatile, 7292 bool HasRestrict) { 7293 QualType ParamTypes[2] = { 7294 S.Context.getLValueReferenceType(CandidateTy), 7295 S.Context.IntTy 7296 }; 7297 7298 // Non-volatile version. 7299 if (Args.size() == 1) 7300 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7301 else 7302 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7303 7304 // Use a heuristic to reduce number of builtin candidates in the set: 7305 // add volatile version only if there are conversions to a volatile type. 7306 if (HasVolatile) { 7307 ParamTypes[0] = 7308 S.Context.getLValueReferenceType( 7309 S.Context.getVolatileType(CandidateTy)); 7310 if (Args.size() == 1) 7311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7312 else 7313 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7314 } 7315 7316 // Add restrict version only if there are conversions to a restrict type 7317 // and our candidate type is a non-restrict-qualified pointer. 7318 if (HasRestrict && CandidateTy->isAnyPointerType() && 7319 !CandidateTy.isRestrictQualified()) { 7320 ParamTypes[0] 7321 = S.Context.getLValueReferenceType( 7322 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7323 if (Args.size() == 1) 7324 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7325 else 7326 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7327 7328 if (HasVolatile) { 7329 ParamTypes[0] 7330 = S.Context.getLValueReferenceType( 7331 S.Context.getCVRQualifiedType(CandidateTy, 7332 (Qualifiers::Volatile | 7333 Qualifiers::Restrict))); 7334 if (Args.size() == 1) 7335 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7336 else 7337 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7338 } 7339 } 7340 7341 } 7342 7343 public: 7344 BuiltinOperatorOverloadBuilder( 7345 Sema &S, ArrayRef<Expr *> Args, 7346 Qualifiers VisibleTypeConversionsQuals, 7347 bool HasArithmeticOrEnumeralCandidateType, 7348 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7349 OverloadCandidateSet &CandidateSet) 7350 : S(S), Args(Args), 7351 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7352 HasArithmeticOrEnumeralCandidateType( 7353 HasArithmeticOrEnumeralCandidateType), 7354 CandidateTypes(CandidateTypes), 7355 CandidateSet(CandidateSet) { 7356 // Validate some of our static helper constants in debug builds. 7357 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7358 "Invalid first promoted integral type"); 7359 assert(getArithmeticType(LastPromotedIntegralType - 1) 7360 == S.Context.UnsignedInt128Ty && 7361 "Invalid last promoted integral type"); 7362 assert(getArithmeticType(FirstPromotedArithmeticType) 7363 == S.Context.FloatTy && 7364 "Invalid first promoted arithmetic type"); 7365 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7366 == S.Context.UnsignedInt128Ty && 7367 "Invalid last promoted arithmetic type"); 7368 } 7369 7370 // C++ [over.built]p3: 7371 // 7372 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7373 // is either volatile or empty, there exist candidate operator 7374 // functions of the form 7375 // 7376 // VQ T& operator++(VQ T&); 7377 // T operator++(VQ T&, int); 7378 // 7379 // C++ [over.built]p4: 7380 // 7381 // For every pair (T, VQ), where T is an arithmetic type other 7382 // than bool, and VQ is either volatile or empty, there exist 7383 // candidate operator functions of the form 7384 // 7385 // VQ T& operator--(VQ T&); 7386 // T operator--(VQ T&, int); 7387 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7388 if (!HasArithmeticOrEnumeralCandidateType) 7389 return; 7390 7391 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7392 Arith < NumArithmeticTypes; ++Arith) { 7393 addPlusPlusMinusMinusStyleOverloads( 7394 getArithmeticType(Arith), 7395 VisibleTypeConversionsQuals.hasVolatile(), 7396 VisibleTypeConversionsQuals.hasRestrict()); 7397 } 7398 } 7399 7400 // C++ [over.built]p5: 7401 // 7402 // For every pair (T, VQ), where T is a cv-qualified or 7403 // cv-unqualified object type, and VQ is either volatile or 7404 // empty, there exist candidate operator functions of the form 7405 // 7406 // T*VQ& operator++(T*VQ&); 7407 // T*VQ& operator--(T*VQ&); 7408 // T* operator++(T*VQ&, int); 7409 // T* operator--(T*VQ&, int); 7410 void addPlusPlusMinusMinusPointerOverloads() { 7411 for (BuiltinCandidateTypeSet::iterator 7412 Ptr = CandidateTypes[0].pointer_begin(), 7413 PtrEnd = CandidateTypes[0].pointer_end(); 7414 Ptr != PtrEnd; ++Ptr) { 7415 // Skip pointer types that aren't pointers to object types. 7416 if (!(*Ptr)->getPointeeType()->isObjectType()) 7417 continue; 7418 7419 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7420 (!(*Ptr).isVolatileQualified() && 7421 VisibleTypeConversionsQuals.hasVolatile()), 7422 (!(*Ptr).isRestrictQualified() && 7423 VisibleTypeConversionsQuals.hasRestrict())); 7424 } 7425 } 7426 7427 // C++ [over.built]p6: 7428 // For every cv-qualified or cv-unqualified object type T, there 7429 // exist candidate operator functions of the form 7430 // 7431 // T& operator*(T*); 7432 // 7433 // C++ [over.built]p7: 7434 // For every function type T that does not have cv-qualifiers or a 7435 // ref-qualifier, there exist candidate operator functions of the form 7436 // T& operator*(T*); 7437 void addUnaryStarPointerOverloads() { 7438 for (BuiltinCandidateTypeSet::iterator 7439 Ptr = CandidateTypes[0].pointer_begin(), 7440 PtrEnd = CandidateTypes[0].pointer_end(); 7441 Ptr != PtrEnd; ++Ptr) { 7442 QualType ParamTy = *Ptr; 7443 QualType PointeeTy = ParamTy->getPointeeType(); 7444 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7445 continue; 7446 7447 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7448 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7449 continue; 7450 7451 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7452 &ParamTy, Args, CandidateSet); 7453 } 7454 } 7455 7456 // C++ [over.built]p9: 7457 // For every promoted arithmetic type T, there exist candidate 7458 // operator functions of the form 7459 // 7460 // T operator+(T); 7461 // T operator-(T); 7462 void addUnaryPlusOrMinusArithmeticOverloads() { 7463 if (!HasArithmeticOrEnumeralCandidateType) 7464 return; 7465 7466 for (unsigned Arith = FirstPromotedArithmeticType; 7467 Arith < LastPromotedArithmeticType; ++Arith) { 7468 QualType ArithTy = getArithmeticType(Arith); 7469 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7470 } 7471 7472 // Extension: We also add these operators for vector types. 7473 for (BuiltinCandidateTypeSet::iterator 7474 Vec = CandidateTypes[0].vector_begin(), 7475 VecEnd = CandidateTypes[0].vector_end(); 7476 Vec != VecEnd; ++Vec) { 7477 QualType VecTy = *Vec; 7478 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7479 } 7480 } 7481 7482 // C++ [over.built]p8: 7483 // For every type T, there exist candidate operator functions of 7484 // the form 7485 // 7486 // T* operator+(T*); 7487 void addUnaryPlusPointerOverloads() { 7488 for (BuiltinCandidateTypeSet::iterator 7489 Ptr = CandidateTypes[0].pointer_begin(), 7490 PtrEnd = CandidateTypes[0].pointer_end(); 7491 Ptr != PtrEnd; ++Ptr) { 7492 QualType ParamTy = *Ptr; 7493 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7494 } 7495 } 7496 7497 // C++ [over.built]p10: 7498 // For every promoted integral type T, there exist candidate 7499 // operator functions of the form 7500 // 7501 // T operator~(T); 7502 void addUnaryTildePromotedIntegralOverloads() { 7503 if (!HasArithmeticOrEnumeralCandidateType) 7504 return; 7505 7506 for (unsigned Int = FirstPromotedIntegralType; 7507 Int < LastPromotedIntegralType; ++Int) { 7508 QualType IntTy = getArithmeticType(Int); 7509 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7510 } 7511 7512 // Extension: We also add this operator for vector types. 7513 for (BuiltinCandidateTypeSet::iterator 7514 Vec = CandidateTypes[0].vector_begin(), 7515 VecEnd = CandidateTypes[0].vector_end(); 7516 Vec != VecEnd; ++Vec) { 7517 QualType VecTy = *Vec; 7518 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7519 } 7520 } 7521 7522 // C++ [over.match.oper]p16: 7523 // For every pointer to member type T, there exist candidate operator 7524 // functions of the form 7525 // 7526 // bool operator==(T,T); 7527 // bool operator!=(T,T); 7528 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7529 /// Set of (canonical) types that we've already handled. 7530 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7531 7532 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7533 for (BuiltinCandidateTypeSet::iterator 7534 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7535 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7536 MemPtr != MemPtrEnd; 7537 ++MemPtr) { 7538 // Don't add the same builtin candidate twice. 7539 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7540 continue; 7541 7542 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7543 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7544 } 7545 } 7546 } 7547 7548 // C++ [over.built]p15: 7549 // 7550 // For every T, where T is an enumeration type, a pointer type, or 7551 // std::nullptr_t, there exist candidate operator functions of the form 7552 // 7553 // bool operator<(T, T); 7554 // bool operator>(T, T); 7555 // bool operator<=(T, T); 7556 // bool operator>=(T, T); 7557 // bool operator==(T, T); 7558 // bool operator!=(T, T); 7559 void addRelationalPointerOrEnumeralOverloads() { 7560 // C++ [over.match.oper]p3: 7561 // [...]the built-in candidates include all of the candidate operator 7562 // functions defined in 13.6 that, compared to the given operator, [...] 7563 // do not have the same parameter-type-list as any non-template non-member 7564 // candidate. 7565 // 7566 // Note that in practice, this only affects enumeration types because there 7567 // aren't any built-in candidates of record type, and a user-defined operator 7568 // must have an operand of record or enumeration type. Also, the only other 7569 // overloaded operator with enumeration arguments, operator=, 7570 // cannot be overloaded for enumeration types, so this is the only place 7571 // where we must suppress candidates like this. 7572 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7573 UserDefinedBinaryOperators; 7574 7575 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7576 if (CandidateTypes[ArgIdx].enumeration_begin() != 7577 CandidateTypes[ArgIdx].enumeration_end()) { 7578 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7579 CEnd = CandidateSet.end(); 7580 C != CEnd; ++C) { 7581 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7582 continue; 7583 7584 if (C->Function->isFunctionTemplateSpecialization()) 7585 continue; 7586 7587 QualType FirstParamType = 7588 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7589 QualType SecondParamType = 7590 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7591 7592 // Skip if either parameter isn't of enumeral type. 7593 if (!FirstParamType->isEnumeralType() || 7594 !SecondParamType->isEnumeralType()) 7595 continue; 7596 7597 // Add this operator to the set of known user-defined operators. 7598 UserDefinedBinaryOperators.insert( 7599 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7600 S.Context.getCanonicalType(SecondParamType))); 7601 } 7602 } 7603 } 7604 7605 /// Set of (canonical) types that we've already handled. 7606 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7607 7608 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7609 for (BuiltinCandidateTypeSet::iterator 7610 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7611 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7612 Ptr != PtrEnd; ++Ptr) { 7613 // Don't add the same builtin candidate twice. 7614 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7615 continue; 7616 7617 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7618 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7619 } 7620 for (BuiltinCandidateTypeSet::iterator 7621 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7622 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7623 Enum != EnumEnd; ++Enum) { 7624 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7625 7626 // Don't add the same builtin candidate twice, or if a user defined 7627 // candidate exists. 7628 if (!AddedTypes.insert(CanonType).second || 7629 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7630 CanonType))) 7631 continue; 7632 7633 QualType ParamTypes[2] = { *Enum, *Enum }; 7634 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7635 } 7636 7637 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7638 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7639 if (AddedTypes.insert(NullPtrTy).second && 7640 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7641 NullPtrTy))) { 7642 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7643 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7644 CandidateSet); 7645 } 7646 } 7647 } 7648 } 7649 7650 // C++ [over.built]p13: 7651 // 7652 // For every cv-qualified or cv-unqualified object type T 7653 // there exist candidate operator functions of the form 7654 // 7655 // T* operator+(T*, ptrdiff_t); 7656 // T& operator[](T*, ptrdiff_t); [BELOW] 7657 // T* operator-(T*, ptrdiff_t); 7658 // T* operator+(ptrdiff_t, T*); 7659 // T& operator[](ptrdiff_t, T*); [BELOW] 7660 // 7661 // C++ [over.built]p14: 7662 // 7663 // For every T, where T is a pointer to object type, there 7664 // exist candidate operator functions of the form 7665 // 7666 // ptrdiff_t operator-(T, T); 7667 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7668 /// Set of (canonical) types that we've already handled. 7669 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7670 7671 for (int Arg = 0; Arg < 2; ++Arg) { 7672 QualType AsymmetricParamTypes[2] = { 7673 S.Context.getPointerDiffType(), 7674 S.Context.getPointerDiffType(), 7675 }; 7676 for (BuiltinCandidateTypeSet::iterator 7677 Ptr = CandidateTypes[Arg].pointer_begin(), 7678 PtrEnd = CandidateTypes[Arg].pointer_end(); 7679 Ptr != PtrEnd; ++Ptr) { 7680 QualType PointeeTy = (*Ptr)->getPointeeType(); 7681 if (!PointeeTy->isObjectType()) 7682 continue; 7683 7684 AsymmetricParamTypes[Arg] = *Ptr; 7685 if (Arg == 0 || Op == OO_Plus) { 7686 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7687 // T* operator+(ptrdiff_t, T*); 7688 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7689 } 7690 if (Op == OO_Minus) { 7691 // ptrdiff_t operator-(T, T); 7692 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7693 continue; 7694 7695 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7696 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7697 Args, CandidateSet); 7698 } 7699 } 7700 } 7701 } 7702 7703 // C++ [over.built]p12: 7704 // 7705 // For every pair of promoted arithmetic types L and R, there 7706 // exist candidate operator functions of the form 7707 // 7708 // LR operator*(L, R); 7709 // LR operator/(L, R); 7710 // LR operator+(L, R); 7711 // LR operator-(L, R); 7712 // bool operator<(L, R); 7713 // bool operator>(L, R); 7714 // bool operator<=(L, R); 7715 // bool operator>=(L, R); 7716 // bool operator==(L, R); 7717 // bool operator!=(L, R); 7718 // 7719 // where LR is the result of the usual arithmetic conversions 7720 // between types L and R. 7721 // 7722 // C++ [over.built]p24: 7723 // 7724 // For every pair of promoted arithmetic types L and R, there exist 7725 // candidate operator functions of the form 7726 // 7727 // LR operator?(bool, L, R); 7728 // 7729 // where LR is the result of the usual arithmetic conversions 7730 // between types L and R. 7731 // Our candidates ignore the first parameter. 7732 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7733 if (!HasArithmeticOrEnumeralCandidateType) 7734 return; 7735 7736 for (unsigned Left = FirstPromotedArithmeticType; 7737 Left < LastPromotedArithmeticType; ++Left) { 7738 for (unsigned Right = FirstPromotedArithmeticType; 7739 Right < LastPromotedArithmeticType; ++Right) { 7740 QualType LandR[2] = { getArithmeticType(Left), 7741 getArithmeticType(Right) }; 7742 QualType Result = 7743 isComparison ? S.Context.BoolTy 7744 : getUsualArithmeticConversions(Left, Right); 7745 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7746 } 7747 } 7748 7749 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7750 // conditional operator for vector types. 7751 for (BuiltinCandidateTypeSet::iterator 7752 Vec1 = CandidateTypes[0].vector_begin(), 7753 Vec1End = CandidateTypes[0].vector_end(); 7754 Vec1 != Vec1End; ++Vec1) { 7755 for (BuiltinCandidateTypeSet::iterator 7756 Vec2 = CandidateTypes[1].vector_begin(), 7757 Vec2End = CandidateTypes[1].vector_end(); 7758 Vec2 != Vec2End; ++Vec2) { 7759 QualType LandR[2] = { *Vec1, *Vec2 }; 7760 QualType Result = S.Context.BoolTy; 7761 if (!isComparison) { 7762 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7763 Result = *Vec1; 7764 else 7765 Result = *Vec2; 7766 } 7767 7768 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7769 } 7770 } 7771 } 7772 7773 // C++ [over.built]p17: 7774 // 7775 // For every pair of promoted integral types L and R, there 7776 // exist candidate operator functions of the form 7777 // 7778 // LR operator%(L, R); 7779 // LR operator&(L, R); 7780 // LR operator^(L, R); 7781 // LR operator|(L, R); 7782 // L operator<<(L, R); 7783 // L operator>>(L, R); 7784 // 7785 // where LR is the result of the usual arithmetic conversions 7786 // between types L and R. 7787 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7788 if (!HasArithmeticOrEnumeralCandidateType) 7789 return; 7790 7791 for (unsigned Left = FirstPromotedIntegralType; 7792 Left < LastPromotedIntegralType; ++Left) { 7793 for (unsigned Right = FirstPromotedIntegralType; 7794 Right < LastPromotedIntegralType; ++Right) { 7795 QualType LandR[2] = { getArithmeticType(Left), 7796 getArithmeticType(Right) }; 7797 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7798 ? LandR[0] 7799 : getUsualArithmeticConversions(Left, Right); 7800 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7801 } 7802 } 7803 } 7804 7805 // C++ [over.built]p20: 7806 // 7807 // For every pair (T, VQ), where T is an enumeration or 7808 // pointer to member type and VQ is either volatile or 7809 // empty, there exist candidate operator functions of the form 7810 // 7811 // VQ T& operator=(VQ T&, T); 7812 void addAssignmentMemberPointerOrEnumeralOverloads() { 7813 /// Set of (canonical) types that we've already handled. 7814 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7815 7816 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7817 for (BuiltinCandidateTypeSet::iterator 7818 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7819 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7820 Enum != EnumEnd; ++Enum) { 7821 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7822 continue; 7823 7824 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7825 } 7826 7827 for (BuiltinCandidateTypeSet::iterator 7828 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7829 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7830 MemPtr != MemPtrEnd; ++MemPtr) { 7831 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7832 continue; 7833 7834 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7835 } 7836 } 7837 } 7838 7839 // C++ [over.built]p19: 7840 // 7841 // For every pair (T, VQ), where T is any type and VQ is either 7842 // volatile or empty, there exist candidate operator functions 7843 // of the form 7844 // 7845 // T*VQ& operator=(T*VQ&, T*); 7846 // 7847 // C++ [over.built]p21: 7848 // 7849 // For every pair (T, VQ), where T is a cv-qualified or 7850 // cv-unqualified object type and VQ is either volatile or 7851 // empty, there exist candidate operator functions of the form 7852 // 7853 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7854 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7855 void addAssignmentPointerOverloads(bool isEqualOp) { 7856 /// Set of (canonical) types that we've already handled. 7857 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7858 7859 for (BuiltinCandidateTypeSet::iterator 7860 Ptr = CandidateTypes[0].pointer_begin(), 7861 PtrEnd = CandidateTypes[0].pointer_end(); 7862 Ptr != PtrEnd; ++Ptr) { 7863 // If this is operator=, keep track of the builtin candidates we added. 7864 if (isEqualOp) 7865 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7866 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7867 continue; 7868 7869 // non-volatile version 7870 QualType ParamTypes[2] = { 7871 S.Context.getLValueReferenceType(*Ptr), 7872 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7873 }; 7874 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7875 /*IsAssigmentOperator=*/ isEqualOp); 7876 7877 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7878 VisibleTypeConversionsQuals.hasVolatile(); 7879 if (NeedVolatile) { 7880 // volatile version 7881 ParamTypes[0] = 7882 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7884 /*IsAssigmentOperator=*/isEqualOp); 7885 } 7886 7887 if (!(*Ptr).isRestrictQualified() && 7888 VisibleTypeConversionsQuals.hasRestrict()) { 7889 // restrict version 7890 ParamTypes[0] 7891 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7893 /*IsAssigmentOperator=*/isEqualOp); 7894 7895 if (NeedVolatile) { 7896 // volatile restrict version 7897 ParamTypes[0] 7898 = S.Context.getLValueReferenceType( 7899 S.Context.getCVRQualifiedType(*Ptr, 7900 (Qualifiers::Volatile | 7901 Qualifiers::Restrict))); 7902 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7903 /*IsAssigmentOperator=*/isEqualOp); 7904 } 7905 } 7906 } 7907 7908 if (isEqualOp) { 7909 for (BuiltinCandidateTypeSet::iterator 7910 Ptr = CandidateTypes[1].pointer_begin(), 7911 PtrEnd = CandidateTypes[1].pointer_end(); 7912 Ptr != PtrEnd; ++Ptr) { 7913 // Make sure we don't add the same candidate twice. 7914 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7915 continue; 7916 7917 QualType ParamTypes[2] = { 7918 S.Context.getLValueReferenceType(*Ptr), 7919 *Ptr, 7920 }; 7921 7922 // non-volatile version 7923 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7924 /*IsAssigmentOperator=*/true); 7925 7926 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7927 VisibleTypeConversionsQuals.hasVolatile(); 7928 if (NeedVolatile) { 7929 // volatile version 7930 ParamTypes[0] = 7931 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7932 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7933 /*IsAssigmentOperator=*/true); 7934 } 7935 7936 if (!(*Ptr).isRestrictQualified() && 7937 VisibleTypeConversionsQuals.hasRestrict()) { 7938 // restrict version 7939 ParamTypes[0] 7940 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7941 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7942 /*IsAssigmentOperator=*/true); 7943 7944 if (NeedVolatile) { 7945 // volatile restrict version 7946 ParamTypes[0] 7947 = S.Context.getLValueReferenceType( 7948 S.Context.getCVRQualifiedType(*Ptr, 7949 (Qualifiers::Volatile | 7950 Qualifiers::Restrict))); 7951 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7952 /*IsAssigmentOperator=*/true); 7953 } 7954 } 7955 } 7956 } 7957 } 7958 7959 // C++ [over.built]p18: 7960 // 7961 // For every triple (L, VQ, R), where L is an arithmetic type, 7962 // VQ is either volatile or empty, and R is a promoted 7963 // arithmetic type, there exist candidate operator functions of 7964 // the form 7965 // 7966 // VQ L& operator=(VQ L&, R); 7967 // VQ L& operator*=(VQ L&, R); 7968 // VQ L& operator/=(VQ L&, R); 7969 // VQ L& operator+=(VQ L&, R); 7970 // VQ L& operator-=(VQ L&, R); 7971 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7972 if (!HasArithmeticOrEnumeralCandidateType) 7973 return; 7974 7975 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7976 for (unsigned Right = FirstPromotedArithmeticType; 7977 Right < LastPromotedArithmeticType; ++Right) { 7978 QualType ParamTypes[2]; 7979 ParamTypes[1] = getArithmeticType(Right); 7980 7981 // Add this built-in operator as a candidate (VQ is empty). 7982 ParamTypes[0] = 7983 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7985 /*IsAssigmentOperator=*/isEqualOp); 7986 7987 // Add this built-in operator as a candidate (VQ is 'volatile'). 7988 if (VisibleTypeConversionsQuals.hasVolatile()) { 7989 ParamTypes[0] = 7990 S.Context.getVolatileType(getArithmeticType(Left)); 7991 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7993 /*IsAssigmentOperator=*/isEqualOp); 7994 } 7995 } 7996 } 7997 7998 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7999 for (BuiltinCandidateTypeSet::iterator 8000 Vec1 = CandidateTypes[0].vector_begin(), 8001 Vec1End = CandidateTypes[0].vector_end(); 8002 Vec1 != Vec1End; ++Vec1) { 8003 for (BuiltinCandidateTypeSet::iterator 8004 Vec2 = CandidateTypes[1].vector_begin(), 8005 Vec2End = CandidateTypes[1].vector_end(); 8006 Vec2 != Vec2End; ++Vec2) { 8007 QualType ParamTypes[2]; 8008 ParamTypes[1] = *Vec2; 8009 // Add this built-in operator as a candidate (VQ is empty). 8010 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8011 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8012 /*IsAssigmentOperator=*/isEqualOp); 8013 8014 // Add this built-in operator as a candidate (VQ is 'volatile'). 8015 if (VisibleTypeConversionsQuals.hasVolatile()) { 8016 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8017 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8018 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8019 /*IsAssigmentOperator=*/isEqualOp); 8020 } 8021 } 8022 } 8023 } 8024 8025 // C++ [over.built]p22: 8026 // 8027 // For every triple (L, VQ, R), where L is an integral type, VQ 8028 // is either volatile or empty, and R is a promoted integral 8029 // type, there exist candidate operator functions of the form 8030 // 8031 // VQ L& operator%=(VQ L&, R); 8032 // VQ L& operator<<=(VQ L&, R); 8033 // VQ L& operator>>=(VQ L&, R); 8034 // VQ L& operator&=(VQ L&, R); 8035 // VQ L& operator^=(VQ L&, R); 8036 // VQ L& operator|=(VQ L&, R); 8037 void addAssignmentIntegralOverloads() { 8038 if (!HasArithmeticOrEnumeralCandidateType) 8039 return; 8040 8041 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8042 for (unsigned Right = FirstPromotedIntegralType; 8043 Right < LastPromotedIntegralType; ++Right) { 8044 QualType ParamTypes[2]; 8045 ParamTypes[1] = getArithmeticType(Right); 8046 8047 // Add this built-in operator as a candidate (VQ is empty). 8048 ParamTypes[0] = 8049 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8050 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8051 if (VisibleTypeConversionsQuals.hasVolatile()) { 8052 // Add this built-in operator as a candidate (VQ is 'volatile'). 8053 ParamTypes[0] = getArithmeticType(Left); 8054 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8055 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8056 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8057 } 8058 } 8059 } 8060 } 8061 8062 // C++ [over.operator]p23: 8063 // 8064 // There also exist candidate operator functions of the form 8065 // 8066 // bool operator!(bool); 8067 // bool operator&&(bool, bool); 8068 // bool operator||(bool, bool); 8069 void addExclaimOverload() { 8070 QualType ParamTy = S.Context.BoolTy; 8071 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8072 /*IsAssignmentOperator=*/false, 8073 /*NumContextualBoolArguments=*/1); 8074 } 8075 void addAmpAmpOrPipePipeOverload() { 8076 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8077 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8078 /*IsAssignmentOperator=*/false, 8079 /*NumContextualBoolArguments=*/2); 8080 } 8081 8082 // C++ [over.built]p13: 8083 // 8084 // For every cv-qualified or cv-unqualified object type T there 8085 // exist candidate operator functions of the form 8086 // 8087 // T* operator+(T*, ptrdiff_t); [ABOVE] 8088 // T& operator[](T*, ptrdiff_t); 8089 // T* operator-(T*, ptrdiff_t); [ABOVE] 8090 // T* operator+(ptrdiff_t, T*); [ABOVE] 8091 // T& operator[](ptrdiff_t, T*); 8092 void addSubscriptOverloads() { 8093 for (BuiltinCandidateTypeSet::iterator 8094 Ptr = CandidateTypes[0].pointer_begin(), 8095 PtrEnd = CandidateTypes[0].pointer_end(); 8096 Ptr != PtrEnd; ++Ptr) { 8097 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8098 QualType PointeeType = (*Ptr)->getPointeeType(); 8099 if (!PointeeType->isObjectType()) 8100 continue; 8101 8102 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8103 8104 // T& operator[](T*, ptrdiff_t) 8105 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8106 } 8107 8108 for (BuiltinCandidateTypeSet::iterator 8109 Ptr = CandidateTypes[1].pointer_begin(), 8110 PtrEnd = CandidateTypes[1].pointer_end(); 8111 Ptr != PtrEnd; ++Ptr) { 8112 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8113 QualType PointeeType = (*Ptr)->getPointeeType(); 8114 if (!PointeeType->isObjectType()) 8115 continue; 8116 8117 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8118 8119 // T& operator[](ptrdiff_t, T*) 8120 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8121 } 8122 } 8123 8124 // C++ [over.built]p11: 8125 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8126 // C1 is the same type as C2 or is a derived class of C2, T is an object 8127 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8128 // there exist candidate operator functions of the form 8129 // 8130 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8131 // 8132 // where CV12 is the union of CV1 and CV2. 8133 void addArrowStarOverloads() { 8134 for (BuiltinCandidateTypeSet::iterator 8135 Ptr = CandidateTypes[0].pointer_begin(), 8136 PtrEnd = CandidateTypes[0].pointer_end(); 8137 Ptr != PtrEnd; ++Ptr) { 8138 QualType C1Ty = (*Ptr); 8139 QualType C1; 8140 QualifierCollector Q1; 8141 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8142 if (!isa<RecordType>(C1)) 8143 continue; 8144 // heuristic to reduce number of builtin candidates in the set. 8145 // Add volatile/restrict version only if there are conversions to a 8146 // volatile/restrict type. 8147 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8148 continue; 8149 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8150 continue; 8151 for (BuiltinCandidateTypeSet::iterator 8152 MemPtr = CandidateTypes[1].member_pointer_begin(), 8153 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8154 MemPtr != MemPtrEnd; ++MemPtr) { 8155 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8156 QualType C2 = QualType(mptr->getClass(), 0); 8157 C2 = C2.getUnqualifiedType(); 8158 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8159 break; 8160 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8161 // build CV12 T& 8162 QualType T = mptr->getPointeeType(); 8163 if (!VisibleTypeConversionsQuals.hasVolatile() && 8164 T.isVolatileQualified()) 8165 continue; 8166 if (!VisibleTypeConversionsQuals.hasRestrict() && 8167 T.isRestrictQualified()) 8168 continue; 8169 T = Q1.apply(S.Context, T); 8170 QualType ResultTy = S.Context.getLValueReferenceType(T); 8171 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8172 } 8173 } 8174 } 8175 8176 // Note that we don't consider the first argument, since it has been 8177 // contextually converted to bool long ago. The candidates below are 8178 // therefore added as binary. 8179 // 8180 // C++ [over.built]p25: 8181 // For every type T, where T is a pointer, pointer-to-member, or scoped 8182 // enumeration type, there exist candidate operator functions of the form 8183 // 8184 // T operator?(bool, T, T); 8185 // 8186 void addConditionalOperatorOverloads() { 8187 /// Set of (canonical) types that we've already handled. 8188 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8189 8190 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8191 for (BuiltinCandidateTypeSet::iterator 8192 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8193 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8194 Ptr != PtrEnd; ++Ptr) { 8195 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8196 continue; 8197 8198 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8199 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8200 } 8201 8202 for (BuiltinCandidateTypeSet::iterator 8203 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8204 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8205 MemPtr != MemPtrEnd; ++MemPtr) { 8206 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8207 continue; 8208 8209 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8210 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8211 } 8212 8213 if (S.getLangOpts().CPlusPlus11) { 8214 for (BuiltinCandidateTypeSet::iterator 8215 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8216 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8217 Enum != EnumEnd; ++Enum) { 8218 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8219 continue; 8220 8221 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8222 continue; 8223 8224 QualType ParamTypes[2] = { *Enum, *Enum }; 8225 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8226 } 8227 } 8228 } 8229 } 8230 }; 8231 8232 } // end anonymous namespace 8233 8234 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8235 /// operator overloads to the candidate set (C++ [over.built]), based 8236 /// on the operator @p Op and the arguments given. For example, if the 8237 /// operator is a binary '+', this routine might add "int 8238 /// operator+(int, int)" to cover integer addition. 8239 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8240 SourceLocation OpLoc, 8241 ArrayRef<Expr *> Args, 8242 OverloadCandidateSet &CandidateSet) { 8243 // Find all of the types that the arguments can convert to, but only 8244 // if the operator we're looking at has built-in operator candidates 8245 // that make use of these types. Also record whether we encounter non-record 8246 // candidate types or either arithmetic or enumeral candidate types. 8247 Qualifiers VisibleTypeConversionsQuals; 8248 VisibleTypeConversionsQuals.addConst(); 8249 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8250 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8251 8252 bool HasNonRecordCandidateType = false; 8253 bool HasArithmeticOrEnumeralCandidateType = false; 8254 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8255 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8256 CandidateTypes.emplace_back(*this); 8257 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8258 OpLoc, 8259 true, 8260 (Op == OO_Exclaim || 8261 Op == OO_AmpAmp || 8262 Op == OO_PipePipe), 8263 VisibleTypeConversionsQuals); 8264 HasNonRecordCandidateType = HasNonRecordCandidateType || 8265 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8266 HasArithmeticOrEnumeralCandidateType = 8267 HasArithmeticOrEnumeralCandidateType || 8268 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8269 } 8270 8271 // Exit early when no non-record types have been added to the candidate set 8272 // for any of the arguments to the operator. 8273 // 8274 // We can't exit early for !, ||, or &&, since there we have always have 8275 // 'bool' overloads. 8276 if (!HasNonRecordCandidateType && 8277 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8278 return; 8279 8280 // Setup an object to manage the common state for building overloads. 8281 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8282 VisibleTypeConversionsQuals, 8283 HasArithmeticOrEnumeralCandidateType, 8284 CandidateTypes, CandidateSet); 8285 8286 // Dispatch over the operation to add in only those overloads which apply. 8287 switch (Op) { 8288 case OO_None: 8289 case NUM_OVERLOADED_OPERATORS: 8290 llvm_unreachable("Expected an overloaded operator"); 8291 8292 case OO_New: 8293 case OO_Delete: 8294 case OO_Array_New: 8295 case OO_Array_Delete: 8296 case OO_Call: 8297 llvm_unreachable( 8298 "Special operators don't use AddBuiltinOperatorCandidates"); 8299 8300 case OO_Comma: 8301 case OO_Arrow: 8302 case OO_Coawait: 8303 // C++ [over.match.oper]p3: 8304 // -- For the operator ',', the unary operator '&', the 8305 // operator '->', or the operator 'co_await', the 8306 // built-in candidates set is empty. 8307 break; 8308 8309 case OO_Plus: // '+' is either unary or binary 8310 if (Args.size() == 1) 8311 OpBuilder.addUnaryPlusPointerOverloads(); 8312 // Fall through. 8313 8314 case OO_Minus: // '-' is either unary or binary 8315 if (Args.size() == 1) { 8316 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8317 } else { 8318 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8319 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8320 } 8321 break; 8322 8323 case OO_Star: // '*' is either unary or binary 8324 if (Args.size() == 1) 8325 OpBuilder.addUnaryStarPointerOverloads(); 8326 else 8327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8328 break; 8329 8330 case OO_Slash: 8331 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8332 break; 8333 8334 case OO_PlusPlus: 8335 case OO_MinusMinus: 8336 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8337 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8338 break; 8339 8340 case OO_EqualEqual: 8341 case OO_ExclaimEqual: 8342 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8343 // Fall through. 8344 8345 case OO_Less: 8346 case OO_Greater: 8347 case OO_LessEqual: 8348 case OO_GreaterEqual: 8349 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8350 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8351 break; 8352 8353 case OO_Percent: 8354 case OO_Caret: 8355 case OO_Pipe: 8356 case OO_LessLess: 8357 case OO_GreaterGreater: 8358 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8359 break; 8360 8361 case OO_Amp: // '&' is either unary or binary 8362 if (Args.size() == 1) 8363 // C++ [over.match.oper]p3: 8364 // -- For the operator ',', the unary operator '&', or the 8365 // operator '->', the built-in candidates set is empty. 8366 break; 8367 8368 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8369 break; 8370 8371 case OO_Tilde: 8372 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8373 break; 8374 8375 case OO_Equal: 8376 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8377 // Fall through. 8378 8379 case OO_PlusEqual: 8380 case OO_MinusEqual: 8381 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8382 // Fall through. 8383 8384 case OO_StarEqual: 8385 case OO_SlashEqual: 8386 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8387 break; 8388 8389 case OO_PercentEqual: 8390 case OO_LessLessEqual: 8391 case OO_GreaterGreaterEqual: 8392 case OO_AmpEqual: 8393 case OO_CaretEqual: 8394 case OO_PipeEqual: 8395 OpBuilder.addAssignmentIntegralOverloads(); 8396 break; 8397 8398 case OO_Exclaim: 8399 OpBuilder.addExclaimOverload(); 8400 break; 8401 8402 case OO_AmpAmp: 8403 case OO_PipePipe: 8404 OpBuilder.addAmpAmpOrPipePipeOverload(); 8405 break; 8406 8407 case OO_Subscript: 8408 OpBuilder.addSubscriptOverloads(); 8409 break; 8410 8411 case OO_ArrowStar: 8412 OpBuilder.addArrowStarOverloads(); 8413 break; 8414 8415 case OO_Conditional: 8416 OpBuilder.addConditionalOperatorOverloads(); 8417 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8418 break; 8419 } 8420 } 8421 8422 /// \brief Add function candidates found via argument-dependent lookup 8423 /// to the set of overloading candidates. 8424 /// 8425 /// This routine performs argument-dependent name lookup based on the 8426 /// given function name (which may also be an operator name) and adds 8427 /// all of the overload candidates found by ADL to the overload 8428 /// candidate set (C++ [basic.lookup.argdep]). 8429 void 8430 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8431 SourceLocation Loc, 8432 ArrayRef<Expr *> Args, 8433 TemplateArgumentListInfo *ExplicitTemplateArgs, 8434 OverloadCandidateSet& CandidateSet, 8435 bool PartialOverloading) { 8436 ADLResult Fns; 8437 8438 // FIXME: This approach for uniquing ADL results (and removing 8439 // redundant candidates from the set) relies on pointer-equality, 8440 // which means we need to key off the canonical decl. However, 8441 // always going back to the canonical decl might not get us the 8442 // right set of default arguments. What default arguments are 8443 // we supposed to consider on ADL candidates, anyway? 8444 8445 // FIXME: Pass in the explicit template arguments? 8446 ArgumentDependentLookup(Name, Loc, Args, Fns); 8447 8448 // Erase all of the candidates we already knew about. 8449 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8450 CandEnd = CandidateSet.end(); 8451 Cand != CandEnd; ++Cand) 8452 if (Cand->Function) { 8453 Fns.erase(Cand->Function); 8454 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8455 Fns.erase(FunTmpl); 8456 } 8457 8458 // For each of the ADL candidates we found, add it to the overload 8459 // set. 8460 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8461 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8462 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8463 if (ExplicitTemplateArgs) 8464 continue; 8465 8466 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8467 PartialOverloading); 8468 } else 8469 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8470 FoundDecl, ExplicitTemplateArgs, 8471 Args, CandidateSet, PartialOverloading); 8472 } 8473 } 8474 8475 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8476 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8477 // on Cand1 and Cand2 have conditions that evaluate to true. 8478 // 8479 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8480 // Cand1's first N enable_if attributes have precisely the same conditions as 8481 // Cand2's first N enable_if attributes (where N = the number of enable_if 8482 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8483 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8484 const FunctionDecl *Cand2) { 8485 8486 // FIXME: The next several lines are just 8487 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8488 // instead of reverse order which is how they're stored in the AST. 8489 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8490 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8491 8492 // Candidate 1 is better if it has strictly more attributes and 8493 // the common sequence is identical. 8494 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8495 return false; 8496 8497 auto Cand1I = Cand1Attrs.begin(); 8498 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8499 for (auto &Cand2A : Cand2Attrs) { 8500 Cand1ID.clear(); 8501 Cand2ID.clear(); 8502 8503 auto &Cand1A = *Cand1I++; 8504 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8505 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8506 if (Cand1ID != Cand2ID) 8507 return false; 8508 } 8509 8510 return true; 8511 } 8512 8513 /// isBetterOverloadCandidate - Determines whether the first overload 8514 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8515 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8516 const OverloadCandidate &Cand2, 8517 SourceLocation Loc, 8518 bool UserDefinedConversion) { 8519 // Define viable functions to be better candidates than non-viable 8520 // functions. 8521 if (!Cand2.Viable) 8522 return Cand1.Viable; 8523 else if (!Cand1.Viable) 8524 return false; 8525 8526 // C++ [over.match.best]p1: 8527 // 8528 // -- if F is a static member function, ICS1(F) is defined such 8529 // that ICS1(F) is neither better nor worse than ICS1(G) for 8530 // any function G, and, symmetrically, ICS1(G) is neither 8531 // better nor worse than ICS1(F). 8532 unsigned StartArg = 0; 8533 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8534 StartArg = 1; 8535 8536 // C++ [over.match.best]p1: 8537 // A viable function F1 is defined to be a better function than another 8538 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8539 // conversion sequence than ICSi(F2), and then... 8540 unsigned NumArgs = Cand1.NumConversions; 8541 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8542 bool HasBetterConversion = false; 8543 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8544 switch (CompareImplicitConversionSequences(S, Loc, 8545 Cand1.Conversions[ArgIdx], 8546 Cand2.Conversions[ArgIdx])) { 8547 case ImplicitConversionSequence::Better: 8548 // Cand1 has a better conversion sequence. 8549 HasBetterConversion = true; 8550 break; 8551 8552 case ImplicitConversionSequence::Worse: 8553 // Cand1 can't be better than Cand2. 8554 return false; 8555 8556 case ImplicitConversionSequence::Indistinguishable: 8557 // Do nothing. 8558 break; 8559 } 8560 } 8561 8562 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8563 // ICSj(F2), or, if not that, 8564 if (HasBetterConversion) 8565 return true; 8566 8567 // -- the context is an initialization by user-defined conversion 8568 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8569 // from the return type of F1 to the destination type (i.e., 8570 // the type of the entity being initialized) is a better 8571 // conversion sequence than the standard conversion sequence 8572 // from the return type of F2 to the destination type. 8573 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8574 isa<CXXConversionDecl>(Cand1.Function) && 8575 isa<CXXConversionDecl>(Cand2.Function)) { 8576 // First check whether we prefer one of the conversion functions over the 8577 // other. This only distinguishes the results in non-standard, extension 8578 // cases such as the conversion from a lambda closure type to a function 8579 // pointer or block. 8580 ImplicitConversionSequence::CompareKind Result = 8581 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8582 if (Result == ImplicitConversionSequence::Indistinguishable) 8583 Result = CompareStandardConversionSequences(S, Loc, 8584 Cand1.FinalConversion, 8585 Cand2.FinalConversion); 8586 8587 if (Result != ImplicitConversionSequence::Indistinguishable) 8588 return Result == ImplicitConversionSequence::Better; 8589 8590 // FIXME: Compare kind of reference binding if conversion functions 8591 // convert to a reference type used in direct reference binding, per 8592 // C++14 [over.match.best]p1 section 2 bullet 3. 8593 } 8594 8595 // -- F1 is a non-template function and F2 is a function template 8596 // specialization, or, if not that, 8597 bool Cand1IsSpecialization = Cand1.Function && 8598 Cand1.Function->getPrimaryTemplate(); 8599 bool Cand2IsSpecialization = Cand2.Function && 8600 Cand2.Function->getPrimaryTemplate(); 8601 if (Cand1IsSpecialization != Cand2IsSpecialization) 8602 return Cand2IsSpecialization; 8603 8604 // -- F1 and F2 are function template specializations, and the function 8605 // template for F1 is more specialized than the template for F2 8606 // according to the partial ordering rules described in 14.5.5.2, or, 8607 // if not that, 8608 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8609 if (FunctionTemplateDecl *BetterTemplate 8610 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8611 Cand2.Function->getPrimaryTemplate(), 8612 Loc, 8613 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8614 : TPOC_Call, 8615 Cand1.ExplicitCallArguments, 8616 Cand2.ExplicitCallArguments)) 8617 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8618 } 8619 8620 // Check for enable_if value-based overload resolution. 8621 if (Cand1.Function && Cand2.Function && 8622 (Cand1.Function->hasAttr<EnableIfAttr>() || 8623 Cand2.Function->hasAttr<EnableIfAttr>())) 8624 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8625 8626 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8627 Cand1.Function && Cand2.Function) { 8628 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8629 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8630 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8631 } 8632 8633 bool HasPS1 = Cand1.Function != nullptr && 8634 functionHasPassObjectSizeParams(Cand1.Function); 8635 bool HasPS2 = Cand2.Function != nullptr && 8636 functionHasPassObjectSizeParams(Cand2.Function); 8637 return HasPS1 != HasPS2 && HasPS1; 8638 } 8639 8640 /// Determine whether two declarations are "equivalent" for the purposes of 8641 /// name lookup and overload resolution. This applies when the same internal/no 8642 /// linkage entity is defined by two modules (probably by textually including 8643 /// the same header). In such a case, we don't consider the declarations to 8644 /// declare the same entity, but we also don't want lookups with both 8645 /// declarations visible to be ambiguous in some cases (this happens when using 8646 /// a modularized libstdc++). 8647 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8648 const NamedDecl *B) { 8649 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8650 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8651 if (!VA || !VB) 8652 return false; 8653 8654 // The declarations must be declaring the same name as an internal linkage 8655 // entity in different modules. 8656 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8657 VB->getDeclContext()->getRedeclContext()) || 8658 getOwningModule(const_cast<ValueDecl *>(VA)) == 8659 getOwningModule(const_cast<ValueDecl *>(VB)) || 8660 VA->isExternallyVisible() || VB->isExternallyVisible()) 8661 return false; 8662 8663 // Check that the declarations appear to be equivalent. 8664 // 8665 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8666 // For constants and functions, we should check the initializer or body is 8667 // the same. For non-constant variables, we shouldn't allow it at all. 8668 if (Context.hasSameType(VA->getType(), VB->getType())) 8669 return true; 8670 8671 // Enum constants within unnamed enumerations will have different types, but 8672 // may still be similar enough to be interchangeable for our purposes. 8673 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8674 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8675 // Only handle anonymous enums. If the enumerations were named and 8676 // equivalent, they would have been merged to the same type. 8677 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8678 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8679 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8680 !Context.hasSameType(EnumA->getIntegerType(), 8681 EnumB->getIntegerType())) 8682 return false; 8683 // Allow this only if the value is the same for both enumerators. 8684 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8685 } 8686 } 8687 8688 // Nothing else is sufficiently similar. 8689 return false; 8690 } 8691 8692 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8693 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8694 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8695 8696 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8697 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8698 << !M << (M ? M->getFullModuleName() : ""); 8699 8700 for (auto *E : Equiv) { 8701 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8702 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8703 << !M << (M ? M->getFullModuleName() : ""); 8704 } 8705 } 8706 8707 /// \brief Computes the best viable function (C++ 13.3.3) 8708 /// within an overload candidate set. 8709 /// 8710 /// \param Loc The location of the function name (or operator symbol) for 8711 /// which overload resolution occurs. 8712 /// 8713 /// \param Best If overload resolution was successful or found a deleted 8714 /// function, \p Best points to the candidate function found. 8715 /// 8716 /// \returns The result of overload resolution. 8717 OverloadingResult 8718 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8719 iterator &Best, 8720 bool UserDefinedConversion) { 8721 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8722 std::transform(begin(), end(), std::back_inserter(Candidates), 8723 [](OverloadCandidate &Cand) { return &Cand; }); 8724 8725 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA 8726 // but accepted by both clang and NVCC. However during a particular 8727 // compilation mode only one call variant is viable. We need to 8728 // exclude non-viable overload candidates from consideration based 8729 // only on their host/device attributes. Specifically, if one 8730 // candidate call is WrongSide and the other is SameSide, we ignore 8731 // the WrongSide candidate. 8732 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads) { 8733 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8734 bool ContainsSameSideCandidate = 8735 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8736 return Cand->Function && 8737 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8738 Sema::CFP_SameSide; 8739 }); 8740 if (ContainsSameSideCandidate) { 8741 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8742 return Cand->Function && 8743 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8744 Sema::CFP_WrongSide; 8745 }; 8746 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8747 IsWrongSideCandidate), 8748 Candidates.end()); 8749 } 8750 } 8751 8752 // Find the best viable function. 8753 Best = end(); 8754 for (auto *Cand : Candidates) 8755 if (Cand->Viable) 8756 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8757 UserDefinedConversion)) 8758 Best = Cand; 8759 8760 // If we didn't find any viable functions, abort. 8761 if (Best == end()) 8762 return OR_No_Viable_Function; 8763 8764 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8765 8766 // Make sure that this function is better than every other viable 8767 // function. If not, we have an ambiguity. 8768 for (auto *Cand : Candidates) { 8769 if (Cand->Viable && 8770 Cand != Best && 8771 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8772 UserDefinedConversion)) { 8773 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8774 Cand->Function)) { 8775 EquivalentCands.push_back(Cand->Function); 8776 continue; 8777 } 8778 8779 Best = end(); 8780 return OR_Ambiguous; 8781 } 8782 } 8783 8784 // Best is the best viable function. 8785 if (Best->Function && 8786 (Best->Function->isDeleted() || 8787 S.isFunctionConsideredUnavailable(Best->Function))) 8788 return OR_Deleted; 8789 8790 if (!EquivalentCands.empty()) 8791 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8792 EquivalentCands); 8793 8794 return OR_Success; 8795 } 8796 8797 namespace { 8798 8799 enum OverloadCandidateKind { 8800 oc_function, 8801 oc_method, 8802 oc_constructor, 8803 oc_function_template, 8804 oc_method_template, 8805 oc_constructor_template, 8806 oc_implicit_default_constructor, 8807 oc_implicit_copy_constructor, 8808 oc_implicit_move_constructor, 8809 oc_implicit_copy_assignment, 8810 oc_implicit_move_assignment, 8811 oc_implicit_inherited_constructor 8812 }; 8813 8814 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8815 FunctionDecl *Fn, 8816 std::string &Description) { 8817 bool isTemplate = false; 8818 8819 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8820 isTemplate = true; 8821 Description = S.getTemplateArgumentBindingsText( 8822 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8823 } 8824 8825 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8826 if (!Ctor->isImplicit()) 8827 return isTemplate ? oc_constructor_template : oc_constructor; 8828 8829 if (Ctor->getInheritedConstructor()) 8830 return oc_implicit_inherited_constructor; 8831 8832 if (Ctor->isDefaultConstructor()) 8833 return oc_implicit_default_constructor; 8834 8835 if (Ctor->isMoveConstructor()) 8836 return oc_implicit_move_constructor; 8837 8838 assert(Ctor->isCopyConstructor() && 8839 "unexpected sort of implicit constructor"); 8840 return oc_implicit_copy_constructor; 8841 } 8842 8843 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8844 // This actually gets spelled 'candidate function' for now, but 8845 // it doesn't hurt to split it out. 8846 if (!Meth->isImplicit()) 8847 return isTemplate ? oc_method_template : oc_method; 8848 8849 if (Meth->isMoveAssignmentOperator()) 8850 return oc_implicit_move_assignment; 8851 8852 if (Meth->isCopyAssignmentOperator()) 8853 return oc_implicit_copy_assignment; 8854 8855 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8856 return oc_method; 8857 } 8858 8859 return isTemplate ? oc_function_template : oc_function; 8860 } 8861 8862 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8863 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8864 if (!Ctor) return; 8865 8866 Ctor = Ctor->getInheritedConstructor(); 8867 if (!Ctor) return; 8868 8869 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8870 } 8871 8872 } // end anonymous namespace 8873 8874 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8875 const FunctionDecl *FD) { 8876 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8877 bool AlwaysTrue; 8878 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8879 return false; 8880 if (!AlwaysTrue) 8881 return false; 8882 } 8883 return true; 8884 } 8885 8886 /// \brief Returns true if we can take the address of the function. 8887 /// 8888 /// \param Complain - If true, we'll emit a diagnostic 8889 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8890 /// we in overload resolution? 8891 /// \param Loc - The location of the statement we're complaining about. Ignored 8892 /// if we're not complaining, or if we're in overload resolution. 8893 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8894 bool Complain, 8895 bool InOverloadResolution, 8896 SourceLocation Loc) { 8897 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8898 if (Complain) { 8899 if (InOverloadResolution) 8900 S.Diag(FD->getLocStart(), 8901 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8902 else 8903 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8904 } 8905 return false; 8906 } 8907 8908 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8909 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8910 if (I == FD->param_end()) 8911 return true; 8912 8913 if (Complain) { 8914 // Add one to ParamNo because it's user-facing 8915 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8916 if (InOverloadResolution) 8917 S.Diag(FD->getLocation(), 8918 diag::note_ovl_candidate_has_pass_object_size_params) 8919 << ParamNo; 8920 else 8921 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8922 << FD << ParamNo; 8923 } 8924 return false; 8925 } 8926 8927 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8928 const FunctionDecl *FD) { 8929 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8930 /*InOverloadResolution=*/true, 8931 /*Loc=*/SourceLocation()); 8932 } 8933 8934 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8935 bool Complain, 8936 SourceLocation Loc) { 8937 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8938 /*InOverloadResolution=*/false, 8939 Loc); 8940 } 8941 8942 // Notes the location of an overload candidate. 8943 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8944 bool TakingAddress) { 8945 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8946 return; 8947 8948 std::string FnDesc; 8949 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8950 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8951 << (unsigned) K << FnDesc; 8952 8953 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8954 Diag(Fn->getLocation(), PD); 8955 MaybeEmitInheritedConstructorNote(*this, Fn); 8956 } 8957 8958 // Notes the location of all overload candidates designated through 8959 // OverloadedExpr 8960 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8961 bool TakingAddress) { 8962 assert(OverloadedExpr->getType() == Context.OverloadTy); 8963 8964 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8965 OverloadExpr *OvlExpr = Ovl.Expression; 8966 8967 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8968 IEnd = OvlExpr->decls_end(); 8969 I != IEnd; ++I) { 8970 if (FunctionTemplateDecl *FunTmpl = 8971 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8972 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8973 TakingAddress); 8974 } else if (FunctionDecl *Fun 8975 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8976 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8977 } 8978 } 8979 } 8980 8981 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8982 /// "lead" diagnostic; it will be given two arguments, the source and 8983 /// target types of the conversion. 8984 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8985 Sema &S, 8986 SourceLocation CaretLoc, 8987 const PartialDiagnostic &PDiag) const { 8988 S.Diag(CaretLoc, PDiag) 8989 << Ambiguous.getFromType() << Ambiguous.getToType(); 8990 // FIXME: The note limiting machinery is borrowed from 8991 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8992 // refactoring here. 8993 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8994 unsigned CandsShown = 0; 8995 AmbiguousConversionSequence::const_iterator I, E; 8996 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8997 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8998 break; 8999 ++CandsShown; 9000 S.NoteOverloadCandidate(*I); 9001 } 9002 if (I != E) 9003 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9004 } 9005 9006 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9007 unsigned I, bool TakingCandidateAddress) { 9008 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9009 assert(Conv.isBad()); 9010 assert(Cand->Function && "for now, candidate must be a function"); 9011 FunctionDecl *Fn = Cand->Function; 9012 9013 // There's a conversion slot for the object argument if this is a 9014 // non-constructor method. Note that 'I' corresponds the 9015 // conversion-slot index. 9016 bool isObjectArgument = false; 9017 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9018 if (I == 0) 9019 isObjectArgument = true; 9020 else 9021 I--; 9022 } 9023 9024 std::string FnDesc; 9025 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9026 9027 Expr *FromExpr = Conv.Bad.FromExpr; 9028 QualType FromTy = Conv.Bad.getFromType(); 9029 QualType ToTy = Conv.Bad.getToType(); 9030 9031 if (FromTy == S.Context.OverloadTy) { 9032 assert(FromExpr && "overload set argument came from implicit argument?"); 9033 Expr *E = FromExpr->IgnoreParens(); 9034 if (isa<UnaryOperator>(E)) 9035 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9036 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9037 9038 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9039 << (unsigned) FnKind << FnDesc 9040 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9041 << ToTy << Name << I+1; 9042 MaybeEmitInheritedConstructorNote(S, Fn); 9043 return; 9044 } 9045 9046 // Do some hand-waving analysis to see if the non-viability is due 9047 // to a qualifier mismatch. 9048 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9049 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9050 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9051 CToTy = RT->getPointeeType(); 9052 else { 9053 // TODO: detect and diagnose the full richness of const mismatches. 9054 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9055 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9056 CFromTy = FromPT->getPointeeType(); 9057 CToTy = ToPT->getPointeeType(); 9058 } 9059 } 9060 9061 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9062 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9063 Qualifiers FromQs = CFromTy.getQualifiers(); 9064 Qualifiers ToQs = CToTy.getQualifiers(); 9065 9066 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9068 << (unsigned) FnKind << FnDesc 9069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9070 << FromTy 9071 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9072 << (unsigned) isObjectArgument << I+1; 9073 MaybeEmitInheritedConstructorNote(S, Fn); 9074 return; 9075 } 9076 9077 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9079 << (unsigned) FnKind << FnDesc 9080 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9081 << FromTy 9082 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9083 << (unsigned) isObjectArgument << I+1; 9084 MaybeEmitInheritedConstructorNote(S, Fn); 9085 return; 9086 } 9087 9088 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9090 << (unsigned) FnKind << FnDesc 9091 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9092 << FromTy 9093 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9094 << (unsigned) isObjectArgument << I+1; 9095 MaybeEmitInheritedConstructorNote(S, Fn); 9096 return; 9097 } 9098 9099 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9100 assert(CVR && "unexpected qualifiers mismatch"); 9101 9102 if (isObjectArgument) { 9103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9104 << (unsigned) FnKind << FnDesc 9105 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9106 << FromTy << (CVR - 1); 9107 } else { 9108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9109 << (unsigned) FnKind << FnDesc 9110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9111 << FromTy << (CVR - 1) << I+1; 9112 } 9113 MaybeEmitInheritedConstructorNote(S, Fn); 9114 return; 9115 } 9116 9117 // Special diagnostic for failure to convert an initializer list, since 9118 // telling the user that it has type void is not useful. 9119 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9121 << (unsigned) FnKind << FnDesc 9122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9123 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9124 MaybeEmitInheritedConstructorNote(S, Fn); 9125 return; 9126 } 9127 9128 // Diagnose references or pointers to incomplete types differently, 9129 // since it's far from impossible that the incompleteness triggered 9130 // the failure. 9131 QualType TempFromTy = FromTy.getNonReferenceType(); 9132 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9133 TempFromTy = PTy->getPointeeType(); 9134 if (TempFromTy->isIncompleteType()) { 9135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9136 << (unsigned) FnKind << FnDesc 9137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9139 MaybeEmitInheritedConstructorNote(S, Fn); 9140 return; 9141 } 9142 9143 // Diagnose base -> derived pointer conversions. 9144 unsigned BaseToDerivedConversion = 0; 9145 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9146 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9147 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9148 FromPtrTy->getPointeeType()) && 9149 !FromPtrTy->getPointeeType()->isIncompleteType() && 9150 !ToPtrTy->getPointeeType()->isIncompleteType() && 9151 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9152 FromPtrTy->getPointeeType())) 9153 BaseToDerivedConversion = 1; 9154 } 9155 } else if (const ObjCObjectPointerType *FromPtrTy 9156 = FromTy->getAs<ObjCObjectPointerType>()) { 9157 if (const ObjCObjectPointerType *ToPtrTy 9158 = ToTy->getAs<ObjCObjectPointerType>()) 9159 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9160 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9161 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9162 FromPtrTy->getPointeeType()) && 9163 FromIface->isSuperClassOf(ToIface)) 9164 BaseToDerivedConversion = 2; 9165 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9166 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9167 !FromTy->isIncompleteType() && 9168 !ToRefTy->getPointeeType()->isIncompleteType() && 9169 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9170 BaseToDerivedConversion = 3; 9171 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9172 ToTy.getNonReferenceType().getCanonicalType() == 9173 FromTy.getNonReferenceType().getCanonicalType()) { 9174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9175 << (unsigned) FnKind << FnDesc 9176 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9177 << (unsigned) isObjectArgument << I + 1; 9178 MaybeEmitInheritedConstructorNote(S, Fn); 9179 return; 9180 } 9181 } 9182 9183 if (BaseToDerivedConversion) { 9184 S.Diag(Fn->getLocation(), 9185 diag::note_ovl_candidate_bad_base_to_derived_conv) 9186 << (unsigned) FnKind << FnDesc 9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9188 << (BaseToDerivedConversion - 1) 9189 << FromTy << ToTy << I+1; 9190 MaybeEmitInheritedConstructorNote(S, Fn); 9191 return; 9192 } 9193 9194 if (isa<ObjCObjectPointerType>(CFromTy) && 9195 isa<PointerType>(CToTy)) { 9196 Qualifiers FromQs = CFromTy.getQualifiers(); 9197 Qualifiers ToQs = CToTy.getQualifiers(); 9198 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9200 << (unsigned) FnKind << FnDesc 9201 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9202 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9203 MaybeEmitInheritedConstructorNote(S, Fn); 9204 return; 9205 } 9206 } 9207 9208 if (TakingCandidateAddress && 9209 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9210 return; 9211 9212 // Emit the generic diagnostic and, optionally, add the hints to it. 9213 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9214 FDiag << (unsigned) FnKind << FnDesc 9215 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9216 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9217 << (unsigned) (Cand->Fix.Kind); 9218 9219 // If we can fix the conversion, suggest the FixIts. 9220 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9221 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9222 FDiag << *HI; 9223 S.Diag(Fn->getLocation(), FDiag); 9224 9225 MaybeEmitInheritedConstructorNote(S, Fn); 9226 } 9227 9228 /// Additional arity mismatch diagnosis specific to a function overload 9229 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9230 /// over a candidate in any candidate set. 9231 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9232 unsigned NumArgs) { 9233 FunctionDecl *Fn = Cand->Function; 9234 unsigned MinParams = Fn->getMinRequiredArguments(); 9235 9236 // With invalid overloaded operators, it's possible that we think we 9237 // have an arity mismatch when in fact it looks like we have the 9238 // right number of arguments, because only overloaded operators have 9239 // the weird behavior of overloading member and non-member functions. 9240 // Just don't report anything. 9241 if (Fn->isInvalidDecl() && 9242 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9243 return true; 9244 9245 if (NumArgs < MinParams) { 9246 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9247 (Cand->FailureKind == ovl_fail_bad_deduction && 9248 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9249 } else { 9250 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9251 (Cand->FailureKind == ovl_fail_bad_deduction && 9252 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9253 } 9254 9255 return false; 9256 } 9257 9258 /// General arity mismatch diagnosis over a candidate in a candidate set. 9259 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9260 assert(isa<FunctionDecl>(D) && 9261 "The templated declaration should at least be a function" 9262 " when diagnosing bad template argument deduction due to too many" 9263 " or too few arguments"); 9264 9265 FunctionDecl *Fn = cast<FunctionDecl>(D); 9266 9267 // TODO: treat calls to a missing default constructor as a special case 9268 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9269 unsigned MinParams = Fn->getMinRequiredArguments(); 9270 9271 // at least / at most / exactly 9272 unsigned mode, modeCount; 9273 if (NumFormalArgs < MinParams) { 9274 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9275 FnTy->isTemplateVariadic()) 9276 mode = 0; // "at least" 9277 else 9278 mode = 2; // "exactly" 9279 modeCount = MinParams; 9280 } else { 9281 if (MinParams != FnTy->getNumParams()) 9282 mode = 1; // "at most" 9283 else 9284 mode = 2; // "exactly" 9285 modeCount = FnTy->getNumParams(); 9286 } 9287 9288 std::string Description; 9289 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9290 9291 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9293 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9294 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9295 else 9296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9297 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9298 << mode << modeCount << NumFormalArgs; 9299 MaybeEmitInheritedConstructorNote(S, Fn); 9300 } 9301 9302 /// Arity mismatch diagnosis specific to a function overload candidate. 9303 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9304 unsigned NumFormalArgs) { 9305 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9306 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9307 } 9308 9309 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9310 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9311 return FD->getDescribedFunctionTemplate(); 9312 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9313 return RD->getDescribedClassTemplate(); 9314 9315 llvm_unreachable("Unsupported: Getting the described template declaration" 9316 " for bad deduction diagnosis"); 9317 } 9318 9319 /// Diagnose a failed template-argument deduction. 9320 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9321 DeductionFailureInfo &DeductionFailure, 9322 unsigned NumArgs, 9323 bool TakingCandidateAddress) { 9324 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9325 NamedDecl *ParamD; 9326 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9327 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9328 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9329 switch (DeductionFailure.Result) { 9330 case Sema::TDK_Success: 9331 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9332 9333 case Sema::TDK_Incomplete: { 9334 assert(ParamD && "no parameter found for incomplete deduction result"); 9335 S.Diag(Templated->getLocation(), 9336 diag::note_ovl_candidate_incomplete_deduction) 9337 << ParamD->getDeclName(); 9338 MaybeEmitInheritedConstructorNote(S, Templated); 9339 return; 9340 } 9341 9342 case Sema::TDK_Underqualified: { 9343 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9344 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9345 9346 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9347 9348 // Param will have been canonicalized, but it should just be a 9349 // qualified version of ParamD, so move the qualifiers to that. 9350 QualifierCollector Qs; 9351 Qs.strip(Param); 9352 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9353 assert(S.Context.hasSameType(Param, NonCanonParam)); 9354 9355 // Arg has also been canonicalized, but there's nothing we can do 9356 // about that. It also doesn't matter as much, because it won't 9357 // have any template parameters in it (because deduction isn't 9358 // done on dependent types). 9359 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9360 9361 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9362 << ParamD->getDeclName() << Arg << NonCanonParam; 9363 MaybeEmitInheritedConstructorNote(S, Templated); 9364 return; 9365 } 9366 9367 case Sema::TDK_Inconsistent: { 9368 assert(ParamD && "no parameter found for inconsistent deduction result"); 9369 int which = 0; 9370 if (isa<TemplateTypeParmDecl>(ParamD)) 9371 which = 0; 9372 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9373 which = 1; 9374 else { 9375 which = 2; 9376 } 9377 9378 S.Diag(Templated->getLocation(), 9379 diag::note_ovl_candidate_inconsistent_deduction) 9380 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9381 << *DeductionFailure.getSecondArg(); 9382 MaybeEmitInheritedConstructorNote(S, Templated); 9383 return; 9384 } 9385 9386 case Sema::TDK_InvalidExplicitArguments: 9387 assert(ParamD && "no parameter found for invalid explicit arguments"); 9388 if (ParamD->getDeclName()) 9389 S.Diag(Templated->getLocation(), 9390 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9391 << ParamD->getDeclName(); 9392 else { 9393 int index = 0; 9394 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9395 index = TTP->getIndex(); 9396 else if (NonTypeTemplateParmDecl *NTTP 9397 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9398 index = NTTP->getIndex(); 9399 else 9400 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9401 S.Diag(Templated->getLocation(), 9402 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9403 << (index + 1); 9404 } 9405 MaybeEmitInheritedConstructorNote(S, Templated); 9406 return; 9407 9408 case Sema::TDK_TooManyArguments: 9409 case Sema::TDK_TooFewArguments: 9410 DiagnoseArityMismatch(S, Templated, NumArgs); 9411 return; 9412 9413 case Sema::TDK_InstantiationDepth: 9414 S.Diag(Templated->getLocation(), 9415 diag::note_ovl_candidate_instantiation_depth); 9416 MaybeEmitInheritedConstructorNote(S, Templated); 9417 return; 9418 9419 case Sema::TDK_SubstitutionFailure: { 9420 // Format the template argument list into the argument string. 9421 SmallString<128> TemplateArgString; 9422 if (TemplateArgumentList *Args = 9423 DeductionFailure.getTemplateArgumentList()) { 9424 TemplateArgString = " "; 9425 TemplateArgString += S.getTemplateArgumentBindingsText( 9426 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9427 } 9428 9429 // If this candidate was disabled by enable_if, say so. 9430 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9431 if (PDiag && PDiag->second.getDiagID() == 9432 diag::err_typename_nested_not_found_enable_if) { 9433 // FIXME: Use the source range of the condition, and the fully-qualified 9434 // name of the enable_if template. These are both present in PDiag. 9435 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9436 << "'enable_if'" << TemplateArgString; 9437 return; 9438 } 9439 9440 // Format the SFINAE diagnostic into the argument string. 9441 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9442 // formatted message in another diagnostic. 9443 SmallString<128> SFINAEArgString; 9444 SourceRange R; 9445 if (PDiag) { 9446 SFINAEArgString = ": "; 9447 R = SourceRange(PDiag->first, PDiag->first); 9448 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9449 } 9450 9451 S.Diag(Templated->getLocation(), 9452 diag::note_ovl_candidate_substitution_failure) 9453 << TemplateArgString << SFINAEArgString << R; 9454 MaybeEmitInheritedConstructorNote(S, Templated); 9455 return; 9456 } 9457 9458 case Sema::TDK_FailedOverloadResolution: { 9459 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9460 S.Diag(Templated->getLocation(), 9461 diag::note_ovl_candidate_failed_overload_resolution) 9462 << R.Expression->getName(); 9463 return; 9464 } 9465 9466 case Sema::TDK_DeducedMismatch: { 9467 // Format the template argument list into the argument string. 9468 SmallString<128> TemplateArgString; 9469 if (TemplateArgumentList *Args = 9470 DeductionFailure.getTemplateArgumentList()) { 9471 TemplateArgString = " "; 9472 TemplateArgString += S.getTemplateArgumentBindingsText( 9473 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9474 } 9475 9476 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9477 << (*DeductionFailure.getCallArgIndex() + 1) 9478 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9479 << TemplateArgString; 9480 break; 9481 } 9482 9483 case Sema::TDK_NonDeducedMismatch: { 9484 // FIXME: Provide a source location to indicate what we couldn't match. 9485 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9486 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9487 if (FirstTA.getKind() == TemplateArgument::Template && 9488 SecondTA.getKind() == TemplateArgument::Template) { 9489 TemplateName FirstTN = FirstTA.getAsTemplate(); 9490 TemplateName SecondTN = SecondTA.getAsTemplate(); 9491 if (FirstTN.getKind() == TemplateName::Template && 9492 SecondTN.getKind() == TemplateName::Template) { 9493 if (FirstTN.getAsTemplateDecl()->getName() == 9494 SecondTN.getAsTemplateDecl()->getName()) { 9495 // FIXME: This fixes a bad diagnostic where both templates are named 9496 // the same. This particular case is a bit difficult since: 9497 // 1) It is passed as a string to the diagnostic printer. 9498 // 2) The diagnostic printer only attempts to find a better 9499 // name for types, not decls. 9500 // Ideally, this should folded into the diagnostic printer. 9501 S.Diag(Templated->getLocation(), 9502 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9503 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9504 return; 9505 } 9506 } 9507 } 9508 9509 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9510 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9511 return; 9512 9513 // FIXME: For generic lambda parameters, check if the function is a lambda 9514 // call operator, and if so, emit a prettier and more informative 9515 // diagnostic that mentions 'auto' and lambda in addition to 9516 // (or instead of?) the canonical template type parameters. 9517 S.Diag(Templated->getLocation(), 9518 diag::note_ovl_candidate_non_deduced_mismatch) 9519 << FirstTA << SecondTA; 9520 return; 9521 } 9522 // TODO: diagnose these individually, then kill off 9523 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9524 case Sema::TDK_MiscellaneousDeductionFailure: 9525 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9526 MaybeEmitInheritedConstructorNote(S, Templated); 9527 return; 9528 } 9529 } 9530 9531 /// Diagnose a failed template-argument deduction, for function calls. 9532 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9533 unsigned NumArgs, 9534 bool TakingCandidateAddress) { 9535 unsigned TDK = Cand->DeductionFailure.Result; 9536 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9537 if (CheckArityMismatch(S, Cand, NumArgs)) 9538 return; 9539 } 9540 DiagnoseBadDeduction(S, Cand->Function, // pattern 9541 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9542 } 9543 9544 /// CUDA: diagnose an invalid call across targets. 9545 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9546 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9547 FunctionDecl *Callee = Cand->Function; 9548 9549 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9550 CalleeTarget = S.IdentifyCUDATarget(Callee); 9551 9552 std::string FnDesc; 9553 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9554 9555 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9556 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9557 9558 // This could be an implicit constructor for which we could not infer the 9559 // target due to a collsion. Diagnose that case. 9560 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9561 if (Meth != nullptr && Meth->isImplicit()) { 9562 CXXRecordDecl *ParentClass = Meth->getParent(); 9563 Sema::CXXSpecialMember CSM; 9564 9565 switch (FnKind) { 9566 default: 9567 return; 9568 case oc_implicit_default_constructor: 9569 CSM = Sema::CXXDefaultConstructor; 9570 break; 9571 case oc_implicit_copy_constructor: 9572 CSM = Sema::CXXCopyConstructor; 9573 break; 9574 case oc_implicit_move_constructor: 9575 CSM = Sema::CXXMoveConstructor; 9576 break; 9577 case oc_implicit_copy_assignment: 9578 CSM = Sema::CXXCopyAssignment; 9579 break; 9580 case oc_implicit_move_assignment: 9581 CSM = Sema::CXXMoveAssignment; 9582 break; 9583 }; 9584 9585 bool ConstRHS = false; 9586 if (Meth->getNumParams()) { 9587 if (const ReferenceType *RT = 9588 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9589 ConstRHS = RT->getPointeeType().isConstQualified(); 9590 } 9591 } 9592 9593 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9594 /* ConstRHS */ ConstRHS, 9595 /* Diagnose */ true); 9596 } 9597 } 9598 9599 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9600 FunctionDecl *Callee = Cand->Function; 9601 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9602 9603 S.Diag(Callee->getLocation(), 9604 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9605 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9606 } 9607 9608 /// Generates a 'note' diagnostic for an overload candidate. We've 9609 /// already generated a primary error at the call site. 9610 /// 9611 /// It really does need to be a single diagnostic with its caret 9612 /// pointed at the candidate declaration. Yes, this creates some 9613 /// major challenges of technical writing. Yes, this makes pointing 9614 /// out problems with specific arguments quite awkward. It's still 9615 /// better than generating twenty screens of text for every failed 9616 /// overload. 9617 /// 9618 /// It would be great to be able to express per-candidate problems 9619 /// more richly for those diagnostic clients that cared, but we'd 9620 /// still have to be just as careful with the default diagnostics. 9621 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9622 unsigned NumArgs, 9623 bool TakingCandidateAddress) { 9624 FunctionDecl *Fn = Cand->Function; 9625 9626 // Note deleted candidates, but only if they're viable. 9627 if (Cand->Viable && (Fn->isDeleted() || 9628 S.isFunctionConsideredUnavailable(Fn))) { 9629 std::string FnDesc; 9630 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9631 9632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9633 << FnKind << FnDesc 9634 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9635 MaybeEmitInheritedConstructorNote(S, Fn); 9636 return; 9637 } 9638 9639 // We don't really have anything else to say about viable candidates. 9640 if (Cand->Viable) { 9641 S.NoteOverloadCandidate(Fn); 9642 return; 9643 } 9644 9645 switch (Cand->FailureKind) { 9646 case ovl_fail_too_many_arguments: 9647 case ovl_fail_too_few_arguments: 9648 return DiagnoseArityMismatch(S, Cand, NumArgs); 9649 9650 case ovl_fail_bad_deduction: 9651 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9652 9653 case ovl_fail_illegal_constructor: { 9654 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9655 << (Fn->getPrimaryTemplate() ? 1 : 0); 9656 MaybeEmitInheritedConstructorNote(S, Fn); 9657 return; 9658 } 9659 9660 case ovl_fail_trivial_conversion: 9661 case ovl_fail_bad_final_conversion: 9662 case ovl_fail_final_conversion_not_exact: 9663 return S.NoteOverloadCandidate(Fn); 9664 9665 case ovl_fail_bad_conversion: { 9666 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9667 for (unsigned N = Cand->NumConversions; I != N; ++I) 9668 if (Cand->Conversions[I].isBad()) 9669 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9670 9671 // FIXME: this currently happens when we're called from SemaInit 9672 // when user-conversion overload fails. Figure out how to handle 9673 // those conditions and diagnose them well. 9674 return S.NoteOverloadCandidate(Fn); 9675 } 9676 9677 case ovl_fail_bad_target: 9678 return DiagnoseBadTarget(S, Cand); 9679 9680 case ovl_fail_enable_if: 9681 return DiagnoseFailedEnableIfAttr(S, Cand); 9682 9683 case ovl_fail_addr_not_available: { 9684 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9685 (void)Available; 9686 assert(!Available); 9687 break; 9688 } 9689 } 9690 } 9691 9692 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9693 // Desugar the type of the surrogate down to a function type, 9694 // retaining as many typedefs as possible while still showing 9695 // the function type (and, therefore, its parameter types). 9696 QualType FnType = Cand->Surrogate->getConversionType(); 9697 bool isLValueReference = false; 9698 bool isRValueReference = false; 9699 bool isPointer = false; 9700 if (const LValueReferenceType *FnTypeRef = 9701 FnType->getAs<LValueReferenceType>()) { 9702 FnType = FnTypeRef->getPointeeType(); 9703 isLValueReference = true; 9704 } else if (const RValueReferenceType *FnTypeRef = 9705 FnType->getAs<RValueReferenceType>()) { 9706 FnType = FnTypeRef->getPointeeType(); 9707 isRValueReference = true; 9708 } 9709 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9710 FnType = FnTypePtr->getPointeeType(); 9711 isPointer = true; 9712 } 9713 // Desugar down to a function type. 9714 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9715 // Reconstruct the pointer/reference as appropriate. 9716 if (isPointer) FnType = S.Context.getPointerType(FnType); 9717 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9718 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9719 9720 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9721 << FnType; 9722 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9723 } 9724 9725 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9726 SourceLocation OpLoc, 9727 OverloadCandidate *Cand) { 9728 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9729 std::string TypeStr("operator"); 9730 TypeStr += Opc; 9731 TypeStr += "("; 9732 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9733 if (Cand->NumConversions == 1) { 9734 TypeStr += ")"; 9735 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9736 } else { 9737 TypeStr += ", "; 9738 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9739 TypeStr += ")"; 9740 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9741 } 9742 } 9743 9744 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9745 OverloadCandidate *Cand) { 9746 unsigned NoOperands = Cand->NumConversions; 9747 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9748 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9749 if (ICS.isBad()) break; // all meaningless after first invalid 9750 if (!ICS.isAmbiguous()) continue; 9751 9752 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9753 S.PDiag(diag::note_ambiguous_type_conversion)); 9754 } 9755 } 9756 9757 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9758 if (Cand->Function) 9759 return Cand->Function->getLocation(); 9760 if (Cand->IsSurrogate) 9761 return Cand->Surrogate->getLocation(); 9762 return SourceLocation(); 9763 } 9764 9765 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9766 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9767 case Sema::TDK_Success: 9768 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9769 9770 case Sema::TDK_Invalid: 9771 case Sema::TDK_Incomplete: 9772 return 1; 9773 9774 case Sema::TDK_Underqualified: 9775 case Sema::TDK_Inconsistent: 9776 return 2; 9777 9778 case Sema::TDK_SubstitutionFailure: 9779 case Sema::TDK_DeducedMismatch: 9780 case Sema::TDK_NonDeducedMismatch: 9781 case Sema::TDK_MiscellaneousDeductionFailure: 9782 return 3; 9783 9784 case Sema::TDK_InstantiationDepth: 9785 case Sema::TDK_FailedOverloadResolution: 9786 return 4; 9787 9788 case Sema::TDK_InvalidExplicitArguments: 9789 return 5; 9790 9791 case Sema::TDK_TooManyArguments: 9792 case Sema::TDK_TooFewArguments: 9793 return 6; 9794 } 9795 llvm_unreachable("Unhandled deduction result"); 9796 } 9797 9798 namespace { 9799 struct CompareOverloadCandidatesForDisplay { 9800 Sema &S; 9801 SourceLocation Loc; 9802 size_t NumArgs; 9803 9804 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9805 : S(S), NumArgs(nArgs) {} 9806 9807 bool operator()(const OverloadCandidate *L, 9808 const OverloadCandidate *R) { 9809 // Fast-path this check. 9810 if (L == R) return false; 9811 9812 // Order first by viability. 9813 if (L->Viable) { 9814 if (!R->Viable) return true; 9815 9816 // TODO: introduce a tri-valued comparison for overload 9817 // candidates. Would be more worthwhile if we had a sort 9818 // that could exploit it. 9819 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9820 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9821 } else if (R->Viable) 9822 return false; 9823 9824 assert(L->Viable == R->Viable); 9825 9826 // Criteria by which we can sort non-viable candidates: 9827 if (!L->Viable) { 9828 // 1. Arity mismatches come after other candidates. 9829 if (L->FailureKind == ovl_fail_too_many_arguments || 9830 L->FailureKind == ovl_fail_too_few_arguments) { 9831 if (R->FailureKind == ovl_fail_too_many_arguments || 9832 R->FailureKind == ovl_fail_too_few_arguments) { 9833 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9834 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9835 if (LDist == RDist) { 9836 if (L->FailureKind == R->FailureKind) 9837 // Sort non-surrogates before surrogates. 9838 return !L->IsSurrogate && R->IsSurrogate; 9839 // Sort candidates requiring fewer parameters than there were 9840 // arguments given after candidates requiring more parameters 9841 // than there were arguments given. 9842 return L->FailureKind == ovl_fail_too_many_arguments; 9843 } 9844 return LDist < RDist; 9845 } 9846 return false; 9847 } 9848 if (R->FailureKind == ovl_fail_too_many_arguments || 9849 R->FailureKind == ovl_fail_too_few_arguments) 9850 return true; 9851 9852 // 2. Bad conversions come first and are ordered by the number 9853 // of bad conversions and quality of good conversions. 9854 if (L->FailureKind == ovl_fail_bad_conversion) { 9855 if (R->FailureKind != ovl_fail_bad_conversion) 9856 return true; 9857 9858 // The conversion that can be fixed with a smaller number of changes, 9859 // comes first. 9860 unsigned numLFixes = L->Fix.NumConversionsFixed; 9861 unsigned numRFixes = R->Fix.NumConversionsFixed; 9862 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9863 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9864 if (numLFixes != numRFixes) { 9865 return numLFixes < numRFixes; 9866 } 9867 9868 // If there's any ordering between the defined conversions... 9869 // FIXME: this might not be transitive. 9870 assert(L->NumConversions == R->NumConversions); 9871 9872 int leftBetter = 0; 9873 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9874 for (unsigned E = L->NumConversions; I != E; ++I) { 9875 switch (CompareImplicitConversionSequences(S, Loc, 9876 L->Conversions[I], 9877 R->Conversions[I])) { 9878 case ImplicitConversionSequence::Better: 9879 leftBetter++; 9880 break; 9881 9882 case ImplicitConversionSequence::Worse: 9883 leftBetter--; 9884 break; 9885 9886 case ImplicitConversionSequence::Indistinguishable: 9887 break; 9888 } 9889 } 9890 if (leftBetter > 0) return true; 9891 if (leftBetter < 0) return false; 9892 9893 } else if (R->FailureKind == ovl_fail_bad_conversion) 9894 return false; 9895 9896 if (L->FailureKind == ovl_fail_bad_deduction) { 9897 if (R->FailureKind != ovl_fail_bad_deduction) 9898 return true; 9899 9900 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9901 return RankDeductionFailure(L->DeductionFailure) 9902 < RankDeductionFailure(R->DeductionFailure); 9903 } else if (R->FailureKind == ovl_fail_bad_deduction) 9904 return false; 9905 9906 // TODO: others? 9907 } 9908 9909 // Sort everything else by location. 9910 SourceLocation LLoc = GetLocationForCandidate(L); 9911 SourceLocation RLoc = GetLocationForCandidate(R); 9912 9913 // Put candidates without locations (e.g. builtins) at the end. 9914 if (LLoc.isInvalid()) return false; 9915 if (RLoc.isInvalid()) return true; 9916 9917 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9918 } 9919 }; 9920 } 9921 9922 /// CompleteNonViableCandidate - Normally, overload resolution only 9923 /// computes up to the first. Produces the FixIt set if possible. 9924 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9925 ArrayRef<Expr *> Args) { 9926 assert(!Cand->Viable); 9927 9928 // Don't do anything on failures other than bad conversion. 9929 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9930 9931 // We only want the FixIts if all the arguments can be corrected. 9932 bool Unfixable = false; 9933 // Use a implicit copy initialization to check conversion fixes. 9934 Cand->Fix.setConversionChecker(TryCopyInitialization); 9935 9936 // Skip forward to the first bad conversion. 9937 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9938 unsigned ConvCount = Cand->NumConversions; 9939 while (true) { 9940 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9941 ConvIdx++; 9942 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9943 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9944 break; 9945 } 9946 } 9947 9948 if (ConvIdx == ConvCount) 9949 return; 9950 9951 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9952 "remaining conversion is initialized?"); 9953 9954 // FIXME: this should probably be preserved from the overload 9955 // operation somehow. 9956 bool SuppressUserConversions = false; 9957 9958 const FunctionProtoType* Proto; 9959 unsigned ArgIdx = ConvIdx; 9960 9961 if (Cand->IsSurrogate) { 9962 QualType ConvType 9963 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9964 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9965 ConvType = ConvPtrType->getPointeeType(); 9966 Proto = ConvType->getAs<FunctionProtoType>(); 9967 ArgIdx--; 9968 } else if (Cand->Function) { 9969 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9970 if (isa<CXXMethodDecl>(Cand->Function) && 9971 !isa<CXXConstructorDecl>(Cand->Function)) 9972 ArgIdx--; 9973 } else { 9974 // Builtin binary operator with a bad first conversion. 9975 assert(ConvCount <= 3); 9976 for (; ConvIdx != ConvCount; ++ConvIdx) 9977 Cand->Conversions[ConvIdx] 9978 = TryCopyInitialization(S, Args[ConvIdx], 9979 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9980 SuppressUserConversions, 9981 /*InOverloadResolution*/ true, 9982 /*AllowObjCWritebackConversion=*/ 9983 S.getLangOpts().ObjCAutoRefCount); 9984 return; 9985 } 9986 9987 // Fill in the rest of the conversions. 9988 unsigned NumParams = Proto->getNumParams(); 9989 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9990 if (ArgIdx < NumParams) { 9991 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9992 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9993 /*InOverloadResolution=*/true, 9994 /*AllowObjCWritebackConversion=*/ 9995 S.getLangOpts().ObjCAutoRefCount); 9996 // Store the FixIt in the candidate if it exists. 9997 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9998 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9999 } 10000 else 10001 Cand->Conversions[ConvIdx].setEllipsis(); 10002 } 10003 } 10004 10005 /// PrintOverloadCandidates - When overload resolution fails, prints 10006 /// diagnostic messages containing the candidates in the candidate 10007 /// set. 10008 void OverloadCandidateSet::NoteCandidates(Sema &S, 10009 OverloadCandidateDisplayKind OCD, 10010 ArrayRef<Expr *> Args, 10011 StringRef Opc, 10012 SourceLocation OpLoc) { 10013 // Sort the candidates by viability and position. Sorting directly would 10014 // be prohibitive, so we make a set of pointers and sort those. 10015 SmallVector<OverloadCandidate*, 32> Cands; 10016 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10017 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10018 if (Cand->Viable) 10019 Cands.push_back(Cand); 10020 else if (OCD == OCD_AllCandidates) { 10021 CompleteNonViableCandidate(S, Cand, Args); 10022 if (Cand->Function || Cand->IsSurrogate) 10023 Cands.push_back(Cand); 10024 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10025 // want to list every possible builtin candidate. 10026 } 10027 } 10028 10029 std::sort(Cands.begin(), Cands.end(), 10030 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10031 10032 bool ReportedAmbiguousConversions = false; 10033 10034 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10035 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10036 unsigned CandsShown = 0; 10037 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10038 OverloadCandidate *Cand = *I; 10039 10040 // Set an arbitrary limit on the number of candidate functions we'll spam 10041 // the user with. FIXME: This limit should depend on details of the 10042 // candidate list. 10043 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10044 break; 10045 } 10046 ++CandsShown; 10047 10048 if (Cand->Function) 10049 NoteFunctionCandidate(S, Cand, Args.size(), 10050 /*TakingCandidateAddress=*/false); 10051 else if (Cand->IsSurrogate) 10052 NoteSurrogateCandidate(S, Cand); 10053 else { 10054 assert(Cand->Viable && 10055 "Non-viable built-in candidates are not added to Cands."); 10056 // Generally we only see ambiguities including viable builtin 10057 // operators if overload resolution got screwed up by an 10058 // ambiguous user-defined conversion. 10059 // 10060 // FIXME: It's quite possible for different conversions to see 10061 // different ambiguities, though. 10062 if (!ReportedAmbiguousConversions) { 10063 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10064 ReportedAmbiguousConversions = true; 10065 } 10066 10067 // If this is a viable builtin, print it. 10068 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10069 } 10070 } 10071 10072 if (I != E) 10073 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10074 } 10075 10076 static SourceLocation 10077 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10078 return Cand->Specialization ? Cand->Specialization->getLocation() 10079 : SourceLocation(); 10080 } 10081 10082 namespace { 10083 struct CompareTemplateSpecCandidatesForDisplay { 10084 Sema &S; 10085 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10086 10087 bool operator()(const TemplateSpecCandidate *L, 10088 const TemplateSpecCandidate *R) { 10089 // Fast-path this check. 10090 if (L == R) 10091 return false; 10092 10093 // Assuming that both candidates are not matches... 10094 10095 // Sort by the ranking of deduction failures. 10096 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10097 return RankDeductionFailure(L->DeductionFailure) < 10098 RankDeductionFailure(R->DeductionFailure); 10099 10100 // Sort everything else by location. 10101 SourceLocation LLoc = GetLocationForCandidate(L); 10102 SourceLocation RLoc = GetLocationForCandidate(R); 10103 10104 // Put candidates without locations (e.g. builtins) at the end. 10105 if (LLoc.isInvalid()) 10106 return false; 10107 if (RLoc.isInvalid()) 10108 return true; 10109 10110 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10111 } 10112 }; 10113 } 10114 10115 /// Diagnose a template argument deduction failure. 10116 /// We are treating these failures as overload failures due to bad 10117 /// deductions. 10118 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10119 bool ForTakingAddress) { 10120 DiagnoseBadDeduction(S, Specialization, // pattern 10121 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10122 } 10123 10124 void TemplateSpecCandidateSet::destroyCandidates() { 10125 for (iterator i = begin(), e = end(); i != e; ++i) { 10126 i->DeductionFailure.Destroy(); 10127 } 10128 } 10129 10130 void TemplateSpecCandidateSet::clear() { 10131 destroyCandidates(); 10132 Candidates.clear(); 10133 } 10134 10135 /// NoteCandidates - When no template specialization match is found, prints 10136 /// diagnostic messages containing the non-matching specializations that form 10137 /// the candidate set. 10138 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10139 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10140 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10141 // Sort the candidates by position (assuming no candidate is a match). 10142 // Sorting directly would be prohibitive, so we make a set of pointers 10143 // and sort those. 10144 SmallVector<TemplateSpecCandidate *, 32> Cands; 10145 Cands.reserve(size()); 10146 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10147 if (Cand->Specialization) 10148 Cands.push_back(Cand); 10149 // Otherwise, this is a non-matching builtin candidate. We do not, 10150 // in general, want to list every possible builtin candidate. 10151 } 10152 10153 std::sort(Cands.begin(), Cands.end(), 10154 CompareTemplateSpecCandidatesForDisplay(S)); 10155 10156 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10157 // for generalization purposes (?). 10158 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10159 10160 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10161 unsigned CandsShown = 0; 10162 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10163 TemplateSpecCandidate *Cand = *I; 10164 10165 // Set an arbitrary limit on the number of candidates we'll spam 10166 // the user with. FIXME: This limit should depend on details of the 10167 // candidate list. 10168 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10169 break; 10170 ++CandsShown; 10171 10172 assert(Cand->Specialization && 10173 "Non-matching built-in candidates are not added to Cands."); 10174 Cand->NoteDeductionFailure(S, ForTakingAddress); 10175 } 10176 10177 if (I != E) 10178 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10179 } 10180 10181 // [PossiblyAFunctionType] --> [Return] 10182 // NonFunctionType --> NonFunctionType 10183 // R (A) --> R(A) 10184 // R (*)(A) --> R (A) 10185 // R (&)(A) --> R (A) 10186 // R (S::*)(A) --> R (A) 10187 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10188 QualType Ret = PossiblyAFunctionType; 10189 if (const PointerType *ToTypePtr = 10190 PossiblyAFunctionType->getAs<PointerType>()) 10191 Ret = ToTypePtr->getPointeeType(); 10192 else if (const ReferenceType *ToTypeRef = 10193 PossiblyAFunctionType->getAs<ReferenceType>()) 10194 Ret = ToTypeRef->getPointeeType(); 10195 else if (const MemberPointerType *MemTypePtr = 10196 PossiblyAFunctionType->getAs<MemberPointerType>()) 10197 Ret = MemTypePtr->getPointeeType(); 10198 Ret = 10199 Context.getCanonicalType(Ret).getUnqualifiedType(); 10200 return Ret; 10201 } 10202 10203 namespace { 10204 // A helper class to help with address of function resolution 10205 // - allows us to avoid passing around all those ugly parameters 10206 class AddressOfFunctionResolver { 10207 Sema& S; 10208 Expr* SourceExpr; 10209 const QualType& TargetType; 10210 QualType TargetFunctionType; // Extracted function type from target type 10211 10212 bool Complain; 10213 //DeclAccessPair& ResultFunctionAccessPair; 10214 ASTContext& Context; 10215 10216 bool TargetTypeIsNonStaticMemberFunction; 10217 bool FoundNonTemplateFunction; 10218 bool StaticMemberFunctionFromBoundPointer; 10219 bool HasComplained; 10220 10221 OverloadExpr::FindResult OvlExprInfo; 10222 OverloadExpr *OvlExpr; 10223 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10224 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10225 TemplateSpecCandidateSet FailedCandidates; 10226 10227 public: 10228 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10229 const QualType &TargetType, bool Complain) 10230 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10231 Complain(Complain), Context(S.getASTContext()), 10232 TargetTypeIsNonStaticMemberFunction( 10233 !!TargetType->getAs<MemberPointerType>()), 10234 FoundNonTemplateFunction(false), 10235 StaticMemberFunctionFromBoundPointer(false), 10236 HasComplained(false), 10237 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10238 OvlExpr(OvlExprInfo.Expression), 10239 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10240 ExtractUnqualifiedFunctionTypeFromTargetType(); 10241 10242 if (TargetFunctionType->isFunctionType()) { 10243 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10244 if (!UME->isImplicitAccess() && 10245 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10246 StaticMemberFunctionFromBoundPointer = true; 10247 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10248 DeclAccessPair dap; 10249 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10250 OvlExpr, false, &dap)) { 10251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10252 if (!Method->isStatic()) { 10253 // If the target type is a non-function type and the function found 10254 // is a non-static member function, pretend as if that was the 10255 // target, it's the only possible type to end up with. 10256 TargetTypeIsNonStaticMemberFunction = true; 10257 10258 // And skip adding the function if its not in the proper form. 10259 // We'll diagnose this due to an empty set of functions. 10260 if (!OvlExprInfo.HasFormOfMemberPointer) 10261 return; 10262 } 10263 10264 Matches.push_back(std::make_pair(dap, Fn)); 10265 } 10266 return; 10267 } 10268 10269 if (OvlExpr->hasExplicitTemplateArgs()) 10270 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10271 10272 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10273 // C++ [over.over]p4: 10274 // If more than one function is selected, [...] 10275 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10276 if (FoundNonTemplateFunction) 10277 EliminateAllTemplateMatches(); 10278 else 10279 EliminateAllExceptMostSpecializedTemplate(); 10280 } 10281 } 10282 10283 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10284 Matches.size() > 1) 10285 EliminateSuboptimalCudaMatches(); 10286 } 10287 10288 bool hasComplained() const { return HasComplained; } 10289 10290 private: 10291 // Is A considered a better overload candidate for the desired type than B? 10292 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10293 return hasBetterEnableIfAttrs(S, A, B); 10294 } 10295 10296 // Returns true if we've eliminated any (read: all but one) candidates, false 10297 // otherwise. 10298 bool eliminiateSuboptimalOverloadCandidates() { 10299 // Same algorithm as overload resolution -- one pass to pick the "best", 10300 // another pass to be sure that nothing is better than the best. 10301 auto Best = Matches.begin(); 10302 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10303 if (isBetterCandidate(I->second, Best->second)) 10304 Best = I; 10305 10306 const FunctionDecl *BestFn = Best->second; 10307 auto IsBestOrInferiorToBest = [this, BestFn]( 10308 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10309 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10310 }; 10311 10312 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10313 // option, so we can potentially give the user a better error 10314 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10315 return false; 10316 Matches[0] = *Best; 10317 Matches.resize(1); 10318 return true; 10319 } 10320 10321 bool isTargetTypeAFunction() const { 10322 return TargetFunctionType->isFunctionType(); 10323 } 10324 10325 // [ToType] [Return] 10326 10327 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10328 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10329 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10330 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10331 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10332 } 10333 10334 // return true if any matching specializations were found 10335 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10336 const DeclAccessPair& CurAccessFunPair) { 10337 if (CXXMethodDecl *Method 10338 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10339 // Skip non-static function templates when converting to pointer, and 10340 // static when converting to member pointer. 10341 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10342 return false; 10343 } 10344 else if (TargetTypeIsNonStaticMemberFunction) 10345 return false; 10346 10347 // C++ [over.over]p2: 10348 // If the name is a function template, template argument deduction is 10349 // done (14.8.2.2), and if the argument deduction succeeds, the 10350 // resulting template argument list is used to generate a single 10351 // function template specialization, which is added to the set of 10352 // overloaded functions considered. 10353 FunctionDecl *Specialization = nullptr; 10354 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10355 if (Sema::TemplateDeductionResult Result 10356 = S.DeduceTemplateArguments(FunctionTemplate, 10357 &OvlExplicitTemplateArgs, 10358 TargetFunctionType, Specialization, 10359 Info, /*InOverloadResolution=*/true)) { 10360 // Make a note of the failed deduction for diagnostics. 10361 FailedCandidates.addCandidate() 10362 .set(FunctionTemplate->getTemplatedDecl(), 10363 MakeDeductionFailureInfo(Context, Result, Info)); 10364 return false; 10365 } 10366 10367 // Template argument deduction ensures that we have an exact match or 10368 // compatible pointer-to-function arguments that would be adjusted by ICS. 10369 // This function template specicalization works. 10370 assert(S.isSameOrCompatibleFunctionType( 10371 Context.getCanonicalType(Specialization->getType()), 10372 Context.getCanonicalType(TargetFunctionType))); 10373 10374 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10375 return false; 10376 10377 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10378 return true; 10379 } 10380 10381 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10382 const DeclAccessPair& CurAccessFunPair) { 10383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10384 // Skip non-static functions when converting to pointer, and static 10385 // when converting to member pointer. 10386 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10387 return false; 10388 } 10389 else if (TargetTypeIsNonStaticMemberFunction) 10390 return false; 10391 10392 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10393 if (S.getLangOpts().CUDA) 10394 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10395 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10396 return false; 10397 10398 // If any candidate has a placeholder return type, trigger its deduction 10399 // now. 10400 if (S.getLangOpts().CPlusPlus14 && 10401 FunDecl->getReturnType()->isUndeducedType() && 10402 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10403 HasComplained |= Complain; 10404 return false; 10405 } 10406 10407 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10408 return false; 10409 10410 QualType ResultTy; 10411 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10412 FunDecl->getType()) || 10413 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10414 ResultTy) || 10415 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10416 Matches.push_back(std::make_pair( 10417 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10418 FoundNonTemplateFunction = true; 10419 return true; 10420 } 10421 } 10422 10423 return false; 10424 } 10425 10426 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10427 bool Ret = false; 10428 10429 // If the overload expression doesn't have the form of a pointer to 10430 // member, don't try to convert it to a pointer-to-member type. 10431 if (IsInvalidFormOfPointerToMemberFunction()) 10432 return false; 10433 10434 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10435 E = OvlExpr->decls_end(); 10436 I != E; ++I) { 10437 // Look through any using declarations to find the underlying function. 10438 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10439 10440 // C++ [over.over]p3: 10441 // Non-member functions and static member functions match 10442 // targets of type "pointer-to-function" or "reference-to-function." 10443 // Nonstatic member functions match targets of 10444 // type "pointer-to-member-function." 10445 // Note that according to DR 247, the containing class does not matter. 10446 if (FunctionTemplateDecl *FunctionTemplate 10447 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10448 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10449 Ret = true; 10450 } 10451 // If we have explicit template arguments supplied, skip non-templates. 10452 else if (!OvlExpr->hasExplicitTemplateArgs() && 10453 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10454 Ret = true; 10455 } 10456 assert(Ret || Matches.empty()); 10457 return Ret; 10458 } 10459 10460 void EliminateAllExceptMostSpecializedTemplate() { 10461 // [...] and any given function template specialization F1 is 10462 // eliminated if the set contains a second function template 10463 // specialization whose function template is more specialized 10464 // than the function template of F1 according to the partial 10465 // ordering rules of 14.5.5.2. 10466 10467 // The algorithm specified above is quadratic. We instead use a 10468 // two-pass algorithm (similar to the one used to identify the 10469 // best viable function in an overload set) that identifies the 10470 // best function template (if it exists). 10471 10472 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10473 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10474 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10475 10476 // TODO: It looks like FailedCandidates does not serve much purpose 10477 // here, since the no_viable diagnostic has index 0. 10478 UnresolvedSetIterator Result = S.getMostSpecialized( 10479 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10480 SourceExpr->getLocStart(), S.PDiag(), 10481 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10482 .second->getDeclName(), 10483 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10484 Complain, TargetFunctionType); 10485 10486 if (Result != MatchesCopy.end()) { 10487 // Make it the first and only element 10488 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10489 Matches[0].second = cast<FunctionDecl>(*Result); 10490 Matches.resize(1); 10491 } else 10492 HasComplained |= Complain; 10493 } 10494 10495 void EliminateAllTemplateMatches() { 10496 // [...] any function template specializations in the set are 10497 // eliminated if the set also contains a non-template function, [...] 10498 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10499 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10500 ++I; 10501 else { 10502 Matches[I] = Matches[--N]; 10503 Matches.resize(N); 10504 } 10505 } 10506 } 10507 10508 void EliminateSuboptimalCudaMatches() { 10509 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10510 } 10511 10512 public: 10513 void ComplainNoMatchesFound() const { 10514 assert(Matches.empty()); 10515 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10516 << OvlExpr->getName() << TargetFunctionType 10517 << OvlExpr->getSourceRange(); 10518 if (FailedCandidates.empty()) 10519 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10520 /*TakingAddress=*/true); 10521 else { 10522 // We have some deduction failure messages. Use them to diagnose 10523 // the function templates, and diagnose the non-template candidates 10524 // normally. 10525 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10526 IEnd = OvlExpr->decls_end(); 10527 I != IEnd; ++I) 10528 if (FunctionDecl *Fun = 10529 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10530 if (!functionHasPassObjectSizeParams(Fun)) 10531 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10532 /*TakingAddress=*/true); 10533 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10534 } 10535 } 10536 10537 bool IsInvalidFormOfPointerToMemberFunction() const { 10538 return TargetTypeIsNonStaticMemberFunction && 10539 !OvlExprInfo.HasFormOfMemberPointer; 10540 } 10541 10542 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10543 // TODO: Should we condition this on whether any functions might 10544 // have matched, or is it more appropriate to do that in callers? 10545 // TODO: a fixit wouldn't hurt. 10546 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10547 << TargetType << OvlExpr->getSourceRange(); 10548 } 10549 10550 bool IsStaticMemberFunctionFromBoundPointer() const { 10551 return StaticMemberFunctionFromBoundPointer; 10552 } 10553 10554 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10555 S.Diag(OvlExpr->getLocStart(), 10556 diag::err_invalid_form_pointer_member_function) 10557 << OvlExpr->getSourceRange(); 10558 } 10559 10560 void ComplainOfInvalidConversion() const { 10561 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10562 << OvlExpr->getName() << TargetType; 10563 } 10564 10565 void ComplainMultipleMatchesFound() const { 10566 assert(Matches.size() > 1); 10567 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10568 << OvlExpr->getName() 10569 << OvlExpr->getSourceRange(); 10570 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10571 /*TakingAddress=*/true); 10572 } 10573 10574 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10575 10576 int getNumMatches() const { return Matches.size(); } 10577 10578 FunctionDecl* getMatchingFunctionDecl() const { 10579 if (Matches.size() != 1) return nullptr; 10580 return Matches[0].second; 10581 } 10582 10583 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10584 if (Matches.size() != 1) return nullptr; 10585 return &Matches[0].first; 10586 } 10587 }; 10588 } 10589 10590 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10591 /// an overloaded function (C++ [over.over]), where @p From is an 10592 /// expression with overloaded function type and @p ToType is the type 10593 /// we're trying to resolve to. For example: 10594 /// 10595 /// @code 10596 /// int f(double); 10597 /// int f(int); 10598 /// 10599 /// int (*pfd)(double) = f; // selects f(double) 10600 /// @endcode 10601 /// 10602 /// This routine returns the resulting FunctionDecl if it could be 10603 /// resolved, and NULL otherwise. When @p Complain is true, this 10604 /// routine will emit diagnostics if there is an error. 10605 FunctionDecl * 10606 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10607 QualType TargetType, 10608 bool Complain, 10609 DeclAccessPair &FoundResult, 10610 bool *pHadMultipleCandidates) { 10611 assert(AddressOfExpr->getType() == Context.OverloadTy); 10612 10613 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10614 Complain); 10615 int NumMatches = Resolver.getNumMatches(); 10616 FunctionDecl *Fn = nullptr; 10617 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10618 if (NumMatches == 0 && ShouldComplain) { 10619 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10620 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10621 else 10622 Resolver.ComplainNoMatchesFound(); 10623 } 10624 else if (NumMatches > 1 && ShouldComplain) 10625 Resolver.ComplainMultipleMatchesFound(); 10626 else if (NumMatches == 1) { 10627 Fn = Resolver.getMatchingFunctionDecl(); 10628 assert(Fn); 10629 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10630 if (Complain) { 10631 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10632 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10633 else 10634 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10635 } 10636 } 10637 10638 if (pHadMultipleCandidates) 10639 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10640 return Fn; 10641 } 10642 10643 /// \brief Given an expression that refers to an overloaded function, try to 10644 /// resolve that overloaded function expression down to a single function. 10645 /// 10646 /// This routine can only resolve template-ids that refer to a single function 10647 /// template, where that template-id refers to a single template whose template 10648 /// arguments are either provided by the template-id or have defaults, 10649 /// as described in C++0x [temp.arg.explicit]p3. 10650 /// 10651 /// If no template-ids are found, no diagnostics are emitted and NULL is 10652 /// returned. 10653 FunctionDecl * 10654 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10655 bool Complain, 10656 DeclAccessPair *FoundResult) { 10657 // C++ [over.over]p1: 10658 // [...] [Note: any redundant set of parentheses surrounding the 10659 // overloaded function name is ignored (5.1). ] 10660 // C++ [over.over]p1: 10661 // [...] The overloaded function name can be preceded by the & 10662 // operator. 10663 10664 // If we didn't actually find any template-ids, we're done. 10665 if (!ovl->hasExplicitTemplateArgs()) 10666 return nullptr; 10667 10668 TemplateArgumentListInfo ExplicitTemplateArgs; 10669 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10670 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10671 10672 // Look through all of the overloaded functions, searching for one 10673 // whose type matches exactly. 10674 FunctionDecl *Matched = nullptr; 10675 for (UnresolvedSetIterator I = ovl->decls_begin(), 10676 E = ovl->decls_end(); I != E; ++I) { 10677 // C++0x [temp.arg.explicit]p3: 10678 // [...] In contexts where deduction is done and fails, or in contexts 10679 // where deduction is not done, if a template argument list is 10680 // specified and it, along with any default template arguments, 10681 // identifies a single function template specialization, then the 10682 // template-id is an lvalue for the function template specialization. 10683 FunctionTemplateDecl *FunctionTemplate 10684 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10685 10686 // C++ [over.over]p2: 10687 // If the name is a function template, template argument deduction is 10688 // done (14.8.2.2), and if the argument deduction succeeds, the 10689 // resulting template argument list is used to generate a single 10690 // function template specialization, which is added to the set of 10691 // overloaded functions considered. 10692 FunctionDecl *Specialization = nullptr; 10693 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10694 if (TemplateDeductionResult Result 10695 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10696 Specialization, Info, 10697 /*InOverloadResolution=*/true)) { 10698 // Make a note of the failed deduction for diagnostics. 10699 // TODO: Actually use the failed-deduction info? 10700 FailedCandidates.addCandidate() 10701 .set(FunctionTemplate->getTemplatedDecl(), 10702 MakeDeductionFailureInfo(Context, Result, Info)); 10703 continue; 10704 } 10705 10706 assert(Specialization && "no specialization and no error?"); 10707 10708 // Multiple matches; we can't resolve to a single declaration. 10709 if (Matched) { 10710 if (Complain) { 10711 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10712 << ovl->getName(); 10713 NoteAllOverloadCandidates(ovl); 10714 } 10715 return nullptr; 10716 } 10717 10718 Matched = Specialization; 10719 if (FoundResult) *FoundResult = I.getPair(); 10720 } 10721 10722 if (Matched && getLangOpts().CPlusPlus14 && 10723 Matched->getReturnType()->isUndeducedType() && 10724 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10725 return nullptr; 10726 10727 return Matched; 10728 } 10729 10730 10731 10732 10733 // Resolve and fix an overloaded expression that can be resolved 10734 // because it identifies a single function template specialization. 10735 // 10736 // Last three arguments should only be supplied if Complain = true 10737 // 10738 // Return true if it was logically possible to so resolve the 10739 // expression, regardless of whether or not it succeeded. Always 10740 // returns true if 'complain' is set. 10741 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10742 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10743 bool complain, SourceRange OpRangeForComplaining, 10744 QualType DestTypeForComplaining, 10745 unsigned DiagIDForComplaining) { 10746 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10747 10748 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10749 10750 DeclAccessPair found; 10751 ExprResult SingleFunctionExpression; 10752 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10753 ovl.Expression, /*complain*/ false, &found)) { 10754 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10755 SrcExpr = ExprError(); 10756 return true; 10757 } 10758 10759 // It is only correct to resolve to an instance method if we're 10760 // resolving a form that's permitted to be a pointer to member. 10761 // Otherwise we'll end up making a bound member expression, which 10762 // is illegal in all the contexts we resolve like this. 10763 if (!ovl.HasFormOfMemberPointer && 10764 isa<CXXMethodDecl>(fn) && 10765 cast<CXXMethodDecl>(fn)->isInstance()) { 10766 if (!complain) return false; 10767 10768 Diag(ovl.Expression->getExprLoc(), 10769 diag::err_bound_member_function) 10770 << 0 << ovl.Expression->getSourceRange(); 10771 10772 // TODO: I believe we only end up here if there's a mix of 10773 // static and non-static candidates (otherwise the expression 10774 // would have 'bound member' type, not 'overload' type). 10775 // Ideally we would note which candidate was chosen and why 10776 // the static candidates were rejected. 10777 SrcExpr = ExprError(); 10778 return true; 10779 } 10780 10781 // Fix the expression to refer to 'fn'. 10782 SingleFunctionExpression = 10783 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10784 10785 // If desired, do function-to-pointer decay. 10786 if (doFunctionPointerConverion) { 10787 SingleFunctionExpression = 10788 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10789 if (SingleFunctionExpression.isInvalid()) { 10790 SrcExpr = ExprError(); 10791 return true; 10792 } 10793 } 10794 } 10795 10796 if (!SingleFunctionExpression.isUsable()) { 10797 if (complain) { 10798 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10799 << ovl.Expression->getName() 10800 << DestTypeForComplaining 10801 << OpRangeForComplaining 10802 << ovl.Expression->getQualifierLoc().getSourceRange(); 10803 NoteAllOverloadCandidates(SrcExpr.get()); 10804 10805 SrcExpr = ExprError(); 10806 return true; 10807 } 10808 10809 return false; 10810 } 10811 10812 SrcExpr = SingleFunctionExpression; 10813 return true; 10814 } 10815 10816 /// \brief Add a single candidate to the overload set. 10817 static void AddOverloadedCallCandidate(Sema &S, 10818 DeclAccessPair FoundDecl, 10819 TemplateArgumentListInfo *ExplicitTemplateArgs, 10820 ArrayRef<Expr *> Args, 10821 OverloadCandidateSet &CandidateSet, 10822 bool PartialOverloading, 10823 bool KnownValid) { 10824 NamedDecl *Callee = FoundDecl.getDecl(); 10825 if (isa<UsingShadowDecl>(Callee)) 10826 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10827 10828 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10829 if (ExplicitTemplateArgs) { 10830 assert(!KnownValid && "Explicit template arguments?"); 10831 return; 10832 } 10833 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10834 /*SuppressUsedConversions=*/false, 10835 PartialOverloading); 10836 return; 10837 } 10838 10839 if (FunctionTemplateDecl *FuncTemplate 10840 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10841 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10842 ExplicitTemplateArgs, Args, CandidateSet, 10843 /*SuppressUsedConversions=*/false, 10844 PartialOverloading); 10845 return; 10846 } 10847 10848 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10849 } 10850 10851 /// \brief Add the overload candidates named by callee and/or found by argument 10852 /// dependent lookup to the given overload set. 10853 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10854 ArrayRef<Expr *> Args, 10855 OverloadCandidateSet &CandidateSet, 10856 bool PartialOverloading) { 10857 10858 #ifndef NDEBUG 10859 // Verify that ArgumentDependentLookup is consistent with the rules 10860 // in C++0x [basic.lookup.argdep]p3: 10861 // 10862 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10863 // and let Y be the lookup set produced by argument dependent 10864 // lookup (defined as follows). If X contains 10865 // 10866 // -- a declaration of a class member, or 10867 // 10868 // -- a block-scope function declaration that is not a 10869 // using-declaration, or 10870 // 10871 // -- a declaration that is neither a function or a function 10872 // template 10873 // 10874 // then Y is empty. 10875 10876 if (ULE->requiresADL()) { 10877 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10878 E = ULE->decls_end(); I != E; ++I) { 10879 assert(!(*I)->getDeclContext()->isRecord()); 10880 assert(isa<UsingShadowDecl>(*I) || 10881 !(*I)->getDeclContext()->isFunctionOrMethod()); 10882 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10883 } 10884 } 10885 #endif 10886 10887 // It would be nice to avoid this copy. 10888 TemplateArgumentListInfo TABuffer; 10889 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10890 if (ULE->hasExplicitTemplateArgs()) { 10891 ULE->copyTemplateArgumentsInto(TABuffer); 10892 ExplicitTemplateArgs = &TABuffer; 10893 } 10894 10895 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10896 E = ULE->decls_end(); I != E; ++I) 10897 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10898 CandidateSet, PartialOverloading, 10899 /*KnownValid*/ true); 10900 10901 if (ULE->requiresADL()) 10902 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10903 Args, ExplicitTemplateArgs, 10904 CandidateSet, PartialOverloading); 10905 } 10906 10907 /// Determine whether a declaration with the specified name could be moved into 10908 /// a different namespace. 10909 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10910 switch (Name.getCXXOverloadedOperator()) { 10911 case OO_New: case OO_Array_New: 10912 case OO_Delete: case OO_Array_Delete: 10913 return false; 10914 10915 default: 10916 return true; 10917 } 10918 } 10919 10920 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10921 /// template, where the non-dependent name was declared after the template 10922 /// was defined. This is common in code written for a compilers which do not 10923 /// correctly implement two-stage name lookup. 10924 /// 10925 /// Returns true if a viable candidate was found and a diagnostic was issued. 10926 static bool 10927 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10928 const CXXScopeSpec &SS, LookupResult &R, 10929 OverloadCandidateSet::CandidateSetKind CSK, 10930 TemplateArgumentListInfo *ExplicitTemplateArgs, 10931 ArrayRef<Expr *> Args, 10932 bool *DoDiagnoseEmptyLookup = nullptr) { 10933 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10934 return false; 10935 10936 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10937 if (DC->isTransparentContext()) 10938 continue; 10939 10940 SemaRef.LookupQualifiedName(R, DC); 10941 10942 if (!R.empty()) { 10943 R.suppressDiagnostics(); 10944 10945 if (isa<CXXRecordDecl>(DC)) { 10946 // Don't diagnose names we find in classes; we get much better 10947 // diagnostics for these from DiagnoseEmptyLookup. 10948 R.clear(); 10949 if (DoDiagnoseEmptyLookup) 10950 *DoDiagnoseEmptyLookup = true; 10951 return false; 10952 } 10953 10954 OverloadCandidateSet Candidates(FnLoc, CSK); 10955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10956 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10957 ExplicitTemplateArgs, Args, 10958 Candidates, false, /*KnownValid*/ false); 10959 10960 OverloadCandidateSet::iterator Best; 10961 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10962 // No viable functions. Don't bother the user with notes for functions 10963 // which don't work and shouldn't be found anyway. 10964 R.clear(); 10965 return false; 10966 } 10967 10968 // Find the namespaces where ADL would have looked, and suggest 10969 // declaring the function there instead. 10970 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10971 Sema::AssociatedClassSet AssociatedClasses; 10972 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10973 AssociatedNamespaces, 10974 AssociatedClasses); 10975 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10976 if (canBeDeclaredInNamespace(R.getLookupName())) { 10977 DeclContext *Std = SemaRef.getStdNamespace(); 10978 for (Sema::AssociatedNamespaceSet::iterator 10979 it = AssociatedNamespaces.begin(), 10980 end = AssociatedNamespaces.end(); it != end; ++it) { 10981 // Never suggest declaring a function within namespace 'std'. 10982 if (Std && Std->Encloses(*it)) 10983 continue; 10984 10985 // Never suggest declaring a function within a namespace with a 10986 // reserved name, like __gnu_cxx. 10987 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10988 if (NS && 10989 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10990 continue; 10991 10992 SuggestedNamespaces.insert(*it); 10993 } 10994 } 10995 10996 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10997 << R.getLookupName(); 10998 if (SuggestedNamespaces.empty()) { 10999 SemaRef.Diag(Best->Function->getLocation(), 11000 diag::note_not_found_by_two_phase_lookup) 11001 << R.getLookupName() << 0; 11002 } else if (SuggestedNamespaces.size() == 1) { 11003 SemaRef.Diag(Best->Function->getLocation(), 11004 diag::note_not_found_by_two_phase_lookup) 11005 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11006 } else { 11007 // FIXME: It would be useful to list the associated namespaces here, 11008 // but the diagnostics infrastructure doesn't provide a way to produce 11009 // a localized representation of a list of items. 11010 SemaRef.Diag(Best->Function->getLocation(), 11011 diag::note_not_found_by_two_phase_lookup) 11012 << R.getLookupName() << 2; 11013 } 11014 11015 // Try to recover by calling this function. 11016 return true; 11017 } 11018 11019 R.clear(); 11020 } 11021 11022 return false; 11023 } 11024 11025 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11026 /// template, where the non-dependent operator was declared after the template 11027 /// was defined. 11028 /// 11029 /// Returns true if a viable candidate was found and a diagnostic was issued. 11030 static bool 11031 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11032 SourceLocation OpLoc, 11033 ArrayRef<Expr *> Args) { 11034 DeclarationName OpName = 11035 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11036 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11037 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11038 OverloadCandidateSet::CSK_Operator, 11039 /*ExplicitTemplateArgs=*/nullptr, Args); 11040 } 11041 11042 namespace { 11043 class BuildRecoveryCallExprRAII { 11044 Sema &SemaRef; 11045 public: 11046 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11047 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11048 SemaRef.IsBuildingRecoveryCallExpr = true; 11049 } 11050 11051 ~BuildRecoveryCallExprRAII() { 11052 SemaRef.IsBuildingRecoveryCallExpr = false; 11053 } 11054 }; 11055 11056 } 11057 11058 static std::unique_ptr<CorrectionCandidateCallback> 11059 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11060 bool HasTemplateArgs, bool AllowTypoCorrection) { 11061 if (!AllowTypoCorrection) 11062 return llvm::make_unique<NoTypoCorrectionCCC>(); 11063 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11064 HasTemplateArgs, ME); 11065 } 11066 11067 /// Attempts to recover from a call where no functions were found. 11068 /// 11069 /// Returns true if new candidates were found. 11070 static ExprResult 11071 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11072 UnresolvedLookupExpr *ULE, 11073 SourceLocation LParenLoc, 11074 MutableArrayRef<Expr *> Args, 11075 SourceLocation RParenLoc, 11076 bool EmptyLookup, bool AllowTypoCorrection) { 11077 // Do not try to recover if it is already building a recovery call. 11078 // This stops infinite loops for template instantiations like 11079 // 11080 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11081 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11082 // 11083 if (SemaRef.IsBuildingRecoveryCallExpr) 11084 return ExprError(); 11085 BuildRecoveryCallExprRAII RCE(SemaRef); 11086 11087 CXXScopeSpec SS; 11088 SS.Adopt(ULE->getQualifierLoc()); 11089 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11090 11091 TemplateArgumentListInfo TABuffer; 11092 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11093 if (ULE->hasExplicitTemplateArgs()) { 11094 ULE->copyTemplateArgumentsInto(TABuffer); 11095 ExplicitTemplateArgs = &TABuffer; 11096 } 11097 11098 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11099 Sema::LookupOrdinaryName); 11100 bool DoDiagnoseEmptyLookup = EmptyLookup; 11101 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11102 OverloadCandidateSet::CSK_Normal, 11103 ExplicitTemplateArgs, Args, 11104 &DoDiagnoseEmptyLookup) && 11105 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11106 S, SS, R, 11107 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11108 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11109 ExplicitTemplateArgs, Args))) 11110 return ExprError(); 11111 11112 assert(!R.empty() && "lookup results empty despite recovery"); 11113 11114 // Build an implicit member call if appropriate. Just drop the 11115 // casts and such from the call, we don't really care. 11116 ExprResult NewFn = ExprError(); 11117 if ((*R.begin())->isCXXClassMember()) 11118 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11119 ExplicitTemplateArgs, S); 11120 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11121 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11122 ExplicitTemplateArgs); 11123 else 11124 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11125 11126 if (NewFn.isInvalid()) 11127 return ExprError(); 11128 11129 // This shouldn't cause an infinite loop because we're giving it 11130 // an expression with viable lookup results, which should never 11131 // end up here. 11132 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11133 MultiExprArg(Args.data(), Args.size()), 11134 RParenLoc); 11135 } 11136 11137 /// \brief Constructs and populates an OverloadedCandidateSet from 11138 /// the given function. 11139 /// \returns true when an the ExprResult output parameter has been set. 11140 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11141 UnresolvedLookupExpr *ULE, 11142 MultiExprArg Args, 11143 SourceLocation RParenLoc, 11144 OverloadCandidateSet *CandidateSet, 11145 ExprResult *Result) { 11146 #ifndef NDEBUG 11147 if (ULE->requiresADL()) { 11148 // To do ADL, we must have found an unqualified name. 11149 assert(!ULE->getQualifier() && "qualified name with ADL"); 11150 11151 // We don't perform ADL for implicit declarations of builtins. 11152 // Verify that this was correctly set up. 11153 FunctionDecl *F; 11154 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11155 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11156 F->getBuiltinID() && F->isImplicit()) 11157 llvm_unreachable("performing ADL for builtin"); 11158 11159 // We don't perform ADL in C. 11160 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11161 } 11162 #endif 11163 11164 UnbridgedCastsSet UnbridgedCasts; 11165 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11166 *Result = ExprError(); 11167 return true; 11168 } 11169 11170 // Add the functions denoted by the callee to the set of candidate 11171 // functions, including those from argument-dependent lookup. 11172 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11173 11174 if (getLangOpts().MSVCCompat && 11175 CurContext->isDependentContext() && !isSFINAEContext() && 11176 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11177 11178 OverloadCandidateSet::iterator Best; 11179 if (CandidateSet->empty() || 11180 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11181 OR_No_Viable_Function) { 11182 // In Microsoft mode, if we are inside a template class member function then 11183 // create a type dependent CallExpr. The goal is to postpone name lookup 11184 // to instantiation time to be able to search into type dependent base 11185 // classes. 11186 CallExpr *CE = new (Context) CallExpr( 11187 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11188 CE->setTypeDependent(true); 11189 CE->setValueDependent(true); 11190 CE->setInstantiationDependent(true); 11191 *Result = CE; 11192 return true; 11193 } 11194 } 11195 11196 if (CandidateSet->empty()) 11197 return false; 11198 11199 UnbridgedCasts.restore(); 11200 return false; 11201 } 11202 11203 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11204 /// the completed call expression. If overload resolution fails, emits 11205 /// diagnostics and returns ExprError() 11206 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11207 UnresolvedLookupExpr *ULE, 11208 SourceLocation LParenLoc, 11209 MultiExprArg Args, 11210 SourceLocation RParenLoc, 11211 Expr *ExecConfig, 11212 OverloadCandidateSet *CandidateSet, 11213 OverloadCandidateSet::iterator *Best, 11214 OverloadingResult OverloadResult, 11215 bool AllowTypoCorrection) { 11216 if (CandidateSet->empty()) 11217 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11218 RParenLoc, /*EmptyLookup=*/true, 11219 AllowTypoCorrection); 11220 11221 switch (OverloadResult) { 11222 case OR_Success: { 11223 FunctionDecl *FDecl = (*Best)->Function; 11224 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11225 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11226 return ExprError(); 11227 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11228 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11229 ExecConfig); 11230 } 11231 11232 case OR_No_Viable_Function: { 11233 // Try to recover by looking for viable functions which the user might 11234 // have meant to call. 11235 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11236 Args, RParenLoc, 11237 /*EmptyLookup=*/false, 11238 AllowTypoCorrection); 11239 if (!Recovery.isInvalid()) 11240 return Recovery; 11241 11242 // If the user passes in a function that we can't take the address of, we 11243 // generally end up emitting really bad error messages. Here, we attempt to 11244 // emit better ones. 11245 for (const Expr *Arg : Args) { 11246 if (!Arg->getType()->isFunctionType()) 11247 continue; 11248 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11249 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11250 if (FD && 11251 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11252 Arg->getExprLoc())) 11253 return ExprError(); 11254 } 11255 } 11256 11257 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11258 << ULE->getName() << Fn->getSourceRange(); 11259 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11260 break; 11261 } 11262 11263 case OR_Ambiguous: 11264 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11265 << ULE->getName() << Fn->getSourceRange(); 11266 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11267 break; 11268 11269 case OR_Deleted: { 11270 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11271 << (*Best)->Function->isDeleted() 11272 << ULE->getName() 11273 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11274 << Fn->getSourceRange(); 11275 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11276 11277 // We emitted an error for the unvailable/deleted function call but keep 11278 // the call in the AST. 11279 FunctionDecl *FDecl = (*Best)->Function; 11280 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11281 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11282 ExecConfig); 11283 } 11284 } 11285 11286 // Overload resolution failed. 11287 return ExprError(); 11288 } 11289 11290 static void markUnaddressableCandidatesUnviable(Sema &S, 11291 OverloadCandidateSet &CS) { 11292 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11293 if (I->Viable && 11294 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11295 I->Viable = false; 11296 I->FailureKind = ovl_fail_addr_not_available; 11297 } 11298 } 11299 } 11300 11301 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11302 /// (which eventually refers to the declaration Func) and the call 11303 /// arguments Args/NumArgs, attempt to resolve the function call down 11304 /// to a specific function. If overload resolution succeeds, returns 11305 /// the call expression produced by overload resolution. 11306 /// Otherwise, emits diagnostics and returns ExprError. 11307 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11308 UnresolvedLookupExpr *ULE, 11309 SourceLocation LParenLoc, 11310 MultiExprArg Args, 11311 SourceLocation RParenLoc, 11312 Expr *ExecConfig, 11313 bool AllowTypoCorrection, 11314 bool CalleesAddressIsTaken) { 11315 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11316 OverloadCandidateSet::CSK_Normal); 11317 ExprResult result; 11318 11319 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11320 &result)) 11321 return result; 11322 11323 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11324 // functions that aren't addressible are considered unviable. 11325 if (CalleesAddressIsTaken) 11326 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11327 11328 OverloadCandidateSet::iterator Best; 11329 OverloadingResult OverloadResult = 11330 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11331 11332 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11333 RParenLoc, ExecConfig, &CandidateSet, 11334 &Best, OverloadResult, 11335 AllowTypoCorrection); 11336 } 11337 11338 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11339 return Functions.size() > 1 || 11340 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11341 } 11342 11343 /// \brief Create a unary operation that may resolve to an overloaded 11344 /// operator. 11345 /// 11346 /// \param OpLoc The location of the operator itself (e.g., '*'). 11347 /// 11348 /// \param Opc The UnaryOperatorKind that describes this operator. 11349 /// 11350 /// \param Fns The set of non-member functions that will be 11351 /// considered by overload resolution. The caller needs to build this 11352 /// set based on the context using, e.g., 11353 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11354 /// set should not contain any member functions; those will be added 11355 /// by CreateOverloadedUnaryOp(). 11356 /// 11357 /// \param Input The input argument. 11358 ExprResult 11359 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11360 const UnresolvedSetImpl &Fns, 11361 Expr *Input) { 11362 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11363 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11364 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11365 // TODO: provide better source location info. 11366 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11367 11368 if (checkPlaceholderForOverload(*this, Input)) 11369 return ExprError(); 11370 11371 Expr *Args[2] = { Input, nullptr }; 11372 unsigned NumArgs = 1; 11373 11374 // For post-increment and post-decrement, add the implicit '0' as 11375 // the second argument, so that we know this is a post-increment or 11376 // post-decrement. 11377 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11378 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11379 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11380 SourceLocation()); 11381 NumArgs = 2; 11382 } 11383 11384 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11385 11386 if (Input->isTypeDependent()) { 11387 if (Fns.empty()) 11388 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11389 VK_RValue, OK_Ordinary, OpLoc); 11390 11391 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11392 UnresolvedLookupExpr *Fn 11393 = UnresolvedLookupExpr::Create(Context, NamingClass, 11394 NestedNameSpecifierLoc(), OpNameInfo, 11395 /*ADL*/ true, IsOverloaded(Fns), 11396 Fns.begin(), Fns.end()); 11397 return new (Context) 11398 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11399 VK_RValue, OpLoc, false); 11400 } 11401 11402 // Build an empty overload set. 11403 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11404 11405 // Add the candidates from the given function set. 11406 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11407 11408 // Add operator candidates that are member functions. 11409 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11410 11411 // Add candidates from ADL. 11412 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11413 /*ExplicitTemplateArgs*/nullptr, 11414 CandidateSet); 11415 11416 // Add builtin operator candidates. 11417 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11418 11419 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11420 11421 // Perform overload resolution. 11422 OverloadCandidateSet::iterator Best; 11423 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11424 case OR_Success: { 11425 // We found a built-in operator or an overloaded operator. 11426 FunctionDecl *FnDecl = Best->Function; 11427 11428 if (FnDecl) { 11429 // We matched an overloaded operator. Build a call to that 11430 // operator. 11431 11432 // Convert the arguments. 11433 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11434 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11435 11436 ExprResult InputRes = 11437 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11438 Best->FoundDecl, Method); 11439 if (InputRes.isInvalid()) 11440 return ExprError(); 11441 Input = InputRes.get(); 11442 } else { 11443 // Convert the arguments. 11444 ExprResult InputInit 11445 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11446 Context, 11447 FnDecl->getParamDecl(0)), 11448 SourceLocation(), 11449 Input); 11450 if (InputInit.isInvalid()) 11451 return ExprError(); 11452 Input = InputInit.get(); 11453 } 11454 11455 // Build the actual expression node. 11456 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11457 HadMultipleCandidates, OpLoc); 11458 if (FnExpr.isInvalid()) 11459 return ExprError(); 11460 11461 // Determine the result type. 11462 QualType ResultTy = FnDecl->getReturnType(); 11463 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11464 ResultTy = ResultTy.getNonLValueExprType(Context); 11465 11466 Args[0] = Input; 11467 CallExpr *TheCall = 11468 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11469 ResultTy, VK, OpLoc, false); 11470 11471 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11472 return ExprError(); 11473 11474 return MaybeBindToTemporary(TheCall); 11475 } else { 11476 // We matched a built-in operator. Convert the arguments, then 11477 // break out so that we will build the appropriate built-in 11478 // operator node. 11479 ExprResult InputRes = 11480 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11481 Best->Conversions[0], AA_Passing); 11482 if (InputRes.isInvalid()) 11483 return ExprError(); 11484 Input = InputRes.get(); 11485 break; 11486 } 11487 } 11488 11489 case OR_No_Viable_Function: 11490 // This is an erroneous use of an operator which can be overloaded by 11491 // a non-member function. Check for non-member operators which were 11492 // defined too late to be candidates. 11493 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11494 // FIXME: Recover by calling the found function. 11495 return ExprError(); 11496 11497 // No viable function; fall through to handling this as a 11498 // built-in operator, which will produce an error message for us. 11499 break; 11500 11501 case OR_Ambiguous: 11502 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11503 << UnaryOperator::getOpcodeStr(Opc) 11504 << Input->getType() 11505 << Input->getSourceRange(); 11506 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11507 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11508 return ExprError(); 11509 11510 case OR_Deleted: 11511 Diag(OpLoc, diag::err_ovl_deleted_oper) 11512 << Best->Function->isDeleted() 11513 << UnaryOperator::getOpcodeStr(Opc) 11514 << getDeletedOrUnavailableSuffix(Best->Function) 11515 << Input->getSourceRange(); 11516 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11517 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11518 return ExprError(); 11519 } 11520 11521 // Either we found no viable overloaded operator or we matched a 11522 // built-in operator. In either case, fall through to trying to 11523 // build a built-in operation. 11524 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11525 } 11526 11527 /// \brief Create a binary operation that may resolve to an overloaded 11528 /// operator. 11529 /// 11530 /// \param OpLoc The location of the operator itself (e.g., '+'). 11531 /// 11532 /// \param Opc The BinaryOperatorKind that describes this operator. 11533 /// 11534 /// \param Fns The set of non-member functions that will be 11535 /// considered by overload resolution. The caller needs to build this 11536 /// set based on the context using, e.g., 11537 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11538 /// set should not contain any member functions; those will be added 11539 /// by CreateOverloadedBinOp(). 11540 /// 11541 /// \param LHS Left-hand argument. 11542 /// \param RHS Right-hand argument. 11543 ExprResult 11544 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11545 BinaryOperatorKind Opc, 11546 const UnresolvedSetImpl &Fns, 11547 Expr *LHS, Expr *RHS) { 11548 Expr *Args[2] = { LHS, RHS }; 11549 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11550 11551 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11552 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11553 11554 // If either side is type-dependent, create an appropriate dependent 11555 // expression. 11556 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11557 if (Fns.empty()) { 11558 // If there are no functions to store, just build a dependent 11559 // BinaryOperator or CompoundAssignment. 11560 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11561 return new (Context) BinaryOperator( 11562 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11563 OpLoc, FPFeatures.fp_contract); 11564 11565 return new (Context) CompoundAssignOperator( 11566 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11567 Context.DependentTy, Context.DependentTy, OpLoc, 11568 FPFeatures.fp_contract); 11569 } 11570 11571 // FIXME: save results of ADL from here? 11572 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11573 // TODO: provide better source location info in DNLoc component. 11574 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11575 UnresolvedLookupExpr *Fn 11576 = UnresolvedLookupExpr::Create(Context, NamingClass, 11577 NestedNameSpecifierLoc(), OpNameInfo, 11578 /*ADL*/ true, IsOverloaded(Fns), 11579 Fns.begin(), Fns.end()); 11580 return new (Context) 11581 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11582 VK_RValue, OpLoc, FPFeatures.fp_contract); 11583 } 11584 11585 // Always do placeholder-like conversions on the RHS. 11586 if (checkPlaceholderForOverload(*this, Args[1])) 11587 return ExprError(); 11588 11589 // Do placeholder-like conversion on the LHS; note that we should 11590 // not get here with a PseudoObject LHS. 11591 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11592 if (checkPlaceholderForOverload(*this, Args[0])) 11593 return ExprError(); 11594 11595 // If this is the assignment operator, we only perform overload resolution 11596 // if the left-hand side is a class or enumeration type. This is actually 11597 // a hack. The standard requires that we do overload resolution between the 11598 // various built-in candidates, but as DR507 points out, this can lead to 11599 // problems. So we do it this way, which pretty much follows what GCC does. 11600 // Note that we go the traditional code path for compound assignment forms. 11601 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11602 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11603 11604 // If this is the .* operator, which is not overloadable, just 11605 // create a built-in binary operator. 11606 if (Opc == BO_PtrMemD) 11607 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11608 11609 // Build an empty overload set. 11610 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11611 11612 // Add the candidates from the given function set. 11613 AddFunctionCandidates(Fns, Args, CandidateSet); 11614 11615 // Add operator candidates that are member functions. 11616 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11617 11618 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11619 // performed for an assignment operator (nor for operator[] nor operator->, 11620 // which don't get here). 11621 if (Opc != BO_Assign) 11622 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11623 /*ExplicitTemplateArgs*/ nullptr, 11624 CandidateSet); 11625 11626 // Add builtin operator candidates. 11627 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11628 11629 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11630 11631 // Perform overload resolution. 11632 OverloadCandidateSet::iterator Best; 11633 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11634 case OR_Success: { 11635 // We found a built-in operator or an overloaded operator. 11636 FunctionDecl *FnDecl = Best->Function; 11637 11638 if (FnDecl) { 11639 // We matched an overloaded operator. Build a call to that 11640 // operator. 11641 11642 // Convert the arguments. 11643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11644 // Best->Access is only meaningful for class members. 11645 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11646 11647 ExprResult Arg1 = 11648 PerformCopyInitialization( 11649 InitializedEntity::InitializeParameter(Context, 11650 FnDecl->getParamDecl(0)), 11651 SourceLocation(), Args[1]); 11652 if (Arg1.isInvalid()) 11653 return ExprError(); 11654 11655 ExprResult Arg0 = 11656 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11657 Best->FoundDecl, Method); 11658 if (Arg0.isInvalid()) 11659 return ExprError(); 11660 Args[0] = Arg0.getAs<Expr>(); 11661 Args[1] = RHS = Arg1.getAs<Expr>(); 11662 } else { 11663 // Convert the arguments. 11664 ExprResult Arg0 = PerformCopyInitialization( 11665 InitializedEntity::InitializeParameter(Context, 11666 FnDecl->getParamDecl(0)), 11667 SourceLocation(), Args[0]); 11668 if (Arg0.isInvalid()) 11669 return ExprError(); 11670 11671 ExprResult Arg1 = 11672 PerformCopyInitialization( 11673 InitializedEntity::InitializeParameter(Context, 11674 FnDecl->getParamDecl(1)), 11675 SourceLocation(), Args[1]); 11676 if (Arg1.isInvalid()) 11677 return ExprError(); 11678 Args[0] = LHS = Arg0.getAs<Expr>(); 11679 Args[1] = RHS = Arg1.getAs<Expr>(); 11680 } 11681 11682 // Build the actual expression node. 11683 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11684 Best->FoundDecl, 11685 HadMultipleCandidates, OpLoc); 11686 if (FnExpr.isInvalid()) 11687 return ExprError(); 11688 11689 // Determine the result type. 11690 QualType ResultTy = FnDecl->getReturnType(); 11691 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11692 ResultTy = ResultTy.getNonLValueExprType(Context); 11693 11694 CXXOperatorCallExpr *TheCall = 11695 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11696 Args, ResultTy, VK, OpLoc, 11697 FPFeatures.fp_contract); 11698 11699 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11700 FnDecl)) 11701 return ExprError(); 11702 11703 ArrayRef<const Expr *> ArgsArray(Args, 2); 11704 // Cut off the implicit 'this'. 11705 if (isa<CXXMethodDecl>(FnDecl)) 11706 ArgsArray = ArgsArray.slice(1); 11707 11708 // Check for a self move. 11709 if (Op == OO_Equal) 11710 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11711 11712 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11713 TheCall->getSourceRange(), VariadicDoesNotApply); 11714 11715 return MaybeBindToTemporary(TheCall); 11716 } else { 11717 // We matched a built-in operator. Convert the arguments, then 11718 // break out so that we will build the appropriate built-in 11719 // operator node. 11720 ExprResult ArgsRes0 = 11721 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11722 Best->Conversions[0], AA_Passing); 11723 if (ArgsRes0.isInvalid()) 11724 return ExprError(); 11725 Args[0] = ArgsRes0.get(); 11726 11727 ExprResult ArgsRes1 = 11728 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11729 Best->Conversions[1], AA_Passing); 11730 if (ArgsRes1.isInvalid()) 11731 return ExprError(); 11732 Args[1] = ArgsRes1.get(); 11733 break; 11734 } 11735 } 11736 11737 case OR_No_Viable_Function: { 11738 // C++ [over.match.oper]p9: 11739 // If the operator is the operator , [...] and there are no 11740 // viable functions, then the operator is assumed to be the 11741 // built-in operator and interpreted according to clause 5. 11742 if (Opc == BO_Comma) 11743 break; 11744 11745 // For class as left operand for assignment or compound assigment 11746 // operator do not fall through to handling in built-in, but report that 11747 // no overloaded assignment operator found 11748 ExprResult Result = ExprError(); 11749 if (Args[0]->getType()->isRecordType() && 11750 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11751 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11752 << BinaryOperator::getOpcodeStr(Opc) 11753 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11754 if (Args[0]->getType()->isIncompleteType()) { 11755 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11756 << Args[0]->getType() 11757 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11758 } 11759 } else { 11760 // This is an erroneous use of an operator which can be overloaded by 11761 // a non-member function. Check for non-member operators which were 11762 // defined too late to be candidates. 11763 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11764 // FIXME: Recover by calling the found function. 11765 return ExprError(); 11766 11767 // No viable function; try to create a built-in operation, which will 11768 // produce an error. Then, show the non-viable candidates. 11769 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11770 } 11771 assert(Result.isInvalid() && 11772 "C++ binary operator overloading is missing candidates!"); 11773 if (Result.isInvalid()) 11774 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11775 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11776 return Result; 11777 } 11778 11779 case OR_Ambiguous: 11780 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11781 << BinaryOperator::getOpcodeStr(Opc) 11782 << Args[0]->getType() << Args[1]->getType() 11783 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11784 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11785 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11786 return ExprError(); 11787 11788 case OR_Deleted: 11789 if (isImplicitlyDeleted(Best->Function)) { 11790 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11791 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11792 << Context.getRecordType(Method->getParent()) 11793 << getSpecialMember(Method); 11794 11795 // The user probably meant to call this special member. Just 11796 // explain why it's deleted. 11797 NoteDeletedFunction(Method); 11798 return ExprError(); 11799 } else { 11800 Diag(OpLoc, diag::err_ovl_deleted_oper) 11801 << Best->Function->isDeleted() 11802 << BinaryOperator::getOpcodeStr(Opc) 11803 << getDeletedOrUnavailableSuffix(Best->Function) 11804 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11805 } 11806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11807 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11808 return ExprError(); 11809 } 11810 11811 // We matched a built-in operator; build it. 11812 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11813 } 11814 11815 ExprResult 11816 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11817 SourceLocation RLoc, 11818 Expr *Base, Expr *Idx) { 11819 Expr *Args[2] = { Base, Idx }; 11820 DeclarationName OpName = 11821 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11822 11823 // If either side is type-dependent, create an appropriate dependent 11824 // expression. 11825 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11826 11827 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11828 // CHECKME: no 'operator' keyword? 11829 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11830 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11831 UnresolvedLookupExpr *Fn 11832 = UnresolvedLookupExpr::Create(Context, NamingClass, 11833 NestedNameSpecifierLoc(), OpNameInfo, 11834 /*ADL*/ true, /*Overloaded*/ false, 11835 UnresolvedSetIterator(), 11836 UnresolvedSetIterator()); 11837 // Can't add any actual overloads yet 11838 11839 return new (Context) 11840 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11841 Context.DependentTy, VK_RValue, RLoc, false); 11842 } 11843 11844 // Handle placeholders on both operands. 11845 if (checkPlaceholderForOverload(*this, Args[0])) 11846 return ExprError(); 11847 if (checkPlaceholderForOverload(*this, Args[1])) 11848 return ExprError(); 11849 11850 // Build an empty overload set. 11851 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11852 11853 // Subscript can only be overloaded as a member function. 11854 11855 // Add operator candidates that are member functions. 11856 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11857 11858 // Add builtin operator candidates. 11859 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11860 11861 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11862 11863 // Perform overload resolution. 11864 OverloadCandidateSet::iterator Best; 11865 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11866 case OR_Success: { 11867 // We found a built-in operator or an overloaded operator. 11868 FunctionDecl *FnDecl = Best->Function; 11869 11870 if (FnDecl) { 11871 // We matched an overloaded operator. Build a call to that 11872 // operator. 11873 11874 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11875 11876 // Convert the arguments. 11877 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11878 ExprResult Arg0 = 11879 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11880 Best->FoundDecl, Method); 11881 if (Arg0.isInvalid()) 11882 return ExprError(); 11883 Args[0] = Arg0.get(); 11884 11885 // Convert the arguments. 11886 ExprResult InputInit 11887 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11888 Context, 11889 FnDecl->getParamDecl(0)), 11890 SourceLocation(), 11891 Args[1]); 11892 if (InputInit.isInvalid()) 11893 return ExprError(); 11894 11895 Args[1] = InputInit.getAs<Expr>(); 11896 11897 // Build the actual expression node. 11898 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11899 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11900 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11901 Best->FoundDecl, 11902 HadMultipleCandidates, 11903 OpLocInfo.getLoc(), 11904 OpLocInfo.getInfo()); 11905 if (FnExpr.isInvalid()) 11906 return ExprError(); 11907 11908 // Determine the result type 11909 QualType ResultTy = FnDecl->getReturnType(); 11910 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11911 ResultTy = ResultTy.getNonLValueExprType(Context); 11912 11913 CXXOperatorCallExpr *TheCall = 11914 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11915 FnExpr.get(), Args, 11916 ResultTy, VK, RLoc, 11917 false); 11918 11919 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11920 return ExprError(); 11921 11922 return MaybeBindToTemporary(TheCall); 11923 } else { 11924 // We matched a built-in operator. Convert the arguments, then 11925 // break out so that we will build the appropriate built-in 11926 // operator node. 11927 ExprResult ArgsRes0 = 11928 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11929 Best->Conversions[0], AA_Passing); 11930 if (ArgsRes0.isInvalid()) 11931 return ExprError(); 11932 Args[0] = ArgsRes0.get(); 11933 11934 ExprResult ArgsRes1 = 11935 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11936 Best->Conversions[1], AA_Passing); 11937 if (ArgsRes1.isInvalid()) 11938 return ExprError(); 11939 Args[1] = ArgsRes1.get(); 11940 11941 break; 11942 } 11943 } 11944 11945 case OR_No_Viable_Function: { 11946 if (CandidateSet.empty()) 11947 Diag(LLoc, diag::err_ovl_no_oper) 11948 << Args[0]->getType() << /*subscript*/ 0 11949 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11950 else 11951 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11952 << Args[0]->getType() 11953 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11954 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11955 "[]", LLoc); 11956 return ExprError(); 11957 } 11958 11959 case OR_Ambiguous: 11960 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11961 << "[]" 11962 << Args[0]->getType() << Args[1]->getType() 11963 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11964 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11965 "[]", LLoc); 11966 return ExprError(); 11967 11968 case OR_Deleted: 11969 Diag(LLoc, diag::err_ovl_deleted_oper) 11970 << Best->Function->isDeleted() << "[]" 11971 << getDeletedOrUnavailableSuffix(Best->Function) 11972 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11973 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11974 "[]", LLoc); 11975 return ExprError(); 11976 } 11977 11978 // We matched a built-in operator; build it. 11979 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11980 } 11981 11982 /// BuildCallToMemberFunction - Build a call to a member 11983 /// function. MemExpr is the expression that refers to the member 11984 /// function (and includes the object parameter), Args/NumArgs are the 11985 /// arguments to the function call (not including the object 11986 /// parameter). The caller needs to validate that the member 11987 /// expression refers to a non-static member function or an overloaded 11988 /// member function. 11989 ExprResult 11990 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11991 SourceLocation LParenLoc, 11992 MultiExprArg Args, 11993 SourceLocation RParenLoc) { 11994 assert(MemExprE->getType() == Context.BoundMemberTy || 11995 MemExprE->getType() == Context.OverloadTy); 11996 11997 // Dig out the member expression. This holds both the object 11998 // argument and the member function we're referring to. 11999 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12000 12001 // Determine whether this is a call to a pointer-to-member function. 12002 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12003 assert(op->getType() == Context.BoundMemberTy); 12004 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12005 12006 QualType fnType = 12007 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12008 12009 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12010 QualType resultType = proto->getCallResultType(Context); 12011 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12012 12013 // Check that the object type isn't more qualified than the 12014 // member function we're calling. 12015 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12016 12017 QualType objectType = op->getLHS()->getType(); 12018 if (op->getOpcode() == BO_PtrMemI) 12019 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12020 Qualifiers objectQuals = objectType.getQualifiers(); 12021 12022 Qualifiers difference = objectQuals - funcQuals; 12023 difference.removeObjCGCAttr(); 12024 difference.removeAddressSpace(); 12025 if (difference) { 12026 std::string qualsString = difference.getAsString(); 12027 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12028 << fnType.getUnqualifiedType() 12029 << qualsString 12030 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12031 } 12032 12033 CXXMemberCallExpr *call 12034 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12035 resultType, valueKind, RParenLoc); 12036 12037 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12038 call, nullptr)) 12039 return ExprError(); 12040 12041 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12042 return ExprError(); 12043 12044 if (CheckOtherCall(call, proto)) 12045 return ExprError(); 12046 12047 return MaybeBindToTemporary(call); 12048 } 12049 12050 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12051 return new (Context) 12052 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12053 12054 UnbridgedCastsSet UnbridgedCasts; 12055 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12056 return ExprError(); 12057 12058 MemberExpr *MemExpr; 12059 CXXMethodDecl *Method = nullptr; 12060 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12061 NestedNameSpecifier *Qualifier = nullptr; 12062 if (isa<MemberExpr>(NakedMemExpr)) { 12063 MemExpr = cast<MemberExpr>(NakedMemExpr); 12064 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12065 FoundDecl = MemExpr->getFoundDecl(); 12066 Qualifier = MemExpr->getQualifier(); 12067 UnbridgedCasts.restore(); 12068 } else { 12069 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12070 Qualifier = UnresExpr->getQualifier(); 12071 12072 QualType ObjectType = UnresExpr->getBaseType(); 12073 Expr::Classification ObjectClassification 12074 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12075 : UnresExpr->getBase()->Classify(Context); 12076 12077 // Add overload candidates 12078 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12079 OverloadCandidateSet::CSK_Normal); 12080 12081 // FIXME: avoid copy. 12082 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12083 if (UnresExpr->hasExplicitTemplateArgs()) { 12084 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12085 TemplateArgs = &TemplateArgsBuffer; 12086 } 12087 12088 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12089 E = UnresExpr->decls_end(); I != E; ++I) { 12090 12091 NamedDecl *Func = *I; 12092 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12093 if (isa<UsingShadowDecl>(Func)) 12094 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12095 12096 12097 // Microsoft supports direct constructor calls. 12098 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12099 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12100 Args, CandidateSet); 12101 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12102 // If explicit template arguments were provided, we can't call a 12103 // non-template member function. 12104 if (TemplateArgs) 12105 continue; 12106 12107 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12108 ObjectClassification, Args, CandidateSet, 12109 /*SuppressUserConversions=*/false); 12110 } else { 12111 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12112 I.getPair(), ActingDC, TemplateArgs, 12113 ObjectType, ObjectClassification, 12114 Args, CandidateSet, 12115 /*SuppressUsedConversions=*/false); 12116 } 12117 } 12118 12119 DeclarationName DeclName = UnresExpr->getMemberName(); 12120 12121 UnbridgedCasts.restore(); 12122 12123 OverloadCandidateSet::iterator Best; 12124 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12125 Best)) { 12126 case OR_Success: 12127 Method = cast<CXXMethodDecl>(Best->Function); 12128 FoundDecl = Best->FoundDecl; 12129 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12130 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12131 return ExprError(); 12132 // If FoundDecl is different from Method (such as if one is a template 12133 // and the other a specialization), make sure DiagnoseUseOfDecl is 12134 // called on both. 12135 // FIXME: This would be more comprehensively addressed by modifying 12136 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12137 // being used. 12138 if (Method != FoundDecl.getDecl() && 12139 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12140 return ExprError(); 12141 break; 12142 12143 case OR_No_Viable_Function: 12144 Diag(UnresExpr->getMemberLoc(), 12145 diag::err_ovl_no_viable_member_function_in_call) 12146 << DeclName << MemExprE->getSourceRange(); 12147 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12148 // FIXME: Leaking incoming expressions! 12149 return ExprError(); 12150 12151 case OR_Ambiguous: 12152 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12153 << DeclName << MemExprE->getSourceRange(); 12154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12155 // FIXME: Leaking incoming expressions! 12156 return ExprError(); 12157 12158 case OR_Deleted: 12159 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12160 << Best->Function->isDeleted() 12161 << DeclName 12162 << getDeletedOrUnavailableSuffix(Best->Function) 12163 << MemExprE->getSourceRange(); 12164 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12165 // FIXME: Leaking incoming expressions! 12166 return ExprError(); 12167 } 12168 12169 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12170 12171 // If overload resolution picked a static member, build a 12172 // non-member call based on that function. 12173 if (Method->isStatic()) { 12174 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12175 RParenLoc); 12176 } 12177 12178 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12179 } 12180 12181 QualType ResultType = Method->getReturnType(); 12182 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12183 ResultType = ResultType.getNonLValueExprType(Context); 12184 12185 assert(Method && "Member call to something that isn't a method?"); 12186 CXXMemberCallExpr *TheCall = 12187 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12188 ResultType, VK, RParenLoc); 12189 12190 // (CUDA B.1): Check for invalid calls between targets. 12191 if (getLangOpts().CUDA) { 12192 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12193 if (CheckCUDATarget(Caller, Method)) { 12194 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12195 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12196 << IdentifyCUDATarget(Caller); 12197 return ExprError(); 12198 } 12199 } 12200 } 12201 12202 // Check for a valid return type. 12203 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12204 TheCall, Method)) 12205 return ExprError(); 12206 12207 // Convert the object argument (for a non-static member function call). 12208 // We only need to do this if there was actually an overload; otherwise 12209 // it was done at lookup. 12210 if (!Method->isStatic()) { 12211 ExprResult ObjectArg = 12212 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12213 FoundDecl, Method); 12214 if (ObjectArg.isInvalid()) 12215 return ExprError(); 12216 MemExpr->setBase(ObjectArg.get()); 12217 } 12218 12219 // Convert the rest of the arguments 12220 const FunctionProtoType *Proto = 12221 Method->getType()->getAs<FunctionProtoType>(); 12222 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12223 RParenLoc)) 12224 return ExprError(); 12225 12226 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12227 12228 if (CheckFunctionCall(Method, TheCall, Proto)) 12229 return ExprError(); 12230 12231 // In the case the method to call was not selected by the overloading 12232 // resolution process, we still need to handle the enable_if attribute. Do 12233 // that here, so it will not hide previous -- and more relevant -- errors 12234 if (isa<MemberExpr>(NakedMemExpr)) { 12235 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12236 Diag(MemExprE->getLocStart(), 12237 diag::err_ovl_no_viable_member_function_in_call) 12238 << Method << Method->getSourceRange(); 12239 Diag(Method->getLocation(), 12240 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12241 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12242 return ExprError(); 12243 } 12244 } 12245 12246 if ((isa<CXXConstructorDecl>(CurContext) || 12247 isa<CXXDestructorDecl>(CurContext)) && 12248 TheCall->getMethodDecl()->isPure()) { 12249 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12250 12251 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12252 MemExpr->performsVirtualDispatch(getLangOpts())) { 12253 Diag(MemExpr->getLocStart(), 12254 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12255 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12256 << MD->getParent()->getDeclName(); 12257 12258 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12259 if (getLangOpts().AppleKext) 12260 Diag(MemExpr->getLocStart(), 12261 diag::note_pure_qualified_call_kext) 12262 << MD->getParent()->getDeclName() 12263 << MD->getDeclName(); 12264 } 12265 } 12266 12267 if (CXXDestructorDecl *DD = 12268 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12269 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12270 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() || 12271 getLangOpts().AppleKext; 12272 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12273 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12274 MemExpr->getMemberLoc()); 12275 } 12276 12277 return MaybeBindToTemporary(TheCall); 12278 } 12279 12280 /// BuildCallToObjectOfClassType - Build a call to an object of class 12281 /// type (C++ [over.call.object]), which can end up invoking an 12282 /// overloaded function call operator (@c operator()) or performing a 12283 /// user-defined conversion on the object argument. 12284 ExprResult 12285 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12286 SourceLocation LParenLoc, 12287 MultiExprArg Args, 12288 SourceLocation RParenLoc) { 12289 if (checkPlaceholderForOverload(*this, Obj)) 12290 return ExprError(); 12291 ExprResult Object = Obj; 12292 12293 UnbridgedCastsSet UnbridgedCasts; 12294 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12295 return ExprError(); 12296 12297 assert(Object.get()->getType()->isRecordType() && 12298 "Requires object type argument"); 12299 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12300 12301 // C++ [over.call.object]p1: 12302 // If the primary-expression E in the function call syntax 12303 // evaluates to a class object of type "cv T", then the set of 12304 // candidate functions includes at least the function call 12305 // operators of T. The function call operators of T are obtained by 12306 // ordinary lookup of the name operator() in the context of 12307 // (E).operator(). 12308 OverloadCandidateSet CandidateSet(LParenLoc, 12309 OverloadCandidateSet::CSK_Operator); 12310 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12311 12312 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12313 diag::err_incomplete_object_call, Object.get())) 12314 return true; 12315 12316 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12317 LookupQualifiedName(R, Record->getDecl()); 12318 R.suppressDiagnostics(); 12319 12320 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12321 Oper != OperEnd; ++Oper) { 12322 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12323 Object.get()->Classify(Context), 12324 Args, CandidateSet, 12325 /*SuppressUserConversions=*/ false); 12326 } 12327 12328 // C++ [over.call.object]p2: 12329 // In addition, for each (non-explicit in C++0x) conversion function 12330 // declared in T of the form 12331 // 12332 // operator conversion-type-id () cv-qualifier; 12333 // 12334 // where cv-qualifier is the same cv-qualification as, or a 12335 // greater cv-qualification than, cv, and where conversion-type-id 12336 // denotes the type "pointer to function of (P1,...,Pn) returning 12337 // R", or the type "reference to pointer to function of 12338 // (P1,...,Pn) returning R", or the type "reference to function 12339 // of (P1,...,Pn) returning R", a surrogate call function [...] 12340 // is also considered as a candidate function. Similarly, 12341 // surrogate call functions are added to the set of candidate 12342 // functions for each conversion function declared in an 12343 // accessible base class provided the function is not hidden 12344 // within T by another intervening declaration. 12345 const auto &Conversions = 12346 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12348 NamedDecl *D = *I; 12349 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12350 if (isa<UsingShadowDecl>(D)) 12351 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12352 12353 // Skip over templated conversion functions; they aren't 12354 // surrogates. 12355 if (isa<FunctionTemplateDecl>(D)) 12356 continue; 12357 12358 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12359 if (!Conv->isExplicit()) { 12360 // Strip the reference type (if any) and then the pointer type (if 12361 // any) to get down to what might be a function type. 12362 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12363 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12364 ConvType = ConvPtrType->getPointeeType(); 12365 12366 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12367 { 12368 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12369 Object.get(), Args, CandidateSet); 12370 } 12371 } 12372 } 12373 12374 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12375 12376 // Perform overload resolution. 12377 OverloadCandidateSet::iterator Best; 12378 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12379 Best)) { 12380 case OR_Success: 12381 // Overload resolution succeeded; we'll build the appropriate call 12382 // below. 12383 break; 12384 12385 case OR_No_Viable_Function: 12386 if (CandidateSet.empty()) 12387 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12388 << Object.get()->getType() << /*call*/ 1 12389 << Object.get()->getSourceRange(); 12390 else 12391 Diag(Object.get()->getLocStart(), 12392 diag::err_ovl_no_viable_object_call) 12393 << Object.get()->getType() << Object.get()->getSourceRange(); 12394 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12395 break; 12396 12397 case OR_Ambiguous: 12398 Diag(Object.get()->getLocStart(), 12399 diag::err_ovl_ambiguous_object_call) 12400 << Object.get()->getType() << Object.get()->getSourceRange(); 12401 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12402 break; 12403 12404 case OR_Deleted: 12405 Diag(Object.get()->getLocStart(), 12406 diag::err_ovl_deleted_object_call) 12407 << Best->Function->isDeleted() 12408 << Object.get()->getType() 12409 << getDeletedOrUnavailableSuffix(Best->Function) 12410 << Object.get()->getSourceRange(); 12411 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12412 break; 12413 } 12414 12415 if (Best == CandidateSet.end()) 12416 return true; 12417 12418 UnbridgedCasts.restore(); 12419 12420 if (Best->Function == nullptr) { 12421 // Since there is no function declaration, this is one of the 12422 // surrogate candidates. Dig out the conversion function. 12423 CXXConversionDecl *Conv 12424 = cast<CXXConversionDecl>( 12425 Best->Conversions[0].UserDefined.ConversionFunction); 12426 12427 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12428 Best->FoundDecl); 12429 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12430 return ExprError(); 12431 assert(Conv == Best->FoundDecl.getDecl() && 12432 "Found Decl & conversion-to-functionptr should be same, right?!"); 12433 // We selected one of the surrogate functions that converts the 12434 // object parameter to a function pointer. Perform the conversion 12435 // on the object argument, then let ActOnCallExpr finish the job. 12436 12437 // Create an implicit member expr to refer to the conversion operator. 12438 // and then call it. 12439 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12440 Conv, HadMultipleCandidates); 12441 if (Call.isInvalid()) 12442 return ExprError(); 12443 // Record usage of conversion in an implicit cast. 12444 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12445 CK_UserDefinedConversion, Call.get(), 12446 nullptr, VK_RValue); 12447 12448 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12449 } 12450 12451 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12452 12453 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12454 // that calls this method, using Object for the implicit object 12455 // parameter and passing along the remaining arguments. 12456 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12457 12458 // An error diagnostic has already been printed when parsing the declaration. 12459 if (Method->isInvalidDecl()) 12460 return ExprError(); 12461 12462 const FunctionProtoType *Proto = 12463 Method->getType()->getAs<FunctionProtoType>(); 12464 12465 unsigned NumParams = Proto->getNumParams(); 12466 12467 DeclarationNameInfo OpLocInfo( 12468 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12469 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12470 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12471 HadMultipleCandidates, 12472 OpLocInfo.getLoc(), 12473 OpLocInfo.getInfo()); 12474 if (NewFn.isInvalid()) 12475 return true; 12476 12477 // Build the full argument list for the method call (the implicit object 12478 // parameter is placed at the beginning of the list). 12479 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12480 MethodArgs[0] = Object.get(); 12481 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12482 12483 // Once we've built TheCall, all of the expressions are properly 12484 // owned. 12485 QualType ResultTy = Method->getReturnType(); 12486 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12487 ResultTy = ResultTy.getNonLValueExprType(Context); 12488 12489 CXXOperatorCallExpr *TheCall = new (Context) 12490 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12491 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12492 ResultTy, VK, RParenLoc, false); 12493 MethodArgs.reset(); 12494 12495 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12496 return true; 12497 12498 // We may have default arguments. If so, we need to allocate more 12499 // slots in the call for them. 12500 if (Args.size() < NumParams) 12501 TheCall->setNumArgs(Context, NumParams + 1); 12502 12503 bool IsError = false; 12504 12505 // Initialize the implicit object parameter. 12506 ExprResult ObjRes = 12507 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12508 Best->FoundDecl, Method); 12509 if (ObjRes.isInvalid()) 12510 IsError = true; 12511 else 12512 Object = ObjRes; 12513 TheCall->setArg(0, Object.get()); 12514 12515 // Check the argument types. 12516 for (unsigned i = 0; i != NumParams; i++) { 12517 Expr *Arg; 12518 if (i < Args.size()) { 12519 Arg = Args[i]; 12520 12521 // Pass the argument. 12522 12523 ExprResult InputInit 12524 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12525 Context, 12526 Method->getParamDecl(i)), 12527 SourceLocation(), Arg); 12528 12529 IsError |= InputInit.isInvalid(); 12530 Arg = InputInit.getAs<Expr>(); 12531 } else { 12532 ExprResult DefArg 12533 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12534 if (DefArg.isInvalid()) { 12535 IsError = true; 12536 break; 12537 } 12538 12539 Arg = DefArg.getAs<Expr>(); 12540 } 12541 12542 TheCall->setArg(i + 1, Arg); 12543 } 12544 12545 // If this is a variadic call, handle args passed through "...". 12546 if (Proto->isVariadic()) { 12547 // Promote the arguments (C99 6.5.2.2p7). 12548 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12549 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12550 nullptr); 12551 IsError |= Arg.isInvalid(); 12552 TheCall->setArg(i + 1, Arg.get()); 12553 } 12554 } 12555 12556 if (IsError) return true; 12557 12558 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12559 12560 if (CheckFunctionCall(Method, TheCall, Proto)) 12561 return true; 12562 12563 return MaybeBindToTemporary(TheCall); 12564 } 12565 12566 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12567 /// (if one exists), where @c Base is an expression of class type and 12568 /// @c Member is the name of the member we're trying to find. 12569 ExprResult 12570 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12571 bool *NoArrowOperatorFound) { 12572 assert(Base->getType()->isRecordType() && 12573 "left-hand side must have class type"); 12574 12575 if (checkPlaceholderForOverload(*this, Base)) 12576 return ExprError(); 12577 12578 SourceLocation Loc = Base->getExprLoc(); 12579 12580 // C++ [over.ref]p1: 12581 // 12582 // [...] An expression x->m is interpreted as (x.operator->())->m 12583 // for a class object x of type T if T::operator->() exists and if 12584 // the operator is selected as the best match function by the 12585 // overload resolution mechanism (13.3). 12586 DeclarationName OpName = 12587 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12588 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12589 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12590 12591 if (RequireCompleteType(Loc, Base->getType(), 12592 diag::err_typecheck_incomplete_tag, Base)) 12593 return ExprError(); 12594 12595 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12596 LookupQualifiedName(R, BaseRecord->getDecl()); 12597 R.suppressDiagnostics(); 12598 12599 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12600 Oper != OperEnd; ++Oper) { 12601 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12602 None, CandidateSet, /*SuppressUserConversions=*/false); 12603 } 12604 12605 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12606 12607 // Perform overload resolution. 12608 OverloadCandidateSet::iterator Best; 12609 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12610 case OR_Success: 12611 // Overload resolution succeeded; we'll build the call below. 12612 break; 12613 12614 case OR_No_Viable_Function: 12615 if (CandidateSet.empty()) { 12616 QualType BaseType = Base->getType(); 12617 if (NoArrowOperatorFound) { 12618 // Report this specific error to the caller instead of emitting a 12619 // diagnostic, as requested. 12620 *NoArrowOperatorFound = true; 12621 return ExprError(); 12622 } 12623 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12624 << BaseType << Base->getSourceRange(); 12625 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12626 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12627 << FixItHint::CreateReplacement(OpLoc, "."); 12628 } 12629 } else 12630 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12631 << "operator->" << Base->getSourceRange(); 12632 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12633 return ExprError(); 12634 12635 case OR_Ambiguous: 12636 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12637 << "->" << Base->getType() << Base->getSourceRange(); 12638 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12639 return ExprError(); 12640 12641 case OR_Deleted: 12642 Diag(OpLoc, diag::err_ovl_deleted_oper) 12643 << Best->Function->isDeleted() 12644 << "->" 12645 << getDeletedOrUnavailableSuffix(Best->Function) 12646 << Base->getSourceRange(); 12647 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12648 return ExprError(); 12649 } 12650 12651 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12652 12653 // Convert the object parameter. 12654 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12655 ExprResult BaseResult = 12656 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12657 Best->FoundDecl, Method); 12658 if (BaseResult.isInvalid()) 12659 return ExprError(); 12660 Base = BaseResult.get(); 12661 12662 // Build the operator call. 12663 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12664 HadMultipleCandidates, OpLoc); 12665 if (FnExpr.isInvalid()) 12666 return ExprError(); 12667 12668 QualType ResultTy = Method->getReturnType(); 12669 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12670 ResultTy = ResultTy.getNonLValueExprType(Context); 12671 CXXOperatorCallExpr *TheCall = 12672 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12673 Base, ResultTy, VK, OpLoc, false); 12674 12675 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12676 return ExprError(); 12677 12678 return MaybeBindToTemporary(TheCall); 12679 } 12680 12681 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12682 /// a literal operator described by the provided lookup results. 12683 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12684 DeclarationNameInfo &SuffixInfo, 12685 ArrayRef<Expr*> Args, 12686 SourceLocation LitEndLoc, 12687 TemplateArgumentListInfo *TemplateArgs) { 12688 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12689 12690 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12691 OverloadCandidateSet::CSK_Normal); 12692 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12693 /*SuppressUserConversions=*/true); 12694 12695 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12696 12697 // Perform overload resolution. This will usually be trivial, but might need 12698 // to perform substitutions for a literal operator template. 12699 OverloadCandidateSet::iterator Best; 12700 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12701 case OR_Success: 12702 case OR_Deleted: 12703 break; 12704 12705 case OR_No_Viable_Function: 12706 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12707 << R.getLookupName(); 12708 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12709 return ExprError(); 12710 12711 case OR_Ambiguous: 12712 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12713 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12714 return ExprError(); 12715 } 12716 12717 FunctionDecl *FD = Best->Function; 12718 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12719 HadMultipleCandidates, 12720 SuffixInfo.getLoc(), 12721 SuffixInfo.getInfo()); 12722 if (Fn.isInvalid()) 12723 return true; 12724 12725 // Check the argument types. This should almost always be a no-op, except 12726 // that array-to-pointer decay is applied to string literals. 12727 Expr *ConvArgs[2]; 12728 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12729 ExprResult InputInit = PerformCopyInitialization( 12730 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12731 SourceLocation(), Args[ArgIdx]); 12732 if (InputInit.isInvalid()) 12733 return true; 12734 ConvArgs[ArgIdx] = InputInit.get(); 12735 } 12736 12737 QualType ResultTy = FD->getReturnType(); 12738 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12739 ResultTy = ResultTy.getNonLValueExprType(Context); 12740 12741 UserDefinedLiteral *UDL = 12742 new (Context) UserDefinedLiteral(Context, Fn.get(), 12743 llvm::makeArrayRef(ConvArgs, Args.size()), 12744 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12745 12746 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12747 return ExprError(); 12748 12749 if (CheckFunctionCall(FD, UDL, nullptr)) 12750 return ExprError(); 12751 12752 return MaybeBindToTemporary(UDL); 12753 } 12754 12755 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12756 /// given LookupResult is non-empty, it is assumed to describe a member which 12757 /// will be invoked. Otherwise, the function will be found via argument 12758 /// dependent lookup. 12759 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12760 /// otherwise CallExpr is set to ExprError() and some non-success value 12761 /// is returned. 12762 Sema::ForRangeStatus 12763 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12764 SourceLocation RangeLoc, 12765 const DeclarationNameInfo &NameInfo, 12766 LookupResult &MemberLookup, 12767 OverloadCandidateSet *CandidateSet, 12768 Expr *Range, ExprResult *CallExpr) { 12769 Scope *S = nullptr; 12770 12771 CandidateSet->clear(); 12772 if (!MemberLookup.empty()) { 12773 ExprResult MemberRef = 12774 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12775 /*IsPtr=*/false, CXXScopeSpec(), 12776 /*TemplateKWLoc=*/SourceLocation(), 12777 /*FirstQualifierInScope=*/nullptr, 12778 MemberLookup, 12779 /*TemplateArgs=*/nullptr, S); 12780 if (MemberRef.isInvalid()) { 12781 *CallExpr = ExprError(); 12782 return FRS_DiagnosticIssued; 12783 } 12784 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12785 if (CallExpr->isInvalid()) { 12786 *CallExpr = ExprError(); 12787 return FRS_DiagnosticIssued; 12788 } 12789 } else { 12790 UnresolvedSet<0> FoundNames; 12791 UnresolvedLookupExpr *Fn = 12792 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12793 NestedNameSpecifierLoc(), NameInfo, 12794 /*NeedsADL=*/true, /*Overloaded=*/false, 12795 FoundNames.begin(), FoundNames.end()); 12796 12797 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12798 CandidateSet, CallExpr); 12799 if (CandidateSet->empty() || CandidateSetError) { 12800 *CallExpr = ExprError(); 12801 return FRS_NoViableFunction; 12802 } 12803 OverloadCandidateSet::iterator Best; 12804 OverloadingResult OverloadResult = 12805 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12806 12807 if (OverloadResult == OR_No_Viable_Function) { 12808 *CallExpr = ExprError(); 12809 return FRS_NoViableFunction; 12810 } 12811 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12812 Loc, nullptr, CandidateSet, &Best, 12813 OverloadResult, 12814 /*AllowTypoCorrection=*/false); 12815 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12816 *CallExpr = ExprError(); 12817 return FRS_DiagnosticIssued; 12818 } 12819 } 12820 return FRS_Success; 12821 } 12822 12823 12824 /// FixOverloadedFunctionReference - E is an expression that refers to 12825 /// a C++ overloaded function (possibly with some parentheses and 12826 /// perhaps a '&' around it). We have resolved the overloaded function 12827 /// to the function declaration Fn, so patch up the expression E to 12828 /// refer (possibly indirectly) to Fn. Returns the new expr. 12829 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12830 FunctionDecl *Fn) { 12831 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12832 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12833 Found, Fn); 12834 if (SubExpr == PE->getSubExpr()) 12835 return PE; 12836 12837 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12838 } 12839 12840 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12841 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12842 Found, Fn); 12843 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12844 SubExpr->getType()) && 12845 "Implicit cast type cannot be determined from overload"); 12846 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12847 if (SubExpr == ICE->getSubExpr()) 12848 return ICE; 12849 12850 return ImplicitCastExpr::Create(Context, ICE->getType(), 12851 ICE->getCastKind(), 12852 SubExpr, nullptr, 12853 ICE->getValueKind()); 12854 } 12855 12856 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12857 assert(UnOp->getOpcode() == UO_AddrOf && 12858 "Can only take the address of an overloaded function"); 12859 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12860 if (Method->isStatic()) { 12861 // Do nothing: static member functions aren't any different 12862 // from non-member functions. 12863 } else { 12864 // Fix the subexpression, which really has to be an 12865 // UnresolvedLookupExpr holding an overloaded member function 12866 // or template. 12867 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12868 Found, Fn); 12869 if (SubExpr == UnOp->getSubExpr()) 12870 return UnOp; 12871 12872 assert(isa<DeclRefExpr>(SubExpr) 12873 && "fixed to something other than a decl ref"); 12874 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12875 && "fixed to a member ref with no nested name qualifier"); 12876 12877 // We have taken the address of a pointer to member 12878 // function. Perform the computation here so that we get the 12879 // appropriate pointer to member type. 12880 QualType ClassType 12881 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12882 QualType MemPtrType 12883 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12884 12885 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12886 VK_RValue, OK_Ordinary, 12887 UnOp->getOperatorLoc()); 12888 } 12889 } 12890 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12891 Found, Fn); 12892 if (SubExpr == UnOp->getSubExpr()) 12893 return UnOp; 12894 12895 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12896 Context.getPointerType(SubExpr->getType()), 12897 VK_RValue, OK_Ordinary, 12898 UnOp->getOperatorLoc()); 12899 } 12900 12901 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12902 // FIXME: avoid copy. 12903 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12904 if (ULE->hasExplicitTemplateArgs()) { 12905 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12906 TemplateArgs = &TemplateArgsBuffer; 12907 } 12908 12909 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12910 ULE->getQualifierLoc(), 12911 ULE->getTemplateKeywordLoc(), 12912 Fn, 12913 /*enclosing*/ false, // FIXME? 12914 ULE->getNameLoc(), 12915 Fn->getType(), 12916 VK_LValue, 12917 Found.getDecl(), 12918 TemplateArgs); 12919 MarkDeclRefReferenced(DRE); 12920 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12921 return DRE; 12922 } 12923 12924 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12925 // FIXME: avoid copy. 12926 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12927 if (MemExpr->hasExplicitTemplateArgs()) { 12928 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12929 TemplateArgs = &TemplateArgsBuffer; 12930 } 12931 12932 Expr *Base; 12933 12934 // If we're filling in a static method where we used to have an 12935 // implicit member access, rewrite to a simple decl ref. 12936 if (MemExpr->isImplicitAccess()) { 12937 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12938 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12939 MemExpr->getQualifierLoc(), 12940 MemExpr->getTemplateKeywordLoc(), 12941 Fn, 12942 /*enclosing*/ false, 12943 MemExpr->getMemberLoc(), 12944 Fn->getType(), 12945 VK_LValue, 12946 Found.getDecl(), 12947 TemplateArgs); 12948 MarkDeclRefReferenced(DRE); 12949 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12950 return DRE; 12951 } else { 12952 SourceLocation Loc = MemExpr->getMemberLoc(); 12953 if (MemExpr->getQualifier()) 12954 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12955 CheckCXXThisCapture(Loc); 12956 Base = new (Context) CXXThisExpr(Loc, 12957 MemExpr->getBaseType(), 12958 /*isImplicit=*/true); 12959 } 12960 } else 12961 Base = MemExpr->getBase(); 12962 12963 ExprValueKind valueKind; 12964 QualType type; 12965 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12966 valueKind = VK_LValue; 12967 type = Fn->getType(); 12968 } else { 12969 valueKind = VK_RValue; 12970 type = Context.BoundMemberTy; 12971 } 12972 12973 MemberExpr *ME = MemberExpr::Create( 12974 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12975 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12976 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12977 OK_Ordinary); 12978 ME->setHadMultipleCandidates(true); 12979 MarkMemberReferenced(ME); 12980 return ME; 12981 } 12982 12983 llvm_unreachable("Invalid reference to overloaded function"); 12984 } 12985 12986 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12987 DeclAccessPair Found, 12988 FunctionDecl *Fn) { 12989 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12990 } 12991