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 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1133 return false; 1134 1135 // Allow overloading of functions with same signature, but 1136 // different CUDA target attributes. 1137 return NewTarget != OldTarget; 1138 } 1139 1140 // The signatures match; this is not an overload. 1141 return false; 1142 } 1143 1144 /// \brief Checks availability of the function depending on the current 1145 /// function context. Inside an unavailable function, unavailability is ignored. 1146 /// 1147 /// \returns true if \arg FD is unavailable and current context is inside 1148 /// an available function, false otherwise. 1149 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1150 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1151 } 1152 1153 /// \brief Tries a user-defined conversion from From to ToType. 1154 /// 1155 /// Produces an implicit conversion sequence for when a standard conversion 1156 /// is not an option. See TryImplicitConversion for more information. 1157 static ImplicitConversionSequence 1158 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1159 bool SuppressUserConversions, 1160 bool AllowExplicit, 1161 bool InOverloadResolution, 1162 bool CStyle, 1163 bool AllowObjCWritebackConversion, 1164 bool AllowObjCConversionOnExplicit) { 1165 ImplicitConversionSequence ICS; 1166 1167 if (SuppressUserConversions) { 1168 // We're not in the case above, so there is no conversion that 1169 // we can perform. 1170 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1171 return ICS; 1172 } 1173 1174 // Attempt user-defined conversion. 1175 OverloadCandidateSet Conversions(From->getExprLoc(), 1176 OverloadCandidateSet::CSK_Normal); 1177 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1178 Conversions, AllowExplicit, 1179 AllowObjCConversionOnExplicit)) { 1180 case OR_Success: 1181 case OR_Deleted: 1182 ICS.setUserDefined(); 1183 ICS.UserDefined.Before.setAsIdentityConversion(); 1184 // C++ [over.ics.user]p4: 1185 // A conversion of an expression of class type to the same class 1186 // type is given Exact Match rank, and a conversion of an 1187 // expression of class type to a base class of that type is 1188 // given Conversion rank, in spite of the fact that a copy 1189 // constructor (i.e., a user-defined conversion function) is 1190 // called for those cases. 1191 if (CXXConstructorDecl *Constructor 1192 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1193 QualType FromCanon 1194 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1195 QualType ToCanon 1196 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1197 if (Constructor->isCopyConstructor() && 1198 (FromCanon == ToCanon || 1199 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1200 // Turn this into a "standard" conversion sequence, so that it 1201 // gets ranked with standard conversion sequences. 1202 ICS.setStandard(); 1203 ICS.Standard.setAsIdentityConversion(); 1204 ICS.Standard.setFromType(From->getType()); 1205 ICS.Standard.setAllToTypes(ToType); 1206 ICS.Standard.CopyConstructor = Constructor; 1207 if (ToCanon != FromCanon) 1208 ICS.Standard.Second = ICK_Derived_To_Base; 1209 } 1210 } 1211 break; 1212 1213 case OR_Ambiguous: 1214 ICS.setAmbiguous(); 1215 ICS.Ambiguous.setFromType(From->getType()); 1216 ICS.Ambiguous.setToType(ToType); 1217 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1218 Cand != Conversions.end(); ++Cand) 1219 if (Cand->Viable) 1220 ICS.Ambiguous.addConversion(Cand->Function); 1221 break; 1222 1223 // Fall through. 1224 case OR_No_Viable_Function: 1225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1226 break; 1227 } 1228 1229 return ICS; 1230 } 1231 1232 /// TryImplicitConversion - Attempt to perform an implicit conversion 1233 /// from the given expression (Expr) to the given type (ToType). This 1234 /// function returns an implicit conversion sequence that can be used 1235 /// to perform the initialization. Given 1236 /// 1237 /// void f(float f); 1238 /// void g(int i) { f(i); } 1239 /// 1240 /// this routine would produce an implicit conversion sequence to 1241 /// describe the initialization of f from i, which will be a standard 1242 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1243 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1244 // 1245 /// Note that this routine only determines how the conversion can be 1246 /// performed; it does not actually perform the conversion. As such, 1247 /// it will not produce any diagnostics if no conversion is available, 1248 /// but will instead return an implicit conversion sequence of kind 1249 /// "BadConversion". 1250 /// 1251 /// If @p SuppressUserConversions, then user-defined conversions are 1252 /// not permitted. 1253 /// If @p AllowExplicit, then explicit user-defined conversions are 1254 /// permitted. 1255 /// 1256 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1257 /// writeback conversion, which allows __autoreleasing id* parameters to 1258 /// be initialized with __strong id* or __weak id* arguments. 1259 static ImplicitConversionSequence 1260 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1261 bool SuppressUserConversions, 1262 bool AllowExplicit, 1263 bool InOverloadResolution, 1264 bool CStyle, 1265 bool AllowObjCWritebackConversion, 1266 bool AllowObjCConversionOnExplicit) { 1267 ImplicitConversionSequence ICS; 1268 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1269 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1270 ICS.setStandard(); 1271 return ICS; 1272 } 1273 1274 if (!S.getLangOpts().CPlusPlus) { 1275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1276 return ICS; 1277 } 1278 1279 // C++ [over.ics.user]p4: 1280 // A conversion of an expression of class type to the same class 1281 // type is given Exact Match rank, and a conversion of an 1282 // expression of class type to a base class of that type is 1283 // given Conversion rank, in spite of the fact that a copy/move 1284 // constructor (i.e., a user-defined conversion function) is 1285 // called for those cases. 1286 QualType FromType = From->getType(); 1287 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1288 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1289 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1290 ICS.setStandard(); 1291 ICS.Standard.setAsIdentityConversion(); 1292 ICS.Standard.setFromType(FromType); 1293 ICS.Standard.setAllToTypes(ToType); 1294 1295 // We don't actually check at this point whether there is a valid 1296 // copy/move constructor, since overloading just assumes that it 1297 // exists. When we actually perform initialization, we'll find the 1298 // appropriate constructor to copy the returned object, if needed. 1299 ICS.Standard.CopyConstructor = nullptr; 1300 1301 // Determine whether this is considered a derived-to-base conversion. 1302 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1303 ICS.Standard.Second = ICK_Derived_To_Base; 1304 1305 return ICS; 1306 } 1307 1308 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1309 AllowExplicit, InOverloadResolution, CStyle, 1310 AllowObjCWritebackConversion, 1311 AllowObjCConversionOnExplicit); 1312 } 1313 1314 ImplicitConversionSequence 1315 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1316 bool SuppressUserConversions, 1317 bool AllowExplicit, 1318 bool InOverloadResolution, 1319 bool CStyle, 1320 bool AllowObjCWritebackConversion) { 1321 return ::TryImplicitConversion(*this, From, ToType, 1322 SuppressUserConversions, AllowExplicit, 1323 InOverloadResolution, CStyle, 1324 AllowObjCWritebackConversion, 1325 /*AllowObjCConversionOnExplicit=*/false); 1326 } 1327 1328 /// PerformImplicitConversion - Perform an implicit conversion of the 1329 /// expression From to the type ToType. Returns the 1330 /// converted expression. Flavor is the kind of conversion we're 1331 /// performing, used in the error message. If @p AllowExplicit, 1332 /// explicit user-defined conversions are permitted. 1333 ExprResult 1334 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1335 AssignmentAction Action, bool AllowExplicit) { 1336 ImplicitConversionSequence ICS; 1337 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1338 } 1339 1340 ExprResult 1341 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1342 AssignmentAction Action, bool AllowExplicit, 1343 ImplicitConversionSequence& ICS) { 1344 if (checkPlaceholderForOverload(*this, From)) 1345 return ExprError(); 1346 1347 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1348 bool AllowObjCWritebackConversion 1349 = getLangOpts().ObjCAutoRefCount && 1350 (Action == AA_Passing || Action == AA_Sending); 1351 if (getLangOpts().ObjC1) 1352 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1353 ToType, From->getType(), From); 1354 ICS = ::TryImplicitConversion(*this, From, ToType, 1355 /*SuppressUserConversions=*/false, 1356 AllowExplicit, 1357 /*InOverloadResolution=*/false, 1358 /*CStyle=*/false, 1359 AllowObjCWritebackConversion, 1360 /*AllowObjCConversionOnExplicit=*/false); 1361 return PerformImplicitConversion(From, ToType, ICS, Action); 1362 } 1363 1364 /// \brief Determine whether the conversion from FromType to ToType is a valid 1365 /// conversion that strips "noreturn" off the nested function type. 1366 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1367 QualType &ResultTy) { 1368 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1369 return false; 1370 1371 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1372 // where F adds one of the following at most once: 1373 // - a pointer 1374 // - a member pointer 1375 // - a block pointer 1376 CanQualType CanTo = Context.getCanonicalType(ToType); 1377 CanQualType CanFrom = Context.getCanonicalType(FromType); 1378 Type::TypeClass TyClass = CanTo->getTypeClass(); 1379 if (TyClass != CanFrom->getTypeClass()) return false; 1380 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1381 if (TyClass == Type::Pointer) { 1382 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1383 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1384 } else if (TyClass == Type::BlockPointer) { 1385 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1386 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1387 } else if (TyClass == Type::MemberPointer) { 1388 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1389 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1390 } else { 1391 return false; 1392 } 1393 1394 TyClass = CanTo->getTypeClass(); 1395 if (TyClass != CanFrom->getTypeClass()) return false; 1396 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1397 return false; 1398 } 1399 1400 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1401 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1402 if (!EInfo.getNoReturn()) return false; 1403 1404 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1405 assert(QualType(FromFn, 0).isCanonical()); 1406 if (QualType(FromFn, 0) != CanTo) return false; 1407 1408 ResultTy = ToType; 1409 return true; 1410 } 1411 1412 /// \brief Determine whether the conversion from FromType to ToType is a valid 1413 /// vector conversion. 1414 /// 1415 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1416 /// conversion. 1417 static bool IsVectorConversion(Sema &S, QualType FromType, 1418 QualType ToType, ImplicitConversionKind &ICK) { 1419 // We need at least one of these types to be a vector type to have a vector 1420 // conversion. 1421 if (!ToType->isVectorType() && !FromType->isVectorType()) 1422 return false; 1423 1424 // Identical types require no conversions. 1425 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1426 return false; 1427 1428 // There are no conversions between extended vector types, only identity. 1429 if (ToType->isExtVectorType()) { 1430 // There are no conversions between extended vector types other than the 1431 // identity conversion. 1432 if (FromType->isExtVectorType()) 1433 return false; 1434 1435 // Vector splat from any arithmetic type to a vector. 1436 if (FromType->isArithmeticType()) { 1437 ICK = ICK_Vector_Splat; 1438 return true; 1439 } 1440 } 1441 1442 // We can perform the conversion between vector types in the following cases: 1443 // 1)vector types are equivalent AltiVec and GCC vector types 1444 // 2)lax vector conversions are permitted and the vector types are of the 1445 // same size 1446 if (ToType->isVectorType() && FromType->isVectorType()) { 1447 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1448 S.isLaxVectorConversion(FromType, ToType)) { 1449 ICK = ICK_Vector_Conversion; 1450 return true; 1451 } 1452 } 1453 1454 return false; 1455 } 1456 1457 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1458 bool InOverloadResolution, 1459 StandardConversionSequence &SCS, 1460 bool CStyle); 1461 1462 /// IsStandardConversion - Determines whether there is a standard 1463 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1464 /// expression From to the type ToType. Standard conversion sequences 1465 /// only consider non-class types; for conversions that involve class 1466 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1467 /// contain the standard conversion sequence required to perform this 1468 /// conversion and this routine will return true. Otherwise, this 1469 /// routine will return false and the value of SCS is unspecified. 1470 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1471 bool InOverloadResolution, 1472 StandardConversionSequence &SCS, 1473 bool CStyle, 1474 bool AllowObjCWritebackConversion) { 1475 QualType FromType = From->getType(); 1476 1477 // Standard conversions (C++ [conv]) 1478 SCS.setAsIdentityConversion(); 1479 SCS.IncompatibleObjC = false; 1480 SCS.setFromType(FromType); 1481 SCS.CopyConstructor = nullptr; 1482 1483 // There are no standard conversions for class types in C++, so 1484 // abort early. When overloading in C, however, we do permit them. 1485 if (S.getLangOpts().CPlusPlus && 1486 (FromType->isRecordType() || ToType->isRecordType())) 1487 return false; 1488 1489 // The first conversion can be an lvalue-to-rvalue conversion, 1490 // array-to-pointer conversion, or function-to-pointer conversion 1491 // (C++ 4p1). 1492 1493 if (FromType == S.Context.OverloadTy) { 1494 DeclAccessPair AccessPair; 1495 if (FunctionDecl *Fn 1496 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1497 AccessPair)) { 1498 // We were able to resolve the address of the overloaded function, 1499 // so we can convert to the type of that function. 1500 FromType = Fn->getType(); 1501 SCS.setFromType(FromType); 1502 1503 // we can sometimes resolve &foo<int> regardless of ToType, so check 1504 // if the type matches (identity) or we are converting to bool 1505 if (!S.Context.hasSameUnqualifiedType( 1506 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1507 QualType resultTy; 1508 // if the function type matches except for [[noreturn]], it's ok 1509 if (!S.IsNoReturnConversion(FromType, 1510 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1511 // otherwise, only a boolean conversion is standard 1512 if (!ToType->isBooleanType()) 1513 return false; 1514 } 1515 1516 // Check if the "from" expression is taking the address of an overloaded 1517 // function and recompute the FromType accordingly. Take advantage of the 1518 // fact that non-static member functions *must* have such an address-of 1519 // expression. 1520 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1521 if (Method && !Method->isStatic()) { 1522 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1523 "Non-unary operator on non-static member address"); 1524 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1525 == UO_AddrOf && 1526 "Non-address-of operator on non-static member address"); 1527 const Type *ClassType 1528 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1529 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1530 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1531 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1532 UO_AddrOf && 1533 "Non-address-of operator for overloaded function expression"); 1534 FromType = S.Context.getPointerType(FromType); 1535 } 1536 1537 // Check that we've computed the proper type after overload resolution. 1538 assert(S.Context.hasSameType( 1539 FromType, 1540 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1541 } else { 1542 return false; 1543 } 1544 } 1545 // Lvalue-to-rvalue conversion (C++11 4.1): 1546 // A glvalue (3.10) of a non-function, non-array type T can 1547 // be converted to a prvalue. 1548 bool argIsLValue = From->isGLValue(); 1549 if (argIsLValue && 1550 !FromType->isFunctionType() && !FromType->isArrayType() && 1551 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1552 SCS.First = ICK_Lvalue_To_Rvalue; 1553 1554 // C11 6.3.2.1p2: 1555 // ... if the lvalue has atomic type, the value has the non-atomic version 1556 // of the type of the lvalue ... 1557 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1558 FromType = Atomic->getValueType(); 1559 1560 // If T is a non-class type, the type of the rvalue is the 1561 // cv-unqualified version of T. Otherwise, the type of the rvalue 1562 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1563 // just strip the qualifiers because they don't matter. 1564 FromType = FromType.getUnqualifiedType(); 1565 } else if (FromType->isArrayType()) { 1566 // Array-to-pointer conversion (C++ 4.2) 1567 SCS.First = ICK_Array_To_Pointer; 1568 1569 // An lvalue or rvalue of type "array of N T" or "array of unknown 1570 // bound of T" can be converted to an rvalue of type "pointer to 1571 // T" (C++ 4.2p1). 1572 FromType = S.Context.getArrayDecayedType(FromType); 1573 1574 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1575 // This conversion is deprecated in C++03 (D.4) 1576 SCS.DeprecatedStringLiteralToCharPtr = true; 1577 1578 // For the purpose of ranking in overload resolution 1579 // (13.3.3.1.1), this conversion is considered an 1580 // array-to-pointer conversion followed by a qualification 1581 // conversion (4.4). (C++ 4.2p2) 1582 SCS.Second = ICK_Identity; 1583 SCS.Third = ICK_Qualification; 1584 SCS.QualificationIncludesObjCLifetime = false; 1585 SCS.setAllToTypes(FromType); 1586 return true; 1587 } 1588 } else if (FromType->isFunctionType() && argIsLValue) { 1589 // Function-to-pointer conversion (C++ 4.3). 1590 SCS.First = ICK_Function_To_Pointer; 1591 1592 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1593 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1594 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1595 return false; 1596 1597 // An lvalue of function type T can be converted to an rvalue of 1598 // type "pointer to T." The result is a pointer to the 1599 // function. (C++ 4.3p1). 1600 FromType = S.Context.getPointerType(FromType); 1601 } else { 1602 // We don't require any conversions for the first step. 1603 SCS.First = ICK_Identity; 1604 } 1605 SCS.setToType(0, FromType); 1606 1607 // The second conversion can be an integral promotion, floating 1608 // point promotion, integral conversion, floating point conversion, 1609 // floating-integral conversion, pointer conversion, 1610 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1611 // For overloading in C, this can also be a "compatible-type" 1612 // conversion. 1613 bool IncompatibleObjC = false; 1614 ImplicitConversionKind SecondICK = ICK_Identity; 1615 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1616 // The unqualified versions of the types are the same: there's no 1617 // conversion to do. 1618 SCS.Second = ICK_Identity; 1619 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1620 // Integral promotion (C++ 4.5). 1621 SCS.Second = ICK_Integral_Promotion; 1622 FromType = ToType.getUnqualifiedType(); 1623 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1624 // Floating point promotion (C++ 4.6). 1625 SCS.Second = ICK_Floating_Promotion; 1626 FromType = ToType.getUnqualifiedType(); 1627 } else if (S.IsComplexPromotion(FromType, ToType)) { 1628 // Complex promotion (Clang extension) 1629 SCS.Second = ICK_Complex_Promotion; 1630 FromType = ToType.getUnqualifiedType(); 1631 } else if (ToType->isBooleanType() && 1632 (FromType->isArithmeticType() || 1633 FromType->isAnyPointerType() || 1634 FromType->isBlockPointerType() || 1635 FromType->isMemberPointerType() || 1636 FromType->isNullPtrType())) { 1637 // Boolean conversions (C++ 4.12). 1638 SCS.Second = ICK_Boolean_Conversion; 1639 FromType = S.Context.BoolTy; 1640 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1641 ToType->isIntegralType(S.Context)) { 1642 // Integral conversions (C++ 4.7). 1643 SCS.Second = ICK_Integral_Conversion; 1644 FromType = ToType.getUnqualifiedType(); 1645 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1646 // Complex conversions (C99 6.3.1.6) 1647 SCS.Second = ICK_Complex_Conversion; 1648 FromType = ToType.getUnqualifiedType(); 1649 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1650 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1651 // Complex-real conversions (C99 6.3.1.7) 1652 SCS.Second = ICK_Complex_Real; 1653 FromType = ToType.getUnqualifiedType(); 1654 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1655 // Floating point conversions (C++ 4.8). 1656 SCS.Second = ICK_Floating_Conversion; 1657 FromType = ToType.getUnqualifiedType(); 1658 } else if ((FromType->isRealFloatingType() && 1659 ToType->isIntegralType(S.Context)) || 1660 (FromType->isIntegralOrUnscopedEnumerationType() && 1661 ToType->isRealFloatingType())) { 1662 // Floating-integral conversions (C++ 4.9). 1663 SCS.Second = ICK_Floating_Integral; 1664 FromType = ToType.getUnqualifiedType(); 1665 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1666 SCS.Second = ICK_Block_Pointer_Conversion; 1667 } else if (AllowObjCWritebackConversion && 1668 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1669 SCS.Second = ICK_Writeback_Conversion; 1670 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1671 FromType, IncompatibleObjC)) { 1672 // Pointer conversions (C++ 4.10). 1673 SCS.Second = ICK_Pointer_Conversion; 1674 SCS.IncompatibleObjC = IncompatibleObjC; 1675 FromType = FromType.getUnqualifiedType(); 1676 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1677 InOverloadResolution, FromType)) { 1678 // Pointer to member conversions (4.11). 1679 SCS.Second = ICK_Pointer_Member; 1680 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1681 SCS.Second = SecondICK; 1682 FromType = ToType.getUnqualifiedType(); 1683 } else if (!S.getLangOpts().CPlusPlus && 1684 S.Context.typesAreCompatible(ToType, FromType)) { 1685 // Compatible conversions (Clang extension for C function overloading) 1686 SCS.Second = ICK_Compatible_Conversion; 1687 FromType = ToType.getUnqualifiedType(); 1688 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1689 // Treat a conversion that strips "noreturn" as an identity conversion. 1690 SCS.Second = ICK_NoReturn_Adjustment; 1691 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1692 InOverloadResolution, 1693 SCS, CStyle)) { 1694 SCS.Second = ICK_TransparentUnionConversion; 1695 FromType = ToType; 1696 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1697 CStyle)) { 1698 // tryAtomicConversion has updated the standard conversion sequence 1699 // appropriately. 1700 return true; 1701 } else if (ToType->isEventT() && 1702 From->isIntegerConstantExpr(S.getASTContext()) && 1703 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1704 SCS.Second = ICK_Zero_Event_Conversion; 1705 FromType = ToType; 1706 } else { 1707 // No second conversion required. 1708 SCS.Second = ICK_Identity; 1709 } 1710 SCS.setToType(1, FromType); 1711 1712 QualType CanonFrom; 1713 QualType CanonTo; 1714 // The third conversion can be a qualification conversion (C++ 4p1). 1715 bool ObjCLifetimeConversion; 1716 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1717 ObjCLifetimeConversion)) { 1718 SCS.Third = ICK_Qualification; 1719 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1720 FromType = ToType; 1721 CanonFrom = S.Context.getCanonicalType(FromType); 1722 CanonTo = S.Context.getCanonicalType(ToType); 1723 } else { 1724 // No conversion required 1725 SCS.Third = ICK_Identity; 1726 1727 // C++ [over.best.ics]p6: 1728 // [...] Any difference in top-level cv-qualification is 1729 // subsumed by the initialization itself and does not constitute 1730 // a conversion. [...] 1731 CanonFrom = S.Context.getCanonicalType(FromType); 1732 CanonTo = S.Context.getCanonicalType(ToType); 1733 if (CanonFrom.getLocalUnqualifiedType() 1734 == CanonTo.getLocalUnqualifiedType() && 1735 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1736 FromType = ToType; 1737 CanonFrom = CanonTo; 1738 } 1739 } 1740 SCS.setToType(2, FromType); 1741 1742 if (CanonFrom == CanonTo) 1743 return true; 1744 1745 // If we have not converted the argument type to the parameter type, 1746 // this is a bad conversion sequence, unless we're resolving an overload in C. 1747 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1748 return false; 1749 1750 ExprResult ER = ExprResult{From}; 1751 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1752 /*Diagnose=*/false, 1753 /*DiagnoseCFAudited=*/false, 1754 /*ConvertRHS=*/false); 1755 if (Conv != Sema::Compatible) 1756 return false; 1757 1758 SCS.setAllToTypes(ToType); 1759 // We need to set all three because we want this conversion to rank terribly, 1760 // and we don't know what conversions it may overlap with. 1761 SCS.First = ICK_C_Only_Conversion; 1762 SCS.Second = ICK_C_Only_Conversion; 1763 SCS.Third = ICK_C_Only_Conversion; 1764 return true; 1765 } 1766 1767 static bool 1768 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1769 QualType &ToType, 1770 bool InOverloadResolution, 1771 StandardConversionSequence &SCS, 1772 bool CStyle) { 1773 1774 const RecordType *UT = ToType->getAsUnionType(); 1775 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1776 return false; 1777 // The field to initialize within the transparent union. 1778 RecordDecl *UD = UT->getDecl(); 1779 // It's compatible if the expression matches any of the fields. 1780 for (const auto *it : UD->fields()) { 1781 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1782 CStyle, /*ObjCWritebackConversion=*/false)) { 1783 ToType = it->getType(); 1784 return true; 1785 } 1786 } 1787 return false; 1788 } 1789 1790 /// IsIntegralPromotion - Determines whether the conversion from the 1791 /// expression From (whose potentially-adjusted type is FromType) to 1792 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1793 /// sets PromotedType to the promoted type. 1794 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1795 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1796 // All integers are built-in. 1797 if (!To) { 1798 return false; 1799 } 1800 1801 // An rvalue of type char, signed char, unsigned char, short int, or 1802 // unsigned short int can be converted to an rvalue of type int if 1803 // int can represent all the values of the source type; otherwise, 1804 // the source rvalue can be converted to an rvalue of type unsigned 1805 // int (C++ 4.5p1). 1806 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1807 !FromType->isEnumeralType()) { 1808 if (// We can promote any signed, promotable integer type to an int 1809 (FromType->isSignedIntegerType() || 1810 // We can promote any unsigned integer type whose size is 1811 // less than int to an int. 1812 (!FromType->isSignedIntegerType() && 1813 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1814 return To->getKind() == BuiltinType::Int; 1815 } 1816 1817 return To->getKind() == BuiltinType::UInt; 1818 } 1819 1820 // C++11 [conv.prom]p3: 1821 // A prvalue of an unscoped enumeration type whose underlying type is not 1822 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1823 // following types that can represent all the values of the enumeration 1824 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1825 // unsigned int, long int, unsigned long int, long long int, or unsigned 1826 // long long int. If none of the types in that list can represent all the 1827 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1828 // type can be converted to an rvalue a prvalue of the extended integer type 1829 // with lowest integer conversion rank (4.13) greater than the rank of long 1830 // long in which all the values of the enumeration can be represented. If 1831 // there are two such extended types, the signed one is chosen. 1832 // C++11 [conv.prom]p4: 1833 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1834 // can be converted to a prvalue of its underlying type. Moreover, if 1835 // integral promotion can be applied to its underlying type, a prvalue of an 1836 // unscoped enumeration type whose underlying type is fixed can also be 1837 // converted to a prvalue of the promoted underlying type. 1838 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1839 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1840 // provided for a scoped enumeration. 1841 if (FromEnumType->getDecl()->isScoped()) 1842 return false; 1843 1844 // We can perform an integral promotion to the underlying type of the enum, 1845 // even if that's not the promoted type. Note that the check for promoting 1846 // the underlying type is based on the type alone, and does not consider 1847 // the bitfield-ness of the actual source expression. 1848 if (FromEnumType->getDecl()->isFixed()) { 1849 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1850 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1851 IsIntegralPromotion(nullptr, Underlying, ToType); 1852 } 1853 1854 // We have already pre-calculated the promotion type, so this is trivial. 1855 if (ToType->isIntegerType() && 1856 isCompleteType(From->getLocStart(), FromType)) 1857 return Context.hasSameUnqualifiedType( 1858 ToType, FromEnumType->getDecl()->getPromotionType()); 1859 } 1860 1861 // C++0x [conv.prom]p2: 1862 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1863 // to an rvalue a prvalue of the first of the following types that can 1864 // represent all the values of its underlying type: int, unsigned int, 1865 // long int, unsigned long int, long long int, or unsigned long long int. 1866 // If none of the types in that list can represent all the values of its 1867 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1868 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1869 // type. 1870 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1871 ToType->isIntegerType()) { 1872 // Determine whether the type we're converting from is signed or 1873 // unsigned. 1874 bool FromIsSigned = FromType->isSignedIntegerType(); 1875 uint64_t FromSize = Context.getTypeSize(FromType); 1876 1877 // The types we'll try to promote to, in the appropriate 1878 // order. Try each of these types. 1879 QualType PromoteTypes[6] = { 1880 Context.IntTy, Context.UnsignedIntTy, 1881 Context.LongTy, Context.UnsignedLongTy , 1882 Context.LongLongTy, Context.UnsignedLongLongTy 1883 }; 1884 for (int Idx = 0; Idx < 6; ++Idx) { 1885 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1886 if (FromSize < ToSize || 1887 (FromSize == ToSize && 1888 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1889 // We found the type that we can promote to. If this is the 1890 // type we wanted, we have a promotion. Otherwise, no 1891 // promotion. 1892 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1893 } 1894 } 1895 } 1896 1897 // An rvalue for an integral bit-field (9.6) can be converted to an 1898 // rvalue of type int if int can represent all the values of the 1899 // bit-field; otherwise, it can be converted to unsigned int if 1900 // unsigned int can represent all the values of the bit-field. If 1901 // the bit-field is larger yet, no integral promotion applies to 1902 // it. If the bit-field has an enumerated type, it is treated as any 1903 // other value of that type for promotion purposes (C++ 4.5p3). 1904 // FIXME: We should delay checking of bit-fields until we actually perform the 1905 // conversion. 1906 if (From) { 1907 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1908 llvm::APSInt BitWidth; 1909 if (FromType->isIntegralType(Context) && 1910 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1911 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1912 ToSize = Context.getTypeSize(ToType); 1913 1914 // Are we promoting to an int from a bitfield that fits in an int? 1915 if (BitWidth < ToSize || 1916 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1917 return To->getKind() == BuiltinType::Int; 1918 } 1919 1920 // Are we promoting to an unsigned int from an unsigned bitfield 1921 // that fits into an unsigned int? 1922 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1923 return To->getKind() == BuiltinType::UInt; 1924 } 1925 1926 return false; 1927 } 1928 } 1929 } 1930 1931 // An rvalue of type bool can be converted to an rvalue of type int, 1932 // with false becoming zero and true becoming one (C++ 4.5p4). 1933 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1934 return true; 1935 } 1936 1937 return false; 1938 } 1939 1940 /// IsFloatingPointPromotion - Determines whether the conversion from 1941 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1942 /// returns true and sets PromotedType to the promoted type. 1943 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1944 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1945 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1946 /// An rvalue of type float can be converted to an rvalue of type 1947 /// double. (C++ 4.6p1). 1948 if (FromBuiltin->getKind() == BuiltinType::Float && 1949 ToBuiltin->getKind() == BuiltinType::Double) 1950 return true; 1951 1952 // C99 6.3.1.5p1: 1953 // When a float is promoted to double or long double, or a 1954 // double is promoted to long double [...]. 1955 if (!getLangOpts().CPlusPlus && 1956 (FromBuiltin->getKind() == BuiltinType::Float || 1957 FromBuiltin->getKind() == BuiltinType::Double) && 1958 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1959 return true; 1960 1961 // Half can be promoted to float. 1962 if (!getLangOpts().NativeHalfType && 1963 FromBuiltin->getKind() == BuiltinType::Half && 1964 ToBuiltin->getKind() == BuiltinType::Float) 1965 return true; 1966 } 1967 1968 return false; 1969 } 1970 1971 /// \brief Determine if a conversion is a complex promotion. 1972 /// 1973 /// A complex promotion is defined as a complex -> complex conversion 1974 /// where the conversion between the underlying real types is a 1975 /// floating-point or integral promotion. 1976 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1977 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1978 if (!FromComplex) 1979 return false; 1980 1981 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1982 if (!ToComplex) 1983 return false; 1984 1985 return IsFloatingPointPromotion(FromComplex->getElementType(), 1986 ToComplex->getElementType()) || 1987 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1988 ToComplex->getElementType()); 1989 } 1990 1991 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1992 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1993 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1994 /// if non-empty, will be a pointer to ToType that may or may not have 1995 /// the right set of qualifiers on its pointee. 1996 /// 1997 static QualType 1998 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1999 QualType ToPointee, QualType ToType, 2000 ASTContext &Context, 2001 bool StripObjCLifetime = false) { 2002 assert((FromPtr->getTypeClass() == Type::Pointer || 2003 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2004 "Invalid similarly-qualified pointer type"); 2005 2006 /// Conversions to 'id' subsume cv-qualifier conversions. 2007 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2008 return ToType.getUnqualifiedType(); 2009 2010 QualType CanonFromPointee 2011 = Context.getCanonicalType(FromPtr->getPointeeType()); 2012 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2013 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2014 2015 if (StripObjCLifetime) 2016 Quals.removeObjCLifetime(); 2017 2018 // Exact qualifier match -> return the pointer type we're converting to. 2019 if (CanonToPointee.getLocalQualifiers() == Quals) { 2020 // ToType is exactly what we need. Return it. 2021 if (!ToType.isNull()) 2022 return ToType.getUnqualifiedType(); 2023 2024 // Build a pointer to ToPointee. It has the right qualifiers 2025 // already. 2026 if (isa<ObjCObjectPointerType>(ToType)) 2027 return Context.getObjCObjectPointerType(ToPointee); 2028 return Context.getPointerType(ToPointee); 2029 } 2030 2031 // Just build a canonical type that has the right qualifiers. 2032 QualType QualifiedCanonToPointee 2033 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2034 2035 if (isa<ObjCObjectPointerType>(ToType)) 2036 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2037 return Context.getPointerType(QualifiedCanonToPointee); 2038 } 2039 2040 static bool isNullPointerConstantForConversion(Expr *Expr, 2041 bool InOverloadResolution, 2042 ASTContext &Context) { 2043 // Handle value-dependent integral null pointer constants correctly. 2044 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2045 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2046 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2047 return !InOverloadResolution; 2048 2049 return Expr->isNullPointerConstant(Context, 2050 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2051 : Expr::NPC_ValueDependentIsNull); 2052 } 2053 2054 /// IsPointerConversion - Determines whether the conversion of the 2055 /// expression From, which has the (possibly adjusted) type FromType, 2056 /// can be converted to the type ToType via a pointer conversion (C++ 2057 /// 4.10). If so, returns true and places the converted type (that 2058 /// might differ from ToType in its cv-qualifiers at some level) into 2059 /// ConvertedType. 2060 /// 2061 /// This routine also supports conversions to and from block pointers 2062 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2063 /// pointers to interfaces. FIXME: Once we've determined the 2064 /// appropriate overloading rules for Objective-C, we may want to 2065 /// split the Objective-C checks into a different routine; however, 2066 /// GCC seems to consider all of these conversions to be pointer 2067 /// conversions, so for now they live here. IncompatibleObjC will be 2068 /// set if the conversion is an allowed Objective-C conversion that 2069 /// should result in a warning. 2070 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2071 bool InOverloadResolution, 2072 QualType& ConvertedType, 2073 bool &IncompatibleObjC) { 2074 IncompatibleObjC = false; 2075 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2076 IncompatibleObjC)) 2077 return true; 2078 2079 // Conversion from a null pointer constant to any Objective-C pointer type. 2080 if (ToType->isObjCObjectPointerType() && 2081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2082 ConvertedType = ToType; 2083 return true; 2084 } 2085 2086 // Blocks: Block pointers can be converted to void*. 2087 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2088 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2089 ConvertedType = ToType; 2090 return true; 2091 } 2092 // Blocks: A null pointer constant can be converted to a block 2093 // pointer type. 2094 if (ToType->isBlockPointerType() && 2095 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2096 ConvertedType = ToType; 2097 return true; 2098 } 2099 2100 // If the left-hand-side is nullptr_t, the right side can be a null 2101 // pointer constant. 2102 if (ToType->isNullPtrType() && 2103 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2104 ConvertedType = ToType; 2105 return true; 2106 } 2107 2108 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2109 if (!ToTypePtr) 2110 return false; 2111 2112 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2113 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2114 ConvertedType = ToType; 2115 return true; 2116 } 2117 2118 // Beyond this point, both types need to be pointers 2119 // , including objective-c pointers. 2120 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2121 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2122 !getLangOpts().ObjCAutoRefCount) { 2123 ConvertedType = BuildSimilarlyQualifiedPointerType( 2124 FromType->getAs<ObjCObjectPointerType>(), 2125 ToPointeeType, 2126 ToType, Context); 2127 return true; 2128 } 2129 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2130 if (!FromTypePtr) 2131 return false; 2132 2133 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2134 2135 // If the unqualified pointee types are the same, this can't be a 2136 // pointer conversion, so don't do all of the work below. 2137 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2138 return false; 2139 2140 // An rvalue of type "pointer to cv T," where T is an object type, 2141 // can be converted to an rvalue of type "pointer to cv void" (C++ 2142 // 4.10p2). 2143 if (FromPointeeType->isIncompleteOrObjectType() && 2144 ToPointeeType->isVoidType()) { 2145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2146 ToPointeeType, 2147 ToType, Context, 2148 /*StripObjCLifetime=*/true); 2149 return true; 2150 } 2151 2152 // MSVC allows implicit function to void* type conversion. 2153 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2154 ToPointeeType->isVoidType()) { 2155 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2156 ToPointeeType, 2157 ToType, Context); 2158 return true; 2159 } 2160 2161 // When we're overloading in C, we allow a special kind of pointer 2162 // conversion for compatible-but-not-identical pointee types. 2163 if (!getLangOpts().CPlusPlus && 2164 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2166 ToPointeeType, 2167 ToType, Context); 2168 return true; 2169 } 2170 2171 // C++ [conv.ptr]p3: 2172 // 2173 // An rvalue of type "pointer to cv D," where D is a class type, 2174 // can be converted to an rvalue of type "pointer to cv B," where 2175 // B is a base class (clause 10) of D. If B is an inaccessible 2176 // (clause 11) or ambiguous (10.2) base class of D, a program that 2177 // necessitates this conversion is ill-formed. The result of the 2178 // conversion is a pointer to the base class sub-object of the 2179 // derived class object. The null pointer value is converted to 2180 // the null pointer value of the destination type. 2181 // 2182 // Note that we do not check for ambiguity or inaccessibility 2183 // here. That is handled by CheckPointerConversion. 2184 if (getLangOpts().CPlusPlus && 2185 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2186 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2187 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2188 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2189 ToPointeeType, 2190 ToType, Context); 2191 return true; 2192 } 2193 2194 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2195 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2196 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2197 ToPointeeType, 2198 ToType, Context); 2199 return true; 2200 } 2201 2202 return false; 2203 } 2204 2205 /// \brief Adopt the given qualifiers for the given type. 2206 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2207 Qualifiers TQs = T.getQualifiers(); 2208 2209 // Check whether qualifiers already match. 2210 if (TQs == Qs) 2211 return T; 2212 2213 if (Qs.compatiblyIncludes(TQs)) 2214 return Context.getQualifiedType(T, Qs); 2215 2216 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2217 } 2218 2219 /// isObjCPointerConversion - Determines whether this is an 2220 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2221 /// with the same arguments and return values. 2222 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2223 QualType& ConvertedType, 2224 bool &IncompatibleObjC) { 2225 if (!getLangOpts().ObjC1) 2226 return false; 2227 2228 // The set of qualifiers on the type we're converting from. 2229 Qualifiers FromQualifiers = FromType.getQualifiers(); 2230 2231 // First, we handle all conversions on ObjC object pointer types. 2232 const ObjCObjectPointerType* ToObjCPtr = 2233 ToType->getAs<ObjCObjectPointerType>(); 2234 const ObjCObjectPointerType *FromObjCPtr = 2235 FromType->getAs<ObjCObjectPointerType>(); 2236 2237 if (ToObjCPtr && FromObjCPtr) { 2238 // If the pointee types are the same (ignoring qualifications), 2239 // then this is not a pointer conversion. 2240 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2241 FromObjCPtr->getPointeeType())) 2242 return false; 2243 2244 // Conversion between Objective-C pointers. 2245 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2246 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2247 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2248 if (getLangOpts().CPlusPlus && LHS && RHS && 2249 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2250 FromObjCPtr->getPointeeType())) 2251 return false; 2252 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2253 ToObjCPtr->getPointeeType(), 2254 ToType, Context); 2255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2256 return true; 2257 } 2258 2259 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2260 // Okay: this is some kind of implicit downcast of Objective-C 2261 // interfaces, which is permitted. However, we're going to 2262 // complain about it. 2263 IncompatibleObjC = true; 2264 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2265 ToObjCPtr->getPointeeType(), 2266 ToType, Context); 2267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2268 return true; 2269 } 2270 } 2271 // Beyond this point, both types need to be C pointers or block pointers. 2272 QualType ToPointeeType; 2273 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2274 ToPointeeType = ToCPtr->getPointeeType(); 2275 else if (const BlockPointerType *ToBlockPtr = 2276 ToType->getAs<BlockPointerType>()) { 2277 // Objective C++: We're able to convert from a pointer to any object 2278 // to a block pointer type. 2279 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2280 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2281 return true; 2282 } 2283 ToPointeeType = ToBlockPtr->getPointeeType(); 2284 } 2285 else if (FromType->getAs<BlockPointerType>() && 2286 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2287 // Objective C++: We're able to convert from a block pointer type to a 2288 // pointer to any object. 2289 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2290 return true; 2291 } 2292 else 2293 return false; 2294 2295 QualType FromPointeeType; 2296 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2297 FromPointeeType = FromCPtr->getPointeeType(); 2298 else if (const BlockPointerType *FromBlockPtr = 2299 FromType->getAs<BlockPointerType>()) 2300 FromPointeeType = FromBlockPtr->getPointeeType(); 2301 else 2302 return false; 2303 2304 // If we have pointers to pointers, recursively check whether this 2305 // is an Objective-C conversion. 2306 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2307 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2308 IncompatibleObjC)) { 2309 // We always complain about this conversion. 2310 IncompatibleObjC = true; 2311 ConvertedType = Context.getPointerType(ConvertedType); 2312 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2313 return true; 2314 } 2315 // Allow conversion of pointee being objective-c pointer to another one; 2316 // as in I* to id. 2317 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2318 ToPointeeType->getAs<ObjCObjectPointerType>() && 2319 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2320 IncompatibleObjC)) { 2321 2322 ConvertedType = Context.getPointerType(ConvertedType); 2323 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2324 return true; 2325 } 2326 2327 // If we have pointers to functions or blocks, check whether the only 2328 // differences in the argument and result types are in Objective-C 2329 // pointer conversions. If so, we permit the conversion (but 2330 // complain about it). 2331 const FunctionProtoType *FromFunctionType 2332 = FromPointeeType->getAs<FunctionProtoType>(); 2333 const FunctionProtoType *ToFunctionType 2334 = ToPointeeType->getAs<FunctionProtoType>(); 2335 if (FromFunctionType && ToFunctionType) { 2336 // If the function types are exactly the same, this isn't an 2337 // Objective-C pointer conversion. 2338 if (Context.getCanonicalType(FromPointeeType) 2339 == Context.getCanonicalType(ToPointeeType)) 2340 return false; 2341 2342 // Perform the quick checks that will tell us whether these 2343 // function types are obviously different. 2344 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2345 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2346 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2347 return false; 2348 2349 bool HasObjCConversion = false; 2350 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2351 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2352 // Okay, the types match exactly. Nothing to do. 2353 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2354 ToFunctionType->getReturnType(), 2355 ConvertedType, IncompatibleObjC)) { 2356 // Okay, we have an Objective-C pointer conversion. 2357 HasObjCConversion = true; 2358 } else { 2359 // Function types are too different. Abort. 2360 return false; 2361 } 2362 2363 // Check argument types. 2364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2365 ArgIdx != NumArgs; ++ArgIdx) { 2366 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2367 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2368 if (Context.getCanonicalType(FromArgType) 2369 == Context.getCanonicalType(ToArgType)) { 2370 // Okay, the types match exactly. Nothing to do. 2371 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2372 ConvertedType, IncompatibleObjC)) { 2373 // Okay, we have an Objective-C pointer conversion. 2374 HasObjCConversion = true; 2375 } else { 2376 // Argument types are too different. Abort. 2377 return false; 2378 } 2379 } 2380 2381 if (HasObjCConversion) { 2382 // We had an Objective-C conversion. Allow this pointer 2383 // conversion, but complain about it. 2384 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2385 IncompatibleObjC = true; 2386 return true; 2387 } 2388 } 2389 2390 return false; 2391 } 2392 2393 /// \brief Determine whether this is an Objective-C writeback conversion, 2394 /// used for parameter passing when performing automatic reference counting. 2395 /// 2396 /// \param FromType The type we're converting form. 2397 /// 2398 /// \param ToType The type we're converting to. 2399 /// 2400 /// \param ConvertedType The type that will be produced after applying 2401 /// this conversion. 2402 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2403 QualType &ConvertedType) { 2404 if (!getLangOpts().ObjCAutoRefCount || 2405 Context.hasSameUnqualifiedType(FromType, ToType)) 2406 return false; 2407 2408 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2409 QualType ToPointee; 2410 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2411 ToPointee = ToPointer->getPointeeType(); 2412 else 2413 return false; 2414 2415 Qualifiers ToQuals = ToPointee.getQualifiers(); 2416 if (!ToPointee->isObjCLifetimeType() || 2417 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2418 !ToQuals.withoutObjCLifetime().empty()) 2419 return false; 2420 2421 // Argument must be a pointer to __strong to __weak. 2422 QualType FromPointee; 2423 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2424 FromPointee = FromPointer->getPointeeType(); 2425 else 2426 return false; 2427 2428 Qualifiers FromQuals = FromPointee.getQualifiers(); 2429 if (!FromPointee->isObjCLifetimeType() || 2430 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2431 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2432 return false; 2433 2434 // Make sure that we have compatible qualifiers. 2435 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2436 if (!ToQuals.compatiblyIncludes(FromQuals)) 2437 return false; 2438 2439 // Remove qualifiers from the pointee type we're converting from; they 2440 // aren't used in the compatibility check belong, and we'll be adding back 2441 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2442 FromPointee = FromPointee.getUnqualifiedType(); 2443 2444 // The unqualified form of the pointee types must be compatible. 2445 ToPointee = ToPointee.getUnqualifiedType(); 2446 bool IncompatibleObjC; 2447 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2448 FromPointee = ToPointee; 2449 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2450 IncompatibleObjC)) 2451 return false; 2452 2453 /// \brief Construct the type we're converting to, which is a pointer to 2454 /// __autoreleasing pointee. 2455 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2456 ConvertedType = Context.getPointerType(FromPointee); 2457 return true; 2458 } 2459 2460 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2461 QualType& ConvertedType) { 2462 QualType ToPointeeType; 2463 if (const BlockPointerType *ToBlockPtr = 2464 ToType->getAs<BlockPointerType>()) 2465 ToPointeeType = ToBlockPtr->getPointeeType(); 2466 else 2467 return false; 2468 2469 QualType FromPointeeType; 2470 if (const BlockPointerType *FromBlockPtr = 2471 FromType->getAs<BlockPointerType>()) 2472 FromPointeeType = FromBlockPtr->getPointeeType(); 2473 else 2474 return false; 2475 // We have pointer to blocks, check whether the only 2476 // differences in the argument and result types are in Objective-C 2477 // pointer conversions. If so, we permit the conversion. 2478 2479 const FunctionProtoType *FromFunctionType 2480 = FromPointeeType->getAs<FunctionProtoType>(); 2481 const FunctionProtoType *ToFunctionType 2482 = ToPointeeType->getAs<FunctionProtoType>(); 2483 2484 if (!FromFunctionType || !ToFunctionType) 2485 return false; 2486 2487 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2488 return true; 2489 2490 // Perform the quick checks that will tell us whether these 2491 // function types are obviously different. 2492 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2493 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2494 return false; 2495 2496 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2497 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2498 if (FromEInfo != ToEInfo) 2499 return false; 2500 2501 bool IncompatibleObjC = false; 2502 if (Context.hasSameType(FromFunctionType->getReturnType(), 2503 ToFunctionType->getReturnType())) { 2504 // Okay, the types match exactly. Nothing to do. 2505 } else { 2506 QualType RHS = FromFunctionType->getReturnType(); 2507 QualType LHS = ToFunctionType->getReturnType(); 2508 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2509 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2510 LHS = LHS.getUnqualifiedType(); 2511 2512 if (Context.hasSameType(RHS,LHS)) { 2513 // OK exact match. 2514 } else if (isObjCPointerConversion(RHS, LHS, 2515 ConvertedType, IncompatibleObjC)) { 2516 if (IncompatibleObjC) 2517 return false; 2518 // Okay, we have an Objective-C pointer conversion. 2519 } 2520 else 2521 return false; 2522 } 2523 2524 // Check argument types. 2525 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2526 ArgIdx != NumArgs; ++ArgIdx) { 2527 IncompatibleObjC = false; 2528 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2529 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2530 if (Context.hasSameType(FromArgType, ToArgType)) { 2531 // Okay, the types match exactly. Nothing to do. 2532 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2533 ConvertedType, IncompatibleObjC)) { 2534 if (IncompatibleObjC) 2535 return false; 2536 // Okay, we have an Objective-C pointer conversion. 2537 } else 2538 // Argument types are too different. Abort. 2539 return false; 2540 } 2541 if (LangOpts.ObjCAutoRefCount && 2542 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2543 ToFunctionType)) 2544 return false; 2545 2546 ConvertedType = ToType; 2547 return true; 2548 } 2549 2550 enum { 2551 ft_default, 2552 ft_different_class, 2553 ft_parameter_arity, 2554 ft_parameter_mismatch, 2555 ft_return_type, 2556 ft_qualifer_mismatch 2557 }; 2558 2559 /// Attempts to get the FunctionProtoType from a Type. Handles 2560 /// MemberFunctionPointers properly. 2561 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2562 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2563 return FPT; 2564 2565 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2566 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2567 2568 return nullptr; 2569 } 2570 2571 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2572 /// function types. Catches different number of parameter, mismatch in 2573 /// parameter types, and different return types. 2574 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2575 QualType FromType, QualType ToType) { 2576 // If either type is not valid, include no extra info. 2577 if (FromType.isNull() || ToType.isNull()) { 2578 PDiag << ft_default; 2579 return; 2580 } 2581 2582 // Get the function type from the pointers. 2583 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2584 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2585 *ToMember = ToType->getAs<MemberPointerType>(); 2586 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2587 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2588 << QualType(FromMember->getClass(), 0); 2589 return; 2590 } 2591 FromType = FromMember->getPointeeType(); 2592 ToType = ToMember->getPointeeType(); 2593 } 2594 2595 if (FromType->isPointerType()) 2596 FromType = FromType->getPointeeType(); 2597 if (ToType->isPointerType()) 2598 ToType = ToType->getPointeeType(); 2599 2600 // Remove references. 2601 FromType = FromType.getNonReferenceType(); 2602 ToType = ToType.getNonReferenceType(); 2603 2604 // Don't print extra info for non-specialized template functions. 2605 if (FromType->isInstantiationDependentType() && 2606 !FromType->getAs<TemplateSpecializationType>()) { 2607 PDiag << ft_default; 2608 return; 2609 } 2610 2611 // No extra info for same types. 2612 if (Context.hasSameType(FromType, ToType)) { 2613 PDiag << ft_default; 2614 return; 2615 } 2616 2617 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2618 *ToFunction = tryGetFunctionProtoType(ToType); 2619 2620 // Both types need to be function types. 2621 if (!FromFunction || !ToFunction) { 2622 PDiag << ft_default; 2623 return; 2624 } 2625 2626 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2627 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2628 << FromFunction->getNumParams(); 2629 return; 2630 } 2631 2632 // Handle different parameter types. 2633 unsigned ArgPos; 2634 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2635 PDiag << ft_parameter_mismatch << ArgPos + 1 2636 << ToFunction->getParamType(ArgPos) 2637 << FromFunction->getParamType(ArgPos); 2638 return; 2639 } 2640 2641 // Handle different return type. 2642 if (!Context.hasSameType(FromFunction->getReturnType(), 2643 ToFunction->getReturnType())) { 2644 PDiag << ft_return_type << ToFunction->getReturnType() 2645 << FromFunction->getReturnType(); 2646 return; 2647 } 2648 2649 unsigned FromQuals = FromFunction->getTypeQuals(), 2650 ToQuals = ToFunction->getTypeQuals(); 2651 if (FromQuals != ToQuals) { 2652 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2653 return; 2654 } 2655 2656 // Unable to find a difference, so add no extra info. 2657 PDiag << ft_default; 2658 } 2659 2660 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2661 /// for equality of their argument types. Caller has already checked that 2662 /// they have same number of arguments. If the parameters are different, 2663 /// ArgPos will have the parameter index of the first different parameter. 2664 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2665 const FunctionProtoType *NewType, 2666 unsigned *ArgPos) { 2667 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2668 N = NewType->param_type_begin(), 2669 E = OldType->param_type_end(); 2670 O && (O != E); ++O, ++N) { 2671 if (!Context.hasSameType(O->getUnqualifiedType(), 2672 N->getUnqualifiedType())) { 2673 if (ArgPos) 2674 *ArgPos = O - OldType->param_type_begin(); 2675 return false; 2676 } 2677 } 2678 return true; 2679 } 2680 2681 /// CheckPointerConversion - Check the pointer conversion from the 2682 /// expression From to the type ToType. This routine checks for 2683 /// ambiguous or inaccessible derived-to-base pointer 2684 /// conversions for which IsPointerConversion has already returned 2685 /// true. It returns true and produces a diagnostic if there was an 2686 /// error, or returns false otherwise. 2687 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2688 CastKind &Kind, 2689 CXXCastPath& BasePath, 2690 bool IgnoreBaseAccess, 2691 bool Diagnose) { 2692 QualType FromType = From->getType(); 2693 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2694 2695 Kind = CK_BitCast; 2696 2697 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2698 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2699 Expr::NPCK_ZeroExpression) { 2700 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2701 DiagRuntimeBehavior(From->getExprLoc(), From, 2702 PDiag(diag::warn_impcast_bool_to_null_pointer) 2703 << ToType << From->getSourceRange()); 2704 else if (!isUnevaluatedContext()) 2705 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2706 << ToType << From->getSourceRange(); 2707 } 2708 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2709 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2710 QualType FromPointeeType = FromPtrType->getPointeeType(), 2711 ToPointeeType = ToPtrType->getPointeeType(); 2712 2713 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2714 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2715 // We must have a derived-to-base conversion. Check an 2716 // ambiguous or inaccessible conversion. 2717 unsigned InaccessibleID = 0; 2718 unsigned AmbigiousID = 0; 2719 if (Diagnose) { 2720 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2721 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2722 } 2723 if (CheckDerivedToBaseConversion( 2724 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2725 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2726 &BasePath, IgnoreBaseAccess)) 2727 return true; 2728 2729 // The conversion was successful. 2730 Kind = CK_DerivedToBase; 2731 } 2732 2733 if (Diagnose && !IsCStyleOrFunctionalCast && 2734 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2735 assert(getLangOpts().MSVCCompat && 2736 "this should only be possible with MSVCCompat!"); 2737 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2738 << From->getSourceRange(); 2739 } 2740 } 2741 } else if (const ObjCObjectPointerType *ToPtrType = 2742 ToType->getAs<ObjCObjectPointerType>()) { 2743 if (const ObjCObjectPointerType *FromPtrType = 2744 FromType->getAs<ObjCObjectPointerType>()) { 2745 // Objective-C++ conversions are always okay. 2746 // FIXME: We should have a different class of conversions for the 2747 // Objective-C++ implicit conversions. 2748 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2749 return false; 2750 } else if (FromType->isBlockPointerType()) { 2751 Kind = CK_BlockPointerToObjCPointerCast; 2752 } else { 2753 Kind = CK_CPointerToObjCPointerCast; 2754 } 2755 } else if (ToType->isBlockPointerType()) { 2756 if (!FromType->isBlockPointerType()) 2757 Kind = CK_AnyPointerToBlockPointerCast; 2758 } 2759 2760 // We shouldn't fall into this case unless it's valid for other 2761 // reasons. 2762 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2763 Kind = CK_NullToPointer; 2764 2765 return false; 2766 } 2767 2768 /// IsMemberPointerConversion - Determines whether the conversion of the 2769 /// expression From, which has the (possibly adjusted) type FromType, can be 2770 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2771 /// If so, returns true and places the converted type (that might differ from 2772 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2773 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2774 QualType ToType, 2775 bool InOverloadResolution, 2776 QualType &ConvertedType) { 2777 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2778 if (!ToTypePtr) 2779 return false; 2780 2781 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2782 if (From->isNullPointerConstant(Context, 2783 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2784 : Expr::NPC_ValueDependentIsNull)) { 2785 ConvertedType = ToType; 2786 return true; 2787 } 2788 2789 // Otherwise, both types have to be member pointers. 2790 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2791 if (!FromTypePtr) 2792 return false; 2793 2794 // A pointer to member of B can be converted to a pointer to member of D, 2795 // where D is derived from B (C++ 4.11p2). 2796 QualType FromClass(FromTypePtr->getClass(), 0); 2797 QualType ToClass(ToTypePtr->getClass(), 0); 2798 2799 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2800 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2801 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2802 ToClass.getTypePtr()); 2803 return true; 2804 } 2805 2806 return false; 2807 } 2808 2809 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2810 /// expression From to the type ToType. This routine checks for ambiguous or 2811 /// virtual or inaccessible base-to-derived member pointer conversions 2812 /// for which IsMemberPointerConversion has already returned true. It returns 2813 /// true and produces a diagnostic if there was an error, or returns false 2814 /// otherwise. 2815 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2816 CastKind &Kind, 2817 CXXCastPath &BasePath, 2818 bool IgnoreBaseAccess) { 2819 QualType FromType = From->getType(); 2820 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2821 if (!FromPtrType) { 2822 // This must be a null pointer to member pointer conversion 2823 assert(From->isNullPointerConstant(Context, 2824 Expr::NPC_ValueDependentIsNull) && 2825 "Expr must be null pointer constant!"); 2826 Kind = CK_NullToMemberPointer; 2827 return false; 2828 } 2829 2830 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2831 assert(ToPtrType && "No member pointer cast has a target type " 2832 "that is not a member pointer."); 2833 2834 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2835 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2836 2837 // FIXME: What about dependent types? 2838 assert(FromClass->isRecordType() && "Pointer into non-class."); 2839 assert(ToClass->isRecordType() && "Pointer into non-class."); 2840 2841 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2842 /*DetectVirtual=*/true); 2843 bool DerivationOkay = 2844 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2845 assert(DerivationOkay && 2846 "Should not have been called if derivation isn't OK."); 2847 (void)DerivationOkay; 2848 2849 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2850 getUnqualifiedType())) { 2851 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2852 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2853 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2854 return true; 2855 } 2856 2857 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2858 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2859 << FromClass << ToClass << QualType(VBase, 0) 2860 << From->getSourceRange(); 2861 return true; 2862 } 2863 2864 if (!IgnoreBaseAccess) 2865 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2866 Paths.front(), 2867 diag::err_downcast_from_inaccessible_base); 2868 2869 // Must be a base to derived member conversion. 2870 BuildBasePathArray(Paths, BasePath); 2871 Kind = CK_BaseToDerivedMemberPointer; 2872 return false; 2873 } 2874 2875 /// Determine whether the lifetime conversion between the two given 2876 /// qualifiers sets is nontrivial. 2877 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2878 Qualifiers ToQuals) { 2879 // Converting anything to const __unsafe_unretained is trivial. 2880 if (ToQuals.hasConst() && 2881 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2882 return false; 2883 2884 return true; 2885 } 2886 2887 /// IsQualificationConversion - Determines whether the conversion from 2888 /// an rvalue of type FromType to ToType is a qualification conversion 2889 /// (C++ 4.4). 2890 /// 2891 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2892 /// when the qualification conversion involves a change in the Objective-C 2893 /// object lifetime. 2894 bool 2895 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2896 bool CStyle, bool &ObjCLifetimeConversion) { 2897 FromType = Context.getCanonicalType(FromType); 2898 ToType = Context.getCanonicalType(ToType); 2899 ObjCLifetimeConversion = false; 2900 2901 // If FromType and ToType are the same type, this is not a 2902 // qualification conversion. 2903 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2904 return false; 2905 2906 // (C++ 4.4p4): 2907 // A conversion can add cv-qualifiers at levels other than the first 2908 // in multi-level pointers, subject to the following rules: [...] 2909 bool PreviousToQualsIncludeConst = true; 2910 bool UnwrappedAnyPointer = false; 2911 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2912 // Within each iteration of the loop, we check the qualifiers to 2913 // determine if this still looks like a qualification 2914 // conversion. Then, if all is well, we unwrap one more level of 2915 // pointers or pointers-to-members and do it all again 2916 // until there are no more pointers or pointers-to-members left to 2917 // unwrap. 2918 UnwrappedAnyPointer = true; 2919 2920 Qualifiers FromQuals = FromType.getQualifiers(); 2921 Qualifiers ToQuals = ToType.getQualifiers(); 2922 2923 // Objective-C ARC: 2924 // Check Objective-C lifetime conversions. 2925 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2926 UnwrappedAnyPointer) { 2927 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2928 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2929 ObjCLifetimeConversion = true; 2930 FromQuals.removeObjCLifetime(); 2931 ToQuals.removeObjCLifetime(); 2932 } else { 2933 // Qualification conversions cannot cast between different 2934 // Objective-C lifetime qualifiers. 2935 return false; 2936 } 2937 } 2938 2939 // Allow addition/removal of GC attributes but not changing GC attributes. 2940 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2941 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2942 FromQuals.removeObjCGCAttr(); 2943 ToQuals.removeObjCGCAttr(); 2944 } 2945 2946 // -- for every j > 0, if const is in cv 1,j then const is in cv 2947 // 2,j, and similarly for volatile. 2948 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2949 return false; 2950 2951 // -- if the cv 1,j and cv 2,j are different, then const is in 2952 // every cv for 0 < k < j. 2953 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2954 && !PreviousToQualsIncludeConst) 2955 return false; 2956 2957 // Keep track of whether all prior cv-qualifiers in the "to" type 2958 // include const. 2959 PreviousToQualsIncludeConst 2960 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2961 } 2962 2963 // We are left with FromType and ToType being the pointee types 2964 // after unwrapping the original FromType and ToType the same number 2965 // of types. If we unwrapped any pointers, and if FromType and 2966 // ToType have the same unqualified type (since we checked 2967 // qualifiers above), then this is a qualification conversion. 2968 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2969 } 2970 2971 /// \brief - Determine whether this is a conversion from a scalar type to an 2972 /// atomic type. 2973 /// 2974 /// If successful, updates \c SCS's second and third steps in the conversion 2975 /// sequence to finish the conversion. 2976 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2977 bool InOverloadResolution, 2978 StandardConversionSequence &SCS, 2979 bool CStyle) { 2980 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2981 if (!ToAtomic) 2982 return false; 2983 2984 StandardConversionSequence InnerSCS; 2985 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2986 InOverloadResolution, InnerSCS, 2987 CStyle, /*AllowObjCWritebackConversion=*/false)) 2988 return false; 2989 2990 SCS.Second = InnerSCS.Second; 2991 SCS.setToType(1, InnerSCS.getToType(1)); 2992 SCS.Third = InnerSCS.Third; 2993 SCS.QualificationIncludesObjCLifetime 2994 = InnerSCS.QualificationIncludesObjCLifetime; 2995 SCS.setToType(2, InnerSCS.getToType(2)); 2996 return true; 2997 } 2998 2999 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3000 CXXConstructorDecl *Constructor, 3001 QualType Type) { 3002 const FunctionProtoType *CtorType = 3003 Constructor->getType()->getAs<FunctionProtoType>(); 3004 if (CtorType->getNumParams() > 0) { 3005 QualType FirstArg = CtorType->getParamType(0); 3006 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3007 return true; 3008 } 3009 return false; 3010 } 3011 3012 static OverloadingResult 3013 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3014 CXXRecordDecl *To, 3015 UserDefinedConversionSequence &User, 3016 OverloadCandidateSet &CandidateSet, 3017 bool AllowExplicit) { 3018 DeclContext::lookup_result R = S.LookupConstructors(To); 3019 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3020 Con != ConEnd; ++Con) { 3021 NamedDecl *D = *Con; 3022 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3023 3024 // Find the constructor (which may be a template). 3025 CXXConstructorDecl *Constructor = nullptr; 3026 FunctionTemplateDecl *ConstructorTmpl 3027 = dyn_cast<FunctionTemplateDecl>(D); 3028 if (ConstructorTmpl) 3029 Constructor 3030 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3031 else 3032 Constructor = cast<CXXConstructorDecl>(D); 3033 3034 bool Usable = !Constructor->isInvalidDecl() && 3035 S.isInitListConstructor(Constructor) && 3036 (AllowExplicit || !Constructor->isExplicit()); 3037 if (Usable) { 3038 // If the first argument is (a reference to) the target type, 3039 // suppress conversions. 3040 bool SuppressUserConversions = 3041 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 3042 if (ConstructorTmpl) 3043 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3044 /*ExplicitArgs*/ nullptr, 3045 From, CandidateSet, 3046 SuppressUserConversions); 3047 else 3048 S.AddOverloadCandidate(Constructor, FoundDecl, 3049 From, CandidateSet, 3050 SuppressUserConversions); 3051 } 3052 } 3053 3054 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3055 3056 OverloadCandidateSet::iterator Best; 3057 switch (auto Result = 3058 CandidateSet.BestViableFunction(S, From->getLocStart(), 3059 Best, true)) { 3060 case OR_Deleted: 3061 case OR_Success: { 3062 // Record the standard conversion we used and the conversion function. 3063 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3064 QualType ThisType = Constructor->getThisType(S.Context); 3065 // Initializer lists don't have conversions as such. 3066 User.Before.setAsIdentityConversion(); 3067 User.HadMultipleCandidates = HadMultipleCandidates; 3068 User.ConversionFunction = Constructor; 3069 User.FoundConversionFunction = Best->FoundDecl; 3070 User.After.setAsIdentityConversion(); 3071 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3072 User.After.setAllToTypes(ToType); 3073 return Result; 3074 } 3075 3076 case OR_No_Viable_Function: 3077 return OR_No_Viable_Function; 3078 case OR_Ambiguous: 3079 return OR_Ambiguous; 3080 } 3081 3082 llvm_unreachable("Invalid OverloadResult!"); 3083 } 3084 3085 /// Determines whether there is a user-defined conversion sequence 3086 /// (C++ [over.ics.user]) that converts expression From to the type 3087 /// ToType. If such a conversion exists, User will contain the 3088 /// user-defined conversion sequence that performs such a conversion 3089 /// and this routine will return true. Otherwise, this routine returns 3090 /// false and User is unspecified. 3091 /// 3092 /// \param AllowExplicit true if the conversion should consider C++0x 3093 /// "explicit" conversion functions as well as non-explicit conversion 3094 /// functions (C++0x [class.conv.fct]p2). 3095 /// 3096 /// \param AllowObjCConversionOnExplicit true if the conversion should 3097 /// allow an extra Objective-C pointer conversion on uses of explicit 3098 /// constructors. Requires \c AllowExplicit to also be set. 3099 static OverloadingResult 3100 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3101 UserDefinedConversionSequence &User, 3102 OverloadCandidateSet &CandidateSet, 3103 bool AllowExplicit, 3104 bool AllowObjCConversionOnExplicit) { 3105 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3106 3107 // Whether we will only visit constructors. 3108 bool ConstructorsOnly = false; 3109 3110 // If the type we are conversion to is a class type, enumerate its 3111 // constructors. 3112 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3113 // C++ [over.match.ctor]p1: 3114 // When objects of class type are direct-initialized (8.5), or 3115 // copy-initialized from an expression of the same or a 3116 // derived class type (8.5), overload resolution selects the 3117 // constructor. [...] For copy-initialization, the candidate 3118 // functions are all the converting constructors (12.3.1) of 3119 // that class. The argument list is the expression-list within 3120 // the parentheses of the initializer. 3121 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3122 (From->getType()->getAs<RecordType>() && 3123 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3124 ConstructorsOnly = true; 3125 3126 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3127 // We're not going to find any constructors. 3128 } else if (CXXRecordDecl *ToRecordDecl 3129 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3130 3131 Expr **Args = &From; 3132 unsigned NumArgs = 1; 3133 bool ListInitializing = false; 3134 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3135 // But first, see if there is an init-list-constructor that will work. 3136 OverloadingResult Result = IsInitializerListConstructorConversion( 3137 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3138 if (Result != OR_No_Viable_Function) 3139 return Result; 3140 // Never mind. 3141 CandidateSet.clear(); 3142 3143 // If we're list-initializing, we pass the individual elements as 3144 // arguments, not the entire list. 3145 Args = InitList->getInits(); 3146 NumArgs = InitList->getNumInits(); 3147 ListInitializing = true; 3148 } 3149 3150 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3151 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3152 Con != ConEnd; ++Con) { 3153 NamedDecl *D = *Con; 3154 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3155 3156 // Find the constructor (which may be a template). 3157 CXXConstructorDecl *Constructor = nullptr; 3158 FunctionTemplateDecl *ConstructorTmpl 3159 = dyn_cast<FunctionTemplateDecl>(D); 3160 if (ConstructorTmpl) 3161 Constructor 3162 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3163 else 3164 Constructor = cast<CXXConstructorDecl>(D); 3165 3166 bool Usable = !Constructor->isInvalidDecl(); 3167 if (ListInitializing) 3168 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3169 else 3170 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3171 if (Usable) { 3172 bool SuppressUserConversions = !ConstructorsOnly; 3173 if (SuppressUserConversions && ListInitializing) { 3174 SuppressUserConversions = false; 3175 if (NumArgs == 1) { 3176 // If the first argument is (a reference to) the target type, 3177 // suppress conversions. 3178 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3179 S.Context, Constructor, ToType); 3180 } 3181 } 3182 if (ConstructorTmpl) 3183 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3184 /*ExplicitArgs*/ nullptr, 3185 llvm::makeArrayRef(Args, NumArgs), 3186 CandidateSet, SuppressUserConversions); 3187 else 3188 // Allow one user-defined conversion when user specifies a 3189 // From->ToType conversion via an static cast (c-style, etc). 3190 S.AddOverloadCandidate(Constructor, FoundDecl, 3191 llvm::makeArrayRef(Args, NumArgs), 3192 CandidateSet, SuppressUserConversions); 3193 } 3194 } 3195 } 3196 } 3197 3198 // Enumerate conversion functions, if we're allowed to. 3199 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3200 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3201 // No conversion functions from incomplete types. 3202 } else if (const RecordType *FromRecordType 3203 = From->getType()->getAs<RecordType>()) { 3204 if (CXXRecordDecl *FromRecordDecl 3205 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3206 // Add all of the conversion functions as candidates. 3207 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3208 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3209 DeclAccessPair FoundDecl = I.getPair(); 3210 NamedDecl *D = FoundDecl.getDecl(); 3211 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3212 if (isa<UsingShadowDecl>(D)) 3213 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3214 3215 CXXConversionDecl *Conv; 3216 FunctionTemplateDecl *ConvTemplate; 3217 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3218 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3219 else 3220 Conv = cast<CXXConversionDecl>(D); 3221 3222 if (AllowExplicit || !Conv->isExplicit()) { 3223 if (ConvTemplate) 3224 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3225 ActingContext, From, ToType, 3226 CandidateSet, 3227 AllowObjCConversionOnExplicit); 3228 else 3229 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3230 From, ToType, CandidateSet, 3231 AllowObjCConversionOnExplicit); 3232 } 3233 } 3234 } 3235 } 3236 3237 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3238 3239 OverloadCandidateSet::iterator Best; 3240 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3241 Best, true)) { 3242 case OR_Success: 3243 case OR_Deleted: 3244 // Record the standard conversion we used and the conversion function. 3245 if (CXXConstructorDecl *Constructor 3246 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3247 // C++ [over.ics.user]p1: 3248 // If the user-defined conversion is specified by a 3249 // constructor (12.3.1), the initial standard conversion 3250 // sequence converts the source type to the type required by 3251 // the argument of the constructor. 3252 // 3253 QualType ThisType = Constructor->getThisType(S.Context); 3254 if (isa<InitListExpr>(From)) { 3255 // Initializer lists don't have conversions as such. 3256 User.Before.setAsIdentityConversion(); 3257 } else { 3258 if (Best->Conversions[0].isEllipsis()) 3259 User.EllipsisConversion = true; 3260 else { 3261 User.Before = Best->Conversions[0].Standard; 3262 User.EllipsisConversion = false; 3263 } 3264 } 3265 User.HadMultipleCandidates = HadMultipleCandidates; 3266 User.ConversionFunction = Constructor; 3267 User.FoundConversionFunction = Best->FoundDecl; 3268 User.After.setAsIdentityConversion(); 3269 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3270 User.After.setAllToTypes(ToType); 3271 return Result; 3272 } 3273 if (CXXConversionDecl *Conversion 3274 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3275 // C++ [over.ics.user]p1: 3276 // 3277 // [...] If the user-defined conversion is specified by a 3278 // conversion function (12.3.2), the initial standard 3279 // conversion sequence converts the source type to the 3280 // implicit object parameter of the conversion function. 3281 User.Before = Best->Conversions[0].Standard; 3282 User.HadMultipleCandidates = HadMultipleCandidates; 3283 User.ConversionFunction = Conversion; 3284 User.FoundConversionFunction = Best->FoundDecl; 3285 User.EllipsisConversion = false; 3286 3287 // C++ [over.ics.user]p2: 3288 // The second standard conversion sequence converts the 3289 // result of the user-defined conversion to the target type 3290 // for the sequence. Since an implicit conversion sequence 3291 // is an initialization, the special rules for 3292 // initialization by user-defined conversion apply when 3293 // selecting the best user-defined conversion for a 3294 // user-defined conversion sequence (see 13.3.3 and 3295 // 13.3.3.1). 3296 User.After = Best->FinalConversion; 3297 return Result; 3298 } 3299 llvm_unreachable("Not a constructor or conversion function?"); 3300 3301 case OR_No_Viable_Function: 3302 return OR_No_Viable_Function; 3303 3304 case OR_Ambiguous: 3305 return OR_Ambiguous; 3306 } 3307 3308 llvm_unreachable("Invalid OverloadResult!"); 3309 } 3310 3311 bool 3312 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3313 ImplicitConversionSequence ICS; 3314 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3315 OverloadCandidateSet::CSK_Normal); 3316 OverloadingResult OvResult = 3317 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3318 CandidateSet, false, false); 3319 if (OvResult == OR_Ambiguous) 3320 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3321 << From->getType() << ToType << From->getSourceRange(); 3322 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3323 if (!RequireCompleteType(From->getLocStart(), ToType, 3324 diag::err_typecheck_nonviable_condition_incomplete, 3325 From->getType(), From->getSourceRange())) 3326 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3327 << false << From->getType() << From->getSourceRange() << ToType; 3328 } else 3329 return false; 3330 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3331 return true; 3332 } 3333 3334 /// \brief Compare the user-defined conversion functions or constructors 3335 /// of two user-defined conversion sequences to determine whether any ordering 3336 /// is possible. 3337 static ImplicitConversionSequence::CompareKind 3338 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3339 FunctionDecl *Function2) { 3340 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3341 return ImplicitConversionSequence::Indistinguishable; 3342 3343 // Objective-C++: 3344 // If both conversion functions are implicitly-declared conversions from 3345 // a lambda closure type to a function pointer and a block pointer, 3346 // respectively, always prefer the conversion to a function pointer, 3347 // because the function pointer is more lightweight and is more likely 3348 // to keep code working. 3349 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3350 if (!Conv1) 3351 return ImplicitConversionSequence::Indistinguishable; 3352 3353 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3354 if (!Conv2) 3355 return ImplicitConversionSequence::Indistinguishable; 3356 3357 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3358 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3359 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3360 if (Block1 != Block2) 3361 return Block1 ? ImplicitConversionSequence::Worse 3362 : ImplicitConversionSequence::Better; 3363 } 3364 3365 return ImplicitConversionSequence::Indistinguishable; 3366 } 3367 3368 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3369 const ImplicitConversionSequence &ICS) { 3370 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3371 (ICS.isUserDefined() && 3372 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3373 } 3374 3375 /// CompareImplicitConversionSequences - Compare two implicit 3376 /// conversion sequences to determine whether one is better than the 3377 /// other or if they are indistinguishable (C++ 13.3.3.2). 3378 static ImplicitConversionSequence::CompareKind 3379 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3380 const ImplicitConversionSequence& ICS1, 3381 const ImplicitConversionSequence& ICS2) 3382 { 3383 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3384 // conversion sequences (as defined in 13.3.3.1) 3385 // -- a standard conversion sequence (13.3.3.1.1) is a better 3386 // conversion sequence than a user-defined conversion sequence or 3387 // an ellipsis conversion sequence, and 3388 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3389 // conversion sequence than an ellipsis conversion sequence 3390 // (13.3.3.1.3). 3391 // 3392 // C++0x [over.best.ics]p10: 3393 // For the purpose of ranking implicit conversion sequences as 3394 // described in 13.3.3.2, the ambiguous conversion sequence is 3395 // treated as a user-defined sequence that is indistinguishable 3396 // from any other user-defined conversion sequence. 3397 3398 // String literal to 'char *' conversion has been deprecated in C++03. It has 3399 // been removed from C++11. We still accept this conversion, if it happens at 3400 // the best viable function. Otherwise, this conversion is considered worse 3401 // than ellipsis conversion. Consider this as an extension; this is not in the 3402 // standard. For example: 3403 // 3404 // int &f(...); // #1 3405 // void f(char*); // #2 3406 // void g() { int &r = f("foo"); } 3407 // 3408 // In C++03, we pick #2 as the best viable function. 3409 // In C++11, we pick #1 as the best viable function, because ellipsis 3410 // conversion is better than string-literal to char* conversion (since there 3411 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3412 // convert arguments, #2 would be the best viable function in C++11. 3413 // If the best viable function has this conversion, a warning will be issued 3414 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3415 3416 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3417 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3418 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3419 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3420 ? ImplicitConversionSequence::Worse 3421 : ImplicitConversionSequence::Better; 3422 3423 if (ICS1.getKindRank() < ICS2.getKindRank()) 3424 return ImplicitConversionSequence::Better; 3425 if (ICS2.getKindRank() < ICS1.getKindRank()) 3426 return ImplicitConversionSequence::Worse; 3427 3428 // The following checks require both conversion sequences to be of 3429 // the same kind. 3430 if (ICS1.getKind() != ICS2.getKind()) 3431 return ImplicitConversionSequence::Indistinguishable; 3432 3433 ImplicitConversionSequence::CompareKind Result = 3434 ImplicitConversionSequence::Indistinguishable; 3435 3436 // Two implicit conversion sequences of the same form are 3437 // indistinguishable conversion sequences unless one of the 3438 // following rules apply: (C++ 13.3.3.2p3): 3439 3440 // List-initialization sequence L1 is a better conversion sequence than 3441 // list-initialization sequence L2 if: 3442 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3443 // if not that, 3444 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3445 // and N1 is smaller than N2., 3446 // even if one of the other rules in this paragraph would otherwise apply. 3447 if (!ICS1.isBad()) { 3448 if (ICS1.isStdInitializerListElement() && 3449 !ICS2.isStdInitializerListElement()) 3450 return ImplicitConversionSequence::Better; 3451 if (!ICS1.isStdInitializerListElement() && 3452 ICS2.isStdInitializerListElement()) 3453 return ImplicitConversionSequence::Worse; 3454 } 3455 3456 if (ICS1.isStandard()) 3457 // Standard conversion sequence S1 is a better conversion sequence than 3458 // standard conversion sequence S2 if [...] 3459 Result = CompareStandardConversionSequences(S, Loc, 3460 ICS1.Standard, ICS2.Standard); 3461 else if (ICS1.isUserDefined()) { 3462 // User-defined conversion sequence U1 is a better conversion 3463 // sequence than another user-defined conversion sequence U2 if 3464 // they contain the same user-defined conversion function or 3465 // constructor and if the second standard conversion sequence of 3466 // U1 is better than the second standard conversion sequence of 3467 // U2 (C++ 13.3.3.2p3). 3468 if (ICS1.UserDefined.ConversionFunction == 3469 ICS2.UserDefined.ConversionFunction) 3470 Result = CompareStandardConversionSequences(S, Loc, 3471 ICS1.UserDefined.After, 3472 ICS2.UserDefined.After); 3473 else 3474 Result = compareConversionFunctions(S, 3475 ICS1.UserDefined.ConversionFunction, 3476 ICS2.UserDefined.ConversionFunction); 3477 } 3478 3479 return Result; 3480 } 3481 3482 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3483 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3484 Qualifiers Quals; 3485 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3486 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3487 } 3488 3489 return Context.hasSameUnqualifiedType(T1, T2); 3490 } 3491 3492 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3493 // determine if one is a proper subset of the other. 3494 static ImplicitConversionSequence::CompareKind 3495 compareStandardConversionSubsets(ASTContext &Context, 3496 const StandardConversionSequence& SCS1, 3497 const StandardConversionSequence& SCS2) { 3498 ImplicitConversionSequence::CompareKind Result 3499 = ImplicitConversionSequence::Indistinguishable; 3500 3501 // the identity conversion sequence is considered to be a subsequence of 3502 // any non-identity conversion sequence 3503 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3504 return ImplicitConversionSequence::Better; 3505 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3506 return ImplicitConversionSequence::Worse; 3507 3508 if (SCS1.Second != SCS2.Second) { 3509 if (SCS1.Second == ICK_Identity) 3510 Result = ImplicitConversionSequence::Better; 3511 else if (SCS2.Second == ICK_Identity) 3512 Result = ImplicitConversionSequence::Worse; 3513 else 3514 return ImplicitConversionSequence::Indistinguishable; 3515 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3516 return ImplicitConversionSequence::Indistinguishable; 3517 3518 if (SCS1.Third == SCS2.Third) { 3519 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3520 : ImplicitConversionSequence::Indistinguishable; 3521 } 3522 3523 if (SCS1.Third == ICK_Identity) 3524 return Result == ImplicitConversionSequence::Worse 3525 ? ImplicitConversionSequence::Indistinguishable 3526 : ImplicitConversionSequence::Better; 3527 3528 if (SCS2.Third == ICK_Identity) 3529 return Result == ImplicitConversionSequence::Better 3530 ? ImplicitConversionSequence::Indistinguishable 3531 : ImplicitConversionSequence::Worse; 3532 3533 return ImplicitConversionSequence::Indistinguishable; 3534 } 3535 3536 /// \brief Determine whether one of the given reference bindings is better 3537 /// than the other based on what kind of bindings they are. 3538 static bool 3539 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3540 const StandardConversionSequence &SCS2) { 3541 // C++0x [over.ics.rank]p3b4: 3542 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3543 // implicit object parameter of a non-static member function declared 3544 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3545 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3546 // lvalue reference to a function lvalue and S2 binds an rvalue 3547 // reference*. 3548 // 3549 // FIXME: Rvalue references. We're going rogue with the above edits, 3550 // because the semantics in the current C++0x working paper (N3225 at the 3551 // time of this writing) break the standard definition of std::forward 3552 // and std::reference_wrapper when dealing with references to functions. 3553 // Proposed wording changes submitted to CWG for consideration. 3554 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3555 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3556 return false; 3557 3558 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3559 SCS2.IsLvalueReference) || 3560 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3561 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3562 } 3563 3564 /// CompareStandardConversionSequences - Compare two standard 3565 /// conversion sequences to determine whether one is better than the 3566 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3567 static ImplicitConversionSequence::CompareKind 3568 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3569 const StandardConversionSequence& SCS1, 3570 const StandardConversionSequence& SCS2) 3571 { 3572 // Standard conversion sequence S1 is a better conversion sequence 3573 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3574 3575 // -- S1 is a proper subsequence of S2 (comparing the conversion 3576 // sequences in the canonical form defined by 13.3.3.1.1, 3577 // excluding any Lvalue Transformation; the identity conversion 3578 // sequence is considered to be a subsequence of any 3579 // non-identity conversion sequence) or, if not that, 3580 if (ImplicitConversionSequence::CompareKind CK 3581 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3582 return CK; 3583 3584 // -- the rank of S1 is better than the rank of S2 (by the rules 3585 // defined below), or, if not that, 3586 ImplicitConversionRank Rank1 = SCS1.getRank(); 3587 ImplicitConversionRank Rank2 = SCS2.getRank(); 3588 if (Rank1 < Rank2) 3589 return ImplicitConversionSequence::Better; 3590 else if (Rank2 < Rank1) 3591 return ImplicitConversionSequence::Worse; 3592 3593 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3594 // are indistinguishable unless one of the following rules 3595 // applies: 3596 3597 // A conversion that is not a conversion of a pointer, or 3598 // pointer to member, to bool is better than another conversion 3599 // that is such a conversion. 3600 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3601 return SCS2.isPointerConversionToBool() 3602 ? ImplicitConversionSequence::Better 3603 : ImplicitConversionSequence::Worse; 3604 3605 // C++ [over.ics.rank]p4b2: 3606 // 3607 // If class B is derived directly or indirectly from class A, 3608 // conversion of B* to A* is better than conversion of B* to 3609 // void*, and conversion of A* to void* is better than conversion 3610 // of B* to void*. 3611 bool SCS1ConvertsToVoid 3612 = SCS1.isPointerConversionToVoidPointer(S.Context); 3613 bool SCS2ConvertsToVoid 3614 = SCS2.isPointerConversionToVoidPointer(S.Context); 3615 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3616 // Exactly one of the conversion sequences is a conversion to 3617 // a void pointer; it's the worse conversion. 3618 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3619 : ImplicitConversionSequence::Worse; 3620 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3621 // Neither conversion sequence converts to a void pointer; compare 3622 // their derived-to-base conversions. 3623 if (ImplicitConversionSequence::CompareKind DerivedCK 3624 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3625 return DerivedCK; 3626 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3627 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3628 // Both conversion sequences are conversions to void 3629 // pointers. Compare the source types to determine if there's an 3630 // inheritance relationship in their sources. 3631 QualType FromType1 = SCS1.getFromType(); 3632 QualType FromType2 = SCS2.getFromType(); 3633 3634 // Adjust the types we're converting from via the array-to-pointer 3635 // conversion, if we need to. 3636 if (SCS1.First == ICK_Array_To_Pointer) 3637 FromType1 = S.Context.getArrayDecayedType(FromType1); 3638 if (SCS2.First == ICK_Array_To_Pointer) 3639 FromType2 = S.Context.getArrayDecayedType(FromType2); 3640 3641 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3642 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3643 3644 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3645 return ImplicitConversionSequence::Better; 3646 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3647 return ImplicitConversionSequence::Worse; 3648 3649 // Objective-C++: If one interface is more specific than the 3650 // other, it is the better one. 3651 const ObjCObjectPointerType* FromObjCPtr1 3652 = FromType1->getAs<ObjCObjectPointerType>(); 3653 const ObjCObjectPointerType* FromObjCPtr2 3654 = FromType2->getAs<ObjCObjectPointerType>(); 3655 if (FromObjCPtr1 && FromObjCPtr2) { 3656 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3657 FromObjCPtr2); 3658 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3659 FromObjCPtr1); 3660 if (AssignLeft != AssignRight) { 3661 return AssignLeft? ImplicitConversionSequence::Better 3662 : ImplicitConversionSequence::Worse; 3663 } 3664 } 3665 } 3666 3667 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3668 // bullet 3). 3669 if (ImplicitConversionSequence::CompareKind QualCK 3670 = CompareQualificationConversions(S, SCS1, SCS2)) 3671 return QualCK; 3672 3673 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3674 // Check for a better reference binding based on the kind of bindings. 3675 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3676 return ImplicitConversionSequence::Better; 3677 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3678 return ImplicitConversionSequence::Worse; 3679 3680 // C++ [over.ics.rank]p3b4: 3681 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3682 // which the references refer are the same type except for 3683 // top-level cv-qualifiers, and the type to which the reference 3684 // initialized by S2 refers is more cv-qualified than the type 3685 // to which the reference initialized by S1 refers. 3686 QualType T1 = SCS1.getToType(2); 3687 QualType T2 = SCS2.getToType(2); 3688 T1 = S.Context.getCanonicalType(T1); 3689 T2 = S.Context.getCanonicalType(T2); 3690 Qualifiers T1Quals, T2Quals; 3691 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3692 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3693 if (UnqualT1 == UnqualT2) { 3694 // Objective-C++ ARC: If the references refer to objects with different 3695 // lifetimes, prefer bindings that don't change lifetime. 3696 if (SCS1.ObjCLifetimeConversionBinding != 3697 SCS2.ObjCLifetimeConversionBinding) { 3698 return SCS1.ObjCLifetimeConversionBinding 3699 ? ImplicitConversionSequence::Worse 3700 : ImplicitConversionSequence::Better; 3701 } 3702 3703 // If the type is an array type, promote the element qualifiers to the 3704 // type for comparison. 3705 if (isa<ArrayType>(T1) && T1Quals) 3706 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3707 if (isa<ArrayType>(T2) && T2Quals) 3708 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3709 if (T2.isMoreQualifiedThan(T1)) 3710 return ImplicitConversionSequence::Better; 3711 else if (T1.isMoreQualifiedThan(T2)) 3712 return ImplicitConversionSequence::Worse; 3713 } 3714 } 3715 3716 // In Microsoft mode, prefer an integral conversion to a 3717 // floating-to-integral conversion if the integral conversion 3718 // is between types of the same size. 3719 // For example: 3720 // void f(float); 3721 // void f(int); 3722 // int main { 3723 // long a; 3724 // f(a); 3725 // } 3726 // Here, MSVC will call f(int) instead of generating a compile error 3727 // as clang will do in standard mode. 3728 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3729 SCS2.Second == ICK_Floating_Integral && 3730 S.Context.getTypeSize(SCS1.getFromType()) == 3731 S.Context.getTypeSize(SCS1.getToType(2))) 3732 return ImplicitConversionSequence::Better; 3733 3734 return ImplicitConversionSequence::Indistinguishable; 3735 } 3736 3737 /// CompareQualificationConversions - Compares two standard conversion 3738 /// sequences to determine whether they can be ranked based on their 3739 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3740 static ImplicitConversionSequence::CompareKind 3741 CompareQualificationConversions(Sema &S, 3742 const StandardConversionSequence& SCS1, 3743 const StandardConversionSequence& SCS2) { 3744 // C++ 13.3.3.2p3: 3745 // -- S1 and S2 differ only in their qualification conversion and 3746 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3747 // cv-qualification signature of type T1 is a proper subset of 3748 // the cv-qualification signature of type T2, and S1 is not the 3749 // deprecated string literal array-to-pointer conversion (4.2). 3750 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3751 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3752 return ImplicitConversionSequence::Indistinguishable; 3753 3754 // FIXME: the example in the standard doesn't use a qualification 3755 // conversion (!) 3756 QualType T1 = SCS1.getToType(2); 3757 QualType T2 = SCS2.getToType(2); 3758 T1 = S.Context.getCanonicalType(T1); 3759 T2 = S.Context.getCanonicalType(T2); 3760 Qualifiers T1Quals, T2Quals; 3761 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3762 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3763 3764 // If the types are the same, we won't learn anything by unwrapped 3765 // them. 3766 if (UnqualT1 == UnqualT2) 3767 return ImplicitConversionSequence::Indistinguishable; 3768 3769 // If the type is an array type, promote the element qualifiers to the type 3770 // for comparison. 3771 if (isa<ArrayType>(T1) && T1Quals) 3772 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3773 if (isa<ArrayType>(T2) && T2Quals) 3774 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3775 3776 ImplicitConversionSequence::CompareKind Result 3777 = ImplicitConversionSequence::Indistinguishable; 3778 3779 // Objective-C++ ARC: 3780 // Prefer qualification conversions not involving a change in lifetime 3781 // to qualification conversions that do not change lifetime. 3782 if (SCS1.QualificationIncludesObjCLifetime != 3783 SCS2.QualificationIncludesObjCLifetime) { 3784 Result = SCS1.QualificationIncludesObjCLifetime 3785 ? ImplicitConversionSequence::Worse 3786 : ImplicitConversionSequence::Better; 3787 } 3788 3789 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3790 // Within each iteration of the loop, we check the qualifiers to 3791 // determine if this still looks like a qualification 3792 // conversion. Then, if all is well, we unwrap one more level of 3793 // pointers or pointers-to-members and do it all again 3794 // until there are no more pointers or pointers-to-members left 3795 // to unwrap. This essentially mimics what 3796 // IsQualificationConversion does, but here we're checking for a 3797 // strict subset of qualifiers. 3798 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3799 // The qualifiers are the same, so this doesn't tell us anything 3800 // about how the sequences rank. 3801 ; 3802 else if (T2.isMoreQualifiedThan(T1)) { 3803 // T1 has fewer qualifiers, so it could be the better sequence. 3804 if (Result == ImplicitConversionSequence::Worse) 3805 // Neither has qualifiers that are a subset of the other's 3806 // qualifiers. 3807 return ImplicitConversionSequence::Indistinguishable; 3808 3809 Result = ImplicitConversionSequence::Better; 3810 } else if (T1.isMoreQualifiedThan(T2)) { 3811 // T2 has fewer qualifiers, so it could be the better sequence. 3812 if (Result == ImplicitConversionSequence::Better) 3813 // Neither has qualifiers that are a subset of the other's 3814 // qualifiers. 3815 return ImplicitConversionSequence::Indistinguishable; 3816 3817 Result = ImplicitConversionSequence::Worse; 3818 } else { 3819 // Qualifiers are disjoint. 3820 return ImplicitConversionSequence::Indistinguishable; 3821 } 3822 3823 // If the types after this point are equivalent, we're done. 3824 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3825 break; 3826 } 3827 3828 // Check that the winning standard conversion sequence isn't using 3829 // the deprecated string literal array to pointer conversion. 3830 switch (Result) { 3831 case ImplicitConversionSequence::Better: 3832 if (SCS1.DeprecatedStringLiteralToCharPtr) 3833 Result = ImplicitConversionSequence::Indistinguishable; 3834 break; 3835 3836 case ImplicitConversionSequence::Indistinguishable: 3837 break; 3838 3839 case ImplicitConversionSequence::Worse: 3840 if (SCS2.DeprecatedStringLiteralToCharPtr) 3841 Result = ImplicitConversionSequence::Indistinguishable; 3842 break; 3843 } 3844 3845 return Result; 3846 } 3847 3848 /// CompareDerivedToBaseConversions - Compares two standard conversion 3849 /// sequences to determine whether they can be ranked based on their 3850 /// various kinds of derived-to-base conversions (C++ 3851 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3852 /// conversions between Objective-C interface types. 3853 static ImplicitConversionSequence::CompareKind 3854 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3855 const StandardConversionSequence& SCS1, 3856 const StandardConversionSequence& SCS2) { 3857 QualType FromType1 = SCS1.getFromType(); 3858 QualType ToType1 = SCS1.getToType(1); 3859 QualType FromType2 = SCS2.getFromType(); 3860 QualType ToType2 = SCS2.getToType(1); 3861 3862 // Adjust the types we're converting from via the array-to-pointer 3863 // conversion, if we need to. 3864 if (SCS1.First == ICK_Array_To_Pointer) 3865 FromType1 = S.Context.getArrayDecayedType(FromType1); 3866 if (SCS2.First == ICK_Array_To_Pointer) 3867 FromType2 = S.Context.getArrayDecayedType(FromType2); 3868 3869 // Canonicalize all of the types. 3870 FromType1 = S.Context.getCanonicalType(FromType1); 3871 ToType1 = S.Context.getCanonicalType(ToType1); 3872 FromType2 = S.Context.getCanonicalType(FromType2); 3873 ToType2 = S.Context.getCanonicalType(ToType2); 3874 3875 // C++ [over.ics.rank]p4b3: 3876 // 3877 // If class B is derived directly or indirectly from class A and 3878 // class C is derived directly or indirectly from B, 3879 // 3880 // Compare based on pointer conversions. 3881 if (SCS1.Second == ICK_Pointer_Conversion && 3882 SCS2.Second == ICK_Pointer_Conversion && 3883 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3884 FromType1->isPointerType() && FromType2->isPointerType() && 3885 ToType1->isPointerType() && ToType2->isPointerType()) { 3886 QualType FromPointee1 3887 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3888 QualType ToPointee1 3889 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3890 QualType FromPointee2 3891 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3892 QualType ToPointee2 3893 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3894 3895 // -- conversion of C* to B* is better than conversion of C* to A*, 3896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3897 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3898 return ImplicitConversionSequence::Better; 3899 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3900 return ImplicitConversionSequence::Worse; 3901 } 3902 3903 // -- conversion of B* to A* is better than conversion of C* to A*, 3904 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3905 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3906 return ImplicitConversionSequence::Better; 3907 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3908 return ImplicitConversionSequence::Worse; 3909 } 3910 } else if (SCS1.Second == ICK_Pointer_Conversion && 3911 SCS2.Second == ICK_Pointer_Conversion) { 3912 const ObjCObjectPointerType *FromPtr1 3913 = FromType1->getAs<ObjCObjectPointerType>(); 3914 const ObjCObjectPointerType *FromPtr2 3915 = FromType2->getAs<ObjCObjectPointerType>(); 3916 const ObjCObjectPointerType *ToPtr1 3917 = ToType1->getAs<ObjCObjectPointerType>(); 3918 const ObjCObjectPointerType *ToPtr2 3919 = ToType2->getAs<ObjCObjectPointerType>(); 3920 3921 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3922 // Apply the same conversion ranking rules for Objective-C pointer types 3923 // that we do for C++ pointers to class types. However, we employ the 3924 // Objective-C pseudo-subtyping relationship used for assignment of 3925 // Objective-C pointer types. 3926 bool FromAssignLeft 3927 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3928 bool FromAssignRight 3929 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3930 bool ToAssignLeft 3931 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3932 bool ToAssignRight 3933 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3934 3935 // A conversion to an a non-id object pointer type or qualified 'id' 3936 // type is better than a conversion to 'id'. 3937 if (ToPtr1->isObjCIdType() && 3938 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3939 return ImplicitConversionSequence::Worse; 3940 if (ToPtr2->isObjCIdType() && 3941 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3942 return ImplicitConversionSequence::Better; 3943 3944 // A conversion to a non-id object pointer type is better than a 3945 // conversion to a qualified 'id' type 3946 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3947 return ImplicitConversionSequence::Worse; 3948 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3949 return ImplicitConversionSequence::Better; 3950 3951 // A conversion to an a non-Class object pointer type or qualified 'Class' 3952 // type is better than a conversion to 'Class'. 3953 if (ToPtr1->isObjCClassType() && 3954 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3955 return ImplicitConversionSequence::Worse; 3956 if (ToPtr2->isObjCClassType() && 3957 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3958 return ImplicitConversionSequence::Better; 3959 3960 // A conversion to a non-Class object pointer type is better than a 3961 // conversion to a qualified 'Class' type. 3962 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3963 return ImplicitConversionSequence::Worse; 3964 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3965 return ImplicitConversionSequence::Better; 3966 3967 // -- "conversion of C* to B* is better than conversion of C* to A*," 3968 if (S.Context.hasSameType(FromType1, FromType2) && 3969 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3970 (ToAssignLeft != ToAssignRight)) 3971 return ToAssignLeft? ImplicitConversionSequence::Worse 3972 : ImplicitConversionSequence::Better; 3973 3974 // -- "conversion of B* to A* is better than conversion of C* to A*," 3975 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3976 (FromAssignLeft != FromAssignRight)) 3977 return FromAssignLeft? ImplicitConversionSequence::Better 3978 : ImplicitConversionSequence::Worse; 3979 } 3980 } 3981 3982 // Ranking of member-pointer types. 3983 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3984 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3985 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3986 const MemberPointerType * FromMemPointer1 = 3987 FromType1->getAs<MemberPointerType>(); 3988 const MemberPointerType * ToMemPointer1 = 3989 ToType1->getAs<MemberPointerType>(); 3990 const MemberPointerType * FromMemPointer2 = 3991 FromType2->getAs<MemberPointerType>(); 3992 const MemberPointerType * ToMemPointer2 = 3993 ToType2->getAs<MemberPointerType>(); 3994 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3995 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3996 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3997 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3998 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3999 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4000 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4001 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4002 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4003 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4004 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4005 return ImplicitConversionSequence::Worse; 4006 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4007 return ImplicitConversionSequence::Better; 4008 } 4009 // conversion of B::* to C::* is better than conversion of A::* to C::* 4010 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4011 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4012 return ImplicitConversionSequence::Better; 4013 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4014 return ImplicitConversionSequence::Worse; 4015 } 4016 } 4017 4018 if (SCS1.Second == ICK_Derived_To_Base) { 4019 // -- conversion of C to B is better than conversion of C to A, 4020 // -- binding of an expression of type C to a reference of type 4021 // B& is better than binding an expression of type C to a 4022 // reference of type A&, 4023 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4024 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4025 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4026 return ImplicitConversionSequence::Better; 4027 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4028 return ImplicitConversionSequence::Worse; 4029 } 4030 4031 // -- conversion of B to A is better than conversion of C to A. 4032 // -- binding of an expression of type B to a reference of type 4033 // A& is better than binding an expression of type C to a 4034 // reference of type A&, 4035 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4036 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4037 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4038 return ImplicitConversionSequence::Better; 4039 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4040 return ImplicitConversionSequence::Worse; 4041 } 4042 } 4043 4044 return ImplicitConversionSequence::Indistinguishable; 4045 } 4046 4047 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4048 /// C++ class. 4049 static bool isTypeValid(QualType T) { 4050 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4051 return !Record->isInvalidDecl(); 4052 4053 return true; 4054 } 4055 4056 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4057 /// determine whether they are reference-related, 4058 /// reference-compatible, reference-compatible with added 4059 /// qualification, or incompatible, for use in C++ initialization by 4060 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4061 /// type, and the first type (T1) is the pointee type of the reference 4062 /// type being initialized. 4063 Sema::ReferenceCompareResult 4064 Sema::CompareReferenceRelationship(SourceLocation Loc, 4065 QualType OrigT1, QualType OrigT2, 4066 bool &DerivedToBase, 4067 bool &ObjCConversion, 4068 bool &ObjCLifetimeConversion) { 4069 assert(!OrigT1->isReferenceType() && 4070 "T1 must be the pointee type of the reference type"); 4071 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4072 4073 QualType T1 = Context.getCanonicalType(OrigT1); 4074 QualType T2 = Context.getCanonicalType(OrigT2); 4075 Qualifiers T1Quals, T2Quals; 4076 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4077 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4078 4079 // C++ [dcl.init.ref]p4: 4080 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4081 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4082 // T1 is a base class of T2. 4083 DerivedToBase = false; 4084 ObjCConversion = false; 4085 ObjCLifetimeConversion = false; 4086 if (UnqualT1 == UnqualT2) { 4087 // Nothing to do. 4088 } else if (isCompleteType(Loc, OrigT2) && 4089 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4090 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4091 DerivedToBase = true; 4092 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4093 UnqualT2->isObjCObjectOrInterfaceType() && 4094 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4095 ObjCConversion = true; 4096 else 4097 return Ref_Incompatible; 4098 4099 // At this point, we know that T1 and T2 are reference-related (at 4100 // least). 4101 4102 // If the type is an array type, promote the element qualifiers to the type 4103 // for comparison. 4104 if (isa<ArrayType>(T1) && T1Quals) 4105 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4106 if (isa<ArrayType>(T2) && T2Quals) 4107 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4108 4109 // C++ [dcl.init.ref]p4: 4110 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4111 // reference-related to T2 and cv1 is the same cv-qualification 4112 // as, or greater cv-qualification than, cv2. For purposes of 4113 // overload resolution, cases for which cv1 is greater 4114 // cv-qualification than cv2 are identified as 4115 // reference-compatible with added qualification (see 13.3.3.2). 4116 // 4117 // Note that we also require equivalence of Objective-C GC and address-space 4118 // qualifiers when performing these computations, so that e.g., an int in 4119 // address space 1 is not reference-compatible with an int in address 4120 // space 2. 4121 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4122 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4123 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4124 ObjCLifetimeConversion = true; 4125 4126 T1Quals.removeObjCLifetime(); 4127 T2Quals.removeObjCLifetime(); 4128 } 4129 4130 if (T1Quals == T2Quals) 4131 return Ref_Compatible; 4132 else if (T1Quals.compatiblyIncludes(T2Quals)) 4133 return Ref_Compatible_With_Added_Qualification; 4134 else 4135 return Ref_Related; 4136 } 4137 4138 /// \brief Look for a user-defined conversion to an value reference-compatible 4139 /// with DeclType. Return true if something definite is found. 4140 static bool 4141 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4142 QualType DeclType, SourceLocation DeclLoc, 4143 Expr *Init, QualType T2, bool AllowRvalues, 4144 bool AllowExplicit) { 4145 assert(T2->isRecordType() && "Can only find conversions of record types."); 4146 CXXRecordDecl *T2RecordDecl 4147 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4148 4149 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4150 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4151 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4152 NamedDecl *D = *I; 4153 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4154 if (isa<UsingShadowDecl>(D)) 4155 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4156 4157 FunctionTemplateDecl *ConvTemplate 4158 = dyn_cast<FunctionTemplateDecl>(D); 4159 CXXConversionDecl *Conv; 4160 if (ConvTemplate) 4161 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4162 else 4163 Conv = cast<CXXConversionDecl>(D); 4164 4165 // If this is an explicit conversion, and we're not allowed to consider 4166 // explicit conversions, skip it. 4167 if (!AllowExplicit && Conv->isExplicit()) 4168 continue; 4169 4170 if (AllowRvalues) { 4171 bool DerivedToBase = false; 4172 bool ObjCConversion = false; 4173 bool ObjCLifetimeConversion = false; 4174 4175 // If we are initializing an rvalue reference, don't permit conversion 4176 // functions that return lvalues. 4177 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4178 const ReferenceType *RefType 4179 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4180 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4181 continue; 4182 } 4183 4184 if (!ConvTemplate && 4185 S.CompareReferenceRelationship( 4186 DeclLoc, 4187 Conv->getConversionType().getNonReferenceType() 4188 .getUnqualifiedType(), 4189 DeclType.getNonReferenceType().getUnqualifiedType(), 4190 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4191 Sema::Ref_Incompatible) 4192 continue; 4193 } else { 4194 // If the conversion function doesn't return a reference type, 4195 // it can't be considered for this conversion. An rvalue reference 4196 // is only acceptable if its referencee is a function type. 4197 4198 const ReferenceType *RefType = 4199 Conv->getConversionType()->getAs<ReferenceType>(); 4200 if (!RefType || 4201 (!RefType->isLValueReferenceType() && 4202 !RefType->getPointeeType()->isFunctionType())) 4203 continue; 4204 } 4205 4206 if (ConvTemplate) 4207 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4208 Init, DeclType, CandidateSet, 4209 /*AllowObjCConversionOnExplicit=*/false); 4210 else 4211 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4212 DeclType, CandidateSet, 4213 /*AllowObjCConversionOnExplicit=*/false); 4214 } 4215 4216 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4217 4218 OverloadCandidateSet::iterator Best; 4219 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4220 case OR_Success: 4221 // C++ [over.ics.ref]p1: 4222 // 4223 // [...] If the parameter binds directly to the result of 4224 // applying a conversion function to the argument 4225 // expression, the implicit conversion sequence is a 4226 // user-defined conversion sequence (13.3.3.1.2), with the 4227 // second standard conversion sequence either an identity 4228 // conversion or, if the conversion function returns an 4229 // entity of a type that is a derived class of the parameter 4230 // type, a derived-to-base Conversion. 4231 if (!Best->FinalConversion.DirectBinding) 4232 return false; 4233 4234 ICS.setUserDefined(); 4235 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4236 ICS.UserDefined.After = Best->FinalConversion; 4237 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4238 ICS.UserDefined.ConversionFunction = Best->Function; 4239 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4240 ICS.UserDefined.EllipsisConversion = false; 4241 assert(ICS.UserDefined.After.ReferenceBinding && 4242 ICS.UserDefined.After.DirectBinding && 4243 "Expected a direct reference binding!"); 4244 return true; 4245 4246 case OR_Ambiguous: 4247 ICS.setAmbiguous(); 4248 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4249 Cand != CandidateSet.end(); ++Cand) 4250 if (Cand->Viable) 4251 ICS.Ambiguous.addConversion(Cand->Function); 4252 return true; 4253 4254 case OR_No_Viable_Function: 4255 case OR_Deleted: 4256 // There was no suitable conversion, or we found a deleted 4257 // conversion; continue with other checks. 4258 return false; 4259 } 4260 4261 llvm_unreachable("Invalid OverloadResult!"); 4262 } 4263 4264 /// \brief Compute an implicit conversion sequence for reference 4265 /// initialization. 4266 static ImplicitConversionSequence 4267 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4268 SourceLocation DeclLoc, 4269 bool SuppressUserConversions, 4270 bool AllowExplicit) { 4271 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4272 4273 // Most paths end in a failed conversion. 4274 ImplicitConversionSequence ICS; 4275 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4276 4277 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4278 QualType T2 = Init->getType(); 4279 4280 // If the initializer is the address of an overloaded function, try 4281 // to resolve the overloaded function. If all goes well, T2 is the 4282 // type of the resulting function. 4283 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4284 DeclAccessPair Found; 4285 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4286 false, Found)) 4287 T2 = Fn->getType(); 4288 } 4289 4290 // Compute some basic properties of the types and the initializer. 4291 bool isRValRef = DeclType->isRValueReferenceType(); 4292 bool DerivedToBase = false; 4293 bool ObjCConversion = false; 4294 bool ObjCLifetimeConversion = false; 4295 Expr::Classification InitCategory = Init->Classify(S.Context); 4296 Sema::ReferenceCompareResult RefRelationship 4297 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4298 ObjCConversion, ObjCLifetimeConversion); 4299 4300 4301 // C++0x [dcl.init.ref]p5: 4302 // A reference to type "cv1 T1" is initialized by an expression 4303 // of type "cv2 T2" as follows: 4304 4305 // -- If reference is an lvalue reference and the initializer expression 4306 if (!isRValRef) { 4307 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4308 // reference-compatible with "cv2 T2," or 4309 // 4310 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4311 if (InitCategory.isLValue() && 4312 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4313 // C++ [over.ics.ref]p1: 4314 // When a parameter of reference type binds directly (8.5.3) 4315 // to an argument expression, the implicit conversion sequence 4316 // is the identity conversion, unless the argument expression 4317 // has a type that is a derived class of the parameter type, 4318 // in which case the implicit conversion sequence is a 4319 // derived-to-base Conversion (13.3.3.1). 4320 ICS.setStandard(); 4321 ICS.Standard.First = ICK_Identity; 4322 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4323 : ObjCConversion? ICK_Compatible_Conversion 4324 : ICK_Identity; 4325 ICS.Standard.Third = ICK_Identity; 4326 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4327 ICS.Standard.setToType(0, T2); 4328 ICS.Standard.setToType(1, T1); 4329 ICS.Standard.setToType(2, T1); 4330 ICS.Standard.ReferenceBinding = true; 4331 ICS.Standard.DirectBinding = true; 4332 ICS.Standard.IsLvalueReference = !isRValRef; 4333 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4334 ICS.Standard.BindsToRvalue = false; 4335 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4336 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4337 ICS.Standard.CopyConstructor = nullptr; 4338 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4339 4340 // Nothing more to do: the inaccessibility/ambiguity check for 4341 // derived-to-base conversions is suppressed when we're 4342 // computing the implicit conversion sequence (C++ 4343 // [over.best.ics]p2). 4344 return ICS; 4345 } 4346 4347 // -- has a class type (i.e., T2 is a class type), where T1 is 4348 // not reference-related to T2, and can be implicitly 4349 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4350 // is reference-compatible with "cv3 T3" 92) (this 4351 // conversion is selected by enumerating the applicable 4352 // conversion functions (13.3.1.6) and choosing the best 4353 // one through overload resolution (13.3)), 4354 if (!SuppressUserConversions && T2->isRecordType() && 4355 S.isCompleteType(DeclLoc, T2) && 4356 RefRelationship == Sema::Ref_Incompatible) { 4357 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4358 Init, T2, /*AllowRvalues=*/false, 4359 AllowExplicit)) 4360 return ICS; 4361 } 4362 } 4363 4364 // -- Otherwise, the reference shall be an lvalue reference to a 4365 // non-volatile const type (i.e., cv1 shall be const), or the reference 4366 // shall be an rvalue reference. 4367 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4368 return ICS; 4369 4370 // -- If the initializer expression 4371 // 4372 // -- is an xvalue, class prvalue, array prvalue or function 4373 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4374 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4375 (InitCategory.isXValue() || 4376 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4377 (InitCategory.isLValue() && T2->isFunctionType()))) { 4378 ICS.setStandard(); 4379 ICS.Standard.First = ICK_Identity; 4380 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4381 : ObjCConversion? ICK_Compatible_Conversion 4382 : ICK_Identity; 4383 ICS.Standard.Third = ICK_Identity; 4384 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4385 ICS.Standard.setToType(0, T2); 4386 ICS.Standard.setToType(1, T1); 4387 ICS.Standard.setToType(2, T1); 4388 ICS.Standard.ReferenceBinding = true; 4389 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4390 // binding unless we're binding to a class prvalue. 4391 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4392 // allow the use of rvalue references in C++98/03 for the benefit of 4393 // standard library implementors; therefore, we need the xvalue check here. 4394 ICS.Standard.DirectBinding = 4395 S.getLangOpts().CPlusPlus11 || 4396 !(InitCategory.isPRValue() || T2->isRecordType()); 4397 ICS.Standard.IsLvalueReference = !isRValRef; 4398 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4399 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4400 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4401 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4402 ICS.Standard.CopyConstructor = nullptr; 4403 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4404 return ICS; 4405 } 4406 4407 // -- has a class type (i.e., T2 is a class type), where T1 is not 4408 // reference-related to T2, and can be implicitly converted to 4409 // an xvalue, class prvalue, or function lvalue of type 4410 // "cv3 T3", where "cv1 T1" is reference-compatible with 4411 // "cv3 T3", 4412 // 4413 // then the reference is bound to the value of the initializer 4414 // expression in the first case and to the result of the conversion 4415 // in the second case (or, in either case, to an appropriate base 4416 // class subobject). 4417 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4418 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4419 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4420 Init, T2, /*AllowRvalues=*/true, 4421 AllowExplicit)) { 4422 // In the second case, if the reference is an rvalue reference 4423 // and the second standard conversion sequence of the 4424 // user-defined conversion sequence includes an lvalue-to-rvalue 4425 // conversion, the program is ill-formed. 4426 if (ICS.isUserDefined() && isRValRef && 4427 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4428 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4429 4430 return ICS; 4431 } 4432 4433 // A temporary of function type cannot be created; don't even try. 4434 if (T1->isFunctionType()) 4435 return ICS; 4436 4437 // -- Otherwise, a temporary of type "cv1 T1" is created and 4438 // initialized from the initializer expression using the 4439 // rules for a non-reference copy initialization (8.5). The 4440 // reference is then bound to the temporary. If T1 is 4441 // reference-related to T2, cv1 must be the same 4442 // cv-qualification as, or greater cv-qualification than, 4443 // cv2; otherwise, the program is ill-formed. 4444 if (RefRelationship == Sema::Ref_Related) { 4445 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4446 // we would be reference-compatible or reference-compatible with 4447 // added qualification. But that wasn't the case, so the reference 4448 // initialization fails. 4449 // 4450 // Note that we only want to check address spaces and cvr-qualifiers here. 4451 // ObjC GC and lifetime qualifiers aren't important. 4452 Qualifiers T1Quals = T1.getQualifiers(); 4453 Qualifiers T2Quals = T2.getQualifiers(); 4454 T1Quals.removeObjCGCAttr(); 4455 T1Quals.removeObjCLifetime(); 4456 T2Quals.removeObjCGCAttr(); 4457 T2Quals.removeObjCLifetime(); 4458 if (!T1Quals.compatiblyIncludes(T2Quals)) 4459 return ICS; 4460 } 4461 4462 // If at least one of the types is a class type, the types are not 4463 // related, and we aren't allowed any user conversions, the 4464 // reference binding fails. This case is important for breaking 4465 // recursion, since TryImplicitConversion below will attempt to 4466 // create a temporary through the use of a copy constructor. 4467 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4468 (T1->isRecordType() || T2->isRecordType())) 4469 return ICS; 4470 4471 // If T1 is reference-related to T2 and the reference is an rvalue 4472 // reference, the initializer expression shall not be an lvalue. 4473 if (RefRelationship >= Sema::Ref_Related && 4474 isRValRef && Init->Classify(S.Context).isLValue()) 4475 return ICS; 4476 4477 // C++ [over.ics.ref]p2: 4478 // When a parameter of reference type is not bound directly to 4479 // an argument expression, the conversion sequence is the one 4480 // required to convert the argument expression to the 4481 // underlying type of the reference according to 4482 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4483 // to copy-initializing a temporary of the underlying type with 4484 // the argument expression. Any difference in top-level 4485 // cv-qualification is subsumed by the initialization itself 4486 // and does not constitute a conversion. 4487 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4488 /*AllowExplicit=*/false, 4489 /*InOverloadResolution=*/false, 4490 /*CStyle=*/false, 4491 /*AllowObjCWritebackConversion=*/false, 4492 /*AllowObjCConversionOnExplicit=*/false); 4493 4494 // Of course, that's still a reference binding. 4495 if (ICS.isStandard()) { 4496 ICS.Standard.ReferenceBinding = true; 4497 ICS.Standard.IsLvalueReference = !isRValRef; 4498 ICS.Standard.BindsToFunctionLvalue = false; 4499 ICS.Standard.BindsToRvalue = true; 4500 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4501 ICS.Standard.ObjCLifetimeConversionBinding = false; 4502 } else if (ICS.isUserDefined()) { 4503 const ReferenceType *LValRefType = 4504 ICS.UserDefined.ConversionFunction->getReturnType() 4505 ->getAs<LValueReferenceType>(); 4506 4507 // C++ [over.ics.ref]p3: 4508 // Except for an implicit object parameter, for which see 13.3.1, a 4509 // standard conversion sequence cannot be formed if it requires [...] 4510 // binding an rvalue reference to an lvalue other than a function 4511 // lvalue. 4512 // Note that the function case is not possible here. 4513 if (DeclType->isRValueReferenceType() && LValRefType) { 4514 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4515 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4516 // reference to an rvalue! 4517 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4518 return ICS; 4519 } 4520 4521 ICS.UserDefined.Before.setAsIdentityConversion(); 4522 ICS.UserDefined.After.ReferenceBinding = true; 4523 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4524 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4525 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4526 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4527 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4528 } 4529 4530 return ICS; 4531 } 4532 4533 static ImplicitConversionSequence 4534 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4535 bool SuppressUserConversions, 4536 bool InOverloadResolution, 4537 bool AllowObjCWritebackConversion, 4538 bool AllowExplicit = false); 4539 4540 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4541 /// initializer list From. 4542 static ImplicitConversionSequence 4543 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4544 bool SuppressUserConversions, 4545 bool InOverloadResolution, 4546 bool AllowObjCWritebackConversion) { 4547 // C++11 [over.ics.list]p1: 4548 // When an argument is an initializer list, it is not an expression and 4549 // special rules apply for converting it to a parameter type. 4550 4551 ImplicitConversionSequence Result; 4552 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4553 4554 // We need a complete type for what follows. Incomplete types can never be 4555 // initialized from init lists. 4556 if (!S.isCompleteType(From->getLocStart(), ToType)) 4557 return Result; 4558 4559 // Per DR1467: 4560 // If the parameter type is a class X and the initializer list has a single 4561 // element of type cv U, where U is X or a class derived from X, the 4562 // implicit conversion sequence is the one required to convert the element 4563 // to the parameter type. 4564 // 4565 // Otherwise, if the parameter type is a character array [... ] 4566 // and the initializer list has a single element that is an 4567 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4568 // implicit conversion sequence is the identity conversion. 4569 if (From->getNumInits() == 1) { 4570 if (ToType->isRecordType()) { 4571 QualType InitType = From->getInit(0)->getType(); 4572 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4573 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4574 return TryCopyInitialization(S, From->getInit(0), ToType, 4575 SuppressUserConversions, 4576 InOverloadResolution, 4577 AllowObjCWritebackConversion); 4578 } 4579 // FIXME: Check the other conditions here: array of character type, 4580 // initializer is a string literal. 4581 if (ToType->isArrayType()) { 4582 InitializedEntity Entity = 4583 InitializedEntity::InitializeParameter(S.Context, ToType, 4584 /*Consumed=*/false); 4585 if (S.CanPerformCopyInitialization(Entity, From)) { 4586 Result.setStandard(); 4587 Result.Standard.setAsIdentityConversion(); 4588 Result.Standard.setFromType(ToType); 4589 Result.Standard.setAllToTypes(ToType); 4590 return Result; 4591 } 4592 } 4593 } 4594 4595 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4596 // C++11 [over.ics.list]p2: 4597 // If the parameter type is std::initializer_list<X> or "array of X" and 4598 // all the elements can be implicitly converted to X, the implicit 4599 // conversion sequence is the worst conversion necessary to convert an 4600 // element of the list to X. 4601 // 4602 // C++14 [over.ics.list]p3: 4603 // Otherwise, if the parameter type is "array of N X", if the initializer 4604 // list has exactly N elements or if it has fewer than N elements and X is 4605 // default-constructible, and if all the elements of the initializer list 4606 // can be implicitly converted to X, the implicit conversion sequence is 4607 // the worst conversion necessary to convert an element of the list to X. 4608 // 4609 // FIXME: We're missing a lot of these checks. 4610 bool toStdInitializerList = false; 4611 QualType X; 4612 if (ToType->isArrayType()) 4613 X = S.Context.getAsArrayType(ToType)->getElementType(); 4614 else 4615 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4616 if (!X.isNull()) { 4617 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4618 Expr *Init = From->getInit(i); 4619 ImplicitConversionSequence ICS = 4620 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4621 InOverloadResolution, 4622 AllowObjCWritebackConversion); 4623 // If a single element isn't convertible, fail. 4624 if (ICS.isBad()) { 4625 Result = ICS; 4626 break; 4627 } 4628 // Otherwise, look for the worst conversion. 4629 if (Result.isBad() || 4630 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4631 Result) == 4632 ImplicitConversionSequence::Worse) 4633 Result = ICS; 4634 } 4635 4636 // For an empty list, we won't have computed any conversion sequence. 4637 // Introduce the identity conversion sequence. 4638 if (From->getNumInits() == 0) { 4639 Result.setStandard(); 4640 Result.Standard.setAsIdentityConversion(); 4641 Result.Standard.setFromType(ToType); 4642 Result.Standard.setAllToTypes(ToType); 4643 } 4644 4645 Result.setStdInitializerListElement(toStdInitializerList); 4646 return Result; 4647 } 4648 4649 // C++14 [over.ics.list]p4: 4650 // C++11 [over.ics.list]p3: 4651 // Otherwise, if the parameter is a non-aggregate class X and overload 4652 // resolution chooses a single best constructor [...] the implicit 4653 // conversion sequence is a user-defined conversion sequence. If multiple 4654 // constructors are viable but none is better than the others, the 4655 // implicit conversion sequence is a user-defined conversion sequence. 4656 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4657 // This function can deal with initializer lists. 4658 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4659 /*AllowExplicit=*/false, 4660 InOverloadResolution, /*CStyle=*/false, 4661 AllowObjCWritebackConversion, 4662 /*AllowObjCConversionOnExplicit=*/false); 4663 } 4664 4665 // C++14 [over.ics.list]p5: 4666 // C++11 [over.ics.list]p4: 4667 // Otherwise, if the parameter has an aggregate type which can be 4668 // initialized from the initializer list [...] the implicit conversion 4669 // sequence is a user-defined conversion sequence. 4670 if (ToType->isAggregateType()) { 4671 // Type is an aggregate, argument is an init list. At this point it comes 4672 // down to checking whether the initialization works. 4673 // FIXME: Find out whether this parameter is consumed or not. 4674 InitializedEntity Entity = 4675 InitializedEntity::InitializeParameter(S.Context, ToType, 4676 /*Consumed=*/false); 4677 if (S.CanPerformCopyInitialization(Entity, From)) { 4678 Result.setUserDefined(); 4679 Result.UserDefined.Before.setAsIdentityConversion(); 4680 // Initializer lists don't have a type. 4681 Result.UserDefined.Before.setFromType(QualType()); 4682 Result.UserDefined.Before.setAllToTypes(QualType()); 4683 4684 Result.UserDefined.After.setAsIdentityConversion(); 4685 Result.UserDefined.After.setFromType(ToType); 4686 Result.UserDefined.After.setAllToTypes(ToType); 4687 Result.UserDefined.ConversionFunction = nullptr; 4688 } 4689 return Result; 4690 } 4691 4692 // C++14 [over.ics.list]p6: 4693 // C++11 [over.ics.list]p5: 4694 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4695 if (ToType->isReferenceType()) { 4696 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4697 // mention initializer lists in any way. So we go by what list- 4698 // initialization would do and try to extrapolate from that. 4699 4700 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4701 4702 // If the initializer list has a single element that is reference-related 4703 // to the parameter type, we initialize the reference from that. 4704 if (From->getNumInits() == 1) { 4705 Expr *Init = From->getInit(0); 4706 4707 QualType T2 = Init->getType(); 4708 4709 // If the initializer is the address of an overloaded function, try 4710 // to resolve the overloaded function. If all goes well, T2 is the 4711 // type of the resulting function. 4712 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4713 DeclAccessPair Found; 4714 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4715 Init, ToType, false, Found)) 4716 T2 = Fn->getType(); 4717 } 4718 4719 // Compute some basic properties of the types and the initializer. 4720 bool dummy1 = false; 4721 bool dummy2 = false; 4722 bool dummy3 = false; 4723 Sema::ReferenceCompareResult RefRelationship 4724 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4725 dummy2, dummy3); 4726 4727 if (RefRelationship >= Sema::Ref_Related) { 4728 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4729 SuppressUserConversions, 4730 /*AllowExplicit=*/false); 4731 } 4732 } 4733 4734 // Otherwise, we bind the reference to a temporary created from the 4735 // initializer list. 4736 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4737 InOverloadResolution, 4738 AllowObjCWritebackConversion); 4739 if (Result.isFailure()) 4740 return Result; 4741 assert(!Result.isEllipsis() && 4742 "Sub-initialization cannot result in ellipsis conversion."); 4743 4744 // Can we even bind to a temporary? 4745 if (ToType->isRValueReferenceType() || 4746 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4747 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4748 Result.UserDefined.After; 4749 SCS.ReferenceBinding = true; 4750 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4751 SCS.BindsToRvalue = true; 4752 SCS.BindsToFunctionLvalue = false; 4753 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4754 SCS.ObjCLifetimeConversionBinding = false; 4755 } else 4756 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4757 From, ToType); 4758 return Result; 4759 } 4760 4761 // C++14 [over.ics.list]p7: 4762 // C++11 [over.ics.list]p6: 4763 // Otherwise, if the parameter type is not a class: 4764 if (!ToType->isRecordType()) { 4765 // - if the initializer list has one element that is not itself an 4766 // initializer list, the implicit conversion sequence is the one 4767 // required to convert the element to the parameter type. 4768 unsigned NumInits = From->getNumInits(); 4769 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4770 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4771 SuppressUserConversions, 4772 InOverloadResolution, 4773 AllowObjCWritebackConversion); 4774 // - if the initializer list has no elements, the implicit conversion 4775 // sequence is the identity conversion. 4776 else if (NumInits == 0) { 4777 Result.setStandard(); 4778 Result.Standard.setAsIdentityConversion(); 4779 Result.Standard.setFromType(ToType); 4780 Result.Standard.setAllToTypes(ToType); 4781 } 4782 return Result; 4783 } 4784 4785 // C++14 [over.ics.list]p8: 4786 // C++11 [over.ics.list]p7: 4787 // In all cases other than those enumerated above, no conversion is possible 4788 return Result; 4789 } 4790 4791 /// TryCopyInitialization - Try to copy-initialize a value of type 4792 /// ToType from the expression From. Return the implicit conversion 4793 /// sequence required to pass this argument, which may be a bad 4794 /// conversion sequence (meaning that the argument cannot be passed to 4795 /// a parameter of this type). If @p SuppressUserConversions, then we 4796 /// do not permit any user-defined conversion sequences. 4797 static ImplicitConversionSequence 4798 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4799 bool SuppressUserConversions, 4800 bool InOverloadResolution, 4801 bool AllowObjCWritebackConversion, 4802 bool AllowExplicit) { 4803 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4804 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4805 InOverloadResolution,AllowObjCWritebackConversion); 4806 4807 if (ToType->isReferenceType()) 4808 return TryReferenceInit(S, From, ToType, 4809 /*FIXME:*/From->getLocStart(), 4810 SuppressUserConversions, 4811 AllowExplicit); 4812 4813 return TryImplicitConversion(S, From, ToType, 4814 SuppressUserConversions, 4815 /*AllowExplicit=*/false, 4816 InOverloadResolution, 4817 /*CStyle=*/false, 4818 AllowObjCWritebackConversion, 4819 /*AllowObjCConversionOnExplicit=*/false); 4820 } 4821 4822 static bool TryCopyInitialization(const CanQualType FromQTy, 4823 const CanQualType ToQTy, 4824 Sema &S, 4825 SourceLocation Loc, 4826 ExprValueKind FromVK) { 4827 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4828 ImplicitConversionSequence ICS = 4829 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4830 4831 return !ICS.isBad(); 4832 } 4833 4834 /// TryObjectArgumentInitialization - Try to initialize the object 4835 /// parameter of the given member function (@c Method) from the 4836 /// expression @p From. 4837 static ImplicitConversionSequence 4838 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4839 Expr::Classification FromClassification, 4840 CXXMethodDecl *Method, 4841 CXXRecordDecl *ActingContext) { 4842 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4843 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4844 // const volatile object. 4845 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4846 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4847 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4848 4849 // Set up the conversion sequence as a "bad" conversion, to allow us 4850 // to exit early. 4851 ImplicitConversionSequence ICS; 4852 4853 // We need to have an object of class type. 4854 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4855 FromType = PT->getPointeeType(); 4856 4857 // When we had a pointer, it's implicitly dereferenced, so we 4858 // better have an lvalue. 4859 assert(FromClassification.isLValue()); 4860 } 4861 4862 assert(FromType->isRecordType()); 4863 4864 // C++0x [over.match.funcs]p4: 4865 // For non-static member functions, the type of the implicit object 4866 // parameter is 4867 // 4868 // - "lvalue reference to cv X" for functions declared without a 4869 // ref-qualifier or with the & ref-qualifier 4870 // - "rvalue reference to cv X" for functions declared with the && 4871 // ref-qualifier 4872 // 4873 // where X is the class of which the function is a member and cv is the 4874 // cv-qualification on the member function declaration. 4875 // 4876 // However, when finding an implicit conversion sequence for the argument, we 4877 // are not allowed to create temporaries or perform user-defined conversions 4878 // (C++ [over.match.funcs]p5). We perform a simplified version of 4879 // reference binding here, that allows class rvalues to bind to 4880 // non-constant references. 4881 4882 // First check the qualifiers. 4883 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4884 if (ImplicitParamType.getCVRQualifiers() 4885 != FromTypeCanon.getLocalCVRQualifiers() && 4886 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4887 ICS.setBad(BadConversionSequence::bad_qualifiers, 4888 FromType, ImplicitParamType); 4889 return ICS; 4890 } 4891 4892 // Check that we have either the same type or a derived type. It 4893 // affects the conversion rank. 4894 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4895 ImplicitConversionKind SecondKind; 4896 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4897 SecondKind = ICK_Identity; 4898 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4899 SecondKind = ICK_Derived_To_Base; 4900 else { 4901 ICS.setBad(BadConversionSequence::unrelated_class, 4902 FromType, ImplicitParamType); 4903 return ICS; 4904 } 4905 4906 // Check the ref-qualifier. 4907 switch (Method->getRefQualifier()) { 4908 case RQ_None: 4909 // Do nothing; we don't care about lvalueness or rvalueness. 4910 break; 4911 4912 case RQ_LValue: 4913 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4914 // non-const lvalue reference cannot bind to an rvalue 4915 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4916 ImplicitParamType); 4917 return ICS; 4918 } 4919 break; 4920 4921 case RQ_RValue: 4922 if (!FromClassification.isRValue()) { 4923 // rvalue reference cannot bind to an lvalue 4924 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4925 ImplicitParamType); 4926 return ICS; 4927 } 4928 break; 4929 } 4930 4931 // Success. Mark this as a reference binding. 4932 ICS.setStandard(); 4933 ICS.Standard.setAsIdentityConversion(); 4934 ICS.Standard.Second = SecondKind; 4935 ICS.Standard.setFromType(FromType); 4936 ICS.Standard.setAllToTypes(ImplicitParamType); 4937 ICS.Standard.ReferenceBinding = true; 4938 ICS.Standard.DirectBinding = true; 4939 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4940 ICS.Standard.BindsToFunctionLvalue = false; 4941 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4942 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4943 = (Method->getRefQualifier() == RQ_None); 4944 return ICS; 4945 } 4946 4947 /// PerformObjectArgumentInitialization - Perform initialization of 4948 /// the implicit object parameter for the given Method with the given 4949 /// expression. 4950 ExprResult 4951 Sema::PerformObjectArgumentInitialization(Expr *From, 4952 NestedNameSpecifier *Qualifier, 4953 NamedDecl *FoundDecl, 4954 CXXMethodDecl *Method) { 4955 QualType FromRecordType, DestType; 4956 QualType ImplicitParamRecordType = 4957 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4958 4959 Expr::Classification FromClassification; 4960 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4961 FromRecordType = PT->getPointeeType(); 4962 DestType = Method->getThisType(Context); 4963 FromClassification = Expr::Classification::makeSimpleLValue(); 4964 } else { 4965 FromRecordType = From->getType(); 4966 DestType = ImplicitParamRecordType; 4967 FromClassification = From->Classify(Context); 4968 } 4969 4970 // Note that we always use the true parent context when performing 4971 // the actual argument initialization. 4972 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4973 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4974 Method->getParent()); 4975 if (ICS.isBad()) { 4976 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4977 Qualifiers FromQs = FromRecordType.getQualifiers(); 4978 Qualifiers ToQs = DestType.getQualifiers(); 4979 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4980 if (CVR) { 4981 Diag(From->getLocStart(), 4982 diag::err_member_function_call_bad_cvr) 4983 << Method->getDeclName() << FromRecordType << (CVR - 1) 4984 << From->getSourceRange(); 4985 Diag(Method->getLocation(), diag::note_previous_decl) 4986 << Method->getDeclName(); 4987 return ExprError(); 4988 } 4989 } 4990 4991 return Diag(From->getLocStart(), 4992 diag::err_implicit_object_parameter_init) 4993 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4994 } 4995 4996 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4997 ExprResult FromRes = 4998 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4999 if (FromRes.isInvalid()) 5000 return ExprError(); 5001 From = FromRes.get(); 5002 } 5003 5004 if (!Context.hasSameType(From->getType(), DestType)) 5005 From = ImpCastExprToType(From, DestType, CK_NoOp, 5006 From->getValueKind()).get(); 5007 return From; 5008 } 5009 5010 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5011 /// expression From to bool (C++0x [conv]p3). 5012 static ImplicitConversionSequence 5013 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5014 return TryImplicitConversion(S, From, S.Context.BoolTy, 5015 /*SuppressUserConversions=*/false, 5016 /*AllowExplicit=*/true, 5017 /*InOverloadResolution=*/false, 5018 /*CStyle=*/false, 5019 /*AllowObjCWritebackConversion=*/false, 5020 /*AllowObjCConversionOnExplicit=*/false); 5021 } 5022 5023 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5024 /// of the expression From to bool (C++0x [conv]p3). 5025 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5026 if (checkPlaceholderForOverload(*this, From)) 5027 return ExprError(); 5028 5029 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5030 if (!ICS.isBad()) 5031 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5032 5033 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5034 return Diag(From->getLocStart(), 5035 diag::err_typecheck_bool_condition) 5036 << From->getType() << From->getSourceRange(); 5037 return ExprError(); 5038 } 5039 5040 /// Check that the specified conversion is permitted in a converted constant 5041 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5042 /// is acceptable. 5043 static bool CheckConvertedConstantConversions(Sema &S, 5044 StandardConversionSequence &SCS) { 5045 // Since we know that the target type is an integral or unscoped enumeration 5046 // type, most conversion kinds are impossible. All possible First and Third 5047 // conversions are fine. 5048 switch (SCS.Second) { 5049 case ICK_Identity: 5050 case ICK_NoReturn_Adjustment: 5051 case ICK_Integral_Promotion: 5052 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5053 return true; 5054 5055 case ICK_Boolean_Conversion: 5056 // Conversion from an integral or unscoped enumeration type to bool is 5057 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5058 // conversion, so we allow it in a converted constant expression. 5059 // 5060 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5061 // a lot of popular code. We should at least add a warning for this 5062 // (non-conforming) extension. 5063 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5064 SCS.getToType(2)->isBooleanType(); 5065 5066 case ICK_Pointer_Conversion: 5067 case ICK_Pointer_Member: 5068 // C++1z: null pointer conversions and null member pointer conversions are 5069 // only permitted if the source type is std::nullptr_t. 5070 return SCS.getFromType()->isNullPtrType(); 5071 5072 case ICK_Floating_Promotion: 5073 case ICK_Complex_Promotion: 5074 case ICK_Floating_Conversion: 5075 case ICK_Complex_Conversion: 5076 case ICK_Floating_Integral: 5077 case ICK_Compatible_Conversion: 5078 case ICK_Derived_To_Base: 5079 case ICK_Vector_Conversion: 5080 case ICK_Vector_Splat: 5081 case ICK_Complex_Real: 5082 case ICK_Block_Pointer_Conversion: 5083 case ICK_TransparentUnionConversion: 5084 case ICK_Writeback_Conversion: 5085 case ICK_Zero_Event_Conversion: 5086 case ICK_C_Only_Conversion: 5087 return false; 5088 5089 case ICK_Lvalue_To_Rvalue: 5090 case ICK_Array_To_Pointer: 5091 case ICK_Function_To_Pointer: 5092 llvm_unreachable("found a first conversion kind in Second"); 5093 5094 case ICK_Qualification: 5095 llvm_unreachable("found a third conversion kind in Second"); 5096 5097 case ICK_Num_Conversion_Kinds: 5098 break; 5099 } 5100 5101 llvm_unreachable("unknown conversion kind"); 5102 } 5103 5104 /// CheckConvertedConstantExpression - Check that the expression From is a 5105 /// converted constant expression of type T, perform the conversion and produce 5106 /// the converted expression, per C++11 [expr.const]p3. 5107 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5108 QualType T, APValue &Value, 5109 Sema::CCEKind CCE, 5110 bool RequireInt) { 5111 assert(S.getLangOpts().CPlusPlus11 && 5112 "converted constant expression outside C++11"); 5113 5114 if (checkPlaceholderForOverload(S, From)) 5115 return ExprError(); 5116 5117 // C++1z [expr.const]p3: 5118 // A converted constant expression of type T is an expression, 5119 // implicitly converted to type T, where the converted 5120 // expression is a constant expression and the implicit conversion 5121 // sequence contains only [... list of conversions ...]. 5122 ImplicitConversionSequence ICS = 5123 TryCopyInitialization(S, From, T, 5124 /*SuppressUserConversions=*/false, 5125 /*InOverloadResolution=*/false, 5126 /*AllowObjcWritebackConversion=*/false, 5127 /*AllowExplicit=*/false); 5128 StandardConversionSequence *SCS = nullptr; 5129 switch (ICS.getKind()) { 5130 case ImplicitConversionSequence::StandardConversion: 5131 SCS = &ICS.Standard; 5132 break; 5133 case ImplicitConversionSequence::UserDefinedConversion: 5134 // We are converting to a non-class type, so the Before sequence 5135 // must be trivial. 5136 SCS = &ICS.UserDefined.After; 5137 break; 5138 case ImplicitConversionSequence::AmbiguousConversion: 5139 case ImplicitConversionSequence::BadConversion: 5140 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5141 return S.Diag(From->getLocStart(), 5142 diag::err_typecheck_converted_constant_expression) 5143 << From->getType() << From->getSourceRange() << T; 5144 return ExprError(); 5145 5146 case ImplicitConversionSequence::EllipsisConversion: 5147 llvm_unreachable("ellipsis conversion in converted constant expression"); 5148 } 5149 5150 // Check that we would only use permitted conversions. 5151 if (!CheckConvertedConstantConversions(S, *SCS)) { 5152 return S.Diag(From->getLocStart(), 5153 diag::err_typecheck_converted_constant_expression_disallowed) 5154 << From->getType() << From->getSourceRange() << T; 5155 } 5156 // [...] and where the reference binding (if any) binds directly. 5157 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5158 return S.Diag(From->getLocStart(), 5159 diag::err_typecheck_converted_constant_expression_indirect) 5160 << From->getType() << From->getSourceRange() << T; 5161 } 5162 5163 ExprResult Result = 5164 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5165 if (Result.isInvalid()) 5166 return Result; 5167 5168 // Check for a narrowing implicit conversion. 5169 APValue PreNarrowingValue; 5170 QualType PreNarrowingType; 5171 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5172 PreNarrowingType)) { 5173 case NK_Variable_Narrowing: 5174 // Implicit conversion to a narrower type, and the value is not a constant 5175 // expression. We'll diagnose this in a moment. 5176 case NK_Not_Narrowing: 5177 break; 5178 5179 case NK_Constant_Narrowing: 5180 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5181 << CCE << /*Constant*/1 5182 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5183 break; 5184 5185 case NK_Type_Narrowing: 5186 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5187 << CCE << /*Constant*/0 << From->getType() << T; 5188 break; 5189 } 5190 5191 // Check the expression is a constant expression. 5192 SmallVector<PartialDiagnosticAt, 8> Notes; 5193 Expr::EvalResult Eval; 5194 Eval.Diag = &Notes; 5195 5196 if ((T->isReferenceType() 5197 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5198 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5199 (RequireInt && !Eval.Val.isInt())) { 5200 // The expression can't be folded, so we can't keep it at this position in 5201 // the AST. 5202 Result = ExprError(); 5203 } else { 5204 Value = Eval.Val; 5205 5206 if (Notes.empty()) { 5207 // It's a constant expression. 5208 return Result; 5209 } 5210 } 5211 5212 // It's not a constant expression. Produce an appropriate diagnostic. 5213 if (Notes.size() == 1 && 5214 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5215 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5216 else { 5217 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5218 << CCE << From->getSourceRange(); 5219 for (unsigned I = 0; I < Notes.size(); ++I) 5220 S.Diag(Notes[I].first, Notes[I].second); 5221 } 5222 return ExprError(); 5223 } 5224 5225 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5226 APValue &Value, CCEKind CCE) { 5227 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5228 } 5229 5230 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5231 llvm::APSInt &Value, 5232 CCEKind CCE) { 5233 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5234 5235 APValue V; 5236 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5237 if (!R.isInvalid()) 5238 Value = V.getInt(); 5239 return R; 5240 } 5241 5242 5243 /// dropPointerConversions - If the given standard conversion sequence 5244 /// involves any pointer conversions, remove them. This may change 5245 /// the result type of the conversion sequence. 5246 static void dropPointerConversion(StandardConversionSequence &SCS) { 5247 if (SCS.Second == ICK_Pointer_Conversion) { 5248 SCS.Second = ICK_Identity; 5249 SCS.Third = ICK_Identity; 5250 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5251 } 5252 } 5253 5254 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5255 /// convert the expression From to an Objective-C pointer type. 5256 static ImplicitConversionSequence 5257 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5258 // Do an implicit conversion to 'id'. 5259 QualType Ty = S.Context.getObjCIdType(); 5260 ImplicitConversionSequence ICS 5261 = TryImplicitConversion(S, From, Ty, 5262 // FIXME: Are these flags correct? 5263 /*SuppressUserConversions=*/false, 5264 /*AllowExplicit=*/true, 5265 /*InOverloadResolution=*/false, 5266 /*CStyle=*/false, 5267 /*AllowObjCWritebackConversion=*/false, 5268 /*AllowObjCConversionOnExplicit=*/true); 5269 5270 // Strip off any final conversions to 'id'. 5271 switch (ICS.getKind()) { 5272 case ImplicitConversionSequence::BadConversion: 5273 case ImplicitConversionSequence::AmbiguousConversion: 5274 case ImplicitConversionSequence::EllipsisConversion: 5275 break; 5276 5277 case ImplicitConversionSequence::UserDefinedConversion: 5278 dropPointerConversion(ICS.UserDefined.After); 5279 break; 5280 5281 case ImplicitConversionSequence::StandardConversion: 5282 dropPointerConversion(ICS.Standard); 5283 break; 5284 } 5285 5286 return ICS; 5287 } 5288 5289 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5290 /// conversion of the expression From to an Objective-C pointer type. 5291 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5292 if (checkPlaceholderForOverload(*this, From)) 5293 return ExprError(); 5294 5295 QualType Ty = Context.getObjCIdType(); 5296 ImplicitConversionSequence ICS = 5297 TryContextuallyConvertToObjCPointer(*this, From); 5298 if (!ICS.isBad()) 5299 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5300 return ExprError(); 5301 } 5302 5303 /// Determine whether the provided type is an integral type, or an enumeration 5304 /// type of a permitted flavor. 5305 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5306 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5307 : T->isIntegralOrUnscopedEnumerationType(); 5308 } 5309 5310 static ExprResult 5311 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5312 Sema::ContextualImplicitConverter &Converter, 5313 QualType T, UnresolvedSetImpl &ViableConversions) { 5314 5315 if (Converter.Suppress) 5316 return ExprError(); 5317 5318 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5319 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5320 CXXConversionDecl *Conv = 5321 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5322 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5323 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5324 } 5325 return From; 5326 } 5327 5328 static bool 5329 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5330 Sema::ContextualImplicitConverter &Converter, 5331 QualType T, bool HadMultipleCandidates, 5332 UnresolvedSetImpl &ExplicitConversions) { 5333 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5334 DeclAccessPair Found = ExplicitConversions[0]; 5335 CXXConversionDecl *Conversion = 5336 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5337 5338 // The user probably meant to invoke the given explicit 5339 // conversion; use it. 5340 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5341 std::string TypeStr; 5342 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5343 5344 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5345 << FixItHint::CreateInsertion(From->getLocStart(), 5346 "static_cast<" + TypeStr + ">(") 5347 << FixItHint::CreateInsertion( 5348 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5349 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5350 5351 // If we aren't in a SFINAE context, build a call to the 5352 // explicit conversion function. 5353 if (SemaRef.isSFINAEContext()) 5354 return true; 5355 5356 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5357 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5358 HadMultipleCandidates); 5359 if (Result.isInvalid()) 5360 return true; 5361 // Record usage of conversion in an implicit cast. 5362 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5363 CK_UserDefinedConversion, Result.get(), 5364 nullptr, Result.get()->getValueKind()); 5365 } 5366 return false; 5367 } 5368 5369 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5370 Sema::ContextualImplicitConverter &Converter, 5371 QualType T, bool HadMultipleCandidates, 5372 DeclAccessPair &Found) { 5373 CXXConversionDecl *Conversion = 5374 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5375 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5376 5377 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5378 if (!Converter.SuppressConversion) { 5379 if (SemaRef.isSFINAEContext()) 5380 return true; 5381 5382 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5383 << From->getSourceRange(); 5384 } 5385 5386 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5387 HadMultipleCandidates); 5388 if (Result.isInvalid()) 5389 return true; 5390 // Record usage of conversion in an implicit cast. 5391 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5392 CK_UserDefinedConversion, Result.get(), 5393 nullptr, Result.get()->getValueKind()); 5394 return false; 5395 } 5396 5397 static ExprResult finishContextualImplicitConversion( 5398 Sema &SemaRef, SourceLocation Loc, Expr *From, 5399 Sema::ContextualImplicitConverter &Converter) { 5400 if (!Converter.match(From->getType()) && !Converter.Suppress) 5401 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5402 << From->getSourceRange(); 5403 5404 return SemaRef.DefaultLvalueConversion(From); 5405 } 5406 5407 static void 5408 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5409 UnresolvedSetImpl &ViableConversions, 5410 OverloadCandidateSet &CandidateSet) { 5411 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5412 DeclAccessPair FoundDecl = ViableConversions[I]; 5413 NamedDecl *D = FoundDecl.getDecl(); 5414 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5415 if (isa<UsingShadowDecl>(D)) 5416 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5417 5418 CXXConversionDecl *Conv; 5419 FunctionTemplateDecl *ConvTemplate; 5420 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5421 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5422 else 5423 Conv = cast<CXXConversionDecl>(D); 5424 5425 if (ConvTemplate) 5426 SemaRef.AddTemplateConversionCandidate( 5427 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5428 /*AllowObjCConversionOnExplicit=*/false); 5429 else 5430 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5431 ToType, CandidateSet, 5432 /*AllowObjCConversionOnExplicit=*/false); 5433 } 5434 } 5435 5436 /// \brief Attempt to convert the given expression to a type which is accepted 5437 /// by the given converter. 5438 /// 5439 /// This routine will attempt to convert an expression of class type to a 5440 /// type accepted by the specified converter. In C++11 and before, the class 5441 /// must have a single non-explicit conversion function converting to a matching 5442 /// type. In C++1y, there can be multiple such conversion functions, but only 5443 /// one target type. 5444 /// 5445 /// \param Loc The source location of the construct that requires the 5446 /// conversion. 5447 /// 5448 /// \param From The expression we're converting from. 5449 /// 5450 /// \param Converter Used to control and diagnose the conversion process. 5451 /// 5452 /// \returns The expression, converted to an integral or enumeration type if 5453 /// successful. 5454 ExprResult Sema::PerformContextualImplicitConversion( 5455 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5456 // We can't perform any more checking for type-dependent expressions. 5457 if (From->isTypeDependent()) 5458 return From; 5459 5460 // Process placeholders immediately. 5461 if (From->hasPlaceholderType()) { 5462 ExprResult result = CheckPlaceholderExpr(From); 5463 if (result.isInvalid()) 5464 return result; 5465 From = result.get(); 5466 } 5467 5468 // If the expression already has a matching type, we're golden. 5469 QualType T = From->getType(); 5470 if (Converter.match(T)) 5471 return DefaultLvalueConversion(From); 5472 5473 // FIXME: Check for missing '()' if T is a function type? 5474 5475 // We can only perform contextual implicit conversions on objects of class 5476 // type. 5477 const RecordType *RecordTy = T->getAs<RecordType>(); 5478 if (!RecordTy || !getLangOpts().CPlusPlus) { 5479 if (!Converter.Suppress) 5480 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5481 return From; 5482 } 5483 5484 // We must have a complete class type. 5485 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5486 ContextualImplicitConverter &Converter; 5487 Expr *From; 5488 5489 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5490 : Converter(Converter), From(From) {} 5491 5492 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5493 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5494 } 5495 } IncompleteDiagnoser(Converter, From); 5496 5497 if (Converter.Suppress ? !isCompleteType(Loc, T) 5498 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5499 return From; 5500 5501 // Look for a conversion to an integral or enumeration type. 5502 UnresolvedSet<4> 5503 ViableConversions; // These are *potentially* viable in C++1y. 5504 UnresolvedSet<4> ExplicitConversions; 5505 const auto &Conversions = 5506 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5507 5508 bool HadMultipleCandidates = 5509 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5510 5511 // To check that there is only one target type, in C++1y: 5512 QualType ToType; 5513 bool HasUniqueTargetType = true; 5514 5515 // Collect explicit or viable (potentially in C++1y) conversions. 5516 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5517 NamedDecl *D = (*I)->getUnderlyingDecl(); 5518 CXXConversionDecl *Conversion; 5519 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5520 if (ConvTemplate) { 5521 if (getLangOpts().CPlusPlus14) 5522 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5523 else 5524 continue; // C++11 does not consider conversion operator templates(?). 5525 } else 5526 Conversion = cast<CXXConversionDecl>(D); 5527 5528 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5529 "Conversion operator templates are considered potentially " 5530 "viable in C++1y"); 5531 5532 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5533 if (Converter.match(CurToType) || ConvTemplate) { 5534 5535 if (Conversion->isExplicit()) { 5536 // FIXME: For C++1y, do we need this restriction? 5537 // cf. diagnoseNoViableConversion() 5538 if (!ConvTemplate) 5539 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5540 } else { 5541 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5542 if (ToType.isNull()) 5543 ToType = CurToType.getUnqualifiedType(); 5544 else if (HasUniqueTargetType && 5545 (CurToType.getUnqualifiedType() != ToType)) 5546 HasUniqueTargetType = false; 5547 } 5548 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5549 } 5550 } 5551 } 5552 5553 if (getLangOpts().CPlusPlus14) { 5554 // C++1y [conv]p6: 5555 // ... An expression e of class type E appearing in such a context 5556 // is said to be contextually implicitly converted to a specified 5557 // type T and is well-formed if and only if e can be implicitly 5558 // converted to a type T that is determined as follows: E is searched 5559 // for conversion functions whose return type is cv T or reference to 5560 // cv T such that T is allowed by the context. There shall be 5561 // exactly one such T. 5562 5563 // If no unique T is found: 5564 if (ToType.isNull()) { 5565 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5566 HadMultipleCandidates, 5567 ExplicitConversions)) 5568 return ExprError(); 5569 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5570 } 5571 5572 // If more than one unique Ts are found: 5573 if (!HasUniqueTargetType) 5574 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5575 ViableConversions); 5576 5577 // If one unique T is found: 5578 // First, build a candidate set from the previously recorded 5579 // potentially viable conversions. 5580 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5581 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5582 CandidateSet); 5583 5584 // Then, perform overload resolution over the candidate set. 5585 OverloadCandidateSet::iterator Best; 5586 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5587 case OR_Success: { 5588 // Apply this conversion. 5589 DeclAccessPair Found = 5590 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5591 if (recordConversion(*this, Loc, From, Converter, T, 5592 HadMultipleCandidates, Found)) 5593 return ExprError(); 5594 break; 5595 } 5596 case OR_Ambiguous: 5597 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5598 ViableConversions); 5599 case OR_No_Viable_Function: 5600 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5601 HadMultipleCandidates, 5602 ExplicitConversions)) 5603 return ExprError(); 5604 // fall through 'OR_Deleted' case. 5605 case OR_Deleted: 5606 // We'll complain below about a non-integral condition type. 5607 break; 5608 } 5609 } else { 5610 switch (ViableConversions.size()) { 5611 case 0: { 5612 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5613 HadMultipleCandidates, 5614 ExplicitConversions)) 5615 return ExprError(); 5616 5617 // We'll complain below about a non-integral condition type. 5618 break; 5619 } 5620 case 1: { 5621 // Apply this conversion. 5622 DeclAccessPair Found = ViableConversions[0]; 5623 if (recordConversion(*this, Loc, From, Converter, T, 5624 HadMultipleCandidates, Found)) 5625 return ExprError(); 5626 break; 5627 } 5628 default: 5629 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5630 ViableConversions); 5631 } 5632 } 5633 5634 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5635 } 5636 5637 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5638 /// an acceptable non-member overloaded operator for a call whose 5639 /// arguments have types T1 (and, if non-empty, T2). This routine 5640 /// implements the check in C++ [over.match.oper]p3b2 concerning 5641 /// enumeration types. 5642 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5643 FunctionDecl *Fn, 5644 ArrayRef<Expr *> Args) { 5645 QualType T1 = Args[0]->getType(); 5646 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5647 5648 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5649 return true; 5650 5651 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5652 return true; 5653 5654 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5655 if (Proto->getNumParams() < 1) 5656 return false; 5657 5658 if (T1->isEnumeralType()) { 5659 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5660 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5661 return true; 5662 } 5663 5664 if (Proto->getNumParams() < 2) 5665 return false; 5666 5667 if (!T2.isNull() && T2->isEnumeralType()) { 5668 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5669 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5670 return true; 5671 } 5672 5673 return false; 5674 } 5675 5676 /// AddOverloadCandidate - Adds the given function to the set of 5677 /// candidate functions, using the given function call arguments. If 5678 /// @p SuppressUserConversions, then don't allow user-defined 5679 /// conversions via constructors or conversion operators. 5680 /// 5681 /// \param PartialOverloading true if we are performing "partial" overloading 5682 /// based on an incomplete set of function arguments. This feature is used by 5683 /// code completion. 5684 void 5685 Sema::AddOverloadCandidate(FunctionDecl *Function, 5686 DeclAccessPair FoundDecl, 5687 ArrayRef<Expr *> Args, 5688 OverloadCandidateSet &CandidateSet, 5689 bool SuppressUserConversions, 5690 bool PartialOverloading, 5691 bool AllowExplicit) { 5692 const FunctionProtoType *Proto 5693 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5694 assert(Proto && "Functions without a prototype cannot be overloaded"); 5695 assert(!Function->getDescribedFunctionTemplate() && 5696 "Use AddTemplateOverloadCandidate for function templates"); 5697 5698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5699 if (!isa<CXXConstructorDecl>(Method)) { 5700 // If we get here, it's because we're calling a member function 5701 // that is named without a member access expression (e.g., 5702 // "this->f") that was either written explicitly or created 5703 // implicitly. This can happen with a qualified call to a member 5704 // function, e.g., X::f(). We use an empty type for the implied 5705 // object argument (C++ [over.call.func]p3), and the acting context 5706 // is irrelevant. 5707 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5708 QualType(), Expr::Classification::makeSimpleLValue(), 5709 Args, CandidateSet, SuppressUserConversions, 5710 PartialOverloading); 5711 return; 5712 } 5713 // We treat a constructor like a non-member function, since its object 5714 // argument doesn't participate in overload resolution. 5715 } 5716 5717 if (!CandidateSet.isNewCandidate(Function)) 5718 return; 5719 5720 // C++ [over.match.oper]p3: 5721 // if no operand has a class type, only those non-member functions in the 5722 // lookup set that have a first parameter of type T1 or "reference to 5723 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5724 // is a right operand) a second parameter of type T2 or "reference to 5725 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5726 // candidate functions. 5727 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5728 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5729 return; 5730 5731 // C++11 [class.copy]p11: [DR1402] 5732 // A defaulted move constructor that is defined as deleted is ignored by 5733 // overload resolution. 5734 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5735 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5736 Constructor->isMoveConstructor()) 5737 return; 5738 5739 // Overload resolution is always an unevaluated context. 5740 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5741 5742 // Add this candidate 5743 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5744 Candidate.FoundDecl = FoundDecl; 5745 Candidate.Function = Function; 5746 Candidate.Viable = true; 5747 Candidate.IsSurrogate = false; 5748 Candidate.IgnoreObjectArgument = false; 5749 Candidate.ExplicitCallArguments = Args.size(); 5750 5751 if (Constructor) { 5752 // C++ [class.copy]p3: 5753 // A member function template is never instantiated to perform the copy 5754 // of a class object to an object of its class type. 5755 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5756 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5757 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5758 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5759 ClassType))) { 5760 Candidate.Viable = false; 5761 Candidate.FailureKind = ovl_fail_illegal_constructor; 5762 return; 5763 } 5764 } 5765 5766 unsigned NumParams = Proto->getNumParams(); 5767 5768 // (C++ 13.3.2p2): A candidate function having fewer than m 5769 // parameters is viable only if it has an ellipsis in its parameter 5770 // list (8.3.5). 5771 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5772 !Proto->isVariadic()) { 5773 Candidate.Viable = false; 5774 Candidate.FailureKind = ovl_fail_too_many_arguments; 5775 return; 5776 } 5777 5778 // (C++ 13.3.2p2): A candidate function having more than m parameters 5779 // is viable only if the (m+1)st parameter has a default argument 5780 // (8.3.6). For the purposes of overload resolution, the 5781 // parameter list is truncated on the right, so that there are 5782 // exactly m parameters. 5783 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5784 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5785 // Not enough arguments. 5786 Candidate.Viable = false; 5787 Candidate.FailureKind = ovl_fail_too_few_arguments; 5788 return; 5789 } 5790 5791 // (CUDA B.1): Check for invalid calls between targets. 5792 if (getLangOpts().CUDA) 5793 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5794 // Skip the check for callers that are implicit members, because in this 5795 // case we may not yet know what the member's target is; the target is 5796 // inferred for the member automatically, based on the bases and fields of 5797 // the class. 5798 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5799 Candidate.Viable = false; 5800 Candidate.FailureKind = ovl_fail_bad_target; 5801 return; 5802 } 5803 5804 // Determine the implicit conversion sequences for each of the 5805 // arguments. 5806 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5807 if (ArgIdx < NumParams) { 5808 // (C++ 13.3.2p3): for F to be a viable function, there shall 5809 // exist for each argument an implicit conversion sequence 5810 // (13.3.3.1) that converts that argument to the corresponding 5811 // parameter of F. 5812 QualType ParamType = Proto->getParamType(ArgIdx); 5813 Candidate.Conversions[ArgIdx] 5814 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5815 SuppressUserConversions, 5816 /*InOverloadResolution=*/true, 5817 /*AllowObjCWritebackConversion=*/ 5818 getLangOpts().ObjCAutoRefCount, 5819 AllowExplicit); 5820 if (Candidate.Conversions[ArgIdx].isBad()) { 5821 Candidate.Viable = false; 5822 Candidate.FailureKind = ovl_fail_bad_conversion; 5823 return; 5824 } 5825 } else { 5826 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5827 // argument for which there is no corresponding parameter is 5828 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5829 Candidate.Conversions[ArgIdx].setEllipsis(); 5830 } 5831 } 5832 5833 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5834 Candidate.Viable = false; 5835 Candidate.FailureKind = ovl_fail_enable_if; 5836 Candidate.DeductionFailure.Data = FailedAttr; 5837 return; 5838 } 5839 } 5840 5841 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5842 bool IsInstance) { 5843 SmallVector<ObjCMethodDecl*, 4> Methods; 5844 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5845 return nullptr; 5846 5847 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5848 bool Match = true; 5849 ObjCMethodDecl *Method = Methods[b]; 5850 unsigned NumNamedArgs = Sel.getNumArgs(); 5851 // Method might have more arguments than selector indicates. This is due 5852 // to addition of c-style arguments in method. 5853 if (Method->param_size() > NumNamedArgs) 5854 NumNamedArgs = Method->param_size(); 5855 if (Args.size() < NumNamedArgs) 5856 continue; 5857 5858 for (unsigned i = 0; i < NumNamedArgs; i++) { 5859 // We can't do any type-checking on a type-dependent argument. 5860 if (Args[i]->isTypeDependent()) { 5861 Match = false; 5862 break; 5863 } 5864 5865 ParmVarDecl *param = Method->parameters()[i]; 5866 Expr *argExpr = Args[i]; 5867 assert(argExpr && "SelectBestMethod(): missing expression"); 5868 5869 // Strip the unbridged-cast placeholder expression off unless it's 5870 // a consumed argument. 5871 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5872 !param->hasAttr<CFConsumedAttr>()) 5873 argExpr = stripARCUnbridgedCast(argExpr); 5874 5875 // If the parameter is __unknown_anytype, move on to the next method. 5876 if (param->getType() == Context.UnknownAnyTy) { 5877 Match = false; 5878 break; 5879 } 5880 5881 ImplicitConversionSequence ConversionState 5882 = TryCopyInitialization(*this, argExpr, param->getType(), 5883 /*SuppressUserConversions*/false, 5884 /*InOverloadResolution=*/true, 5885 /*AllowObjCWritebackConversion=*/ 5886 getLangOpts().ObjCAutoRefCount, 5887 /*AllowExplicit*/false); 5888 if (ConversionState.isBad()) { 5889 Match = false; 5890 break; 5891 } 5892 } 5893 // Promote additional arguments to variadic methods. 5894 if (Match && Method->isVariadic()) { 5895 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5896 if (Args[i]->isTypeDependent()) { 5897 Match = false; 5898 break; 5899 } 5900 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5901 nullptr); 5902 if (Arg.isInvalid()) { 5903 Match = false; 5904 break; 5905 } 5906 } 5907 } else { 5908 // Check for extra arguments to non-variadic methods. 5909 if (Args.size() != NumNamedArgs) 5910 Match = false; 5911 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5912 // Special case when selectors have no argument. In this case, select 5913 // one with the most general result type of 'id'. 5914 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5915 QualType ReturnT = Methods[b]->getReturnType(); 5916 if (ReturnT->isObjCIdType()) 5917 return Methods[b]; 5918 } 5919 } 5920 } 5921 5922 if (Match) 5923 return Method; 5924 } 5925 return nullptr; 5926 } 5927 5928 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5929 // enable_if is order-sensitive. As a result, we need to reverse things 5930 // sometimes. Size of 4 elements is arbitrary. 5931 static SmallVector<EnableIfAttr *, 4> 5932 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5933 SmallVector<EnableIfAttr *, 4> Result; 5934 if (!Function->hasAttrs()) 5935 return Result; 5936 5937 const auto &FuncAttrs = Function->getAttrs(); 5938 for (Attr *Attr : FuncAttrs) 5939 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5940 Result.push_back(EnableIf); 5941 5942 std::reverse(Result.begin(), Result.end()); 5943 return Result; 5944 } 5945 5946 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5947 bool MissingImplicitThis) { 5948 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5949 if (EnableIfAttrs.empty()) 5950 return nullptr; 5951 5952 SFINAETrap Trap(*this); 5953 SmallVector<Expr *, 16> ConvertedArgs; 5954 bool InitializationFailed = false; 5955 bool ContainsValueDependentExpr = false; 5956 5957 // Convert the arguments. 5958 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5959 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5960 !cast<CXXMethodDecl>(Function)->isStatic() && 5961 !isa<CXXConstructorDecl>(Function)) { 5962 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5963 ExprResult R = 5964 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5965 Method, Method); 5966 if (R.isInvalid()) { 5967 InitializationFailed = true; 5968 break; 5969 } 5970 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5971 ConvertedArgs.push_back(R.get()); 5972 } else { 5973 ExprResult R = 5974 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5975 Context, 5976 Function->getParamDecl(i)), 5977 SourceLocation(), 5978 Args[i]); 5979 if (R.isInvalid()) { 5980 InitializationFailed = true; 5981 break; 5982 } 5983 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5984 ConvertedArgs.push_back(R.get()); 5985 } 5986 } 5987 5988 if (InitializationFailed || Trap.hasErrorOccurred()) 5989 return EnableIfAttrs[0]; 5990 5991 // Push default arguments if needed. 5992 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5993 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5994 ParmVarDecl *P = Function->getParamDecl(i); 5995 ExprResult R = PerformCopyInitialization( 5996 InitializedEntity::InitializeParameter(Context, 5997 Function->getParamDecl(i)), 5998 SourceLocation(), 5999 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6000 : P->getDefaultArg()); 6001 if (R.isInvalid()) { 6002 InitializationFailed = true; 6003 break; 6004 } 6005 ContainsValueDependentExpr |= R.get()->isValueDependent(); 6006 ConvertedArgs.push_back(R.get()); 6007 } 6008 6009 if (InitializationFailed || Trap.hasErrorOccurred()) 6010 return EnableIfAttrs[0]; 6011 } 6012 6013 for (auto *EIA : EnableIfAttrs) { 6014 APValue Result; 6015 if (EIA->getCond()->isValueDependent()) { 6016 // Don't even try now, we'll examine it after instantiation. 6017 continue; 6018 } 6019 6020 if (!EIA->getCond()->EvaluateWithSubstitution( 6021 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 6022 if (!ContainsValueDependentExpr) 6023 return EIA; 6024 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 6025 return EIA; 6026 } 6027 } 6028 return nullptr; 6029 } 6030 6031 /// \brief Add all of the function declarations in the given function set to 6032 /// the overload candidate set. 6033 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6034 ArrayRef<Expr *> Args, 6035 OverloadCandidateSet& CandidateSet, 6036 TemplateArgumentListInfo *ExplicitTemplateArgs, 6037 bool SuppressUserConversions, 6038 bool PartialOverloading) { 6039 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6040 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6042 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6043 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6044 cast<CXXMethodDecl>(FD)->getParent(), 6045 Args[0]->getType(), Args[0]->Classify(Context), 6046 Args.slice(1), CandidateSet, 6047 SuppressUserConversions, PartialOverloading); 6048 else 6049 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6050 SuppressUserConversions, PartialOverloading); 6051 } else { 6052 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6053 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6054 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6055 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6056 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6057 ExplicitTemplateArgs, 6058 Args[0]->getType(), 6059 Args[0]->Classify(Context), Args.slice(1), 6060 CandidateSet, SuppressUserConversions, 6061 PartialOverloading); 6062 else 6063 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6064 ExplicitTemplateArgs, Args, 6065 CandidateSet, SuppressUserConversions, 6066 PartialOverloading); 6067 } 6068 } 6069 } 6070 6071 /// AddMethodCandidate - Adds a named decl (which is some kind of 6072 /// method) as a method candidate to the given overload set. 6073 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6074 QualType ObjectType, 6075 Expr::Classification ObjectClassification, 6076 ArrayRef<Expr *> Args, 6077 OverloadCandidateSet& CandidateSet, 6078 bool SuppressUserConversions) { 6079 NamedDecl *Decl = FoundDecl.getDecl(); 6080 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6081 6082 if (isa<UsingShadowDecl>(Decl)) 6083 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6084 6085 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6086 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6087 "Expected a member function template"); 6088 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6089 /*ExplicitArgs*/ nullptr, 6090 ObjectType, ObjectClassification, 6091 Args, CandidateSet, 6092 SuppressUserConversions); 6093 } else { 6094 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6095 ObjectType, ObjectClassification, 6096 Args, 6097 CandidateSet, SuppressUserConversions); 6098 } 6099 } 6100 6101 /// AddMethodCandidate - Adds the given C++ member function to the set 6102 /// of candidate functions, using the given function call arguments 6103 /// and the object argument (@c Object). For example, in a call 6104 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6105 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6106 /// allow user-defined conversions via constructors or conversion 6107 /// operators. 6108 void 6109 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6110 CXXRecordDecl *ActingContext, QualType ObjectType, 6111 Expr::Classification ObjectClassification, 6112 ArrayRef<Expr *> Args, 6113 OverloadCandidateSet &CandidateSet, 6114 bool SuppressUserConversions, 6115 bool PartialOverloading) { 6116 const FunctionProtoType *Proto 6117 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6118 assert(Proto && "Methods without a prototype cannot be overloaded"); 6119 assert(!isa<CXXConstructorDecl>(Method) && 6120 "Use AddOverloadCandidate for constructors"); 6121 6122 if (!CandidateSet.isNewCandidate(Method)) 6123 return; 6124 6125 // C++11 [class.copy]p23: [DR1402] 6126 // A defaulted move assignment operator that is defined as deleted is 6127 // ignored by overload resolution. 6128 if (Method->isDefaulted() && Method->isDeleted() && 6129 Method->isMoveAssignmentOperator()) 6130 return; 6131 6132 // Overload resolution is always an unevaluated context. 6133 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6134 6135 // Add this candidate 6136 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6137 Candidate.FoundDecl = FoundDecl; 6138 Candidate.Function = Method; 6139 Candidate.IsSurrogate = false; 6140 Candidate.IgnoreObjectArgument = false; 6141 Candidate.ExplicitCallArguments = Args.size(); 6142 6143 unsigned NumParams = Proto->getNumParams(); 6144 6145 // (C++ 13.3.2p2): A candidate function having fewer than m 6146 // parameters is viable only if it has an ellipsis in its parameter 6147 // list (8.3.5). 6148 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6149 !Proto->isVariadic()) { 6150 Candidate.Viable = false; 6151 Candidate.FailureKind = ovl_fail_too_many_arguments; 6152 return; 6153 } 6154 6155 // (C++ 13.3.2p2): A candidate function having more than m parameters 6156 // is viable only if the (m+1)st parameter has a default argument 6157 // (8.3.6). For the purposes of overload resolution, the 6158 // parameter list is truncated on the right, so that there are 6159 // exactly m parameters. 6160 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6161 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6162 // Not enough arguments. 6163 Candidate.Viable = false; 6164 Candidate.FailureKind = ovl_fail_too_few_arguments; 6165 return; 6166 } 6167 6168 Candidate.Viable = true; 6169 6170 if (Method->isStatic() || ObjectType.isNull()) 6171 // The implicit object argument is ignored. 6172 Candidate.IgnoreObjectArgument = true; 6173 else { 6174 // Determine the implicit conversion sequence for the object 6175 // parameter. 6176 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6177 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6178 Method, ActingContext); 6179 if (Candidate.Conversions[0].isBad()) { 6180 Candidate.Viable = false; 6181 Candidate.FailureKind = ovl_fail_bad_conversion; 6182 return; 6183 } 6184 } 6185 6186 // (CUDA B.1): Check for invalid calls between targets. 6187 if (getLangOpts().CUDA) 6188 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6189 if (CheckCUDATarget(Caller, Method)) { 6190 Candidate.Viable = false; 6191 Candidate.FailureKind = ovl_fail_bad_target; 6192 return; 6193 } 6194 6195 // Determine the implicit conversion sequences for each of the 6196 // arguments. 6197 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6198 if (ArgIdx < NumParams) { 6199 // (C++ 13.3.2p3): for F to be a viable function, there shall 6200 // exist for each argument an implicit conversion sequence 6201 // (13.3.3.1) that converts that argument to the corresponding 6202 // parameter of F. 6203 QualType ParamType = Proto->getParamType(ArgIdx); 6204 Candidate.Conversions[ArgIdx + 1] 6205 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6206 SuppressUserConversions, 6207 /*InOverloadResolution=*/true, 6208 /*AllowObjCWritebackConversion=*/ 6209 getLangOpts().ObjCAutoRefCount); 6210 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6211 Candidate.Viable = false; 6212 Candidate.FailureKind = ovl_fail_bad_conversion; 6213 return; 6214 } 6215 } else { 6216 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6217 // argument for which there is no corresponding parameter is 6218 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6219 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6220 } 6221 } 6222 6223 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6224 Candidate.Viable = false; 6225 Candidate.FailureKind = ovl_fail_enable_if; 6226 Candidate.DeductionFailure.Data = FailedAttr; 6227 return; 6228 } 6229 } 6230 6231 /// \brief Add a C++ member function template as a candidate to the candidate 6232 /// set, using template argument deduction to produce an appropriate member 6233 /// function template specialization. 6234 void 6235 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6236 DeclAccessPair FoundDecl, 6237 CXXRecordDecl *ActingContext, 6238 TemplateArgumentListInfo *ExplicitTemplateArgs, 6239 QualType ObjectType, 6240 Expr::Classification ObjectClassification, 6241 ArrayRef<Expr *> Args, 6242 OverloadCandidateSet& CandidateSet, 6243 bool SuppressUserConversions, 6244 bool PartialOverloading) { 6245 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6246 return; 6247 6248 // C++ [over.match.funcs]p7: 6249 // In each case where a candidate is a function template, candidate 6250 // function template specializations are generated using template argument 6251 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6252 // candidate functions in the usual way.113) A given name can refer to one 6253 // or more function templates and also to a set of overloaded non-template 6254 // functions. In such a case, the candidate functions generated from each 6255 // function template are combined with the set of non-template candidate 6256 // functions. 6257 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6258 FunctionDecl *Specialization = nullptr; 6259 if (TemplateDeductionResult Result 6260 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6261 Specialization, Info, PartialOverloading)) { 6262 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6263 Candidate.FoundDecl = FoundDecl; 6264 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6265 Candidate.Viable = false; 6266 Candidate.FailureKind = ovl_fail_bad_deduction; 6267 Candidate.IsSurrogate = false; 6268 Candidate.IgnoreObjectArgument = false; 6269 Candidate.ExplicitCallArguments = Args.size(); 6270 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6271 Info); 6272 return; 6273 } 6274 6275 // Add the function template specialization produced by template argument 6276 // deduction as a candidate. 6277 assert(Specialization && "Missing member function template specialization?"); 6278 assert(isa<CXXMethodDecl>(Specialization) && 6279 "Specialization is not a member function?"); 6280 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6281 ActingContext, ObjectType, ObjectClassification, Args, 6282 CandidateSet, SuppressUserConversions, PartialOverloading); 6283 } 6284 6285 /// \brief Add a C++ function template specialization as a candidate 6286 /// in the candidate set, using template argument deduction to produce 6287 /// an appropriate function template specialization. 6288 void 6289 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6290 DeclAccessPair FoundDecl, 6291 TemplateArgumentListInfo *ExplicitTemplateArgs, 6292 ArrayRef<Expr *> Args, 6293 OverloadCandidateSet& CandidateSet, 6294 bool SuppressUserConversions, 6295 bool PartialOverloading) { 6296 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6297 return; 6298 6299 // C++ [over.match.funcs]p7: 6300 // In each case where a candidate is a function template, candidate 6301 // function template specializations are generated using template argument 6302 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6303 // candidate functions in the usual way.113) A given name can refer to one 6304 // or more function templates and also to a set of overloaded non-template 6305 // functions. In such a case, the candidate functions generated from each 6306 // function template are combined with the set of non-template candidate 6307 // functions. 6308 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6309 FunctionDecl *Specialization = nullptr; 6310 if (TemplateDeductionResult Result 6311 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6312 Specialization, Info, PartialOverloading)) { 6313 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6314 Candidate.FoundDecl = FoundDecl; 6315 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6316 Candidate.Viable = false; 6317 Candidate.FailureKind = ovl_fail_bad_deduction; 6318 Candidate.IsSurrogate = false; 6319 Candidate.IgnoreObjectArgument = false; 6320 Candidate.ExplicitCallArguments = Args.size(); 6321 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6322 Info); 6323 return; 6324 } 6325 6326 // Add the function template specialization produced by template argument 6327 // deduction as a candidate. 6328 assert(Specialization && "Missing function template specialization?"); 6329 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6330 SuppressUserConversions, PartialOverloading); 6331 } 6332 6333 /// Determine whether this is an allowable conversion from the result 6334 /// of an explicit conversion operator to the expected type, per C++ 6335 /// [over.match.conv]p1 and [over.match.ref]p1. 6336 /// 6337 /// \param ConvType The return type of the conversion function. 6338 /// 6339 /// \param ToType The type we are converting to. 6340 /// 6341 /// \param AllowObjCPointerConversion Allow a conversion from one 6342 /// Objective-C pointer to another. 6343 /// 6344 /// \returns true if the conversion is allowable, false otherwise. 6345 static bool isAllowableExplicitConversion(Sema &S, 6346 QualType ConvType, QualType ToType, 6347 bool AllowObjCPointerConversion) { 6348 QualType ToNonRefType = ToType.getNonReferenceType(); 6349 6350 // Easy case: the types are the same. 6351 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6352 return true; 6353 6354 // Allow qualification conversions. 6355 bool ObjCLifetimeConversion; 6356 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6357 ObjCLifetimeConversion)) 6358 return true; 6359 6360 // If we're not allowed to consider Objective-C pointer conversions, 6361 // we're done. 6362 if (!AllowObjCPointerConversion) 6363 return false; 6364 6365 // Is this an Objective-C pointer conversion? 6366 bool IncompatibleObjC = false; 6367 QualType ConvertedType; 6368 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6369 IncompatibleObjC); 6370 } 6371 6372 /// AddConversionCandidate - Add a C++ conversion function as a 6373 /// candidate in the candidate set (C++ [over.match.conv], 6374 /// C++ [over.match.copy]). From is the expression we're converting from, 6375 /// and ToType is the type that we're eventually trying to convert to 6376 /// (which may or may not be the same type as the type that the 6377 /// conversion function produces). 6378 void 6379 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6380 DeclAccessPair FoundDecl, 6381 CXXRecordDecl *ActingContext, 6382 Expr *From, QualType ToType, 6383 OverloadCandidateSet& CandidateSet, 6384 bool AllowObjCConversionOnExplicit) { 6385 assert(!Conversion->getDescribedFunctionTemplate() && 6386 "Conversion function templates use AddTemplateConversionCandidate"); 6387 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6388 if (!CandidateSet.isNewCandidate(Conversion)) 6389 return; 6390 6391 // If the conversion function has an undeduced return type, trigger its 6392 // deduction now. 6393 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6394 if (DeduceReturnType(Conversion, From->getExprLoc())) 6395 return; 6396 ConvType = Conversion->getConversionType().getNonReferenceType(); 6397 } 6398 6399 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6400 // operator is only a candidate if its return type is the target type or 6401 // can be converted to the target type with a qualification conversion. 6402 if (Conversion->isExplicit() && 6403 !isAllowableExplicitConversion(*this, ConvType, ToType, 6404 AllowObjCConversionOnExplicit)) 6405 return; 6406 6407 // Overload resolution is always an unevaluated context. 6408 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6409 6410 // Add this candidate 6411 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6412 Candidate.FoundDecl = FoundDecl; 6413 Candidate.Function = Conversion; 6414 Candidate.IsSurrogate = false; 6415 Candidate.IgnoreObjectArgument = false; 6416 Candidate.FinalConversion.setAsIdentityConversion(); 6417 Candidate.FinalConversion.setFromType(ConvType); 6418 Candidate.FinalConversion.setAllToTypes(ToType); 6419 Candidate.Viable = true; 6420 Candidate.ExplicitCallArguments = 1; 6421 6422 // C++ [over.match.funcs]p4: 6423 // For conversion functions, the function is considered to be a member of 6424 // the class of the implicit implied object argument for the purpose of 6425 // defining the type of the implicit object parameter. 6426 // 6427 // Determine the implicit conversion sequence for the implicit 6428 // object parameter. 6429 QualType ImplicitParamType = From->getType(); 6430 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6431 ImplicitParamType = FromPtrType->getPointeeType(); 6432 CXXRecordDecl *ConversionContext 6433 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6434 6435 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6436 *this, CandidateSet.getLocation(), From->getType(), 6437 From->Classify(Context), Conversion, ConversionContext); 6438 6439 if (Candidate.Conversions[0].isBad()) { 6440 Candidate.Viable = false; 6441 Candidate.FailureKind = ovl_fail_bad_conversion; 6442 return; 6443 } 6444 6445 // We won't go through a user-defined type conversion function to convert a 6446 // derived to base as such conversions are given Conversion Rank. They only 6447 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6448 QualType FromCanon 6449 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6450 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6451 if (FromCanon == ToCanon || 6452 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6453 Candidate.Viable = false; 6454 Candidate.FailureKind = ovl_fail_trivial_conversion; 6455 return; 6456 } 6457 6458 // To determine what the conversion from the result of calling the 6459 // conversion function to the type we're eventually trying to 6460 // convert to (ToType), we need to synthesize a call to the 6461 // conversion function and attempt copy initialization from it. This 6462 // makes sure that we get the right semantics with respect to 6463 // lvalues/rvalues and the type. Fortunately, we can allocate this 6464 // call on the stack and we don't need its arguments to be 6465 // well-formed. 6466 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6467 VK_LValue, From->getLocStart()); 6468 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6469 Context.getPointerType(Conversion->getType()), 6470 CK_FunctionToPointerDecay, 6471 &ConversionRef, VK_RValue); 6472 6473 QualType ConversionType = Conversion->getConversionType(); 6474 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6475 Candidate.Viable = false; 6476 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6477 return; 6478 } 6479 6480 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6481 6482 // Note that it is safe to allocate CallExpr on the stack here because 6483 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6484 // allocator). 6485 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6486 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6487 From->getLocStart()); 6488 ImplicitConversionSequence ICS = 6489 TryCopyInitialization(*this, &Call, ToType, 6490 /*SuppressUserConversions=*/true, 6491 /*InOverloadResolution=*/false, 6492 /*AllowObjCWritebackConversion=*/false); 6493 6494 switch (ICS.getKind()) { 6495 case ImplicitConversionSequence::StandardConversion: 6496 Candidate.FinalConversion = ICS.Standard; 6497 6498 // C++ [over.ics.user]p3: 6499 // If the user-defined conversion is specified by a specialization of a 6500 // conversion function template, the second standard conversion sequence 6501 // shall have exact match rank. 6502 if (Conversion->getPrimaryTemplate() && 6503 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6504 Candidate.Viable = false; 6505 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6506 return; 6507 } 6508 6509 // C++0x [dcl.init.ref]p5: 6510 // In the second case, if the reference is an rvalue reference and 6511 // the second standard conversion sequence of the user-defined 6512 // conversion sequence includes an lvalue-to-rvalue conversion, the 6513 // program is ill-formed. 6514 if (ToType->isRValueReferenceType() && 6515 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6516 Candidate.Viable = false; 6517 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6518 return; 6519 } 6520 break; 6521 6522 case ImplicitConversionSequence::BadConversion: 6523 Candidate.Viable = false; 6524 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6525 return; 6526 6527 default: 6528 llvm_unreachable( 6529 "Can only end up with a standard conversion sequence or failure"); 6530 } 6531 6532 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6533 Candidate.Viable = false; 6534 Candidate.FailureKind = ovl_fail_enable_if; 6535 Candidate.DeductionFailure.Data = FailedAttr; 6536 return; 6537 } 6538 } 6539 6540 /// \brief Adds a conversion function template specialization 6541 /// candidate to the overload set, using template argument deduction 6542 /// to deduce the template arguments of the conversion function 6543 /// template from the type that we are converting to (C++ 6544 /// [temp.deduct.conv]). 6545 void 6546 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6547 DeclAccessPair FoundDecl, 6548 CXXRecordDecl *ActingDC, 6549 Expr *From, QualType ToType, 6550 OverloadCandidateSet &CandidateSet, 6551 bool AllowObjCConversionOnExplicit) { 6552 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6553 "Only conversion function templates permitted here"); 6554 6555 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6556 return; 6557 6558 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6559 CXXConversionDecl *Specialization = nullptr; 6560 if (TemplateDeductionResult Result 6561 = DeduceTemplateArguments(FunctionTemplate, ToType, 6562 Specialization, Info)) { 6563 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6564 Candidate.FoundDecl = FoundDecl; 6565 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6566 Candidate.Viable = false; 6567 Candidate.FailureKind = ovl_fail_bad_deduction; 6568 Candidate.IsSurrogate = false; 6569 Candidate.IgnoreObjectArgument = false; 6570 Candidate.ExplicitCallArguments = 1; 6571 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6572 Info); 6573 return; 6574 } 6575 6576 // Add the conversion function template specialization produced by 6577 // template argument deduction as a candidate. 6578 assert(Specialization && "Missing function template specialization?"); 6579 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6580 CandidateSet, AllowObjCConversionOnExplicit); 6581 } 6582 6583 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6584 /// converts the given @c Object to a function pointer via the 6585 /// conversion function @c Conversion, and then attempts to call it 6586 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6587 /// the type of function that we'll eventually be calling. 6588 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6589 DeclAccessPair FoundDecl, 6590 CXXRecordDecl *ActingContext, 6591 const FunctionProtoType *Proto, 6592 Expr *Object, 6593 ArrayRef<Expr *> Args, 6594 OverloadCandidateSet& CandidateSet) { 6595 if (!CandidateSet.isNewCandidate(Conversion)) 6596 return; 6597 6598 // Overload resolution is always an unevaluated context. 6599 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6600 6601 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6602 Candidate.FoundDecl = FoundDecl; 6603 Candidate.Function = nullptr; 6604 Candidate.Surrogate = Conversion; 6605 Candidate.Viable = true; 6606 Candidate.IsSurrogate = true; 6607 Candidate.IgnoreObjectArgument = false; 6608 Candidate.ExplicitCallArguments = Args.size(); 6609 6610 // Determine the implicit conversion sequence for the implicit 6611 // object parameter. 6612 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6613 *this, CandidateSet.getLocation(), Object->getType(), 6614 Object->Classify(Context), Conversion, ActingContext); 6615 if (ObjectInit.isBad()) { 6616 Candidate.Viable = false; 6617 Candidate.FailureKind = ovl_fail_bad_conversion; 6618 Candidate.Conversions[0] = ObjectInit; 6619 return; 6620 } 6621 6622 // The first conversion is actually a user-defined conversion whose 6623 // first conversion is ObjectInit's standard conversion (which is 6624 // effectively a reference binding). Record it as such. 6625 Candidate.Conversions[0].setUserDefined(); 6626 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6627 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6628 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6629 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6630 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6631 Candidate.Conversions[0].UserDefined.After 6632 = Candidate.Conversions[0].UserDefined.Before; 6633 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6634 6635 // Find the 6636 unsigned NumParams = Proto->getNumParams(); 6637 6638 // (C++ 13.3.2p2): A candidate function having fewer than m 6639 // parameters is viable only if it has an ellipsis in its parameter 6640 // list (8.3.5). 6641 if (Args.size() > NumParams && !Proto->isVariadic()) { 6642 Candidate.Viable = false; 6643 Candidate.FailureKind = ovl_fail_too_many_arguments; 6644 return; 6645 } 6646 6647 // Function types don't have any default arguments, so just check if 6648 // we have enough arguments. 6649 if (Args.size() < NumParams) { 6650 // Not enough arguments. 6651 Candidate.Viable = false; 6652 Candidate.FailureKind = ovl_fail_too_few_arguments; 6653 return; 6654 } 6655 6656 // Determine the implicit conversion sequences for each of the 6657 // arguments. 6658 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6659 if (ArgIdx < NumParams) { 6660 // (C++ 13.3.2p3): for F to be a viable function, there shall 6661 // exist for each argument an implicit conversion sequence 6662 // (13.3.3.1) that converts that argument to the corresponding 6663 // parameter of F. 6664 QualType ParamType = Proto->getParamType(ArgIdx); 6665 Candidate.Conversions[ArgIdx + 1] 6666 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6667 /*SuppressUserConversions=*/false, 6668 /*InOverloadResolution=*/false, 6669 /*AllowObjCWritebackConversion=*/ 6670 getLangOpts().ObjCAutoRefCount); 6671 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6672 Candidate.Viable = false; 6673 Candidate.FailureKind = ovl_fail_bad_conversion; 6674 return; 6675 } 6676 } else { 6677 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6678 // argument for which there is no corresponding parameter is 6679 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6680 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6681 } 6682 } 6683 6684 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6685 Candidate.Viable = false; 6686 Candidate.FailureKind = ovl_fail_enable_if; 6687 Candidate.DeductionFailure.Data = FailedAttr; 6688 return; 6689 } 6690 } 6691 6692 /// \brief Add overload candidates for overloaded operators that are 6693 /// member functions. 6694 /// 6695 /// Add the overloaded operator candidates that are member functions 6696 /// for the operator Op that was used in an operator expression such 6697 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6698 /// CandidateSet will store the added overload candidates. (C++ 6699 /// [over.match.oper]). 6700 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6701 SourceLocation OpLoc, 6702 ArrayRef<Expr *> Args, 6703 OverloadCandidateSet& CandidateSet, 6704 SourceRange OpRange) { 6705 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6706 6707 // C++ [over.match.oper]p3: 6708 // For a unary operator @ with an operand of a type whose 6709 // cv-unqualified version is T1, and for a binary operator @ with 6710 // a left operand of a type whose cv-unqualified version is T1 and 6711 // a right operand of a type whose cv-unqualified version is T2, 6712 // three sets of candidate functions, designated member 6713 // candidates, non-member candidates and built-in candidates, are 6714 // constructed as follows: 6715 QualType T1 = Args[0]->getType(); 6716 6717 // -- If T1 is a complete class type or a class currently being 6718 // defined, the set of member candidates is the result of the 6719 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6720 // the set of member candidates is empty. 6721 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6722 // Complete the type if it can be completed. 6723 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6724 return; 6725 // If the type is neither complete nor being defined, bail out now. 6726 if (!T1Rec->getDecl()->getDefinition()) 6727 return; 6728 6729 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6730 LookupQualifiedName(Operators, T1Rec->getDecl()); 6731 Operators.suppressDiagnostics(); 6732 6733 for (LookupResult::iterator Oper = Operators.begin(), 6734 OperEnd = Operators.end(); 6735 Oper != OperEnd; 6736 ++Oper) 6737 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6738 Args[0]->Classify(Context), 6739 Args.slice(1), 6740 CandidateSet, 6741 /* SuppressUserConversions = */ false); 6742 } 6743 } 6744 6745 /// AddBuiltinCandidate - Add a candidate for a built-in 6746 /// operator. ResultTy and ParamTys are the result and parameter types 6747 /// of the built-in candidate, respectively. Args and NumArgs are the 6748 /// arguments being passed to the candidate. IsAssignmentOperator 6749 /// should be true when this built-in candidate is an assignment 6750 /// operator. NumContextualBoolArguments is the number of arguments 6751 /// (at the beginning of the argument list) that will be contextually 6752 /// converted to bool. 6753 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6754 ArrayRef<Expr *> Args, 6755 OverloadCandidateSet& CandidateSet, 6756 bool IsAssignmentOperator, 6757 unsigned NumContextualBoolArguments) { 6758 // Overload resolution is always an unevaluated context. 6759 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6760 6761 // Add this candidate 6762 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6763 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6764 Candidate.Function = nullptr; 6765 Candidate.IsSurrogate = false; 6766 Candidate.IgnoreObjectArgument = false; 6767 Candidate.BuiltinTypes.ResultTy = ResultTy; 6768 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6769 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6770 6771 // Determine the implicit conversion sequences for each of the 6772 // arguments. 6773 Candidate.Viable = true; 6774 Candidate.ExplicitCallArguments = Args.size(); 6775 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6776 // C++ [over.match.oper]p4: 6777 // For the built-in assignment operators, conversions of the 6778 // left operand are restricted as follows: 6779 // -- no temporaries are introduced to hold the left operand, and 6780 // -- no user-defined conversions are applied to the left 6781 // operand to achieve a type match with the left-most 6782 // parameter of a built-in candidate. 6783 // 6784 // We block these conversions by turning off user-defined 6785 // conversions, since that is the only way that initialization of 6786 // a reference to a non-class type can occur from something that 6787 // is not of the same type. 6788 if (ArgIdx < NumContextualBoolArguments) { 6789 assert(ParamTys[ArgIdx] == Context.BoolTy && 6790 "Contextual conversion to bool requires bool type"); 6791 Candidate.Conversions[ArgIdx] 6792 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6793 } else { 6794 Candidate.Conversions[ArgIdx] 6795 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6796 ArgIdx == 0 && IsAssignmentOperator, 6797 /*InOverloadResolution=*/false, 6798 /*AllowObjCWritebackConversion=*/ 6799 getLangOpts().ObjCAutoRefCount); 6800 } 6801 if (Candidate.Conversions[ArgIdx].isBad()) { 6802 Candidate.Viable = false; 6803 Candidate.FailureKind = ovl_fail_bad_conversion; 6804 break; 6805 } 6806 } 6807 } 6808 6809 namespace { 6810 6811 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6812 /// candidate operator functions for built-in operators (C++ 6813 /// [over.built]). The types are separated into pointer types and 6814 /// enumeration types. 6815 class BuiltinCandidateTypeSet { 6816 /// TypeSet - A set of types. 6817 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6818 6819 /// PointerTypes - The set of pointer types that will be used in the 6820 /// built-in candidates. 6821 TypeSet PointerTypes; 6822 6823 /// MemberPointerTypes - The set of member pointer types that will be 6824 /// used in the built-in candidates. 6825 TypeSet MemberPointerTypes; 6826 6827 /// EnumerationTypes - The set of enumeration types that will be 6828 /// used in the built-in candidates. 6829 TypeSet EnumerationTypes; 6830 6831 /// \brief The set of vector types that will be used in the built-in 6832 /// candidates. 6833 TypeSet VectorTypes; 6834 6835 /// \brief A flag indicating non-record types are viable candidates 6836 bool HasNonRecordTypes; 6837 6838 /// \brief A flag indicating whether either arithmetic or enumeration types 6839 /// were present in the candidate set. 6840 bool HasArithmeticOrEnumeralTypes; 6841 6842 /// \brief A flag indicating whether the nullptr type was present in the 6843 /// candidate set. 6844 bool HasNullPtrType; 6845 6846 /// Sema - The semantic analysis instance where we are building the 6847 /// candidate type set. 6848 Sema &SemaRef; 6849 6850 /// Context - The AST context in which we will build the type sets. 6851 ASTContext &Context; 6852 6853 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6854 const Qualifiers &VisibleQuals); 6855 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6856 6857 public: 6858 /// iterator - Iterates through the types that are part of the set. 6859 typedef TypeSet::iterator iterator; 6860 6861 BuiltinCandidateTypeSet(Sema &SemaRef) 6862 : HasNonRecordTypes(false), 6863 HasArithmeticOrEnumeralTypes(false), 6864 HasNullPtrType(false), 6865 SemaRef(SemaRef), 6866 Context(SemaRef.Context) { } 6867 6868 void AddTypesConvertedFrom(QualType Ty, 6869 SourceLocation Loc, 6870 bool AllowUserConversions, 6871 bool AllowExplicitConversions, 6872 const Qualifiers &VisibleTypeConversionsQuals); 6873 6874 /// pointer_begin - First pointer type found; 6875 iterator pointer_begin() { return PointerTypes.begin(); } 6876 6877 /// pointer_end - Past the last pointer type found; 6878 iterator pointer_end() { return PointerTypes.end(); } 6879 6880 /// member_pointer_begin - First member pointer type found; 6881 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6882 6883 /// member_pointer_end - Past the last member pointer type found; 6884 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6885 6886 /// enumeration_begin - First enumeration type found; 6887 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6888 6889 /// enumeration_end - Past the last enumeration type found; 6890 iterator enumeration_end() { return EnumerationTypes.end(); } 6891 6892 iterator vector_begin() { return VectorTypes.begin(); } 6893 iterator vector_end() { return VectorTypes.end(); } 6894 6895 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6896 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6897 bool hasNullPtrType() const { return HasNullPtrType; } 6898 }; 6899 6900 } // end anonymous namespace 6901 6902 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6903 /// the set of pointer types along with any more-qualified variants of 6904 /// that type. For example, if @p Ty is "int const *", this routine 6905 /// will add "int const *", "int const volatile *", "int const 6906 /// restrict *", and "int const volatile restrict *" to the set of 6907 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6908 /// false otherwise. 6909 /// 6910 /// FIXME: what to do about extended qualifiers? 6911 bool 6912 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6913 const Qualifiers &VisibleQuals) { 6914 6915 // Insert this type. 6916 if (!PointerTypes.insert(Ty).second) 6917 return false; 6918 6919 QualType PointeeTy; 6920 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6921 bool buildObjCPtr = false; 6922 if (!PointerTy) { 6923 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6924 PointeeTy = PTy->getPointeeType(); 6925 buildObjCPtr = true; 6926 } else { 6927 PointeeTy = PointerTy->getPointeeType(); 6928 } 6929 6930 // Don't add qualified variants of arrays. For one, they're not allowed 6931 // (the qualifier would sink to the element type), and for another, the 6932 // only overload situation where it matters is subscript or pointer +- int, 6933 // and those shouldn't have qualifier variants anyway. 6934 if (PointeeTy->isArrayType()) 6935 return true; 6936 6937 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6938 bool hasVolatile = VisibleQuals.hasVolatile(); 6939 bool hasRestrict = VisibleQuals.hasRestrict(); 6940 6941 // Iterate through all strict supersets of BaseCVR. 6942 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6943 if ((CVR | BaseCVR) != CVR) continue; 6944 // Skip over volatile if no volatile found anywhere in the types. 6945 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6946 6947 // Skip over restrict if no restrict found anywhere in the types, or if 6948 // the type cannot be restrict-qualified. 6949 if ((CVR & Qualifiers::Restrict) && 6950 (!hasRestrict || 6951 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6952 continue; 6953 6954 // Build qualified pointee type. 6955 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6956 6957 // Build qualified pointer type. 6958 QualType QPointerTy; 6959 if (!buildObjCPtr) 6960 QPointerTy = Context.getPointerType(QPointeeTy); 6961 else 6962 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6963 6964 // Insert qualified pointer type. 6965 PointerTypes.insert(QPointerTy); 6966 } 6967 6968 return true; 6969 } 6970 6971 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6972 /// to the set of pointer types along with any more-qualified variants of 6973 /// that type. For example, if @p Ty is "int const *", this routine 6974 /// will add "int const *", "int const volatile *", "int const 6975 /// restrict *", and "int const volatile restrict *" to the set of 6976 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6977 /// false otherwise. 6978 /// 6979 /// FIXME: what to do about extended qualifiers? 6980 bool 6981 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6982 QualType Ty) { 6983 // Insert this type. 6984 if (!MemberPointerTypes.insert(Ty).second) 6985 return false; 6986 6987 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6988 assert(PointerTy && "type was not a member pointer type!"); 6989 6990 QualType PointeeTy = PointerTy->getPointeeType(); 6991 // Don't add qualified variants of arrays. For one, they're not allowed 6992 // (the qualifier would sink to the element type), and for another, the 6993 // only overload situation where it matters is subscript or pointer +- int, 6994 // and those shouldn't have qualifier variants anyway. 6995 if (PointeeTy->isArrayType()) 6996 return true; 6997 const Type *ClassTy = PointerTy->getClass(); 6998 6999 // Iterate through all strict supersets of the pointee type's CVR 7000 // qualifiers. 7001 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7002 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7003 if ((CVR | BaseCVR) != CVR) continue; 7004 7005 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7006 MemberPointerTypes.insert( 7007 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7008 } 7009 7010 return true; 7011 } 7012 7013 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7014 /// Ty can be implicit converted to the given set of @p Types. We're 7015 /// primarily interested in pointer types and enumeration types. We also 7016 /// take member pointer types, for the conditional operator. 7017 /// AllowUserConversions is true if we should look at the conversion 7018 /// functions of a class type, and AllowExplicitConversions if we 7019 /// should also include the explicit conversion functions of a class 7020 /// type. 7021 void 7022 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7023 SourceLocation Loc, 7024 bool AllowUserConversions, 7025 bool AllowExplicitConversions, 7026 const Qualifiers &VisibleQuals) { 7027 // Only deal with canonical types. 7028 Ty = Context.getCanonicalType(Ty); 7029 7030 // Look through reference types; they aren't part of the type of an 7031 // expression for the purposes of conversions. 7032 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7033 Ty = RefTy->getPointeeType(); 7034 7035 // If we're dealing with an array type, decay to the pointer. 7036 if (Ty->isArrayType()) 7037 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7038 7039 // Otherwise, we don't care about qualifiers on the type. 7040 Ty = Ty.getLocalUnqualifiedType(); 7041 7042 // Flag if we ever add a non-record type. 7043 const RecordType *TyRec = Ty->getAs<RecordType>(); 7044 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7045 7046 // Flag if we encounter an arithmetic type. 7047 HasArithmeticOrEnumeralTypes = 7048 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7049 7050 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7051 PointerTypes.insert(Ty); 7052 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7053 // Insert our type, and its more-qualified variants, into the set 7054 // of types. 7055 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7056 return; 7057 } else if (Ty->isMemberPointerType()) { 7058 // Member pointers are far easier, since the pointee can't be converted. 7059 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7060 return; 7061 } else if (Ty->isEnumeralType()) { 7062 HasArithmeticOrEnumeralTypes = true; 7063 EnumerationTypes.insert(Ty); 7064 } else if (Ty->isVectorType()) { 7065 // We treat vector types as arithmetic types in many contexts as an 7066 // extension. 7067 HasArithmeticOrEnumeralTypes = true; 7068 VectorTypes.insert(Ty); 7069 } else if (Ty->isNullPtrType()) { 7070 HasNullPtrType = true; 7071 } else if (AllowUserConversions && TyRec) { 7072 // No conversion functions in incomplete types. 7073 if (!SemaRef.isCompleteType(Loc, Ty)) 7074 return; 7075 7076 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7077 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7078 if (isa<UsingShadowDecl>(D)) 7079 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7080 7081 // Skip conversion function templates; they don't tell us anything 7082 // about which builtin types we can convert to. 7083 if (isa<FunctionTemplateDecl>(D)) 7084 continue; 7085 7086 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7087 if (AllowExplicitConversions || !Conv->isExplicit()) { 7088 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7089 VisibleQuals); 7090 } 7091 } 7092 } 7093 } 7094 7095 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7096 /// the volatile- and non-volatile-qualified assignment operators for the 7097 /// given type to the candidate set. 7098 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7099 QualType T, 7100 ArrayRef<Expr *> Args, 7101 OverloadCandidateSet &CandidateSet) { 7102 QualType ParamTypes[2]; 7103 7104 // T& operator=(T&, T) 7105 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7106 ParamTypes[1] = T; 7107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7108 /*IsAssignmentOperator=*/true); 7109 7110 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7111 // volatile T& operator=(volatile T&, T) 7112 ParamTypes[0] 7113 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7114 ParamTypes[1] = T; 7115 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7116 /*IsAssignmentOperator=*/true); 7117 } 7118 } 7119 7120 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7121 /// if any, found in visible type conversion functions found in ArgExpr's type. 7122 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7123 Qualifiers VRQuals; 7124 const RecordType *TyRec; 7125 if (const MemberPointerType *RHSMPType = 7126 ArgExpr->getType()->getAs<MemberPointerType>()) 7127 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7128 else 7129 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7130 if (!TyRec) { 7131 // Just to be safe, assume the worst case. 7132 VRQuals.addVolatile(); 7133 VRQuals.addRestrict(); 7134 return VRQuals; 7135 } 7136 7137 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7138 if (!ClassDecl->hasDefinition()) 7139 return VRQuals; 7140 7141 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7142 if (isa<UsingShadowDecl>(D)) 7143 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7144 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7145 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7146 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7147 CanTy = ResTypeRef->getPointeeType(); 7148 // Need to go down the pointer/mempointer chain and add qualifiers 7149 // as see them. 7150 bool done = false; 7151 while (!done) { 7152 if (CanTy.isRestrictQualified()) 7153 VRQuals.addRestrict(); 7154 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7155 CanTy = ResTypePtr->getPointeeType(); 7156 else if (const MemberPointerType *ResTypeMPtr = 7157 CanTy->getAs<MemberPointerType>()) 7158 CanTy = ResTypeMPtr->getPointeeType(); 7159 else 7160 done = true; 7161 if (CanTy.isVolatileQualified()) 7162 VRQuals.addVolatile(); 7163 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7164 return VRQuals; 7165 } 7166 } 7167 } 7168 return VRQuals; 7169 } 7170 7171 namespace { 7172 7173 /// \brief Helper class to manage the addition of builtin operator overload 7174 /// candidates. It provides shared state and utility methods used throughout 7175 /// the process, as well as a helper method to add each group of builtin 7176 /// operator overloads from the standard to a candidate set. 7177 class BuiltinOperatorOverloadBuilder { 7178 // Common instance state available to all overload candidate addition methods. 7179 Sema &S; 7180 ArrayRef<Expr *> Args; 7181 Qualifiers VisibleTypeConversionsQuals; 7182 bool HasArithmeticOrEnumeralCandidateType; 7183 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7184 OverloadCandidateSet &CandidateSet; 7185 7186 // Define some constants used to index and iterate over the arithemetic types 7187 // provided via the getArithmeticType() method below. 7188 // The "promoted arithmetic types" are the arithmetic 7189 // types are that preserved by promotion (C++ [over.built]p2). 7190 static const unsigned FirstIntegralType = 3; 7191 static const unsigned LastIntegralType = 20; 7192 static const unsigned FirstPromotedIntegralType = 3, 7193 LastPromotedIntegralType = 11; 7194 static const unsigned FirstPromotedArithmeticType = 0, 7195 LastPromotedArithmeticType = 11; 7196 static const unsigned NumArithmeticTypes = 20; 7197 7198 /// \brief Get the canonical type for a given arithmetic type index. 7199 CanQualType getArithmeticType(unsigned index) { 7200 assert(index < NumArithmeticTypes); 7201 static CanQualType ASTContext::* const 7202 ArithmeticTypes[NumArithmeticTypes] = { 7203 // Start of promoted types. 7204 &ASTContext::FloatTy, 7205 &ASTContext::DoubleTy, 7206 &ASTContext::LongDoubleTy, 7207 7208 // Start of integral types. 7209 &ASTContext::IntTy, 7210 &ASTContext::LongTy, 7211 &ASTContext::LongLongTy, 7212 &ASTContext::Int128Ty, 7213 &ASTContext::UnsignedIntTy, 7214 &ASTContext::UnsignedLongTy, 7215 &ASTContext::UnsignedLongLongTy, 7216 &ASTContext::UnsignedInt128Ty, 7217 // End of promoted types. 7218 7219 &ASTContext::BoolTy, 7220 &ASTContext::CharTy, 7221 &ASTContext::WCharTy, 7222 &ASTContext::Char16Ty, 7223 &ASTContext::Char32Ty, 7224 &ASTContext::SignedCharTy, 7225 &ASTContext::ShortTy, 7226 &ASTContext::UnsignedCharTy, 7227 &ASTContext::UnsignedShortTy, 7228 // End of integral types. 7229 // FIXME: What about complex? What about half? 7230 }; 7231 return S.Context.*ArithmeticTypes[index]; 7232 } 7233 7234 /// \brief Gets the canonical type resulting from the usual arithemetic 7235 /// converions for the given arithmetic types. 7236 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7237 // Accelerator table for performing the usual arithmetic conversions. 7238 // The rules are basically: 7239 // - if either is floating-point, use the wider floating-point 7240 // - if same signedness, use the higher rank 7241 // - if same size, use unsigned of the higher rank 7242 // - use the larger type 7243 // These rules, together with the axiom that higher ranks are 7244 // never smaller, are sufficient to precompute all of these results 7245 // *except* when dealing with signed types of higher rank. 7246 // (we could precompute SLL x UI for all known platforms, but it's 7247 // better not to make any assumptions). 7248 // We assume that int128 has a higher rank than long long on all platforms. 7249 enum PromotedType { 7250 Dep=-1, 7251 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7252 }; 7253 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7254 [LastPromotedArithmeticType] = { 7255 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7256 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7257 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7258 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7259 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7260 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7261 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7262 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7263 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7264 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7265 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7266 }; 7267 7268 assert(L < LastPromotedArithmeticType); 7269 assert(R < LastPromotedArithmeticType); 7270 int Idx = ConversionsTable[L][R]; 7271 7272 // Fast path: the table gives us a concrete answer. 7273 if (Idx != Dep) return getArithmeticType(Idx); 7274 7275 // Slow path: we need to compare widths. 7276 // An invariant is that the signed type has higher rank. 7277 CanQualType LT = getArithmeticType(L), 7278 RT = getArithmeticType(R); 7279 unsigned LW = S.Context.getIntWidth(LT), 7280 RW = S.Context.getIntWidth(RT); 7281 7282 // If they're different widths, use the signed type. 7283 if (LW > RW) return LT; 7284 else if (LW < RW) return RT; 7285 7286 // Otherwise, use the unsigned type of the signed type's rank. 7287 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7288 assert(L == SLL || R == SLL); 7289 return S.Context.UnsignedLongLongTy; 7290 } 7291 7292 /// \brief Helper method to factor out the common pattern of adding overloads 7293 /// for '++' and '--' builtin operators. 7294 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7295 bool HasVolatile, 7296 bool HasRestrict) { 7297 QualType ParamTypes[2] = { 7298 S.Context.getLValueReferenceType(CandidateTy), 7299 S.Context.IntTy 7300 }; 7301 7302 // Non-volatile version. 7303 if (Args.size() == 1) 7304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7305 else 7306 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7307 7308 // Use a heuristic to reduce number of builtin candidates in the set: 7309 // add volatile version only if there are conversions to a volatile type. 7310 if (HasVolatile) { 7311 ParamTypes[0] = 7312 S.Context.getLValueReferenceType( 7313 S.Context.getVolatileType(CandidateTy)); 7314 if (Args.size() == 1) 7315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7316 else 7317 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7318 } 7319 7320 // Add restrict version only if there are conversions to a restrict type 7321 // and our candidate type is a non-restrict-qualified pointer. 7322 if (HasRestrict && CandidateTy->isAnyPointerType() && 7323 !CandidateTy.isRestrictQualified()) { 7324 ParamTypes[0] 7325 = S.Context.getLValueReferenceType( 7326 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7327 if (Args.size() == 1) 7328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7329 else 7330 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7331 7332 if (HasVolatile) { 7333 ParamTypes[0] 7334 = S.Context.getLValueReferenceType( 7335 S.Context.getCVRQualifiedType(CandidateTy, 7336 (Qualifiers::Volatile | 7337 Qualifiers::Restrict))); 7338 if (Args.size() == 1) 7339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7340 else 7341 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7342 } 7343 } 7344 7345 } 7346 7347 public: 7348 BuiltinOperatorOverloadBuilder( 7349 Sema &S, ArrayRef<Expr *> Args, 7350 Qualifiers VisibleTypeConversionsQuals, 7351 bool HasArithmeticOrEnumeralCandidateType, 7352 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7353 OverloadCandidateSet &CandidateSet) 7354 : S(S), Args(Args), 7355 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7356 HasArithmeticOrEnumeralCandidateType( 7357 HasArithmeticOrEnumeralCandidateType), 7358 CandidateTypes(CandidateTypes), 7359 CandidateSet(CandidateSet) { 7360 // Validate some of our static helper constants in debug builds. 7361 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7362 "Invalid first promoted integral type"); 7363 assert(getArithmeticType(LastPromotedIntegralType - 1) 7364 == S.Context.UnsignedInt128Ty && 7365 "Invalid last promoted integral type"); 7366 assert(getArithmeticType(FirstPromotedArithmeticType) 7367 == S.Context.FloatTy && 7368 "Invalid first promoted arithmetic type"); 7369 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7370 == S.Context.UnsignedInt128Ty && 7371 "Invalid last promoted arithmetic type"); 7372 } 7373 7374 // C++ [over.built]p3: 7375 // 7376 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7377 // is either volatile or empty, there exist candidate operator 7378 // functions of the form 7379 // 7380 // VQ T& operator++(VQ T&); 7381 // T operator++(VQ T&, int); 7382 // 7383 // C++ [over.built]p4: 7384 // 7385 // For every pair (T, VQ), where T is an arithmetic type other 7386 // than bool, and VQ is either volatile or empty, there exist 7387 // candidate operator functions of the form 7388 // 7389 // VQ T& operator--(VQ T&); 7390 // T operator--(VQ T&, int); 7391 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7392 if (!HasArithmeticOrEnumeralCandidateType) 7393 return; 7394 7395 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7396 Arith < NumArithmeticTypes; ++Arith) { 7397 addPlusPlusMinusMinusStyleOverloads( 7398 getArithmeticType(Arith), 7399 VisibleTypeConversionsQuals.hasVolatile(), 7400 VisibleTypeConversionsQuals.hasRestrict()); 7401 } 7402 } 7403 7404 // C++ [over.built]p5: 7405 // 7406 // For every pair (T, VQ), where T is a cv-qualified or 7407 // cv-unqualified object type, and VQ is either volatile or 7408 // empty, there exist candidate operator functions of the form 7409 // 7410 // T*VQ& operator++(T*VQ&); 7411 // T*VQ& operator--(T*VQ&); 7412 // T* operator++(T*VQ&, int); 7413 // T* operator--(T*VQ&, int); 7414 void addPlusPlusMinusMinusPointerOverloads() { 7415 for (BuiltinCandidateTypeSet::iterator 7416 Ptr = CandidateTypes[0].pointer_begin(), 7417 PtrEnd = CandidateTypes[0].pointer_end(); 7418 Ptr != PtrEnd; ++Ptr) { 7419 // Skip pointer types that aren't pointers to object types. 7420 if (!(*Ptr)->getPointeeType()->isObjectType()) 7421 continue; 7422 7423 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7424 (!(*Ptr).isVolatileQualified() && 7425 VisibleTypeConversionsQuals.hasVolatile()), 7426 (!(*Ptr).isRestrictQualified() && 7427 VisibleTypeConversionsQuals.hasRestrict())); 7428 } 7429 } 7430 7431 // C++ [over.built]p6: 7432 // For every cv-qualified or cv-unqualified object type T, there 7433 // exist candidate operator functions of the form 7434 // 7435 // T& operator*(T*); 7436 // 7437 // C++ [over.built]p7: 7438 // For every function type T that does not have cv-qualifiers or a 7439 // ref-qualifier, there exist candidate operator functions of the form 7440 // T& operator*(T*); 7441 void addUnaryStarPointerOverloads() { 7442 for (BuiltinCandidateTypeSet::iterator 7443 Ptr = CandidateTypes[0].pointer_begin(), 7444 PtrEnd = CandidateTypes[0].pointer_end(); 7445 Ptr != PtrEnd; ++Ptr) { 7446 QualType ParamTy = *Ptr; 7447 QualType PointeeTy = ParamTy->getPointeeType(); 7448 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7449 continue; 7450 7451 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7452 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7453 continue; 7454 7455 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7456 &ParamTy, Args, CandidateSet); 7457 } 7458 } 7459 7460 // C++ [over.built]p9: 7461 // For every promoted arithmetic type T, there exist candidate 7462 // operator functions of the form 7463 // 7464 // T operator+(T); 7465 // T operator-(T); 7466 void addUnaryPlusOrMinusArithmeticOverloads() { 7467 if (!HasArithmeticOrEnumeralCandidateType) 7468 return; 7469 7470 for (unsigned Arith = FirstPromotedArithmeticType; 7471 Arith < LastPromotedArithmeticType; ++Arith) { 7472 QualType ArithTy = getArithmeticType(Arith); 7473 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7474 } 7475 7476 // Extension: We also add these operators for vector types. 7477 for (BuiltinCandidateTypeSet::iterator 7478 Vec = CandidateTypes[0].vector_begin(), 7479 VecEnd = CandidateTypes[0].vector_end(); 7480 Vec != VecEnd; ++Vec) { 7481 QualType VecTy = *Vec; 7482 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7483 } 7484 } 7485 7486 // C++ [over.built]p8: 7487 // For every type T, there exist candidate operator functions of 7488 // the form 7489 // 7490 // T* operator+(T*); 7491 void addUnaryPlusPointerOverloads() { 7492 for (BuiltinCandidateTypeSet::iterator 7493 Ptr = CandidateTypes[0].pointer_begin(), 7494 PtrEnd = CandidateTypes[0].pointer_end(); 7495 Ptr != PtrEnd; ++Ptr) { 7496 QualType ParamTy = *Ptr; 7497 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7498 } 7499 } 7500 7501 // C++ [over.built]p10: 7502 // For every promoted integral type T, there exist candidate 7503 // operator functions of the form 7504 // 7505 // T operator~(T); 7506 void addUnaryTildePromotedIntegralOverloads() { 7507 if (!HasArithmeticOrEnumeralCandidateType) 7508 return; 7509 7510 for (unsigned Int = FirstPromotedIntegralType; 7511 Int < LastPromotedIntegralType; ++Int) { 7512 QualType IntTy = getArithmeticType(Int); 7513 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7514 } 7515 7516 // Extension: We also add this operator for vector types. 7517 for (BuiltinCandidateTypeSet::iterator 7518 Vec = CandidateTypes[0].vector_begin(), 7519 VecEnd = CandidateTypes[0].vector_end(); 7520 Vec != VecEnd; ++Vec) { 7521 QualType VecTy = *Vec; 7522 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7523 } 7524 } 7525 7526 // C++ [over.match.oper]p16: 7527 // For every pointer to member type T, there exist candidate operator 7528 // functions of the form 7529 // 7530 // bool operator==(T,T); 7531 // bool operator!=(T,T); 7532 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7533 /// Set of (canonical) types that we've already handled. 7534 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7535 7536 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7537 for (BuiltinCandidateTypeSet::iterator 7538 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7539 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7540 MemPtr != MemPtrEnd; 7541 ++MemPtr) { 7542 // Don't add the same builtin candidate twice. 7543 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7544 continue; 7545 7546 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7547 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7548 } 7549 } 7550 } 7551 7552 // C++ [over.built]p15: 7553 // 7554 // For every T, where T is an enumeration type, a pointer type, or 7555 // std::nullptr_t, there exist candidate operator functions of the form 7556 // 7557 // bool operator<(T, T); 7558 // bool operator>(T, T); 7559 // bool operator<=(T, T); 7560 // bool operator>=(T, T); 7561 // bool operator==(T, T); 7562 // bool operator!=(T, T); 7563 void addRelationalPointerOrEnumeralOverloads() { 7564 // C++ [over.match.oper]p3: 7565 // [...]the built-in candidates include all of the candidate operator 7566 // functions defined in 13.6 that, compared to the given operator, [...] 7567 // do not have the same parameter-type-list as any non-template non-member 7568 // candidate. 7569 // 7570 // Note that in practice, this only affects enumeration types because there 7571 // aren't any built-in candidates of record type, and a user-defined operator 7572 // must have an operand of record or enumeration type. Also, the only other 7573 // overloaded operator with enumeration arguments, operator=, 7574 // cannot be overloaded for enumeration types, so this is the only place 7575 // where we must suppress candidates like this. 7576 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7577 UserDefinedBinaryOperators; 7578 7579 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7580 if (CandidateTypes[ArgIdx].enumeration_begin() != 7581 CandidateTypes[ArgIdx].enumeration_end()) { 7582 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7583 CEnd = CandidateSet.end(); 7584 C != CEnd; ++C) { 7585 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7586 continue; 7587 7588 if (C->Function->isFunctionTemplateSpecialization()) 7589 continue; 7590 7591 QualType FirstParamType = 7592 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7593 QualType SecondParamType = 7594 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7595 7596 // Skip if either parameter isn't of enumeral type. 7597 if (!FirstParamType->isEnumeralType() || 7598 !SecondParamType->isEnumeralType()) 7599 continue; 7600 7601 // Add this operator to the set of known user-defined operators. 7602 UserDefinedBinaryOperators.insert( 7603 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7604 S.Context.getCanonicalType(SecondParamType))); 7605 } 7606 } 7607 } 7608 7609 /// Set of (canonical) types that we've already handled. 7610 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7611 7612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7613 for (BuiltinCandidateTypeSet::iterator 7614 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7615 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7616 Ptr != PtrEnd; ++Ptr) { 7617 // Don't add the same builtin candidate twice. 7618 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7619 continue; 7620 7621 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7622 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7623 } 7624 for (BuiltinCandidateTypeSet::iterator 7625 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7626 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7627 Enum != EnumEnd; ++Enum) { 7628 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7629 7630 // Don't add the same builtin candidate twice, or if a user defined 7631 // candidate exists. 7632 if (!AddedTypes.insert(CanonType).second || 7633 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7634 CanonType))) 7635 continue; 7636 7637 QualType ParamTypes[2] = { *Enum, *Enum }; 7638 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7639 } 7640 7641 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7642 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7643 if (AddedTypes.insert(NullPtrTy).second && 7644 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7645 NullPtrTy))) { 7646 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7647 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7648 CandidateSet); 7649 } 7650 } 7651 } 7652 } 7653 7654 // C++ [over.built]p13: 7655 // 7656 // For every cv-qualified or cv-unqualified object type T 7657 // there exist candidate operator functions of the form 7658 // 7659 // T* operator+(T*, ptrdiff_t); 7660 // T& operator[](T*, ptrdiff_t); [BELOW] 7661 // T* operator-(T*, ptrdiff_t); 7662 // T* operator+(ptrdiff_t, T*); 7663 // T& operator[](ptrdiff_t, T*); [BELOW] 7664 // 7665 // C++ [over.built]p14: 7666 // 7667 // For every T, where T is a pointer to object type, there 7668 // exist candidate operator functions of the form 7669 // 7670 // ptrdiff_t operator-(T, T); 7671 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7672 /// Set of (canonical) types that we've already handled. 7673 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7674 7675 for (int Arg = 0; Arg < 2; ++Arg) { 7676 QualType AsymmetricParamTypes[2] = { 7677 S.Context.getPointerDiffType(), 7678 S.Context.getPointerDiffType(), 7679 }; 7680 for (BuiltinCandidateTypeSet::iterator 7681 Ptr = CandidateTypes[Arg].pointer_begin(), 7682 PtrEnd = CandidateTypes[Arg].pointer_end(); 7683 Ptr != PtrEnd; ++Ptr) { 7684 QualType PointeeTy = (*Ptr)->getPointeeType(); 7685 if (!PointeeTy->isObjectType()) 7686 continue; 7687 7688 AsymmetricParamTypes[Arg] = *Ptr; 7689 if (Arg == 0 || Op == OO_Plus) { 7690 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7691 // T* operator+(ptrdiff_t, T*); 7692 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7693 } 7694 if (Op == OO_Minus) { 7695 // ptrdiff_t operator-(T, T); 7696 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7697 continue; 7698 7699 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7700 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7701 Args, CandidateSet); 7702 } 7703 } 7704 } 7705 } 7706 7707 // C++ [over.built]p12: 7708 // 7709 // For every pair of promoted arithmetic types L and R, there 7710 // exist candidate operator functions of the form 7711 // 7712 // LR operator*(L, R); 7713 // LR operator/(L, R); 7714 // LR operator+(L, R); 7715 // LR operator-(L, R); 7716 // bool operator<(L, R); 7717 // bool operator>(L, R); 7718 // bool operator<=(L, R); 7719 // bool operator>=(L, R); 7720 // bool operator==(L, R); 7721 // bool operator!=(L, R); 7722 // 7723 // where LR is the result of the usual arithmetic conversions 7724 // between types L and R. 7725 // 7726 // C++ [over.built]p24: 7727 // 7728 // For every pair of promoted arithmetic types L and R, there exist 7729 // candidate operator functions of the form 7730 // 7731 // LR operator?(bool, L, R); 7732 // 7733 // where LR is the result of the usual arithmetic conversions 7734 // between types L and R. 7735 // Our candidates ignore the first parameter. 7736 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7737 if (!HasArithmeticOrEnumeralCandidateType) 7738 return; 7739 7740 for (unsigned Left = FirstPromotedArithmeticType; 7741 Left < LastPromotedArithmeticType; ++Left) { 7742 for (unsigned Right = FirstPromotedArithmeticType; 7743 Right < LastPromotedArithmeticType; ++Right) { 7744 QualType LandR[2] = { getArithmeticType(Left), 7745 getArithmeticType(Right) }; 7746 QualType Result = 7747 isComparison ? S.Context.BoolTy 7748 : getUsualArithmeticConversions(Left, Right); 7749 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7750 } 7751 } 7752 7753 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7754 // conditional operator for vector types. 7755 for (BuiltinCandidateTypeSet::iterator 7756 Vec1 = CandidateTypes[0].vector_begin(), 7757 Vec1End = CandidateTypes[0].vector_end(); 7758 Vec1 != Vec1End; ++Vec1) { 7759 for (BuiltinCandidateTypeSet::iterator 7760 Vec2 = CandidateTypes[1].vector_begin(), 7761 Vec2End = CandidateTypes[1].vector_end(); 7762 Vec2 != Vec2End; ++Vec2) { 7763 QualType LandR[2] = { *Vec1, *Vec2 }; 7764 QualType Result = S.Context.BoolTy; 7765 if (!isComparison) { 7766 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7767 Result = *Vec1; 7768 else 7769 Result = *Vec2; 7770 } 7771 7772 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7773 } 7774 } 7775 } 7776 7777 // C++ [over.built]p17: 7778 // 7779 // For every pair of promoted integral types L and R, there 7780 // exist candidate operator functions of the form 7781 // 7782 // LR operator%(L, R); 7783 // LR operator&(L, R); 7784 // LR operator^(L, R); 7785 // LR operator|(L, R); 7786 // L operator<<(L, R); 7787 // L operator>>(L, R); 7788 // 7789 // where LR is the result of the usual arithmetic conversions 7790 // between types L and R. 7791 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7792 if (!HasArithmeticOrEnumeralCandidateType) 7793 return; 7794 7795 for (unsigned Left = FirstPromotedIntegralType; 7796 Left < LastPromotedIntegralType; ++Left) { 7797 for (unsigned Right = FirstPromotedIntegralType; 7798 Right < LastPromotedIntegralType; ++Right) { 7799 QualType LandR[2] = { getArithmeticType(Left), 7800 getArithmeticType(Right) }; 7801 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7802 ? LandR[0] 7803 : getUsualArithmeticConversions(Left, Right); 7804 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7805 } 7806 } 7807 } 7808 7809 // C++ [over.built]p20: 7810 // 7811 // For every pair (T, VQ), where T is an enumeration or 7812 // pointer to member type and VQ is either volatile or 7813 // empty, there exist candidate operator functions of the form 7814 // 7815 // VQ T& operator=(VQ T&, T); 7816 void addAssignmentMemberPointerOrEnumeralOverloads() { 7817 /// Set of (canonical) types that we've already handled. 7818 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7819 7820 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7821 for (BuiltinCandidateTypeSet::iterator 7822 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7823 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7824 Enum != EnumEnd; ++Enum) { 7825 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7826 continue; 7827 7828 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7829 } 7830 7831 for (BuiltinCandidateTypeSet::iterator 7832 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7833 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7834 MemPtr != MemPtrEnd; ++MemPtr) { 7835 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7836 continue; 7837 7838 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7839 } 7840 } 7841 } 7842 7843 // C++ [over.built]p19: 7844 // 7845 // For every pair (T, VQ), where T is any type and VQ is either 7846 // volatile or empty, there exist candidate operator functions 7847 // of the form 7848 // 7849 // T*VQ& operator=(T*VQ&, T*); 7850 // 7851 // C++ [over.built]p21: 7852 // 7853 // For every pair (T, VQ), where T is a cv-qualified or 7854 // cv-unqualified object type and VQ is either volatile or 7855 // empty, there exist candidate operator functions of the form 7856 // 7857 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7858 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7859 void addAssignmentPointerOverloads(bool isEqualOp) { 7860 /// Set of (canonical) types that we've already handled. 7861 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7862 7863 for (BuiltinCandidateTypeSet::iterator 7864 Ptr = CandidateTypes[0].pointer_begin(), 7865 PtrEnd = CandidateTypes[0].pointer_end(); 7866 Ptr != PtrEnd; ++Ptr) { 7867 // If this is operator=, keep track of the builtin candidates we added. 7868 if (isEqualOp) 7869 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7870 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7871 continue; 7872 7873 // non-volatile version 7874 QualType ParamTypes[2] = { 7875 S.Context.getLValueReferenceType(*Ptr), 7876 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7877 }; 7878 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7879 /*IsAssigmentOperator=*/ isEqualOp); 7880 7881 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7882 VisibleTypeConversionsQuals.hasVolatile(); 7883 if (NeedVolatile) { 7884 // volatile version 7885 ParamTypes[0] = 7886 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7887 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7888 /*IsAssigmentOperator=*/isEqualOp); 7889 } 7890 7891 if (!(*Ptr).isRestrictQualified() && 7892 VisibleTypeConversionsQuals.hasRestrict()) { 7893 // restrict version 7894 ParamTypes[0] 7895 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7897 /*IsAssigmentOperator=*/isEqualOp); 7898 7899 if (NeedVolatile) { 7900 // volatile restrict version 7901 ParamTypes[0] 7902 = S.Context.getLValueReferenceType( 7903 S.Context.getCVRQualifiedType(*Ptr, 7904 (Qualifiers::Volatile | 7905 Qualifiers::Restrict))); 7906 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7907 /*IsAssigmentOperator=*/isEqualOp); 7908 } 7909 } 7910 } 7911 7912 if (isEqualOp) { 7913 for (BuiltinCandidateTypeSet::iterator 7914 Ptr = CandidateTypes[1].pointer_begin(), 7915 PtrEnd = CandidateTypes[1].pointer_end(); 7916 Ptr != PtrEnd; ++Ptr) { 7917 // Make sure we don't add the same candidate twice. 7918 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7919 continue; 7920 7921 QualType ParamTypes[2] = { 7922 S.Context.getLValueReferenceType(*Ptr), 7923 *Ptr, 7924 }; 7925 7926 // non-volatile version 7927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7928 /*IsAssigmentOperator=*/true); 7929 7930 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7931 VisibleTypeConversionsQuals.hasVolatile(); 7932 if (NeedVolatile) { 7933 // volatile version 7934 ParamTypes[0] = 7935 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7936 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7937 /*IsAssigmentOperator=*/true); 7938 } 7939 7940 if (!(*Ptr).isRestrictQualified() && 7941 VisibleTypeConversionsQuals.hasRestrict()) { 7942 // restrict version 7943 ParamTypes[0] 7944 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7945 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7946 /*IsAssigmentOperator=*/true); 7947 7948 if (NeedVolatile) { 7949 // volatile restrict version 7950 ParamTypes[0] 7951 = S.Context.getLValueReferenceType( 7952 S.Context.getCVRQualifiedType(*Ptr, 7953 (Qualifiers::Volatile | 7954 Qualifiers::Restrict))); 7955 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7956 /*IsAssigmentOperator=*/true); 7957 } 7958 } 7959 } 7960 } 7961 } 7962 7963 // C++ [over.built]p18: 7964 // 7965 // For every triple (L, VQ, R), where L is an arithmetic type, 7966 // VQ is either volatile or empty, and R is a promoted 7967 // arithmetic type, there exist candidate operator functions of 7968 // the form 7969 // 7970 // VQ L& operator=(VQ L&, R); 7971 // VQ L& operator*=(VQ L&, R); 7972 // VQ L& operator/=(VQ L&, R); 7973 // VQ L& operator+=(VQ L&, R); 7974 // VQ L& operator-=(VQ L&, R); 7975 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7976 if (!HasArithmeticOrEnumeralCandidateType) 7977 return; 7978 7979 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7980 for (unsigned Right = FirstPromotedArithmeticType; 7981 Right < LastPromotedArithmeticType; ++Right) { 7982 QualType ParamTypes[2]; 7983 ParamTypes[1] = getArithmeticType(Right); 7984 7985 // Add this built-in operator as a candidate (VQ is empty). 7986 ParamTypes[0] = 7987 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7988 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7989 /*IsAssigmentOperator=*/isEqualOp); 7990 7991 // Add this built-in operator as a candidate (VQ is 'volatile'). 7992 if (VisibleTypeConversionsQuals.hasVolatile()) { 7993 ParamTypes[0] = 7994 S.Context.getVolatileType(getArithmeticType(Left)); 7995 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7996 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7997 /*IsAssigmentOperator=*/isEqualOp); 7998 } 7999 } 8000 } 8001 8002 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8003 for (BuiltinCandidateTypeSet::iterator 8004 Vec1 = CandidateTypes[0].vector_begin(), 8005 Vec1End = CandidateTypes[0].vector_end(); 8006 Vec1 != Vec1End; ++Vec1) { 8007 for (BuiltinCandidateTypeSet::iterator 8008 Vec2 = CandidateTypes[1].vector_begin(), 8009 Vec2End = CandidateTypes[1].vector_end(); 8010 Vec2 != Vec2End; ++Vec2) { 8011 QualType ParamTypes[2]; 8012 ParamTypes[1] = *Vec2; 8013 // Add this built-in operator as a candidate (VQ is empty). 8014 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8015 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8016 /*IsAssigmentOperator=*/isEqualOp); 8017 8018 // Add this built-in operator as a candidate (VQ is 'volatile'). 8019 if (VisibleTypeConversionsQuals.hasVolatile()) { 8020 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8021 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8023 /*IsAssigmentOperator=*/isEqualOp); 8024 } 8025 } 8026 } 8027 } 8028 8029 // C++ [over.built]p22: 8030 // 8031 // For every triple (L, VQ, R), where L is an integral type, VQ 8032 // is either volatile or empty, and R is a promoted integral 8033 // type, there exist candidate operator functions of the form 8034 // 8035 // VQ L& operator%=(VQ L&, R); 8036 // VQ L& operator<<=(VQ L&, R); 8037 // VQ L& operator>>=(VQ L&, R); 8038 // VQ L& operator&=(VQ L&, R); 8039 // VQ L& operator^=(VQ L&, R); 8040 // VQ L& operator|=(VQ L&, R); 8041 void addAssignmentIntegralOverloads() { 8042 if (!HasArithmeticOrEnumeralCandidateType) 8043 return; 8044 8045 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8046 for (unsigned Right = FirstPromotedIntegralType; 8047 Right < LastPromotedIntegralType; ++Right) { 8048 QualType ParamTypes[2]; 8049 ParamTypes[1] = getArithmeticType(Right); 8050 8051 // Add this built-in operator as a candidate (VQ is empty). 8052 ParamTypes[0] = 8053 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8054 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8055 if (VisibleTypeConversionsQuals.hasVolatile()) { 8056 // Add this built-in operator as a candidate (VQ is 'volatile'). 8057 ParamTypes[0] = getArithmeticType(Left); 8058 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8059 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8060 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8061 } 8062 } 8063 } 8064 } 8065 8066 // C++ [over.operator]p23: 8067 // 8068 // There also exist candidate operator functions of the form 8069 // 8070 // bool operator!(bool); 8071 // bool operator&&(bool, bool); 8072 // bool operator||(bool, bool); 8073 void addExclaimOverload() { 8074 QualType ParamTy = S.Context.BoolTy; 8075 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8076 /*IsAssignmentOperator=*/false, 8077 /*NumContextualBoolArguments=*/1); 8078 } 8079 void addAmpAmpOrPipePipeOverload() { 8080 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8081 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8082 /*IsAssignmentOperator=*/false, 8083 /*NumContextualBoolArguments=*/2); 8084 } 8085 8086 // C++ [over.built]p13: 8087 // 8088 // For every cv-qualified or cv-unqualified object type T there 8089 // exist candidate operator functions of the form 8090 // 8091 // T* operator+(T*, ptrdiff_t); [ABOVE] 8092 // T& operator[](T*, ptrdiff_t); 8093 // T* operator-(T*, ptrdiff_t); [ABOVE] 8094 // T* operator+(ptrdiff_t, T*); [ABOVE] 8095 // T& operator[](ptrdiff_t, T*); 8096 void addSubscriptOverloads() { 8097 for (BuiltinCandidateTypeSet::iterator 8098 Ptr = CandidateTypes[0].pointer_begin(), 8099 PtrEnd = CandidateTypes[0].pointer_end(); 8100 Ptr != PtrEnd; ++Ptr) { 8101 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8102 QualType PointeeType = (*Ptr)->getPointeeType(); 8103 if (!PointeeType->isObjectType()) 8104 continue; 8105 8106 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8107 8108 // T& operator[](T*, ptrdiff_t) 8109 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8110 } 8111 8112 for (BuiltinCandidateTypeSet::iterator 8113 Ptr = CandidateTypes[1].pointer_begin(), 8114 PtrEnd = CandidateTypes[1].pointer_end(); 8115 Ptr != PtrEnd; ++Ptr) { 8116 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8117 QualType PointeeType = (*Ptr)->getPointeeType(); 8118 if (!PointeeType->isObjectType()) 8119 continue; 8120 8121 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8122 8123 // T& operator[](ptrdiff_t, T*) 8124 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8125 } 8126 } 8127 8128 // C++ [over.built]p11: 8129 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8130 // C1 is the same type as C2 or is a derived class of C2, T is an object 8131 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8132 // there exist candidate operator functions of the form 8133 // 8134 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8135 // 8136 // where CV12 is the union of CV1 and CV2. 8137 void addArrowStarOverloads() { 8138 for (BuiltinCandidateTypeSet::iterator 8139 Ptr = CandidateTypes[0].pointer_begin(), 8140 PtrEnd = CandidateTypes[0].pointer_end(); 8141 Ptr != PtrEnd; ++Ptr) { 8142 QualType C1Ty = (*Ptr); 8143 QualType C1; 8144 QualifierCollector Q1; 8145 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8146 if (!isa<RecordType>(C1)) 8147 continue; 8148 // heuristic to reduce number of builtin candidates in the set. 8149 // Add volatile/restrict version only if there are conversions to a 8150 // volatile/restrict type. 8151 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8152 continue; 8153 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8154 continue; 8155 for (BuiltinCandidateTypeSet::iterator 8156 MemPtr = CandidateTypes[1].member_pointer_begin(), 8157 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8158 MemPtr != MemPtrEnd; ++MemPtr) { 8159 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8160 QualType C2 = QualType(mptr->getClass(), 0); 8161 C2 = C2.getUnqualifiedType(); 8162 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8163 break; 8164 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8165 // build CV12 T& 8166 QualType T = mptr->getPointeeType(); 8167 if (!VisibleTypeConversionsQuals.hasVolatile() && 8168 T.isVolatileQualified()) 8169 continue; 8170 if (!VisibleTypeConversionsQuals.hasRestrict() && 8171 T.isRestrictQualified()) 8172 continue; 8173 T = Q1.apply(S.Context, T); 8174 QualType ResultTy = S.Context.getLValueReferenceType(T); 8175 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8176 } 8177 } 8178 } 8179 8180 // Note that we don't consider the first argument, since it has been 8181 // contextually converted to bool long ago. The candidates below are 8182 // therefore added as binary. 8183 // 8184 // C++ [over.built]p25: 8185 // For every type T, where T is a pointer, pointer-to-member, or scoped 8186 // enumeration type, there exist candidate operator functions of the form 8187 // 8188 // T operator?(bool, T, T); 8189 // 8190 void addConditionalOperatorOverloads() { 8191 /// Set of (canonical) types that we've already handled. 8192 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8193 8194 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8195 for (BuiltinCandidateTypeSet::iterator 8196 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8197 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8198 Ptr != PtrEnd; ++Ptr) { 8199 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8200 continue; 8201 8202 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8203 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8204 } 8205 8206 for (BuiltinCandidateTypeSet::iterator 8207 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8208 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8209 MemPtr != MemPtrEnd; ++MemPtr) { 8210 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8211 continue; 8212 8213 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8214 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8215 } 8216 8217 if (S.getLangOpts().CPlusPlus11) { 8218 for (BuiltinCandidateTypeSet::iterator 8219 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8220 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8221 Enum != EnumEnd; ++Enum) { 8222 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8223 continue; 8224 8225 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8226 continue; 8227 8228 QualType ParamTypes[2] = { *Enum, *Enum }; 8229 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8230 } 8231 } 8232 } 8233 } 8234 }; 8235 8236 } // end anonymous namespace 8237 8238 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8239 /// operator overloads to the candidate set (C++ [over.built]), based 8240 /// on the operator @p Op and the arguments given. For example, if the 8241 /// operator is a binary '+', this routine might add "int 8242 /// operator+(int, int)" to cover integer addition. 8243 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8244 SourceLocation OpLoc, 8245 ArrayRef<Expr *> Args, 8246 OverloadCandidateSet &CandidateSet) { 8247 // Find all of the types that the arguments can convert to, but only 8248 // if the operator we're looking at has built-in operator candidates 8249 // that make use of these types. Also record whether we encounter non-record 8250 // candidate types or either arithmetic or enumeral candidate types. 8251 Qualifiers VisibleTypeConversionsQuals; 8252 VisibleTypeConversionsQuals.addConst(); 8253 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8254 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8255 8256 bool HasNonRecordCandidateType = false; 8257 bool HasArithmeticOrEnumeralCandidateType = false; 8258 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8259 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8260 CandidateTypes.emplace_back(*this); 8261 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8262 OpLoc, 8263 true, 8264 (Op == OO_Exclaim || 8265 Op == OO_AmpAmp || 8266 Op == OO_PipePipe), 8267 VisibleTypeConversionsQuals); 8268 HasNonRecordCandidateType = HasNonRecordCandidateType || 8269 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8270 HasArithmeticOrEnumeralCandidateType = 8271 HasArithmeticOrEnumeralCandidateType || 8272 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8273 } 8274 8275 // Exit early when no non-record types have been added to the candidate set 8276 // for any of the arguments to the operator. 8277 // 8278 // We can't exit early for !, ||, or &&, since there we have always have 8279 // 'bool' overloads. 8280 if (!HasNonRecordCandidateType && 8281 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8282 return; 8283 8284 // Setup an object to manage the common state for building overloads. 8285 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8286 VisibleTypeConversionsQuals, 8287 HasArithmeticOrEnumeralCandidateType, 8288 CandidateTypes, CandidateSet); 8289 8290 // Dispatch over the operation to add in only those overloads which apply. 8291 switch (Op) { 8292 case OO_None: 8293 case NUM_OVERLOADED_OPERATORS: 8294 llvm_unreachable("Expected an overloaded operator"); 8295 8296 case OO_New: 8297 case OO_Delete: 8298 case OO_Array_New: 8299 case OO_Array_Delete: 8300 case OO_Call: 8301 llvm_unreachable( 8302 "Special operators don't use AddBuiltinOperatorCandidates"); 8303 8304 case OO_Comma: 8305 case OO_Arrow: 8306 case OO_Coawait: 8307 // C++ [over.match.oper]p3: 8308 // -- For the operator ',', the unary operator '&', the 8309 // operator '->', or the operator 'co_await', the 8310 // built-in candidates set is empty. 8311 break; 8312 8313 case OO_Plus: // '+' is either unary or binary 8314 if (Args.size() == 1) 8315 OpBuilder.addUnaryPlusPointerOverloads(); 8316 // Fall through. 8317 8318 case OO_Minus: // '-' is either unary or binary 8319 if (Args.size() == 1) { 8320 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8321 } else { 8322 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8323 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8324 } 8325 break; 8326 8327 case OO_Star: // '*' is either unary or binary 8328 if (Args.size() == 1) 8329 OpBuilder.addUnaryStarPointerOverloads(); 8330 else 8331 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8332 break; 8333 8334 case OO_Slash: 8335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8336 break; 8337 8338 case OO_PlusPlus: 8339 case OO_MinusMinus: 8340 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8341 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8342 break; 8343 8344 case OO_EqualEqual: 8345 case OO_ExclaimEqual: 8346 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8347 // Fall through. 8348 8349 case OO_Less: 8350 case OO_Greater: 8351 case OO_LessEqual: 8352 case OO_GreaterEqual: 8353 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8354 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8355 break; 8356 8357 case OO_Percent: 8358 case OO_Caret: 8359 case OO_Pipe: 8360 case OO_LessLess: 8361 case OO_GreaterGreater: 8362 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8363 break; 8364 8365 case OO_Amp: // '&' is either unary or binary 8366 if (Args.size() == 1) 8367 // C++ [over.match.oper]p3: 8368 // -- For the operator ',', the unary operator '&', or the 8369 // operator '->', the built-in candidates set is empty. 8370 break; 8371 8372 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8373 break; 8374 8375 case OO_Tilde: 8376 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8377 break; 8378 8379 case OO_Equal: 8380 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8381 // Fall through. 8382 8383 case OO_PlusEqual: 8384 case OO_MinusEqual: 8385 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8386 // Fall through. 8387 8388 case OO_StarEqual: 8389 case OO_SlashEqual: 8390 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8391 break; 8392 8393 case OO_PercentEqual: 8394 case OO_LessLessEqual: 8395 case OO_GreaterGreaterEqual: 8396 case OO_AmpEqual: 8397 case OO_CaretEqual: 8398 case OO_PipeEqual: 8399 OpBuilder.addAssignmentIntegralOverloads(); 8400 break; 8401 8402 case OO_Exclaim: 8403 OpBuilder.addExclaimOverload(); 8404 break; 8405 8406 case OO_AmpAmp: 8407 case OO_PipePipe: 8408 OpBuilder.addAmpAmpOrPipePipeOverload(); 8409 break; 8410 8411 case OO_Subscript: 8412 OpBuilder.addSubscriptOverloads(); 8413 break; 8414 8415 case OO_ArrowStar: 8416 OpBuilder.addArrowStarOverloads(); 8417 break; 8418 8419 case OO_Conditional: 8420 OpBuilder.addConditionalOperatorOverloads(); 8421 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8422 break; 8423 } 8424 } 8425 8426 /// \brief Add function candidates found via argument-dependent lookup 8427 /// to the set of overloading candidates. 8428 /// 8429 /// This routine performs argument-dependent name lookup based on the 8430 /// given function name (which may also be an operator name) and adds 8431 /// all of the overload candidates found by ADL to the overload 8432 /// candidate set (C++ [basic.lookup.argdep]). 8433 void 8434 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8435 SourceLocation Loc, 8436 ArrayRef<Expr *> Args, 8437 TemplateArgumentListInfo *ExplicitTemplateArgs, 8438 OverloadCandidateSet& CandidateSet, 8439 bool PartialOverloading) { 8440 ADLResult Fns; 8441 8442 // FIXME: This approach for uniquing ADL results (and removing 8443 // redundant candidates from the set) relies on pointer-equality, 8444 // which means we need to key off the canonical decl. However, 8445 // always going back to the canonical decl might not get us the 8446 // right set of default arguments. What default arguments are 8447 // we supposed to consider on ADL candidates, anyway? 8448 8449 // FIXME: Pass in the explicit template arguments? 8450 ArgumentDependentLookup(Name, Loc, Args, Fns); 8451 8452 // Erase all of the candidates we already knew about. 8453 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8454 CandEnd = CandidateSet.end(); 8455 Cand != CandEnd; ++Cand) 8456 if (Cand->Function) { 8457 Fns.erase(Cand->Function); 8458 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8459 Fns.erase(FunTmpl); 8460 } 8461 8462 // For each of the ADL candidates we found, add it to the overload 8463 // set. 8464 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8465 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8466 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8467 if (ExplicitTemplateArgs) 8468 continue; 8469 8470 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8471 PartialOverloading); 8472 } else 8473 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8474 FoundDecl, ExplicitTemplateArgs, 8475 Args, CandidateSet, PartialOverloading); 8476 } 8477 } 8478 8479 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8480 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8481 // on Cand1 and Cand2 have conditions that evaluate to true. 8482 // 8483 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8484 // Cand1's first N enable_if attributes have precisely the same conditions as 8485 // Cand2's first N enable_if attributes (where N = the number of enable_if 8486 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8487 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8488 const FunctionDecl *Cand2) { 8489 8490 // FIXME: The next several lines are just 8491 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8492 // instead of reverse order which is how they're stored in the AST. 8493 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8494 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8495 8496 // Candidate 1 is better if it has strictly more attributes and 8497 // the common sequence is identical. 8498 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8499 return false; 8500 8501 auto Cand1I = Cand1Attrs.begin(); 8502 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8503 for (auto &Cand2A : Cand2Attrs) { 8504 Cand1ID.clear(); 8505 Cand2ID.clear(); 8506 8507 auto &Cand1A = *Cand1I++; 8508 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8509 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8510 if (Cand1ID != Cand2ID) 8511 return false; 8512 } 8513 8514 return true; 8515 } 8516 8517 /// isBetterOverloadCandidate - Determines whether the first overload 8518 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8519 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8520 const OverloadCandidate &Cand2, 8521 SourceLocation Loc, 8522 bool UserDefinedConversion) { 8523 // Define viable functions to be better candidates than non-viable 8524 // functions. 8525 if (!Cand2.Viable) 8526 return Cand1.Viable; 8527 else if (!Cand1.Viable) 8528 return false; 8529 8530 // C++ [over.match.best]p1: 8531 // 8532 // -- if F is a static member function, ICS1(F) is defined such 8533 // that ICS1(F) is neither better nor worse than ICS1(G) for 8534 // any function G, and, symmetrically, ICS1(G) is neither 8535 // better nor worse than ICS1(F). 8536 unsigned StartArg = 0; 8537 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8538 StartArg = 1; 8539 8540 // C++ [over.match.best]p1: 8541 // A viable function F1 is defined to be a better function than another 8542 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8543 // conversion sequence than ICSi(F2), and then... 8544 unsigned NumArgs = Cand1.NumConversions; 8545 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8546 bool HasBetterConversion = false; 8547 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8548 switch (CompareImplicitConversionSequences(S, Loc, 8549 Cand1.Conversions[ArgIdx], 8550 Cand2.Conversions[ArgIdx])) { 8551 case ImplicitConversionSequence::Better: 8552 // Cand1 has a better conversion sequence. 8553 HasBetterConversion = true; 8554 break; 8555 8556 case ImplicitConversionSequence::Worse: 8557 // Cand1 can't be better than Cand2. 8558 return false; 8559 8560 case ImplicitConversionSequence::Indistinguishable: 8561 // Do nothing. 8562 break; 8563 } 8564 } 8565 8566 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8567 // ICSj(F2), or, if not that, 8568 if (HasBetterConversion) 8569 return true; 8570 8571 // -- the context is an initialization by user-defined conversion 8572 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8573 // from the return type of F1 to the destination type (i.e., 8574 // the type of the entity being initialized) is a better 8575 // conversion sequence than the standard conversion sequence 8576 // from the return type of F2 to the destination type. 8577 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8578 isa<CXXConversionDecl>(Cand1.Function) && 8579 isa<CXXConversionDecl>(Cand2.Function)) { 8580 // First check whether we prefer one of the conversion functions over the 8581 // other. This only distinguishes the results in non-standard, extension 8582 // cases such as the conversion from a lambda closure type to a function 8583 // pointer or block. 8584 ImplicitConversionSequence::CompareKind Result = 8585 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8586 if (Result == ImplicitConversionSequence::Indistinguishable) 8587 Result = CompareStandardConversionSequences(S, Loc, 8588 Cand1.FinalConversion, 8589 Cand2.FinalConversion); 8590 8591 if (Result != ImplicitConversionSequence::Indistinguishable) 8592 return Result == ImplicitConversionSequence::Better; 8593 8594 // FIXME: Compare kind of reference binding if conversion functions 8595 // convert to a reference type used in direct reference binding, per 8596 // C++14 [over.match.best]p1 section 2 bullet 3. 8597 } 8598 8599 // -- F1 is a non-template function and F2 is a function template 8600 // specialization, or, if not that, 8601 bool Cand1IsSpecialization = Cand1.Function && 8602 Cand1.Function->getPrimaryTemplate(); 8603 bool Cand2IsSpecialization = Cand2.Function && 8604 Cand2.Function->getPrimaryTemplate(); 8605 if (Cand1IsSpecialization != Cand2IsSpecialization) 8606 return Cand2IsSpecialization; 8607 8608 // -- F1 and F2 are function template specializations, and the function 8609 // template for F1 is more specialized than the template for F2 8610 // according to the partial ordering rules described in 14.5.5.2, or, 8611 // if not that, 8612 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8613 if (FunctionTemplateDecl *BetterTemplate 8614 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8615 Cand2.Function->getPrimaryTemplate(), 8616 Loc, 8617 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8618 : TPOC_Call, 8619 Cand1.ExplicitCallArguments, 8620 Cand2.ExplicitCallArguments)) 8621 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8622 } 8623 8624 // Check for enable_if value-based overload resolution. 8625 if (Cand1.Function && Cand2.Function && 8626 (Cand1.Function->hasAttr<EnableIfAttr>() || 8627 Cand2.Function->hasAttr<EnableIfAttr>())) 8628 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8629 8630 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8631 Cand1.Function && Cand2.Function) { 8632 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8633 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8634 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8635 } 8636 8637 bool HasPS1 = Cand1.Function != nullptr && 8638 functionHasPassObjectSizeParams(Cand1.Function); 8639 bool HasPS2 = Cand2.Function != nullptr && 8640 functionHasPassObjectSizeParams(Cand2.Function); 8641 return HasPS1 != HasPS2 && HasPS1; 8642 } 8643 8644 /// Determine whether two declarations are "equivalent" for the purposes of 8645 /// name lookup and overload resolution. This applies when the same internal/no 8646 /// linkage entity is defined by two modules (probably by textually including 8647 /// the same header). In such a case, we don't consider the declarations to 8648 /// declare the same entity, but we also don't want lookups with both 8649 /// declarations visible to be ambiguous in some cases (this happens when using 8650 /// a modularized libstdc++). 8651 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8652 const NamedDecl *B) { 8653 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8654 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8655 if (!VA || !VB) 8656 return false; 8657 8658 // The declarations must be declaring the same name as an internal linkage 8659 // entity in different modules. 8660 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8661 VB->getDeclContext()->getRedeclContext()) || 8662 getOwningModule(const_cast<ValueDecl *>(VA)) == 8663 getOwningModule(const_cast<ValueDecl *>(VB)) || 8664 VA->isExternallyVisible() || VB->isExternallyVisible()) 8665 return false; 8666 8667 // Check that the declarations appear to be equivalent. 8668 // 8669 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8670 // For constants and functions, we should check the initializer or body is 8671 // the same. For non-constant variables, we shouldn't allow it at all. 8672 if (Context.hasSameType(VA->getType(), VB->getType())) 8673 return true; 8674 8675 // Enum constants within unnamed enumerations will have different types, but 8676 // may still be similar enough to be interchangeable for our purposes. 8677 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8678 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8679 // Only handle anonymous enums. If the enumerations were named and 8680 // equivalent, they would have been merged to the same type. 8681 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8682 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8683 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8684 !Context.hasSameType(EnumA->getIntegerType(), 8685 EnumB->getIntegerType())) 8686 return false; 8687 // Allow this only if the value is the same for both enumerators. 8688 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8689 } 8690 } 8691 8692 // Nothing else is sufficiently similar. 8693 return false; 8694 } 8695 8696 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8697 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8698 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8699 8700 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8701 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8702 << !M << (M ? M->getFullModuleName() : ""); 8703 8704 for (auto *E : Equiv) { 8705 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8706 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8707 << !M << (M ? M->getFullModuleName() : ""); 8708 } 8709 } 8710 8711 /// \brief Computes the best viable function (C++ 13.3.3) 8712 /// within an overload candidate set. 8713 /// 8714 /// \param Loc The location of the function name (or operator symbol) for 8715 /// which overload resolution occurs. 8716 /// 8717 /// \param Best If overload resolution was successful or found a deleted 8718 /// function, \p Best points to the candidate function found. 8719 /// 8720 /// \returns The result of overload resolution. 8721 OverloadingResult 8722 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8723 iterator &Best, 8724 bool UserDefinedConversion) { 8725 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8726 std::transform(begin(), end(), std::back_inserter(Candidates), 8727 [](OverloadCandidate &Cand) { return &Cand; }); 8728 8729 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA 8730 // but accepted by both clang and NVCC. However during a particular 8731 // compilation mode only one call variant is viable. We need to 8732 // exclude non-viable overload candidates from consideration based 8733 // only on their host/device attributes. Specifically, if one 8734 // candidate call is WrongSide and the other is SameSide, we ignore 8735 // the WrongSide candidate. 8736 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads) { 8737 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8738 bool ContainsSameSideCandidate = 8739 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8740 return Cand->Function && 8741 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8742 Sema::CFP_SameSide; 8743 }); 8744 if (ContainsSameSideCandidate) { 8745 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8746 return Cand->Function && 8747 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8748 Sema::CFP_WrongSide; 8749 }; 8750 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8751 IsWrongSideCandidate), 8752 Candidates.end()); 8753 } 8754 } 8755 8756 // Find the best viable function. 8757 Best = end(); 8758 for (auto *Cand : Candidates) 8759 if (Cand->Viable) 8760 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8761 UserDefinedConversion)) 8762 Best = Cand; 8763 8764 // If we didn't find any viable functions, abort. 8765 if (Best == end()) 8766 return OR_No_Viable_Function; 8767 8768 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8769 8770 // Make sure that this function is better than every other viable 8771 // function. If not, we have an ambiguity. 8772 for (auto *Cand : Candidates) { 8773 if (Cand->Viable && 8774 Cand != Best && 8775 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8776 UserDefinedConversion)) { 8777 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8778 Cand->Function)) { 8779 EquivalentCands.push_back(Cand->Function); 8780 continue; 8781 } 8782 8783 Best = end(); 8784 return OR_Ambiguous; 8785 } 8786 } 8787 8788 // Best is the best viable function. 8789 if (Best->Function && 8790 (Best->Function->isDeleted() || 8791 S.isFunctionConsideredUnavailable(Best->Function))) 8792 return OR_Deleted; 8793 8794 if (!EquivalentCands.empty()) 8795 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8796 EquivalentCands); 8797 8798 return OR_Success; 8799 } 8800 8801 namespace { 8802 8803 enum OverloadCandidateKind { 8804 oc_function, 8805 oc_method, 8806 oc_constructor, 8807 oc_function_template, 8808 oc_method_template, 8809 oc_constructor_template, 8810 oc_implicit_default_constructor, 8811 oc_implicit_copy_constructor, 8812 oc_implicit_move_constructor, 8813 oc_implicit_copy_assignment, 8814 oc_implicit_move_assignment, 8815 oc_implicit_inherited_constructor 8816 }; 8817 8818 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8819 FunctionDecl *Fn, 8820 std::string &Description) { 8821 bool isTemplate = false; 8822 8823 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8824 isTemplate = true; 8825 Description = S.getTemplateArgumentBindingsText( 8826 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8827 } 8828 8829 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8830 if (!Ctor->isImplicit()) 8831 return isTemplate ? oc_constructor_template : oc_constructor; 8832 8833 if (Ctor->getInheritedConstructor()) 8834 return oc_implicit_inherited_constructor; 8835 8836 if (Ctor->isDefaultConstructor()) 8837 return oc_implicit_default_constructor; 8838 8839 if (Ctor->isMoveConstructor()) 8840 return oc_implicit_move_constructor; 8841 8842 assert(Ctor->isCopyConstructor() && 8843 "unexpected sort of implicit constructor"); 8844 return oc_implicit_copy_constructor; 8845 } 8846 8847 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8848 // This actually gets spelled 'candidate function' for now, but 8849 // it doesn't hurt to split it out. 8850 if (!Meth->isImplicit()) 8851 return isTemplate ? oc_method_template : oc_method; 8852 8853 if (Meth->isMoveAssignmentOperator()) 8854 return oc_implicit_move_assignment; 8855 8856 if (Meth->isCopyAssignmentOperator()) 8857 return oc_implicit_copy_assignment; 8858 8859 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8860 return oc_method; 8861 } 8862 8863 return isTemplate ? oc_function_template : oc_function; 8864 } 8865 8866 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8867 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8868 if (!Ctor) return; 8869 8870 Ctor = Ctor->getInheritedConstructor(); 8871 if (!Ctor) return; 8872 8873 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8874 } 8875 8876 } // end anonymous namespace 8877 8878 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8879 const FunctionDecl *FD) { 8880 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8881 bool AlwaysTrue; 8882 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8883 return false; 8884 if (!AlwaysTrue) 8885 return false; 8886 } 8887 return true; 8888 } 8889 8890 /// \brief Returns true if we can take the address of the function. 8891 /// 8892 /// \param Complain - If true, we'll emit a diagnostic 8893 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8894 /// we in overload resolution? 8895 /// \param Loc - The location of the statement we're complaining about. Ignored 8896 /// if we're not complaining, or if we're in overload resolution. 8897 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8898 bool Complain, 8899 bool InOverloadResolution, 8900 SourceLocation Loc) { 8901 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8902 if (Complain) { 8903 if (InOverloadResolution) 8904 S.Diag(FD->getLocStart(), 8905 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8906 else 8907 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8908 } 8909 return false; 8910 } 8911 8912 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8913 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8914 if (I == FD->param_end()) 8915 return true; 8916 8917 if (Complain) { 8918 // Add one to ParamNo because it's user-facing 8919 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8920 if (InOverloadResolution) 8921 S.Diag(FD->getLocation(), 8922 diag::note_ovl_candidate_has_pass_object_size_params) 8923 << ParamNo; 8924 else 8925 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8926 << FD << ParamNo; 8927 } 8928 return false; 8929 } 8930 8931 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8932 const FunctionDecl *FD) { 8933 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8934 /*InOverloadResolution=*/true, 8935 /*Loc=*/SourceLocation()); 8936 } 8937 8938 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8939 bool Complain, 8940 SourceLocation Loc) { 8941 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8942 /*InOverloadResolution=*/false, 8943 Loc); 8944 } 8945 8946 // Notes the location of an overload candidate. 8947 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8948 bool TakingAddress) { 8949 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8950 return; 8951 8952 std::string FnDesc; 8953 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8954 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8955 << (unsigned) K << FnDesc; 8956 8957 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8958 Diag(Fn->getLocation(), PD); 8959 MaybeEmitInheritedConstructorNote(*this, Fn); 8960 } 8961 8962 // Notes the location of all overload candidates designated through 8963 // OverloadedExpr 8964 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8965 bool TakingAddress) { 8966 assert(OverloadedExpr->getType() == Context.OverloadTy); 8967 8968 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8969 OverloadExpr *OvlExpr = Ovl.Expression; 8970 8971 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8972 IEnd = OvlExpr->decls_end(); 8973 I != IEnd; ++I) { 8974 if (FunctionTemplateDecl *FunTmpl = 8975 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8976 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8977 TakingAddress); 8978 } else if (FunctionDecl *Fun 8979 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8980 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8981 } 8982 } 8983 } 8984 8985 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8986 /// "lead" diagnostic; it will be given two arguments, the source and 8987 /// target types of the conversion. 8988 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8989 Sema &S, 8990 SourceLocation CaretLoc, 8991 const PartialDiagnostic &PDiag) const { 8992 S.Diag(CaretLoc, PDiag) 8993 << Ambiguous.getFromType() << Ambiguous.getToType(); 8994 // FIXME: The note limiting machinery is borrowed from 8995 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8996 // refactoring here. 8997 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8998 unsigned CandsShown = 0; 8999 AmbiguousConversionSequence::const_iterator I, E; 9000 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9001 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9002 break; 9003 ++CandsShown; 9004 S.NoteOverloadCandidate(*I); 9005 } 9006 if (I != E) 9007 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9008 } 9009 9010 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9011 unsigned I, bool TakingCandidateAddress) { 9012 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9013 assert(Conv.isBad()); 9014 assert(Cand->Function && "for now, candidate must be a function"); 9015 FunctionDecl *Fn = Cand->Function; 9016 9017 // There's a conversion slot for the object argument if this is a 9018 // non-constructor method. Note that 'I' corresponds the 9019 // conversion-slot index. 9020 bool isObjectArgument = false; 9021 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9022 if (I == 0) 9023 isObjectArgument = true; 9024 else 9025 I--; 9026 } 9027 9028 std::string FnDesc; 9029 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9030 9031 Expr *FromExpr = Conv.Bad.FromExpr; 9032 QualType FromTy = Conv.Bad.getFromType(); 9033 QualType ToTy = Conv.Bad.getToType(); 9034 9035 if (FromTy == S.Context.OverloadTy) { 9036 assert(FromExpr && "overload set argument came from implicit argument?"); 9037 Expr *E = FromExpr->IgnoreParens(); 9038 if (isa<UnaryOperator>(E)) 9039 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9040 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9041 9042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9043 << (unsigned) FnKind << FnDesc 9044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9045 << ToTy << Name << I+1; 9046 MaybeEmitInheritedConstructorNote(S, Fn); 9047 return; 9048 } 9049 9050 // Do some hand-waving analysis to see if the non-viability is due 9051 // to a qualifier mismatch. 9052 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9053 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9054 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9055 CToTy = RT->getPointeeType(); 9056 else { 9057 // TODO: detect and diagnose the full richness of const mismatches. 9058 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9059 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9060 CFromTy = FromPT->getPointeeType(); 9061 CToTy = ToPT->getPointeeType(); 9062 } 9063 } 9064 9065 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9066 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9067 Qualifiers FromQs = CFromTy.getQualifiers(); 9068 Qualifiers ToQs = CToTy.getQualifiers(); 9069 9070 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9072 << (unsigned) FnKind << FnDesc 9073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9074 << FromTy 9075 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9076 << (unsigned) isObjectArgument << I+1; 9077 MaybeEmitInheritedConstructorNote(S, Fn); 9078 return; 9079 } 9080 9081 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9083 << (unsigned) FnKind << FnDesc 9084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9085 << FromTy 9086 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9087 << (unsigned) isObjectArgument << I+1; 9088 MaybeEmitInheritedConstructorNote(S, Fn); 9089 return; 9090 } 9091 9092 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9094 << (unsigned) FnKind << FnDesc 9095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9096 << FromTy 9097 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9098 << (unsigned) isObjectArgument << I+1; 9099 MaybeEmitInheritedConstructorNote(S, Fn); 9100 return; 9101 } 9102 9103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9104 assert(CVR && "unexpected qualifiers mismatch"); 9105 9106 if (isObjectArgument) { 9107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9108 << (unsigned) FnKind << FnDesc 9109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9110 << FromTy << (CVR - 1); 9111 } else { 9112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9113 << (unsigned) FnKind << FnDesc 9114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9115 << FromTy << (CVR - 1) << I+1; 9116 } 9117 MaybeEmitInheritedConstructorNote(S, Fn); 9118 return; 9119 } 9120 9121 // Special diagnostic for failure to convert an initializer list, since 9122 // telling the user that it has type void is not useful. 9123 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9125 << (unsigned) FnKind << FnDesc 9126 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9127 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9128 MaybeEmitInheritedConstructorNote(S, Fn); 9129 return; 9130 } 9131 9132 // Diagnose references or pointers to incomplete types differently, 9133 // since it's far from impossible that the incompleteness triggered 9134 // the failure. 9135 QualType TempFromTy = FromTy.getNonReferenceType(); 9136 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9137 TempFromTy = PTy->getPointeeType(); 9138 if (TempFromTy->isIncompleteType()) { 9139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9140 << (unsigned) FnKind << FnDesc 9141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9142 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9143 MaybeEmitInheritedConstructorNote(S, Fn); 9144 return; 9145 } 9146 9147 // Diagnose base -> derived pointer conversions. 9148 unsigned BaseToDerivedConversion = 0; 9149 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9150 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9151 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9152 FromPtrTy->getPointeeType()) && 9153 !FromPtrTy->getPointeeType()->isIncompleteType() && 9154 !ToPtrTy->getPointeeType()->isIncompleteType() && 9155 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9156 FromPtrTy->getPointeeType())) 9157 BaseToDerivedConversion = 1; 9158 } 9159 } else if (const ObjCObjectPointerType *FromPtrTy 9160 = FromTy->getAs<ObjCObjectPointerType>()) { 9161 if (const ObjCObjectPointerType *ToPtrTy 9162 = ToTy->getAs<ObjCObjectPointerType>()) 9163 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9164 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9165 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9166 FromPtrTy->getPointeeType()) && 9167 FromIface->isSuperClassOf(ToIface)) 9168 BaseToDerivedConversion = 2; 9169 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9170 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9171 !FromTy->isIncompleteType() && 9172 !ToRefTy->getPointeeType()->isIncompleteType() && 9173 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9174 BaseToDerivedConversion = 3; 9175 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9176 ToTy.getNonReferenceType().getCanonicalType() == 9177 FromTy.getNonReferenceType().getCanonicalType()) { 9178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9179 << (unsigned) FnKind << FnDesc 9180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9181 << (unsigned) isObjectArgument << I + 1; 9182 MaybeEmitInheritedConstructorNote(S, Fn); 9183 return; 9184 } 9185 } 9186 9187 if (BaseToDerivedConversion) { 9188 S.Diag(Fn->getLocation(), 9189 diag::note_ovl_candidate_bad_base_to_derived_conv) 9190 << (unsigned) FnKind << FnDesc 9191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9192 << (BaseToDerivedConversion - 1) 9193 << FromTy << ToTy << I+1; 9194 MaybeEmitInheritedConstructorNote(S, Fn); 9195 return; 9196 } 9197 9198 if (isa<ObjCObjectPointerType>(CFromTy) && 9199 isa<PointerType>(CToTy)) { 9200 Qualifiers FromQs = CFromTy.getQualifiers(); 9201 Qualifiers ToQs = CToTy.getQualifiers(); 9202 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9204 << (unsigned) FnKind << FnDesc 9205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9206 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9207 MaybeEmitInheritedConstructorNote(S, Fn); 9208 return; 9209 } 9210 } 9211 9212 if (TakingCandidateAddress && 9213 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9214 return; 9215 9216 // Emit the generic diagnostic and, optionally, add the hints to it. 9217 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9218 FDiag << (unsigned) FnKind << FnDesc 9219 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9220 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9221 << (unsigned) (Cand->Fix.Kind); 9222 9223 // If we can fix the conversion, suggest the FixIts. 9224 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9225 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9226 FDiag << *HI; 9227 S.Diag(Fn->getLocation(), FDiag); 9228 9229 MaybeEmitInheritedConstructorNote(S, Fn); 9230 } 9231 9232 /// Additional arity mismatch diagnosis specific to a function overload 9233 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9234 /// over a candidate in any candidate set. 9235 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9236 unsigned NumArgs) { 9237 FunctionDecl *Fn = Cand->Function; 9238 unsigned MinParams = Fn->getMinRequiredArguments(); 9239 9240 // With invalid overloaded operators, it's possible that we think we 9241 // have an arity mismatch when in fact it looks like we have the 9242 // right number of arguments, because only overloaded operators have 9243 // the weird behavior of overloading member and non-member functions. 9244 // Just don't report anything. 9245 if (Fn->isInvalidDecl() && 9246 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9247 return true; 9248 9249 if (NumArgs < MinParams) { 9250 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9251 (Cand->FailureKind == ovl_fail_bad_deduction && 9252 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9253 } else { 9254 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9255 (Cand->FailureKind == ovl_fail_bad_deduction && 9256 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9257 } 9258 9259 return false; 9260 } 9261 9262 /// General arity mismatch diagnosis over a candidate in a candidate set. 9263 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9264 assert(isa<FunctionDecl>(D) && 9265 "The templated declaration should at least be a function" 9266 " when diagnosing bad template argument deduction due to too many" 9267 " or too few arguments"); 9268 9269 FunctionDecl *Fn = cast<FunctionDecl>(D); 9270 9271 // TODO: treat calls to a missing default constructor as a special case 9272 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9273 unsigned MinParams = Fn->getMinRequiredArguments(); 9274 9275 // at least / at most / exactly 9276 unsigned mode, modeCount; 9277 if (NumFormalArgs < MinParams) { 9278 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9279 FnTy->isTemplateVariadic()) 9280 mode = 0; // "at least" 9281 else 9282 mode = 2; // "exactly" 9283 modeCount = MinParams; 9284 } else { 9285 if (MinParams != FnTy->getNumParams()) 9286 mode = 1; // "at most" 9287 else 9288 mode = 2; // "exactly" 9289 modeCount = FnTy->getNumParams(); 9290 } 9291 9292 std::string Description; 9293 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9294 9295 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9297 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9298 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9299 else 9300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9301 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9302 << mode << modeCount << NumFormalArgs; 9303 MaybeEmitInheritedConstructorNote(S, Fn); 9304 } 9305 9306 /// Arity mismatch diagnosis specific to a function overload candidate. 9307 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9308 unsigned NumFormalArgs) { 9309 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9310 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9311 } 9312 9313 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9315 return FD->getDescribedFunctionTemplate(); 9316 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9317 return RD->getDescribedClassTemplate(); 9318 9319 llvm_unreachable("Unsupported: Getting the described template declaration" 9320 " for bad deduction diagnosis"); 9321 } 9322 9323 /// Diagnose a failed template-argument deduction. 9324 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9325 DeductionFailureInfo &DeductionFailure, 9326 unsigned NumArgs, 9327 bool TakingCandidateAddress) { 9328 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9329 NamedDecl *ParamD; 9330 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9331 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9332 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9333 switch (DeductionFailure.Result) { 9334 case Sema::TDK_Success: 9335 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9336 9337 case Sema::TDK_Incomplete: { 9338 assert(ParamD && "no parameter found for incomplete deduction result"); 9339 S.Diag(Templated->getLocation(), 9340 diag::note_ovl_candidate_incomplete_deduction) 9341 << ParamD->getDeclName(); 9342 MaybeEmitInheritedConstructorNote(S, Templated); 9343 return; 9344 } 9345 9346 case Sema::TDK_Underqualified: { 9347 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9348 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9349 9350 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9351 9352 // Param will have been canonicalized, but it should just be a 9353 // qualified version of ParamD, so move the qualifiers to that. 9354 QualifierCollector Qs; 9355 Qs.strip(Param); 9356 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9357 assert(S.Context.hasSameType(Param, NonCanonParam)); 9358 9359 // Arg has also been canonicalized, but there's nothing we can do 9360 // about that. It also doesn't matter as much, because it won't 9361 // have any template parameters in it (because deduction isn't 9362 // done on dependent types). 9363 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9364 9365 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9366 << ParamD->getDeclName() << Arg << NonCanonParam; 9367 MaybeEmitInheritedConstructorNote(S, Templated); 9368 return; 9369 } 9370 9371 case Sema::TDK_Inconsistent: { 9372 assert(ParamD && "no parameter found for inconsistent deduction result"); 9373 int which = 0; 9374 if (isa<TemplateTypeParmDecl>(ParamD)) 9375 which = 0; 9376 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9377 which = 1; 9378 else { 9379 which = 2; 9380 } 9381 9382 S.Diag(Templated->getLocation(), 9383 diag::note_ovl_candidate_inconsistent_deduction) 9384 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9385 << *DeductionFailure.getSecondArg(); 9386 MaybeEmitInheritedConstructorNote(S, Templated); 9387 return; 9388 } 9389 9390 case Sema::TDK_InvalidExplicitArguments: 9391 assert(ParamD && "no parameter found for invalid explicit arguments"); 9392 if (ParamD->getDeclName()) 9393 S.Diag(Templated->getLocation(), 9394 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9395 << ParamD->getDeclName(); 9396 else { 9397 int index = 0; 9398 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9399 index = TTP->getIndex(); 9400 else if (NonTypeTemplateParmDecl *NTTP 9401 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9402 index = NTTP->getIndex(); 9403 else 9404 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9405 S.Diag(Templated->getLocation(), 9406 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9407 << (index + 1); 9408 } 9409 MaybeEmitInheritedConstructorNote(S, Templated); 9410 return; 9411 9412 case Sema::TDK_TooManyArguments: 9413 case Sema::TDK_TooFewArguments: 9414 DiagnoseArityMismatch(S, Templated, NumArgs); 9415 return; 9416 9417 case Sema::TDK_InstantiationDepth: 9418 S.Diag(Templated->getLocation(), 9419 diag::note_ovl_candidate_instantiation_depth); 9420 MaybeEmitInheritedConstructorNote(S, Templated); 9421 return; 9422 9423 case Sema::TDK_SubstitutionFailure: { 9424 // Format the template argument list into the argument string. 9425 SmallString<128> TemplateArgString; 9426 if (TemplateArgumentList *Args = 9427 DeductionFailure.getTemplateArgumentList()) { 9428 TemplateArgString = " "; 9429 TemplateArgString += S.getTemplateArgumentBindingsText( 9430 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9431 } 9432 9433 // If this candidate was disabled by enable_if, say so. 9434 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9435 if (PDiag && PDiag->second.getDiagID() == 9436 diag::err_typename_nested_not_found_enable_if) { 9437 // FIXME: Use the source range of the condition, and the fully-qualified 9438 // name of the enable_if template. These are both present in PDiag. 9439 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9440 << "'enable_if'" << TemplateArgString; 9441 return; 9442 } 9443 9444 // Format the SFINAE diagnostic into the argument string. 9445 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9446 // formatted message in another diagnostic. 9447 SmallString<128> SFINAEArgString; 9448 SourceRange R; 9449 if (PDiag) { 9450 SFINAEArgString = ": "; 9451 R = SourceRange(PDiag->first, PDiag->first); 9452 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9453 } 9454 9455 S.Diag(Templated->getLocation(), 9456 diag::note_ovl_candidate_substitution_failure) 9457 << TemplateArgString << SFINAEArgString << R; 9458 MaybeEmitInheritedConstructorNote(S, Templated); 9459 return; 9460 } 9461 9462 case Sema::TDK_FailedOverloadResolution: { 9463 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9464 S.Diag(Templated->getLocation(), 9465 diag::note_ovl_candidate_failed_overload_resolution) 9466 << R.Expression->getName(); 9467 return; 9468 } 9469 9470 case Sema::TDK_DeducedMismatch: { 9471 // Format the template argument list into the argument string. 9472 SmallString<128> TemplateArgString; 9473 if (TemplateArgumentList *Args = 9474 DeductionFailure.getTemplateArgumentList()) { 9475 TemplateArgString = " "; 9476 TemplateArgString += S.getTemplateArgumentBindingsText( 9477 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9478 } 9479 9480 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9481 << (*DeductionFailure.getCallArgIndex() + 1) 9482 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9483 << TemplateArgString; 9484 break; 9485 } 9486 9487 case Sema::TDK_NonDeducedMismatch: { 9488 // FIXME: Provide a source location to indicate what we couldn't match. 9489 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9490 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9491 if (FirstTA.getKind() == TemplateArgument::Template && 9492 SecondTA.getKind() == TemplateArgument::Template) { 9493 TemplateName FirstTN = FirstTA.getAsTemplate(); 9494 TemplateName SecondTN = SecondTA.getAsTemplate(); 9495 if (FirstTN.getKind() == TemplateName::Template && 9496 SecondTN.getKind() == TemplateName::Template) { 9497 if (FirstTN.getAsTemplateDecl()->getName() == 9498 SecondTN.getAsTemplateDecl()->getName()) { 9499 // FIXME: This fixes a bad diagnostic where both templates are named 9500 // the same. This particular case is a bit difficult since: 9501 // 1) It is passed as a string to the diagnostic printer. 9502 // 2) The diagnostic printer only attempts to find a better 9503 // name for types, not decls. 9504 // Ideally, this should folded into the diagnostic printer. 9505 S.Diag(Templated->getLocation(), 9506 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9507 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9508 return; 9509 } 9510 } 9511 } 9512 9513 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9514 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9515 return; 9516 9517 // FIXME: For generic lambda parameters, check if the function is a lambda 9518 // call operator, and if so, emit a prettier and more informative 9519 // diagnostic that mentions 'auto' and lambda in addition to 9520 // (or instead of?) the canonical template type parameters. 9521 S.Diag(Templated->getLocation(), 9522 diag::note_ovl_candidate_non_deduced_mismatch) 9523 << FirstTA << SecondTA; 9524 return; 9525 } 9526 // TODO: diagnose these individually, then kill off 9527 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9528 case Sema::TDK_MiscellaneousDeductionFailure: 9529 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9530 MaybeEmitInheritedConstructorNote(S, Templated); 9531 return; 9532 } 9533 } 9534 9535 /// Diagnose a failed template-argument deduction, for function calls. 9536 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9537 unsigned NumArgs, 9538 bool TakingCandidateAddress) { 9539 unsigned TDK = Cand->DeductionFailure.Result; 9540 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9541 if (CheckArityMismatch(S, Cand, NumArgs)) 9542 return; 9543 } 9544 DiagnoseBadDeduction(S, Cand->Function, // pattern 9545 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9546 } 9547 9548 /// CUDA: diagnose an invalid call across targets. 9549 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9550 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9551 FunctionDecl *Callee = Cand->Function; 9552 9553 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9554 CalleeTarget = S.IdentifyCUDATarget(Callee); 9555 9556 std::string FnDesc; 9557 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9558 9559 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9560 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9561 9562 // This could be an implicit constructor for which we could not infer the 9563 // target due to a collsion. Diagnose that case. 9564 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9565 if (Meth != nullptr && Meth->isImplicit()) { 9566 CXXRecordDecl *ParentClass = Meth->getParent(); 9567 Sema::CXXSpecialMember CSM; 9568 9569 switch (FnKind) { 9570 default: 9571 return; 9572 case oc_implicit_default_constructor: 9573 CSM = Sema::CXXDefaultConstructor; 9574 break; 9575 case oc_implicit_copy_constructor: 9576 CSM = Sema::CXXCopyConstructor; 9577 break; 9578 case oc_implicit_move_constructor: 9579 CSM = Sema::CXXMoveConstructor; 9580 break; 9581 case oc_implicit_copy_assignment: 9582 CSM = Sema::CXXCopyAssignment; 9583 break; 9584 case oc_implicit_move_assignment: 9585 CSM = Sema::CXXMoveAssignment; 9586 break; 9587 }; 9588 9589 bool ConstRHS = false; 9590 if (Meth->getNumParams()) { 9591 if (const ReferenceType *RT = 9592 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9593 ConstRHS = RT->getPointeeType().isConstQualified(); 9594 } 9595 } 9596 9597 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9598 /* ConstRHS */ ConstRHS, 9599 /* Diagnose */ true); 9600 } 9601 } 9602 9603 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9604 FunctionDecl *Callee = Cand->Function; 9605 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9606 9607 S.Diag(Callee->getLocation(), 9608 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9609 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9610 } 9611 9612 /// Generates a 'note' diagnostic for an overload candidate. We've 9613 /// already generated a primary error at the call site. 9614 /// 9615 /// It really does need to be a single diagnostic with its caret 9616 /// pointed at the candidate declaration. Yes, this creates some 9617 /// major challenges of technical writing. Yes, this makes pointing 9618 /// out problems with specific arguments quite awkward. It's still 9619 /// better than generating twenty screens of text for every failed 9620 /// overload. 9621 /// 9622 /// It would be great to be able to express per-candidate problems 9623 /// more richly for those diagnostic clients that cared, but we'd 9624 /// still have to be just as careful with the default diagnostics. 9625 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9626 unsigned NumArgs, 9627 bool TakingCandidateAddress) { 9628 FunctionDecl *Fn = Cand->Function; 9629 9630 // Note deleted candidates, but only if they're viable. 9631 if (Cand->Viable && (Fn->isDeleted() || 9632 S.isFunctionConsideredUnavailable(Fn))) { 9633 std::string FnDesc; 9634 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9635 9636 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9637 << FnKind << FnDesc 9638 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9639 MaybeEmitInheritedConstructorNote(S, Fn); 9640 return; 9641 } 9642 9643 // We don't really have anything else to say about viable candidates. 9644 if (Cand->Viable) { 9645 S.NoteOverloadCandidate(Fn); 9646 return; 9647 } 9648 9649 switch (Cand->FailureKind) { 9650 case ovl_fail_too_many_arguments: 9651 case ovl_fail_too_few_arguments: 9652 return DiagnoseArityMismatch(S, Cand, NumArgs); 9653 9654 case ovl_fail_bad_deduction: 9655 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9656 9657 case ovl_fail_illegal_constructor: { 9658 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9659 << (Fn->getPrimaryTemplate() ? 1 : 0); 9660 MaybeEmitInheritedConstructorNote(S, Fn); 9661 return; 9662 } 9663 9664 case ovl_fail_trivial_conversion: 9665 case ovl_fail_bad_final_conversion: 9666 case ovl_fail_final_conversion_not_exact: 9667 return S.NoteOverloadCandidate(Fn); 9668 9669 case ovl_fail_bad_conversion: { 9670 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9671 for (unsigned N = Cand->NumConversions; I != N; ++I) 9672 if (Cand->Conversions[I].isBad()) 9673 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9674 9675 // FIXME: this currently happens when we're called from SemaInit 9676 // when user-conversion overload fails. Figure out how to handle 9677 // those conditions and diagnose them well. 9678 return S.NoteOverloadCandidate(Fn); 9679 } 9680 9681 case ovl_fail_bad_target: 9682 return DiagnoseBadTarget(S, Cand); 9683 9684 case ovl_fail_enable_if: 9685 return DiagnoseFailedEnableIfAttr(S, Cand); 9686 9687 case ovl_fail_addr_not_available: { 9688 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9689 (void)Available; 9690 assert(!Available); 9691 break; 9692 } 9693 } 9694 } 9695 9696 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9697 // Desugar the type of the surrogate down to a function type, 9698 // retaining as many typedefs as possible while still showing 9699 // the function type (and, therefore, its parameter types). 9700 QualType FnType = Cand->Surrogate->getConversionType(); 9701 bool isLValueReference = false; 9702 bool isRValueReference = false; 9703 bool isPointer = false; 9704 if (const LValueReferenceType *FnTypeRef = 9705 FnType->getAs<LValueReferenceType>()) { 9706 FnType = FnTypeRef->getPointeeType(); 9707 isLValueReference = true; 9708 } else if (const RValueReferenceType *FnTypeRef = 9709 FnType->getAs<RValueReferenceType>()) { 9710 FnType = FnTypeRef->getPointeeType(); 9711 isRValueReference = true; 9712 } 9713 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9714 FnType = FnTypePtr->getPointeeType(); 9715 isPointer = true; 9716 } 9717 // Desugar down to a function type. 9718 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9719 // Reconstruct the pointer/reference as appropriate. 9720 if (isPointer) FnType = S.Context.getPointerType(FnType); 9721 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9722 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9723 9724 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9725 << FnType; 9726 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9727 } 9728 9729 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9730 SourceLocation OpLoc, 9731 OverloadCandidate *Cand) { 9732 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9733 std::string TypeStr("operator"); 9734 TypeStr += Opc; 9735 TypeStr += "("; 9736 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9737 if (Cand->NumConversions == 1) { 9738 TypeStr += ")"; 9739 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9740 } else { 9741 TypeStr += ", "; 9742 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9743 TypeStr += ")"; 9744 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9745 } 9746 } 9747 9748 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9749 OverloadCandidate *Cand) { 9750 unsigned NoOperands = Cand->NumConversions; 9751 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9752 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9753 if (ICS.isBad()) break; // all meaningless after first invalid 9754 if (!ICS.isAmbiguous()) continue; 9755 9756 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9757 S.PDiag(diag::note_ambiguous_type_conversion)); 9758 } 9759 } 9760 9761 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9762 if (Cand->Function) 9763 return Cand->Function->getLocation(); 9764 if (Cand->IsSurrogate) 9765 return Cand->Surrogate->getLocation(); 9766 return SourceLocation(); 9767 } 9768 9769 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9770 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9771 case Sema::TDK_Success: 9772 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9773 9774 case Sema::TDK_Invalid: 9775 case Sema::TDK_Incomplete: 9776 return 1; 9777 9778 case Sema::TDK_Underqualified: 9779 case Sema::TDK_Inconsistent: 9780 return 2; 9781 9782 case Sema::TDK_SubstitutionFailure: 9783 case Sema::TDK_DeducedMismatch: 9784 case Sema::TDK_NonDeducedMismatch: 9785 case Sema::TDK_MiscellaneousDeductionFailure: 9786 return 3; 9787 9788 case Sema::TDK_InstantiationDepth: 9789 case Sema::TDK_FailedOverloadResolution: 9790 return 4; 9791 9792 case Sema::TDK_InvalidExplicitArguments: 9793 return 5; 9794 9795 case Sema::TDK_TooManyArguments: 9796 case Sema::TDK_TooFewArguments: 9797 return 6; 9798 } 9799 llvm_unreachable("Unhandled deduction result"); 9800 } 9801 9802 namespace { 9803 struct CompareOverloadCandidatesForDisplay { 9804 Sema &S; 9805 SourceLocation Loc; 9806 size_t NumArgs; 9807 9808 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9809 : S(S), NumArgs(nArgs) {} 9810 9811 bool operator()(const OverloadCandidate *L, 9812 const OverloadCandidate *R) { 9813 // Fast-path this check. 9814 if (L == R) return false; 9815 9816 // Order first by viability. 9817 if (L->Viable) { 9818 if (!R->Viable) return true; 9819 9820 // TODO: introduce a tri-valued comparison for overload 9821 // candidates. Would be more worthwhile if we had a sort 9822 // that could exploit it. 9823 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9824 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9825 } else if (R->Viable) 9826 return false; 9827 9828 assert(L->Viable == R->Viable); 9829 9830 // Criteria by which we can sort non-viable candidates: 9831 if (!L->Viable) { 9832 // 1. Arity mismatches come after other candidates. 9833 if (L->FailureKind == ovl_fail_too_many_arguments || 9834 L->FailureKind == ovl_fail_too_few_arguments) { 9835 if (R->FailureKind == ovl_fail_too_many_arguments || 9836 R->FailureKind == ovl_fail_too_few_arguments) { 9837 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9838 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9839 if (LDist == RDist) { 9840 if (L->FailureKind == R->FailureKind) 9841 // Sort non-surrogates before surrogates. 9842 return !L->IsSurrogate && R->IsSurrogate; 9843 // Sort candidates requiring fewer parameters than there were 9844 // arguments given after candidates requiring more parameters 9845 // than there were arguments given. 9846 return L->FailureKind == ovl_fail_too_many_arguments; 9847 } 9848 return LDist < RDist; 9849 } 9850 return false; 9851 } 9852 if (R->FailureKind == ovl_fail_too_many_arguments || 9853 R->FailureKind == ovl_fail_too_few_arguments) 9854 return true; 9855 9856 // 2. Bad conversions come first and are ordered by the number 9857 // of bad conversions and quality of good conversions. 9858 if (L->FailureKind == ovl_fail_bad_conversion) { 9859 if (R->FailureKind != ovl_fail_bad_conversion) 9860 return true; 9861 9862 // The conversion that can be fixed with a smaller number of changes, 9863 // comes first. 9864 unsigned numLFixes = L->Fix.NumConversionsFixed; 9865 unsigned numRFixes = R->Fix.NumConversionsFixed; 9866 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9867 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9868 if (numLFixes != numRFixes) { 9869 return numLFixes < numRFixes; 9870 } 9871 9872 // If there's any ordering between the defined conversions... 9873 // FIXME: this might not be transitive. 9874 assert(L->NumConversions == R->NumConversions); 9875 9876 int leftBetter = 0; 9877 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9878 for (unsigned E = L->NumConversions; I != E; ++I) { 9879 switch (CompareImplicitConversionSequences(S, Loc, 9880 L->Conversions[I], 9881 R->Conversions[I])) { 9882 case ImplicitConversionSequence::Better: 9883 leftBetter++; 9884 break; 9885 9886 case ImplicitConversionSequence::Worse: 9887 leftBetter--; 9888 break; 9889 9890 case ImplicitConversionSequence::Indistinguishable: 9891 break; 9892 } 9893 } 9894 if (leftBetter > 0) return true; 9895 if (leftBetter < 0) return false; 9896 9897 } else if (R->FailureKind == ovl_fail_bad_conversion) 9898 return false; 9899 9900 if (L->FailureKind == ovl_fail_bad_deduction) { 9901 if (R->FailureKind != ovl_fail_bad_deduction) 9902 return true; 9903 9904 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9905 return RankDeductionFailure(L->DeductionFailure) 9906 < RankDeductionFailure(R->DeductionFailure); 9907 } else if (R->FailureKind == ovl_fail_bad_deduction) 9908 return false; 9909 9910 // TODO: others? 9911 } 9912 9913 // Sort everything else by location. 9914 SourceLocation LLoc = GetLocationForCandidate(L); 9915 SourceLocation RLoc = GetLocationForCandidate(R); 9916 9917 // Put candidates without locations (e.g. builtins) at the end. 9918 if (LLoc.isInvalid()) return false; 9919 if (RLoc.isInvalid()) return true; 9920 9921 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9922 } 9923 }; 9924 } 9925 9926 /// CompleteNonViableCandidate - Normally, overload resolution only 9927 /// computes up to the first. Produces the FixIt set if possible. 9928 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9929 ArrayRef<Expr *> Args) { 9930 assert(!Cand->Viable); 9931 9932 // Don't do anything on failures other than bad conversion. 9933 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9934 9935 // We only want the FixIts if all the arguments can be corrected. 9936 bool Unfixable = false; 9937 // Use a implicit copy initialization to check conversion fixes. 9938 Cand->Fix.setConversionChecker(TryCopyInitialization); 9939 9940 // Skip forward to the first bad conversion. 9941 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9942 unsigned ConvCount = Cand->NumConversions; 9943 while (true) { 9944 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9945 ConvIdx++; 9946 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9947 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9948 break; 9949 } 9950 } 9951 9952 if (ConvIdx == ConvCount) 9953 return; 9954 9955 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9956 "remaining conversion is initialized?"); 9957 9958 // FIXME: this should probably be preserved from the overload 9959 // operation somehow. 9960 bool SuppressUserConversions = false; 9961 9962 const FunctionProtoType* Proto; 9963 unsigned ArgIdx = ConvIdx; 9964 9965 if (Cand->IsSurrogate) { 9966 QualType ConvType 9967 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9968 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9969 ConvType = ConvPtrType->getPointeeType(); 9970 Proto = ConvType->getAs<FunctionProtoType>(); 9971 ArgIdx--; 9972 } else if (Cand->Function) { 9973 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9974 if (isa<CXXMethodDecl>(Cand->Function) && 9975 !isa<CXXConstructorDecl>(Cand->Function)) 9976 ArgIdx--; 9977 } else { 9978 // Builtin binary operator with a bad first conversion. 9979 assert(ConvCount <= 3); 9980 for (; ConvIdx != ConvCount; ++ConvIdx) 9981 Cand->Conversions[ConvIdx] 9982 = TryCopyInitialization(S, Args[ConvIdx], 9983 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9984 SuppressUserConversions, 9985 /*InOverloadResolution*/ true, 9986 /*AllowObjCWritebackConversion=*/ 9987 S.getLangOpts().ObjCAutoRefCount); 9988 return; 9989 } 9990 9991 // Fill in the rest of the conversions. 9992 unsigned NumParams = Proto->getNumParams(); 9993 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9994 if (ArgIdx < NumParams) { 9995 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9996 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9997 /*InOverloadResolution=*/true, 9998 /*AllowObjCWritebackConversion=*/ 9999 S.getLangOpts().ObjCAutoRefCount); 10000 // Store the FixIt in the candidate if it exists. 10001 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10002 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10003 } 10004 else 10005 Cand->Conversions[ConvIdx].setEllipsis(); 10006 } 10007 } 10008 10009 /// PrintOverloadCandidates - When overload resolution fails, prints 10010 /// diagnostic messages containing the candidates in the candidate 10011 /// set. 10012 void OverloadCandidateSet::NoteCandidates(Sema &S, 10013 OverloadCandidateDisplayKind OCD, 10014 ArrayRef<Expr *> Args, 10015 StringRef Opc, 10016 SourceLocation OpLoc) { 10017 // Sort the candidates by viability and position. Sorting directly would 10018 // be prohibitive, so we make a set of pointers and sort those. 10019 SmallVector<OverloadCandidate*, 32> Cands; 10020 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10021 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10022 if (Cand->Viable) 10023 Cands.push_back(Cand); 10024 else if (OCD == OCD_AllCandidates) { 10025 CompleteNonViableCandidate(S, Cand, Args); 10026 if (Cand->Function || Cand->IsSurrogate) 10027 Cands.push_back(Cand); 10028 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10029 // want to list every possible builtin candidate. 10030 } 10031 } 10032 10033 std::sort(Cands.begin(), Cands.end(), 10034 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10035 10036 bool ReportedAmbiguousConversions = false; 10037 10038 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10039 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10040 unsigned CandsShown = 0; 10041 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10042 OverloadCandidate *Cand = *I; 10043 10044 // Set an arbitrary limit on the number of candidate functions we'll spam 10045 // the user with. FIXME: This limit should depend on details of the 10046 // candidate list. 10047 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10048 break; 10049 } 10050 ++CandsShown; 10051 10052 if (Cand->Function) 10053 NoteFunctionCandidate(S, Cand, Args.size(), 10054 /*TakingCandidateAddress=*/false); 10055 else if (Cand->IsSurrogate) 10056 NoteSurrogateCandidate(S, Cand); 10057 else { 10058 assert(Cand->Viable && 10059 "Non-viable built-in candidates are not added to Cands."); 10060 // Generally we only see ambiguities including viable builtin 10061 // operators if overload resolution got screwed up by an 10062 // ambiguous user-defined conversion. 10063 // 10064 // FIXME: It's quite possible for different conversions to see 10065 // different ambiguities, though. 10066 if (!ReportedAmbiguousConversions) { 10067 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10068 ReportedAmbiguousConversions = true; 10069 } 10070 10071 // If this is a viable builtin, print it. 10072 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10073 } 10074 } 10075 10076 if (I != E) 10077 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10078 } 10079 10080 static SourceLocation 10081 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10082 return Cand->Specialization ? Cand->Specialization->getLocation() 10083 : SourceLocation(); 10084 } 10085 10086 namespace { 10087 struct CompareTemplateSpecCandidatesForDisplay { 10088 Sema &S; 10089 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10090 10091 bool operator()(const TemplateSpecCandidate *L, 10092 const TemplateSpecCandidate *R) { 10093 // Fast-path this check. 10094 if (L == R) 10095 return false; 10096 10097 // Assuming that both candidates are not matches... 10098 10099 // Sort by the ranking of deduction failures. 10100 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10101 return RankDeductionFailure(L->DeductionFailure) < 10102 RankDeductionFailure(R->DeductionFailure); 10103 10104 // Sort everything else by location. 10105 SourceLocation LLoc = GetLocationForCandidate(L); 10106 SourceLocation RLoc = GetLocationForCandidate(R); 10107 10108 // Put candidates without locations (e.g. builtins) at the end. 10109 if (LLoc.isInvalid()) 10110 return false; 10111 if (RLoc.isInvalid()) 10112 return true; 10113 10114 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10115 } 10116 }; 10117 } 10118 10119 /// Diagnose a template argument deduction failure. 10120 /// We are treating these failures as overload failures due to bad 10121 /// deductions. 10122 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10123 bool ForTakingAddress) { 10124 DiagnoseBadDeduction(S, Specialization, // pattern 10125 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10126 } 10127 10128 void TemplateSpecCandidateSet::destroyCandidates() { 10129 for (iterator i = begin(), e = end(); i != e; ++i) { 10130 i->DeductionFailure.Destroy(); 10131 } 10132 } 10133 10134 void TemplateSpecCandidateSet::clear() { 10135 destroyCandidates(); 10136 Candidates.clear(); 10137 } 10138 10139 /// NoteCandidates - When no template specialization match is found, prints 10140 /// diagnostic messages containing the non-matching specializations that form 10141 /// the candidate set. 10142 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10143 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10144 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10145 // Sort the candidates by position (assuming no candidate is a match). 10146 // Sorting directly would be prohibitive, so we make a set of pointers 10147 // and sort those. 10148 SmallVector<TemplateSpecCandidate *, 32> Cands; 10149 Cands.reserve(size()); 10150 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10151 if (Cand->Specialization) 10152 Cands.push_back(Cand); 10153 // Otherwise, this is a non-matching builtin candidate. We do not, 10154 // in general, want to list every possible builtin candidate. 10155 } 10156 10157 std::sort(Cands.begin(), Cands.end(), 10158 CompareTemplateSpecCandidatesForDisplay(S)); 10159 10160 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10161 // for generalization purposes (?). 10162 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10163 10164 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10165 unsigned CandsShown = 0; 10166 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10167 TemplateSpecCandidate *Cand = *I; 10168 10169 // Set an arbitrary limit on the number of candidates we'll spam 10170 // the user with. FIXME: This limit should depend on details of the 10171 // candidate list. 10172 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10173 break; 10174 ++CandsShown; 10175 10176 assert(Cand->Specialization && 10177 "Non-matching built-in candidates are not added to Cands."); 10178 Cand->NoteDeductionFailure(S, ForTakingAddress); 10179 } 10180 10181 if (I != E) 10182 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10183 } 10184 10185 // [PossiblyAFunctionType] --> [Return] 10186 // NonFunctionType --> NonFunctionType 10187 // R (A) --> R(A) 10188 // R (*)(A) --> R (A) 10189 // R (&)(A) --> R (A) 10190 // R (S::*)(A) --> R (A) 10191 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10192 QualType Ret = PossiblyAFunctionType; 10193 if (const PointerType *ToTypePtr = 10194 PossiblyAFunctionType->getAs<PointerType>()) 10195 Ret = ToTypePtr->getPointeeType(); 10196 else if (const ReferenceType *ToTypeRef = 10197 PossiblyAFunctionType->getAs<ReferenceType>()) 10198 Ret = ToTypeRef->getPointeeType(); 10199 else if (const MemberPointerType *MemTypePtr = 10200 PossiblyAFunctionType->getAs<MemberPointerType>()) 10201 Ret = MemTypePtr->getPointeeType(); 10202 Ret = 10203 Context.getCanonicalType(Ret).getUnqualifiedType(); 10204 return Ret; 10205 } 10206 10207 namespace { 10208 // A helper class to help with address of function resolution 10209 // - allows us to avoid passing around all those ugly parameters 10210 class AddressOfFunctionResolver { 10211 Sema& S; 10212 Expr* SourceExpr; 10213 const QualType& TargetType; 10214 QualType TargetFunctionType; // Extracted function type from target type 10215 10216 bool Complain; 10217 //DeclAccessPair& ResultFunctionAccessPair; 10218 ASTContext& Context; 10219 10220 bool TargetTypeIsNonStaticMemberFunction; 10221 bool FoundNonTemplateFunction; 10222 bool StaticMemberFunctionFromBoundPointer; 10223 bool HasComplained; 10224 10225 OverloadExpr::FindResult OvlExprInfo; 10226 OverloadExpr *OvlExpr; 10227 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10228 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10229 TemplateSpecCandidateSet FailedCandidates; 10230 10231 public: 10232 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10233 const QualType &TargetType, bool Complain) 10234 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10235 Complain(Complain), Context(S.getASTContext()), 10236 TargetTypeIsNonStaticMemberFunction( 10237 !!TargetType->getAs<MemberPointerType>()), 10238 FoundNonTemplateFunction(false), 10239 StaticMemberFunctionFromBoundPointer(false), 10240 HasComplained(false), 10241 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10242 OvlExpr(OvlExprInfo.Expression), 10243 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10244 ExtractUnqualifiedFunctionTypeFromTargetType(); 10245 10246 if (TargetFunctionType->isFunctionType()) { 10247 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10248 if (!UME->isImplicitAccess() && 10249 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10250 StaticMemberFunctionFromBoundPointer = true; 10251 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10252 DeclAccessPair dap; 10253 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10254 OvlExpr, false, &dap)) { 10255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10256 if (!Method->isStatic()) { 10257 // If the target type is a non-function type and the function found 10258 // is a non-static member function, pretend as if that was the 10259 // target, it's the only possible type to end up with. 10260 TargetTypeIsNonStaticMemberFunction = true; 10261 10262 // And skip adding the function if its not in the proper form. 10263 // We'll diagnose this due to an empty set of functions. 10264 if (!OvlExprInfo.HasFormOfMemberPointer) 10265 return; 10266 } 10267 10268 Matches.push_back(std::make_pair(dap, Fn)); 10269 } 10270 return; 10271 } 10272 10273 if (OvlExpr->hasExplicitTemplateArgs()) 10274 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10275 10276 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10277 // C++ [over.over]p4: 10278 // If more than one function is selected, [...] 10279 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10280 if (FoundNonTemplateFunction) 10281 EliminateAllTemplateMatches(); 10282 else 10283 EliminateAllExceptMostSpecializedTemplate(); 10284 } 10285 } 10286 10287 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10288 Matches.size() > 1) 10289 EliminateSuboptimalCudaMatches(); 10290 } 10291 10292 bool hasComplained() const { return HasComplained; } 10293 10294 private: 10295 // Is A considered a better overload candidate for the desired type than B? 10296 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10297 return hasBetterEnableIfAttrs(S, A, B); 10298 } 10299 10300 // Returns true if we've eliminated any (read: all but one) candidates, false 10301 // otherwise. 10302 bool eliminiateSuboptimalOverloadCandidates() { 10303 // Same algorithm as overload resolution -- one pass to pick the "best", 10304 // another pass to be sure that nothing is better than the best. 10305 auto Best = Matches.begin(); 10306 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10307 if (isBetterCandidate(I->second, Best->second)) 10308 Best = I; 10309 10310 const FunctionDecl *BestFn = Best->second; 10311 auto IsBestOrInferiorToBest = [this, BestFn]( 10312 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10313 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10314 }; 10315 10316 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10317 // option, so we can potentially give the user a better error 10318 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10319 return false; 10320 Matches[0] = *Best; 10321 Matches.resize(1); 10322 return true; 10323 } 10324 10325 bool isTargetTypeAFunction() const { 10326 return TargetFunctionType->isFunctionType(); 10327 } 10328 10329 // [ToType] [Return] 10330 10331 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10332 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10333 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10334 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10335 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10336 } 10337 10338 // return true if any matching specializations were found 10339 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10340 const DeclAccessPair& CurAccessFunPair) { 10341 if (CXXMethodDecl *Method 10342 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10343 // Skip non-static function templates when converting to pointer, and 10344 // static when converting to member pointer. 10345 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10346 return false; 10347 } 10348 else if (TargetTypeIsNonStaticMemberFunction) 10349 return false; 10350 10351 // C++ [over.over]p2: 10352 // If the name is a function template, template argument deduction is 10353 // done (14.8.2.2), and if the argument deduction succeeds, the 10354 // resulting template argument list is used to generate a single 10355 // function template specialization, which is added to the set of 10356 // overloaded functions considered. 10357 FunctionDecl *Specialization = nullptr; 10358 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10359 if (Sema::TemplateDeductionResult Result 10360 = S.DeduceTemplateArguments(FunctionTemplate, 10361 &OvlExplicitTemplateArgs, 10362 TargetFunctionType, Specialization, 10363 Info, /*InOverloadResolution=*/true)) { 10364 // Make a note of the failed deduction for diagnostics. 10365 FailedCandidates.addCandidate() 10366 .set(FunctionTemplate->getTemplatedDecl(), 10367 MakeDeductionFailureInfo(Context, Result, Info)); 10368 return false; 10369 } 10370 10371 // Template argument deduction ensures that we have an exact match or 10372 // compatible pointer-to-function arguments that would be adjusted by ICS. 10373 // This function template specicalization works. 10374 assert(S.isSameOrCompatibleFunctionType( 10375 Context.getCanonicalType(Specialization->getType()), 10376 Context.getCanonicalType(TargetFunctionType))); 10377 10378 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10379 return false; 10380 10381 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10382 return true; 10383 } 10384 10385 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10386 const DeclAccessPair& CurAccessFunPair) { 10387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10388 // Skip non-static functions when converting to pointer, and static 10389 // when converting to member pointer. 10390 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10391 return false; 10392 } 10393 else if (TargetTypeIsNonStaticMemberFunction) 10394 return false; 10395 10396 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10397 if (S.getLangOpts().CUDA) 10398 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10399 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10400 return false; 10401 10402 // If any candidate has a placeholder return type, trigger its deduction 10403 // now. 10404 if (S.getLangOpts().CPlusPlus14 && 10405 FunDecl->getReturnType()->isUndeducedType() && 10406 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10407 HasComplained |= Complain; 10408 return false; 10409 } 10410 10411 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10412 return false; 10413 10414 QualType ResultTy; 10415 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10416 FunDecl->getType()) || 10417 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10418 ResultTy) || 10419 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10420 Matches.push_back(std::make_pair( 10421 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10422 FoundNonTemplateFunction = true; 10423 return true; 10424 } 10425 } 10426 10427 return false; 10428 } 10429 10430 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10431 bool Ret = false; 10432 10433 // If the overload expression doesn't have the form of a pointer to 10434 // member, don't try to convert it to a pointer-to-member type. 10435 if (IsInvalidFormOfPointerToMemberFunction()) 10436 return false; 10437 10438 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10439 E = OvlExpr->decls_end(); 10440 I != E; ++I) { 10441 // Look through any using declarations to find the underlying function. 10442 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10443 10444 // C++ [over.over]p3: 10445 // Non-member functions and static member functions match 10446 // targets of type "pointer-to-function" or "reference-to-function." 10447 // Nonstatic member functions match targets of 10448 // type "pointer-to-member-function." 10449 // Note that according to DR 247, the containing class does not matter. 10450 if (FunctionTemplateDecl *FunctionTemplate 10451 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10452 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10453 Ret = true; 10454 } 10455 // If we have explicit template arguments supplied, skip non-templates. 10456 else if (!OvlExpr->hasExplicitTemplateArgs() && 10457 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10458 Ret = true; 10459 } 10460 assert(Ret || Matches.empty()); 10461 return Ret; 10462 } 10463 10464 void EliminateAllExceptMostSpecializedTemplate() { 10465 // [...] and any given function template specialization F1 is 10466 // eliminated if the set contains a second function template 10467 // specialization whose function template is more specialized 10468 // than the function template of F1 according to the partial 10469 // ordering rules of 14.5.5.2. 10470 10471 // The algorithm specified above is quadratic. We instead use a 10472 // two-pass algorithm (similar to the one used to identify the 10473 // best viable function in an overload set) that identifies the 10474 // best function template (if it exists). 10475 10476 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10477 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10478 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10479 10480 // TODO: It looks like FailedCandidates does not serve much purpose 10481 // here, since the no_viable diagnostic has index 0. 10482 UnresolvedSetIterator Result = S.getMostSpecialized( 10483 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10484 SourceExpr->getLocStart(), S.PDiag(), 10485 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10486 .second->getDeclName(), 10487 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10488 Complain, TargetFunctionType); 10489 10490 if (Result != MatchesCopy.end()) { 10491 // Make it the first and only element 10492 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10493 Matches[0].second = cast<FunctionDecl>(*Result); 10494 Matches.resize(1); 10495 } else 10496 HasComplained |= Complain; 10497 } 10498 10499 void EliminateAllTemplateMatches() { 10500 // [...] any function template specializations in the set are 10501 // eliminated if the set also contains a non-template function, [...] 10502 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10503 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10504 ++I; 10505 else { 10506 Matches[I] = Matches[--N]; 10507 Matches.resize(N); 10508 } 10509 } 10510 } 10511 10512 void EliminateSuboptimalCudaMatches() { 10513 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10514 } 10515 10516 public: 10517 void ComplainNoMatchesFound() const { 10518 assert(Matches.empty()); 10519 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10520 << OvlExpr->getName() << TargetFunctionType 10521 << OvlExpr->getSourceRange(); 10522 if (FailedCandidates.empty()) 10523 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10524 /*TakingAddress=*/true); 10525 else { 10526 // We have some deduction failure messages. Use them to diagnose 10527 // the function templates, and diagnose the non-template candidates 10528 // normally. 10529 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10530 IEnd = OvlExpr->decls_end(); 10531 I != IEnd; ++I) 10532 if (FunctionDecl *Fun = 10533 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10534 if (!functionHasPassObjectSizeParams(Fun)) 10535 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10536 /*TakingAddress=*/true); 10537 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10538 } 10539 } 10540 10541 bool IsInvalidFormOfPointerToMemberFunction() const { 10542 return TargetTypeIsNonStaticMemberFunction && 10543 !OvlExprInfo.HasFormOfMemberPointer; 10544 } 10545 10546 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10547 // TODO: Should we condition this on whether any functions might 10548 // have matched, or is it more appropriate to do that in callers? 10549 // TODO: a fixit wouldn't hurt. 10550 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10551 << TargetType << OvlExpr->getSourceRange(); 10552 } 10553 10554 bool IsStaticMemberFunctionFromBoundPointer() const { 10555 return StaticMemberFunctionFromBoundPointer; 10556 } 10557 10558 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10559 S.Diag(OvlExpr->getLocStart(), 10560 diag::err_invalid_form_pointer_member_function) 10561 << OvlExpr->getSourceRange(); 10562 } 10563 10564 void ComplainOfInvalidConversion() const { 10565 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10566 << OvlExpr->getName() << TargetType; 10567 } 10568 10569 void ComplainMultipleMatchesFound() const { 10570 assert(Matches.size() > 1); 10571 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10572 << OvlExpr->getName() 10573 << OvlExpr->getSourceRange(); 10574 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10575 /*TakingAddress=*/true); 10576 } 10577 10578 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10579 10580 int getNumMatches() const { return Matches.size(); } 10581 10582 FunctionDecl* getMatchingFunctionDecl() const { 10583 if (Matches.size() != 1) return nullptr; 10584 return Matches[0].second; 10585 } 10586 10587 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10588 if (Matches.size() != 1) return nullptr; 10589 return &Matches[0].first; 10590 } 10591 }; 10592 } 10593 10594 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10595 /// an overloaded function (C++ [over.over]), where @p From is an 10596 /// expression with overloaded function type and @p ToType is the type 10597 /// we're trying to resolve to. For example: 10598 /// 10599 /// @code 10600 /// int f(double); 10601 /// int f(int); 10602 /// 10603 /// int (*pfd)(double) = f; // selects f(double) 10604 /// @endcode 10605 /// 10606 /// This routine returns the resulting FunctionDecl if it could be 10607 /// resolved, and NULL otherwise. When @p Complain is true, this 10608 /// routine will emit diagnostics if there is an error. 10609 FunctionDecl * 10610 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10611 QualType TargetType, 10612 bool Complain, 10613 DeclAccessPair &FoundResult, 10614 bool *pHadMultipleCandidates) { 10615 assert(AddressOfExpr->getType() == Context.OverloadTy); 10616 10617 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10618 Complain); 10619 int NumMatches = Resolver.getNumMatches(); 10620 FunctionDecl *Fn = nullptr; 10621 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10622 if (NumMatches == 0 && ShouldComplain) { 10623 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10624 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10625 else 10626 Resolver.ComplainNoMatchesFound(); 10627 } 10628 else if (NumMatches > 1 && ShouldComplain) 10629 Resolver.ComplainMultipleMatchesFound(); 10630 else if (NumMatches == 1) { 10631 Fn = Resolver.getMatchingFunctionDecl(); 10632 assert(Fn); 10633 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10634 if (Complain) { 10635 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10636 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10637 else 10638 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10639 } 10640 } 10641 10642 if (pHadMultipleCandidates) 10643 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10644 return Fn; 10645 } 10646 10647 /// \brief Given an expression that refers to an overloaded function, try to 10648 /// resolve that overloaded function expression down to a single function. 10649 /// 10650 /// This routine can only resolve template-ids that refer to a single function 10651 /// template, where that template-id refers to a single template whose template 10652 /// arguments are either provided by the template-id or have defaults, 10653 /// as described in C++0x [temp.arg.explicit]p3. 10654 /// 10655 /// If no template-ids are found, no diagnostics are emitted and NULL is 10656 /// returned. 10657 FunctionDecl * 10658 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10659 bool Complain, 10660 DeclAccessPair *FoundResult) { 10661 // C++ [over.over]p1: 10662 // [...] [Note: any redundant set of parentheses surrounding the 10663 // overloaded function name is ignored (5.1). ] 10664 // C++ [over.over]p1: 10665 // [...] The overloaded function name can be preceded by the & 10666 // operator. 10667 10668 // If we didn't actually find any template-ids, we're done. 10669 if (!ovl->hasExplicitTemplateArgs()) 10670 return nullptr; 10671 10672 TemplateArgumentListInfo ExplicitTemplateArgs; 10673 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10674 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10675 10676 // Look through all of the overloaded functions, searching for one 10677 // whose type matches exactly. 10678 FunctionDecl *Matched = nullptr; 10679 for (UnresolvedSetIterator I = ovl->decls_begin(), 10680 E = ovl->decls_end(); I != E; ++I) { 10681 // C++0x [temp.arg.explicit]p3: 10682 // [...] In contexts where deduction is done and fails, or in contexts 10683 // where deduction is not done, if a template argument list is 10684 // specified and it, along with any default template arguments, 10685 // identifies a single function template specialization, then the 10686 // template-id is an lvalue for the function template specialization. 10687 FunctionTemplateDecl *FunctionTemplate 10688 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10689 10690 // C++ [over.over]p2: 10691 // If the name is a function template, template argument deduction is 10692 // done (14.8.2.2), and if the argument deduction succeeds, the 10693 // resulting template argument list is used to generate a single 10694 // function template specialization, which is added to the set of 10695 // overloaded functions considered. 10696 FunctionDecl *Specialization = nullptr; 10697 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10698 if (TemplateDeductionResult Result 10699 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10700 Specialization, Info, 10701 /*InOverloadResolution=*/true)) { 10702 // Make a note of the failed deduction for diagnostics. 10703 // TODO: Actually use the failed-deduction info? 10704 FailedCandidates.addCandidate() 10705 .set(FunctionTemplate->getTemplatedDecl(), 10706 MakeDeductionFailureInfo(Context, Result, Info)); 10707 continue; 10708 } 10709 10710 assert(Specialization && "no specialization and no error?"); 10711 10712 // Multiple matches; we can't resolve to a single declaration. 10713 if (Matched) { 10714 if (Complain) { 10715 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10716 << ovl->getName(); 10717 NoteAllOverloadCandidates(ovl); 10718 } 10719 return nullptr; 10720 } 10721 10722 Matched = Specialization; 10723 if (FoundResult) *FoundResult = I.getPair(); 10724 } 10725 10726 if (Matched && getLangOpts().CPlusPlus14 && 10727 Matched->getReturnType()->isUndeducedType() && 10728 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10729 return nullptr; 10730 10731 return Matched; 10732 } 10733 10734 10735 10736 10737 // Resolve and fix an overloaded expression that can be resolved 10738 // because it identifies a single function template specialization. 10739 // 10740 // Last three arguments should only be supplied if Complain = true 10741 // 10742 // Return true if it was logically possible to so resolve the 10743 // expression, regardless of whether or not it succeeded. Always 10744 // returns true if 'complain' is set. 10745 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10746 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10747 bool complain, SourceRange OpRangeForComplaining, 10748 QualType DestTypeForComplaining, 10749 unsigned DiagIDForComplaining) { 10750 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10751 10752 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10753 10754 DeclAccessPair found; 10755 ExprResult SingleFunctionExpression; 10756 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10757 ovl.Expression, /*complain*/ false, &found)) { 10758 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10759 SrcExpr = ExprError(); 10760 return true; 10761 } 10762 10763 // It is only correct to resolve to an instance method if we're 10764 // resolving a form that's permitted to be a pointer to member. 10765 // Otherwise we'll end up making a bound member expression, which 10766 // is illegal in all the contexts we resolve like this. 10767 if (!ovl.HasFormOfMemberPointer && 10768 isa<CXXMethodDecl>(fn) && 10769 cast<CXXMethodDecl>(fn)->isInstance()) { 10770 if (!complain) return false; 10771 10772 Diag(ovl.Expression->getExprLoc(), 10773 diag::err_bound_member_function) 10774 << 0 << ovl.Expression->getSourceRange(); 10775 10776 // TODO: I believe we only end up here if there's a mix of 10777 // static and non-static candidates (otherwise the expression 10778 // would have 'bound member' type, not 'overload' type). 10779 // Ideally we would note which candidate was chosen and why 10780 // the static candidates were rejected. 10781 SrcExpr = ExprError(); 10782 return true; 10783 } 10784 10785 // Fix the expression to refer to 'fn'. 10786 SingleFunctionExpression = 10787 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10788 10789 // If desired, do function-to-pointer decay. 10790 if (doFunctionPointerConverion) { 10791 SingleFunctionExpression = 10792 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10793 if (SingleFunctionExpression.isInvalid()) { 10794 SrcExpr = ExprError(); 10795 return true; 10796 } 10797 } 10798 } 10799 10800 if (!SingleFunctionExpression.isUsable()) { 10801 if (complain) { 10802 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10803 << ovl.Expression->getName() 10804 << DestTypeForComplaining 10805 << OpRangeForComplaining 10806 << ovl.Expression->getQualifierLoc().getSourceRange(); 10807 NoteAllOverloadCandidates(SrcExpr.get()); 10808 10809 SrcExpr = ExprError(); 10810 return true; 10811 } 10812 10813 return false; 10814 } 10815 10816 SrcExpr = SingleFunctionExpression; 10817 return true; 10818 } 10819 10820 /// \brief Add a single candidate to the overload set. 10821 static void AddOverloadedCallCandidate(Sema &S, 10822 DeclAccessPair FoundDecl, 10823 TemplateArgumentListInfo *ExplicitTemplateArgs, 10824 ArrayRef<Expr *> Args, 10825 OverloadCandidateSet &CandidateSet, 10826 bool PartialOverloading, 10827 bool KnownValid) { 10828 NamedDecl *Callee = FoundDecl.getDecl(); 10829 if (isa<UsingShadowDecl>(Callee)) 10830 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10831 10832 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10833 if (ExplicitTemplateArgs) { 10834 assert(!KnownValid && "Explicit template arguments?"); 10835 return; 10836 } 10837 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10838 /*SuppressUsedConversions=*/false, 10839 PartialOverloading); 10840 return; 10841 } 10842 10843 if (FunctionTemplateDecl *FuncTemplate 10844 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10845 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10846 ExplicitTemplateArgs, Args, CandidateSet, 10847 /*SuppressUsedConversions=*/false, 10848 PartialOverloading); 10849 return; 10850 } 10851 10852 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10853 } 10854 10855 /// \brief Add the overload candidates named by callee and/or found by argument 10856 /// dependent lookup to the given overload set. 10857 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10858 ArrayRef<Expr *> Args, 10859 OverloadCandidateSet &CandidateSet, 10860 bool PartialOverloading) { 10861 10862 #ifndef NDEBUG 10863 // Verify that ArgumentDependentLookup is consistent with the rules 10864 // in C++0x [basic.lookup.argdep]p3: 10865 // 10866 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10867 // and let Y be the lookup set produced by argument dependent 10868 // lookup (defined as follows). If X contains 10869 // 10870 // -- a declaration of a class member, or 10871 // 10872 // -- a block-scope function declaration that is not a 10873 // using-declaration, or 10874 // 10875 // -- a declaration that is neither a function or a function 10876 // template 10877 // 10878 // then Y is empty. 10879 10880 if (ULE->requiresADL()) { 10881 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10882 E = ULE->decls_end(); I != E; ++I) { 10883 assert(!(*I)->getDeclContext()->isRecord()); 10884 assert(isa<UsingShadowDecl>(*I) || 10885 !(*I)->getDeclContext()->isFunctionOrMethod()); 10886 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10887 } 10888 } 10889 #endif 10890 10891 // It would be nice to avoid this copy. 10892 TemplateArgumentListInfo TABuffer; 10893 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10894 if (ULE->hasExplicitTemplateArgs()) { 10895 ULE->copyTemplateArgumentsInto(TABuffer); 10896 ExplicitTemplateArgs = &TABuffer; 10897 } 10898 10899 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10900 E = ULE->decls_end(); I != E; ++I) 10901 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10902 CandidateSet, PartialOverloading, 10903 /*KnownValid*/ true); 10904 10905 if (ULE->requiresADL()) 10906 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10907 Args, ExplicitTemplateArgs, 10908 CandidateSet, PartialOverloading); 10909 } 10910 10911 /// Determine whether a declaration with the specified name could be moved into 10912 /// a different namespace. 10913 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10914 switch (Name.getCXXOverloadedOperator()) { 10915 case OO_New: case OO_Array_New: 10916 case OO_Delete: case OO_Array_Delete: 10917 return false; 10918 10919 default: 10920 return true; 10921 } 10922 } 10923 10924 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10925 /// template, where the non-dependent name was declared after the template 10926 /// was defined. This is common in code written for a compilers which do not 10927 /// correctly implement two-stage name lookup. 10928 /// 10929 /// Returns true if a viable candidate was found and a diagnostic was issued. 10930 static bool 10931 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10932 const CXXScopeSpec &SS, LookupResult &R, 10933 OverloadCandidateSet::CandidateSetKind CSK, 10934 TemplateArgumentListInfo *ExplicitTemplateArgs, 10935 ArrayRef<Expr *> Args, 10936 bool *DoDiagnoseEmptyLookup = nullptr) { 10937 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10938 return false; 10939 10940 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10941 if (DC->isTransparentContext()) 10942 continue; 10943 10944 SemaRef.LookupQualifiedName(R, DC); 10945 10946 if (!R.empty()) { 10947 R.suppressDiagnostics(); 10948 10949 if (isa<CXXRecordDecl>(DC)) { 10950 // Don't diagnose names we find in classes; we get much better 10951 // diagnostics for these from DiagnoseEmptyLookup. 10952 R.clear(); 10953 if (DoDiagnoseEmptyLookup) 10954 *DoDiagnoseEmptyLookup = true; 10955 return false; 10956 } 10957 10958 OverloadCandidateSet Candidates(FnLoc, CSK); 10959 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10960 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10961 ExplicitTemplateArgs, Args, 10962 Candidates, false, /*KnownValid*/ false); 10963 10964 OverloadCandidateSet::iterator Best; 10965 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10966 // No viable functions. Don't bother the user with notes for functions 10967 // which don't work and shouldn't be found anyway. 10968 R.clear(); 10969 return false; 10970 } 10971 10972 // Find the namespaces where ADL would have looked, and suggest 10973 // declaring the function there instead. 10974 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10975 Sema::AssociatedClassSet AssociatedClasses; 10976 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10977 AssociatedNamespaces, 10978 AssociatedClasses); 10979 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10980 if (canBeDeclaredInNamespace(R.getLookupName())) { 10981 DeclContext *Std = SemaRef.getStdNamespace(); 10982 for (Sema::AssociatedNamespaceSet::iterator 10983 it = AssociatedNamespaces.begin(), 10984 end = AssociatedNamespaces.end(); it != end; ++it) { 10985 // Never suggest declaring a function within namespace 'std'. 10986 if (Std && Std->Encloses(*it)) 10987 continue; 10988 10989 // Never suggest declaring a function within a namespace with a 10990 // reserved name, like __gnu_cxx. 10991 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10992 if (NS && 10993 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10994 continue; 10995 10996 SuggestedNamespaces.insert(*it); 10997 } 10998 } 10999 11000 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11001 << R.getLookupName(); 11002 if (SuggestedNamespaces.empty()) { 11003 SemaRef.Diag(Best->Function->getLocation(), 11004 diag::note_not_found_by_two_phase_lookup) 11005 << R.getLookupName() << 0; 11006 } else if (SuggestedNamespaces.size() == 1) { 11007 SemaRef.Diag(Best->Function->getLocation(), 11008 diag::note_not_found_by_two_phase_lookup) 11009 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11010 } else { 11011 // FIXME: It would be useful to list the associated namespaces here, 11012 // but the diagnostics infrastructure doesn't provide a way to produce 11013 // a localized representation of a list of items. 11014 SemaRef.Diag(Best->Function->getLocation(), 11015 diag::note_not_found_by_two_phase_lookup) 11016 << R.getLookupName() << 2; 11017 } 11018 11019 // Try to recover by calling this function. 11020 return true; 11021 } 11022 11023 R.clear(); 11024 } 11025 11026 return false; 11027 } 11028 11029 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11030 /// template, where the non-dependent operator was declared after the template 11031 /// was defined. 11032 /// 11033 /// Returns true if a viable candidate was found and a diagnostic was issued. 11034 static bool 11035 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11036 SourceLocation OpLoc, 11037 ArrayRef<Expr *> Args) { 11038 DeclarationName OpName = 11039 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11040 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11041 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11042 OverloadCandidateSet::CSK_Operator, 11043 /*ExplicitTemplateArgs=*/nullptr, Args); 11044 } 11045 11046 namespace { 11047 class BuildRecoveryCallExprRAII { 11048 Sema &SemaRef; 11049 public: 11050 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11051 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11052 SemaRef.IsBuildingRecoveryCallExpr = true; 11053 } 11054 11055 ~BuildRecoveryCallExprRAII() { 11056 SemaRef.IsBuildingRecoveryCallExpr = false; 11057 } 11058 }; 11059 11060 } 11061 11062 static std::unique_ptr<CorrectionCandidateCallback> 11063 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11064 bool HasTemplateArgs, bool AllowTypoCorrection) { 11065 if (!AllowTypoCorrection) 11066 return llvm::make_unique<NoTypoCorrectionCCC>(); 11067 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11068 HasTemplateArgs, ME); 11069 } 11070 11071 /// Attempts to recover from a call where no functions were found. 11072 /// 11073 /// Returns true if new candidates were found. 11074 static ExprResult 11075 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11076 UnresolvedLookupExpr *ULE, 11077 SourceLocation LParenLoc, 11078 MutableArrayRef<Expr *> Args, 11079 SourceLocation RParenLoc, 11080 bool EmptyLookup, bool AllowTypoCorrection) { 11081 // Do not try to recover if it is already building a recovery call. 11082 // This stops infinite loops for template instantiations like 11083 // 11084 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11085 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11086 // 11087 if (SemaRef.IsBuildingRecoveryCallExpr) 11088 return ExprError(); 11089 BuildRecoveryCallExprRAII RCE(SemaRef); 11090 11091 CXXScopeSpec SS; 11092 SS.Adopt(ULE->getQualifierLoc()); 11093 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11094 11095 TemplateArgumentListInfo TABuffer; 11096 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11097 if (ULE->hasExplicitTemplateArgs()) { 11098 ULE->copyTemplateArgumentsInto(TABuffer); 11099 ExplicitTemplateArgs = &TABuffer; 11100 } 11101 11102 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11103 Sema::LookupOrdinaryName); 11104 bool DoDiagnoseEmptyLookup = EmptyLookup; 11105 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11106 OverloadCandidateSet::CSK_Normal, 11107 ExplicitTemplateArgs, Args, 11108 &DoDiagnoseEmptyLookup) && 11109 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11110 S, SS, R, 11111 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11112 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11113 ExplicitTemplateArgs, Args))) 11114 return ExprError(); 11115 11116 assert(!R.empty() && "lookup results empty despite recovery"); 11117 11118 // Build an implicit member call if appropriate. Just drop the 11119 // casts and such from the call, we don't really care. 11120 ExprResult NewFn = ExprError(); 11121 if ((*R.begin())->isCXXClassMember()) 11122 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11123 ExplicitTemplateArgs, S); 11124 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11125 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11126 ExplicitTemplateArgs); 11127 else 11128 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11129 11130 if (NewFn.isInvalid()) 11131 return ExprError(); 11132 11133 // This shouldn't cause an infinite loop because we're giving it 11134 // an expression with viable lookup results, which should never 11135 // end up here. 11136 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11137 MultiExprArg(Args.data(), Args.size()), 11138 RParenLoc); 11139 } 11140 11141 /// \brief Constructs and populates an OverloadedCandidateSet from 11142 /// the given function. 11143 /// \returns true when an the ExprResult output parameter has been set. 11144 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11145 UnresolvedLookupExpr *ULE, 11146 MultiExprArg Args, 11147 SourceLocation RParenLoc, 11148 OverloadCandidateSet *CandidateSet, 11149 ExprResult *Result) { 11150 #ifndef NDEBUG 11151 if (ULE->requiresADL()) { 11152 // To do ADL, we must have found an unqualified name. 11153 assert(!ULE->getQualifier() && "qualified name with ADL"); 11154 11155 // We don't perform ADL for implicit declarations of builtins. 11156 // Verify that this was correctly set up. 11157 FunctionDecl *F; 11158 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11159 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11160 F->getBuiltinID() && F->isImplicit()) 11161 llvm_unreachable("performing ADL for builtin"); 11162 11163 // We don't perform ADL in C. 11164 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11165 } 11166 #endif 11167 11168 UnbridgedCastsSet UnbridgedCasts; 11169 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11170 *Result = ExprError(); 11171 return true; 11172 } 11173 11174 // Add the functions denoted by the callee to the set of candidate 11175 // functions, including those from argument-dependent lookup. 11176 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11177 11178 if (getLangOpts().MSVCCompat && 11179 CurContext->isDependentContext() && !isSFINAEContext() && 11180 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11181 11182 OverloadCandidateSet::iterator Best; 11183 if (CandidateSet->empty() || 11184 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11185 OR_No_Viable_Function) { 11186 // In Microsoft mode, if we are inside a template class member function then 11187 // create a type dependent CallExpr. The goal is to postpone name lookup 11188 // to instantiation time to be able to search into type dependent base 11189 // classes. 11190 CallExpr *CE = new (Context) CallExpr( 11191 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11192 CE->setTypeDependent(true); 11193 CE->setValueDependent(true); 11194 CE->setInstantiationDependent(true); 11195 *Result = CE; 11196 return true; 11197 } 11198 } 11199 11200 if (CandidateSet->empty()) 11201 return false; 11202 11203 UnbridgedCasts.restore(); 11204 return false; 11205 } 11206 11207 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11208 /// the completed call expression. If overload resolution fails, emits 11209 /// diagnostics and returns ExprError() 11210 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11211 UnresolvedLookupExpr *ULE, 11212 SourceLocation LParenLoc, 11213 MultiExprArg Args, 11214 SourceLocation RParenLoc, 11215 Expr *ExecConfig, 11216 OverloadCandidateSet *CandidateSet, 11217 OverloadCandidateSet::iterator *Best, 11218 OverloadingResult OverloadResult, 11219 bool AllowTypoCorrection) { 11220 if (CandidateSet->empty()) 11221 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11222 RParenLoc, /*EmptyLookup=*/true, 11223 AllowTypoCorrection); 11224 11225 switch (OverloadResult) { 11226 case OR_Success: { 11227 FunctionDecl *FDecl = (*Best)->Function; 11228 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11229 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11230 return ExprError(); 11231 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11232 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11233 ExecConfig); 11234 } 11235 11236 case OR_No_Viable_Function: { 11237 // Try to recover by looking for viable functions which the user might 11238 // have meant to call. 11239 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11240 Args, RParenLoc, 11241 /*EmptyLookup=*/false, 11242 AllowTypoCorrection); 11243 if (!Recovery.isInvalid()) 11244 return Recovery; 11245 11246 // If the user passes in a function that we can't take the address of, we 11247 // generally end up emitting really bad error messages. Here, we attempt to 11248 // emit better ones. 11249 for (const Expr *Arg : Args) { 11250 if (!Arg->getType()->isFunctionType()) 11251 continue; 11252 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11253 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11254 if (FD && 11255 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11256 Arg->getExprLoc())) 11257 return ExprError(); 11258 } 11259 } 11260 11261 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11262 << ULE->getName() << Fn->getSourceRange(); 11263 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11264 break; 11265 } 11266 11267 case OR_Ambiguous: 11268 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11269 << ULE->getName() << Fn->getSourceRange(); 11270 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11271 break; 11272 11273 case OR_Deleted: { 11274 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11275 << (*Best)->Function->isDeleted() 11276 << ULE->getName() 11277 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11278 << Fn->getSourceRange(); 11279 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11280 11281 // We emitted an error for the unvailable/deleted function call but keep 11282 // the call in the AST. 11283 FunctionDecl *FDecl = (*Best)->Function; 11284 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11285 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11286 ExecConfig); 11287 } 11288 } 11289 11290 // Overload resolution failed. 11291 return ExprError(); 11292 } 11293 11294 static void markUnaddressableCandidatesUnviable(Sema &S, 11295 OverloadCandidateSet &CS) { 11296 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11297 if (I->Viable && 11298 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11299 I->Viable = false; 11300 I->FailureKind = ovl_fail_addr_not_available; 11301 } 11302 } 11303 } 11304 11305 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11306 /// (which eventually refers to the declaration Func) and the call 11307 /// arguments Args/NumArgs, attempt to resolve the function call down 11308 /// to a specific function. If overload resolution succeeds, returns 11309 /// the call expression produced by overload resolution. 11310 /// Otherwise, emits diagnostics and returns ExprError. 11311 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11312 UnresolvedLookupExpr *ULE, 11313 SourceLocation LParenLoc, 11314 MultiExprArg Args, 11315 SourceLocation RParenLoc, 11316 Expr *ExecConfig, 11317 bool AllowTypoCorrection, 11318 bool CalleesAddressIsTaken) { 11319 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11320 OverloadCandidateSet::CSK_Normal); 11321 ExprResult result; 11322 11323 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11324 &result)) 11325 return result; 11326 11327 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11328 // functions that aren't addressible are considered unviable. 11329 if (CalleesAddressIsTaken) 11330 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11331 11332 OverloadCandidateSet::iterator Best; 11333 OverloadingResult OverloadResult = 11334 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11335 11336 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11337 RParenLoc, ExecConfig, &CandidateSet, 11338 &Best, OverloadResult, 11339 AllowTypoCorrection); 11340 } 11341 11342 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11343 return Functions.size() > 1 || 11344 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11345 } 11346 11347 /// \brief Create a unary operation that may resolve to an overloaded 11348 /// operator. 11349 /// 11350 /// \param OpLoc The location of the operator itself (e.g., '*'). 11351 /// 11352 /// \param Opc The UnaryOperatorKind that describes this operator. 11353 /// 11354 /// \param Fns The set of non-member functions that will be 11355 /// considered by overload resolution. The caller needs to build this 11356 /// set based on the context using, e.g., 11357 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11358 /// set should not contain any member functions; those will be added 11359 /// by CreateOverloadedUnaryOp(). 11360 /// 11361 /// \param Input The input argument. 11362 ExprResult 11363 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11364 const UnresolvedSetImpl &Fns, 11365 Expr *Input) { 11366 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11367 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11368 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11369 // TODO: provide better source location info. 11370 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11371 11372 if (checkPlaceholderForOverload(*this, Input)) 11373 return ExprError(); 11374 11375 Expr *Args[2] = { Input, nullptr }; 11376 unsigned NumArgs = 1; 11377 11378 // For post-increment and post-decrement, add the implicit '0' as 11379 // the second argument, so that we know this is a post-increment or 11380 // post-decrement. 11381 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11382 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11383 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11384 SourceLocation()); 11385 NumArgs = 2; 11386 } 11387 11388 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11389 11390 if (Input->isTypeDependent()) { 11391 if (Fns.empty()) 11392 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11393 VK_RValue, OK_Ordinary, OpLoc); 11394 11395 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11396 UnresolvedLookupExpr *Fn 11397 = UnresolvedLookupExpr::Create(Context, NamingClass, 11398 NestedNameSpecifierLoc(), OpNameInfo, 11399 /*ADL*/ true, IsOverloaded(Fns), 11400 Fns.begin(), Fns.end()); 11401 return new (Context) 11402 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11403 VK_RValue, OpLoc, false); 11404 } 11405 11406 // Build an empty overload set. 11407 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11408 11409 // Add the candidates from the given function set. 11410 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11411 11412 // Add operator candidates that are member functions. 11413 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11414 11415 // Add candidates from ADL. 11416 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11417 /*ExplicitTemplateArgs*/nullptr, 11418 CandidateSet); 11419 11420 // Add builtin operator candidates. 11421 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11422 11423 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11424 11425 // Perform overload resolution. 11426 OverloadCandidateSet::iterator Best; 11427 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11428 case OR_Success: { 11429 // We found a built-in operator or an overloaded operator. 11430 FunctionDecl *FnDecl = Best->Function; 11431 11432 if (FnDecl) { 11433 // We matched an overloaded operator. Build a call to that 11434 // operator. 11435 11436 // Convert the arguments. 11437 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11438 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11439 11440 ExprResult InputRes = 11441 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11442 Best->FoundDecl, Method); 11443 if (InputRes.isInvalid()) 11444 return ExprError(); 11445 Input = InputRes.get(); 11446 } else { 11447 // Convert the arguments. 11448 ExprResult InputInit 11449 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11450 Context, 11451 FnDecl->getParamDecl(0)), 11452 SourceLocation(), 11453 Input); 11454 if (InputInit.isInvalid()) 11455 return ExprError(); 11456 Input = InputInit.get(); 11457 } 11458 11459 // Build the actual expression node. 11460 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11461 HadMultipleCandidates, OpLoc); 11462 if (FnExpr.isInvalid()) 11463 return ExprError(); 11464 11465 // Determine the result type. 11466 QualType ResultTy = FnDecl->getReturnType(); 11467 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11468 ResultTy = ResultTy.getNonLValueExprType(Context); 11469 11470 Args[0] = Input; 11471 CallExpr *TheCall = 11472 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11473 ResultTy, VK, OpLoc, false); 11474 11475 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11476 return ExprError(); 11477 11478 return MaybeBindToTemporary(TheCall); 11479 } else { 11480 // We matched a built-in operator. Convert the arguments, then 11481 // break out so that we will build the appropriate built-in 11482 // operator node. 11483 ExprResult InputRes = 11484 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11485 Best->Conversions[0], AA_Passing); 11486 if (InputRes.isInvalid()) 11487 return ExprError(); 11488 Input = InputRes.get(); 11489 break; 11490 } 11491 } 11492 11493 case OR_No_Viable_Function: 11494 // This is an erroneous use of an operator which can be overloaded by 11495 // a non-member function. Check for non-member operators which were 11496 // defined too late to be candidates. 11497 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11498 // FIXME: Recover by calling the found function. 11499 return ExprError(); 11500 11501 // No viable function; fall through to handling this as a 11502 // built-in operator, which will produce an error message for us. 11503 break; 11504 11505 case OR_Ambiguous: 11506 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11507 << UnaryOperator::getOpcodeStr(Opc) 11508 << Input->getType() 11509 << Input->getSourceRange(); 11510 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11511 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11512 return ExprError(); 11513 11514 case OR_Deleted: 11515 Diag(OpLoc, diag::err_ovl_deleted_oper) 11516 << Best->Function->isDeleted() 11517 << UnaryOperator::getOpcodeStr(Opc) 11518 << getDeletedOrUnavailableSuffix(Best->Function) 11519 << Input->getSourceRange(); 11520 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11521 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11522 return ExprError(); 11523 } 11524 11525 // Either we found no viable overloaded operator or we matched a 11526 // built-in operator. In either case, fall through to trying to 11527 // build a built-in operation. 11528 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11529 } 11530 11531 /// \brief Create a binary operation that may resolve to an overloaded 11532 /// operator. 11533 /// 11534 /// \param OpLoc The location of the operator itself (e.g., '+'). 11535 /// 11536 /// \param Opc The BinaryOperatorKind that describes this operator. 11537 /// 11538 /// \param Fns The set of non-member functions that will be 11539 /// considered by overload resolution. The caller needs to build this 11540 /// set based on the context using, e.g., 11541 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11542 /// set should not contain any member functions; those will be added 11543 /// by CreateOverloadedBinOp(). 11544 /// 11545 /// \param LHS Left-hand argument. 11546 /// \param RHS Right-hand argument. 11547 ExprResult 11548 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11549 BinaryOperatorKind Opc, 11550 const UnresolvedSetImpl &Fns, 11551 Expr *LHS, Expr *RHS) { 11552 Expr *Args[2] = { LHS, RHS }; 11553 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11554 11555 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11556 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11557 11558 // If either side is type-dependent, create an appropriate dependent 11559 // expression. 11560 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11561 if (Fns.empty()) { 11562 // If there are no functions to store, just build a dependent 11563 // BinaryOperator or CompoundAssignment. 11564 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11565 return new (Context) BinaryOperator( 11566 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11567 OpLoc, FPFeatures.fp_contract); 11568 11569 return new (Context) CompoundAssignOperator( 11570 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11571 Context.DependentTy, Context.DependentTy, OpLoc, 11572 FPFeatures.fp_contract); 11573 } 11574 11575 // FIXME: save results of ADL from here? 11576 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11577 // TODO: provide better source location info in DNLoc component. 11578 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11579 UnresolvedLookupExpr *Fn 11580 = UnresolvedLookupExpr::Create(Context, NamingClass, 11581 NestedNameSpecifierLoc(), OpNameInfo, 11582 /*ADL*/ true, IsOverloaded(Fns), 11583 Fns.begin(), Fns.end()); 11584 return new (Context) 11585 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11586 VK_RValue, OpLoc, FPFeatures.fp_contract); 11587 } 11588 11589 // Always do placeholder-like conversions on the RHS. 11590 if (checkPlaceholderForOverload(*this, Args[1])) 11591 return ExprError(); 11592 11593 // Do placeholder-like conversion on the LHS; note that we should 11594 // not get here with a PseudoObject LHS. 11595 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11596 if (checkPlaceholderForOverload(*this, Args[0])) 11597 return ExprError(); 11598 11599 // If this is the assignment operator, we only perform overload resolution 11600 // if the left-hand side is a class or enumeration type. This is actually 11601 // a hack. The standard requires that we do overload resolution between the 11602 // various built-in candidates, but as DR507 points out, this can lead to 11603 // problems. So we do it this way, which pretty much follows what GCC does. 11604 // Note that we go the traditional code path for compound assignment forms. 11605 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11606 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11607 11608 // If this is the .* operator, which is not overloadable, just 11609 // create a built-in binary operator. 11610 if (Opc == BO_PtrMemD) 11611 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11612 11613 // Build an empty overload set. 11614 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11615 11616 // Add the candidates from the given function set. 11617 AddFunctionCandidates(Fns, Args, CandidateSet); 11618 11619 // Add operator candidates that are member functions. 11620 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11621 11622 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11623 // performed for an assignment operator (nor for operator[] nor operator->, 11624 // which don't get here). 11625 if (Opc != BO_Assign) 11626 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11627 /*ExplicitTemplateArgs*/ nullptr, 11628 CandidateSet); 11629 11630 // Add builtin operator candidates. 11631 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11632 11633 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11634 11635 // Perform overload resolution. 11636 OverloadCandidateSet::iterator Best; 11637 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11638 case OR_Success: { 11639 // We found a built-in operator or an overloaded operator. 11640 FunctionDecl *FnDecl = Best->Function; 11641 11642 if (FnDecl) { 11643 // We matched an overloaded operator. Build a call to that 11644 // operator. 11645 11646 // Convert the arguments. 11647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11648 // Best->Access is only meaningful for class members. 11649 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11650 11651 ExprResult Arg1 = 11652 PerformCopyInitialization( 11653 InitializedEntity::InitializeParameter(Context, 11654 FnDecl->getParamDecl(0)), 11655 SourceLocation(), Args[1]); 11656 if (Arg1.isInvalid()) 11657 return ExprError(); 11658 11659 ExprResult Arg0 = 11660 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11661 Best->FoundDecl, Method); 11662 if (Arg0.isInvalid()) 11663 return ExprError(); 11664 Args[0] = Arg0.getAs<Expr>(); 11665 Args[1] = RHS = Arg1.getAs<Expr>(); 11666 } else { 11667 // Convert the arguments. 11668 ExprResult Arg0 = PerformCopyInitialization( 11669 InitializedEntity::InitializeParameter(Context, 11670 FnDecl->getParamDecl(0)), 11671 SourceLocation(), Args[0]); 11672 if (Arg0.isInvalid()) 11673 return ExprError(); 11674 11675 ExprResult Arg1 = 11676 PerformCopyInitialization( 11677 InitializedEntity::InitializeParameter(Context, 11678 FnDecl->getParamDecl(1)), 11679 SourceLocation(), Args[1]); 11680 if (Arg1.isInvalid()) 11681 return ExprError(); 11682 Args[0] = LHS = Arg0.getAs<Expr>(); 11683 Args[1] = RHS = Arg1.getAs<Expr>(); 11684 } 11685 11686 // Build the actual expression node. 11687 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11688 Best->FoundDecl, 11689 HadMultipleCandidates, OpLoc); 11690 if (FnExpr.isInvalid()) 11691 return ExprError(); 11692 11693 // Determine the result type. 11694 QualType ResultTy = FnDecl->getReturnType(); 11695 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11696 ResultTy = ResultTy.getNonLValueExprType(Context); 11697 11698 CXXOperatorCallExpr *TheCall = 11699 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11700 Args, ResultTy, VK, OpLoc, 11701 FPFeatures.fp_contract); 11702 11703 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11704 FnDecl)) 11705 return ExprError(); 11706 11707 ArrayRef<const Expr *> ArgsArray(Args, 2); 11708 // Cut off the implicit 'this'. 11709 if (isa<CXXMethodDecl>(FnDecl)) 11710 ArgsArray = ArgsArray.slice(1); 11711 11712 // Check for a self move. 11713 if (Op == OO_Equal) 11714 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11715 11716 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11717 TheCall->getSourceRange(), VariadicDoesNotApply); 11718 11719 return MaybeBindToTemporary(TheCall); 11720 } else { 11721 // We matched a built-in operator. Convert the arguments, then 11722 // break out so that we will build the appropriate built-in 11723 // operator node. 11724 ExprResult ArgsRes0 = 11725 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11726 Best->Conversions[0], AA_Passing); 11727 if (ArgsRes0.isInvalid()) 11728 return ExprError(); 11729 Args[0] = ArgsRes0.get(); 11730 11731 ExprResult ArgsRes1 = 11732 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11733 Best->Conversions[1], AA_Passing); 11734 if (ArgsRes1.isInvalid()) 11735 return ExprError(); 11736 Args[1] = ArgsRes1.get(); 11737 break; 11738 } 11739 } 11740 11741 case OR_No_Viable_Function: { 11742 // C++ [over.match.oper]p9: 11743 // If the operator is the operator , [...] and there are no 11744 // viable functions, then the operator is assumed to be the 11745 // built-in operator and interpreted according to clause 5. 11746 if (Opc == BO_Comma) 11747 break; 11748 11749 // For class as left operand for assignment or compound assigment 11750 // operator do not fall through to handling in built-in, but report that 11751 // no overloaded assignment operator found 11752 ExprResult Result = ExprError(); 11753 if (Args[0]->getType()->isRecordType() && 11754 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11755 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11756 << BinaryOperator::getOpcodeStr(Opc) 11757 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11758 if (Args[0]->getType()->isIncompleteType()) { 11759 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11760 << Args[0]->getType() 11761 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11762 } 11763 } else { 11764 // This is an erroneous use of an operator which can be overloaded by 11765 // a non-member function. Check for non-member operators which were 11766 // defined too late to be candidates. 11767 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11768 // FIXME: Recover by calling the found function. 11769 return ExprError(); 11770 11771 // No viable function; try to create a built-in operation, which will 11772 // produce an error. Then, show the non-viable candidates. 11773 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11774 } 11775 assert(Result.isInvalid() && 11776 "C++ binary operator overloading is missing candidates!"); 11777 if (Result.isInvalid()) 11778 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11779 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11780 return Result; 11781 } 11782 11783 case OR_Ambiguous: 11784 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11785 << BinaryOperator::getOpcodeStr(Opc) 11786 << Args[0]->getType() << Args[1]->getType() 11787 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11788 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11789 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11790 return ExprError(); 11791 11792 case OR_Deleted: 11793 if (isImplicitlyDeleted(Best->Function)) { 11794 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11795 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11796 << Context.getRecordType(Method->getParent()) 11797 << getSpecialMember(Method); 11798 11799 // The user probably meant to call this special member. Just 11800 // explain why it's deleted. 11801 NoteDeletedFunction(Method); 11802 return ExprError(); 11803 } else { 11804 Diag(OpLoc, diag::err_ovl_deleted_oper) 11805 << Best->Function->isDeleted() 11806 << BinaryOperator::getOpcodeStr(Opc) 11807 << getDeletedOrUnavailableSuffix(Best->Function) 11808 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11809 } 11810 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11811 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11812 return ExprError(); 11813 } 11814 11815 // We matched a built-in operator; build it. 11816 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11817 } 11818 11819 ExprResult 11820 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11821 SourceLocation RLoc, 11822 Expr *Base, Expr *Idx) { 11823 Expr *Args[2] = { Base, Idx }; 11824 DeclarationName OpName = 11825 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11826 11827 // If either side is type-dependent, create an appropriate dependent 11828 // expression. 11829 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11830 11831 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11832 // CHECKME: no 'operator' keyword? 11833 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11834 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11835 UnresolvedLookupExpr *Fn 11836 = UnresolvedLookupExpr::Create(Context, NamingClass, 11837 NestedNameSpecifierLoc(), OpNameInfo, 11838 /*ADL*/ true, /*Overloaded*/ false, 11839 UnresolvedSetIterator(), 11840 UnresolvedSetIterator()); 11841 // Can't add any actual overloads yet 11842 11843 return new (Context) 11844 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11845 Context.DependentTy, VK_RValue, RLoc, false); 11846 } 11847 11848 // Handle placeholders on both operands. 11849 if (checkPlaceholderForOverload(*this, Args[0])) 11850 return ExprError(); 11851 if (checkPlaceholderForOverload(*this, Args[1])) 11852 return ExprError(); 11853 11854 // Build an empty overload set. 11855 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11856 11857 // Subscript can only be overloaded as a member function. 11858 11859 // Add operator candidates that are member functions. 11860 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11861 11862 // Add builtin operator candidates. 11863 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11864 11865 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11866 11867 // Perform overload resolution. 11868 OverloadCandidateSet::iterator Best; 11869 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11870 case OR_Success: { 11871 // We found a built-in operator or an overloaded operator. 11872 FunctionDecl *FnDecl = Best->Function; 11873 11874 if (FnDecl) { 11875 // We matched an overloaded operator. Build a call to that 11876 // operator. 11877 11878 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11879 11880 // Convert the arguments. 11881 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11882 ExprResult Arg0 = 11883 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11884 Best->FoundDecl, Method); 11885 if (Arg0.isInvalid()) 11886 return ExprError(); 11887 Args[0] = Arg0.get(); 11888 11889 // Convert the arguments. 11890 ExprResult InputInit 11891 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11892 Context, 11893 FnDecl->getParamDecl(0)), 11894 SourceLocation(), 11895 Args[1]); 11896 if (InputInit.isInvalid()) 11897 return ExprError(); 11898 11899 Args[1] = InputInit.getAs<Expr>(); 11900 11901 // Build the actual expression node. 11902 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11903 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11904 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11905 Best->FoundDecl, 11906 HadMultipleCandidates, 11907 OpLocInfo.getLoc(), 11908 OpLocInfo.getInfo()); 11909 if (FnExpr.isInvalid()) 11910 return ExprError(); 11911 11912 // Determine the result type 11913 QualType ResultTy = FnDecl->getReturnType(); 11914 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11915 ResultTy = ResultTy.getNonLValueExprType(Context); 11916 11917 CXXOperatorCallExpr *TheCall = 11918 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11919 FnExpr.get(), Args, 11920 ResultTy, VK, RLoc, 11921 false); 11922 11923 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11924 return ExprError(); 11925 11926 return MaybeBindToTemporary(TheCall); 11927 } else { 11928 // We matched a built-in operator. Convert the arguments, then 11929 // break out so that we will build the appropriate built-in 11930 // operator node. 11931 ExprResult ArgsRes0 = 11932 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11933 Best->Conversions[0], AA_Passing); 11934 if (ArgsRes0.isInvalid()) 11935 return ExprError(); 11936 Args[0] = ArgsRes0.get(); 11937 11938 ExprResult ArgsRes1 = 11939 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11940 Best->Conversions[1], AA_Passing); 11941 if (ArgsRes1.isInvalid()) 11942 return ExprError(); 11943 Args[1] = ArgsRes1.get(); 11944 11945 break; 11946 } 11947 } 11948 11949 case OR_No_Viable_Function: { 11950 if (CandidateSet.empty()) 11951 Diag(LLoc, diag::err_ovl_no_oper) 11952 << Args[0]->getType() << /*subscript*/ 0 11953 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11954 else 11955 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11956 << Args[0]->getType() 11957 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11959 "[]", LLoc); 11960 return ExprError(); 11961 } 11962 11963 case OR_Ambiguous: 11964 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11965 << "[]" 11966 << Args[0]->getType() << Args[1]->getType() 11967 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11968 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11969 "[]", LLoc); 11970 return ExprError(); 11971 11972 case OR_Deleted: 11973 Diag(LLoc, diag::err_ovl_deleted_oper) 11974 << Best->Function->isDeleted() << "[]" 11975 << getDeletedOrUnavailableSuffix(Best->Function) 11976 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11977 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11978 "[]", LLoc); 11979 return ExprError(); 11980 } 11981 11982 // We matched a built-in operator; build it. 11983 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11984 } 11985 11986 /// BuildCallToMemberFunction - Build a call to a member 11987 /// function. MemExpr is the expression that refers to the member 11988 /// function (and includes the object parameter), Args/NumArgs are the 11989 /// arguments to the function call (not including the object 11990 /// parameter). The caller needs to validate that the member 11991 /// expression refers to a non-static member function or an overloaded 11992 /// member function. 11993 ExprResult 11994 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11995 SourceLocation LParenLoc, 11996 MultiExprArg Args, 11997 SourceLocation RParenLoc) { 11998 assert(MemExprE->getType() == Context.BoundMemberTy || 11999 MemExprE->getType() == Context.OverloadTy); 12000 12001 // Dig out the member expression. This holds both the object 12002 // argument and the member function we're referring to. 12003 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12004 12005 // Determine whether this is a call to a pointer-to-member function. 12006 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12007 assert(op->getType() == Context.BoundMemberTy); 12008 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12009 12010 QualType fnType = 12011 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12012 12013 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12014 QualType resultType = proto->getCallResultType(Context); 12015 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12016 12017 // Check that the object type isn't more qualified than the 12018 // member function we're calling. 12019 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12020 12021 QualType objectType = op->getLHS()->getType(); 12022 if (op->getOpcode() == BO_PtrMemI) 12023 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12024 Qualifiers objectQuals = objectType.getQualifiers(); 12025 12026 Qualifiers difference = objectQuals - funcQuals; 12027 difference.removeObjCGCAttr(); 12028 difference.removeAddressSpace(); 12029 if (difference) { 12030 std::string qualsString = difference.getAsString(); 12031 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12032 << fnType.getUnqualifiedType() 12033 << qualsString 12034 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12035 } 12036 12037 CXXMemberCallExpr *call 12038 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12039 resultType, valueKind, RParenLoc); 12040 12041 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12042 call, nullptr)) 12043 return ExprError(); 12044 12045 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12046 return ExprError(); 12047 12048 if (CheckOtherCall(call, proto)) 12049 return ExprError(); 12050 12051 return MaybeBindToTemporary(call); 12052 } 12053 12054 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12055 return new (Context) 12056 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12057 12058 UnbridgedCastsSet UnbridgedCasts; 12059 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12060 return ExprError(); 12061 12062 MemberExpr *MemExpr; 12063 CXXMethodDecl *Method = nullptr; 12064 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12065 NestedNameSpecifier *Qualifier = nullptr; 12066 if (isa<MemberExpr>(NakedMemExpr)) { 12067 MemExpr = cast<MemberExpr>(NakedMemExpr); 12068 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12069 FoundDecl = MemExpr->getFoundDecl(); 12070 Qualifier = MemExpr->getQualifier(); 12071 UnbridgedCasts.restore(); 12072 } else { 12073 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12074 Qualifier = UnresExpr->getQualifier(); 12075 12076 QualType ObjectType = UnresExpr->getBaseType(); 12077 Expr::Classification ObjectClassification 12078 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12079 : UnresExpr->getBase()->Classify(Context); 12080 12081 // Add overload candidates 12082 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12083 OverloadCandidateSet::CSK_Normal); 12084 12085 // FIXME: avoid copy. 12086 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12087 if (UnresExpr->hasExplicitTemplateArgs()) { 12088 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12089 TemplateArgs = &TemplateArgsBuffer; 12090 } 12091 12092 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12093 E = UnresExpr->decls_end(); I != E; ++I) { 12094 12095 NamedDecl *Func = *I; 12096 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12097 if (isa<UsingShadowDecl>(Func)) 12098 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12099 12100 12101 // Microsoft supports direct constructor calls. 12102 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12103 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12104 Args, CandidateSet); 12105 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12106 // If explicit template arguments were provided, we can't call a 12107 // non-template member function. 12108 if (TemplateArgs) 12109 continue; 12110 12111 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12112 ObjectClassification, Args, CandidateSet, 12113 /*SuppressUserConversions=*/false); 12114 } else { 12115 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12116 I.getPair(), ActingDC, TemplateArgs, 12117 ObjectType, ObjectClassification, 12118 Args, CandidateSet, 12119 /*SuppressUsedConversions=*/false); 12120 } 12121 } 12122 12123 DeclarationName DeclName = UnresExpr->getMemberName(); 12124 12125 UnbridgedCasts.restore(); 12126 12127 OverloadCandidateSet::iterator Best; 12128 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12129 Best)) { 12130 case OR_Success: 12131 Method = cast<CXXMethodDecl>(Best->Function); 12132 FoundDecl = Best->FoundDecl; 12133 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12134 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12135 return ExprError(); 12136 // If FoundDecl is different from Method (such as if one is a template 12137 // and the other a specialization), make sure DiagnoseUseOfDecl is 12138 // called on both. 12139 // FIXME: This would be more comprehensively addressed by modifying 12140 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12141 // being used. 12142 if (Method != FoundDecl.getDecl() && 12143 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12144 return ExprError(); 12145 break; 12146 12147 case OR_No_Viable_Function: 12148 Diag(UnresExpr->getMemberLoc(), 12149 diag::err_ovl_no_viable_member_function_in_call) 12150 << DeclName << MemExprE->getSourceRange(); 12151 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12152 // FIXME: Leaking incoming expressions! 12153 return ExprError(); 12154 12155 case OR_Ambiguous: 12156 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12157 << DeclName << MemExprE->getSourceRange(); 12158 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12159 // FIXME: Leaking incoming expressions! 12160 return ExprError(); 12161 12162 case OR_Deleted: 12163 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12164 << Best->Function->isDeleted() 12165 << DeclName 12166 << getDeletedOrUnavailableSuffix(Best->Function) 12167 << MemExprE->getSourceRange(); 12168 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12169 // FIXME: Leaking incoming expressions! 12170 return ExprError(); 12171 } 12172 12173 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12174 12175 // If overload resolution picked a static member, build a 12176 // non-member call based on that function. 12177 if (Method->isStatic()) { 12178 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12179 RParenLoc); 12180 } 12181 12182 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12183 } 12184 12185 QualType ResultType = Method->getReturnType(); 12186 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12187 ResultType = ResultType.getNonLValueExprType(Context); 12188 12189 assert(Method && "Member call to something that isn't a method?"); 12190 CXXMemberCallExpr *TheCall = 12191 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12192 ResultType, VK, RParenLoc); 12193 12194 // (CUDA B.1): Check for invalid calls between targets. 12195 if (getLangOpts().CUDA) { 12196 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12197 if (CheckCUDATarget(Caller, Method)) { 12198 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12199 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12200 << IdentifyCUDATarget(Caller); 12201 return ExprError(); 12202 } 12203 } 12204 } 12205 12206 // Check for a valid return type. 12207 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12208 TheCall, Method)) 12209 return ExprError(); 12210 12211 // Convert the object argument (for a non-static member function call). 12212 // We only need to do this if there was actually an overload; otherwise 12213 // it was done at lookup. 12214 if (!Method->isStatic()) { 12215 ExprResult ObjectArg = 12216 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12217 FoundDecl, Method); 12218 if (ObjectArg.isInvalid()) 12219 return ExprError(); 12220 MemExpr->setBase(ObjectArg.get()); 12221 } 12222 12223 // Convert the rest of the arguments 12224 const FunctionProtoType *Proto = 12225 Method->getType()->getAs<FunctionProtoType>(); 12226 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12227 RParenLoc)) 12228 return ExprError(); 12229 12230 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12231 12232 if (CheckFunctionCall(Method, TheCall, Proto)) 12233 return ExprError(); 12234 12235 // In the case the method to call was not selected by the overloading 12236 // resolution process, we still need to handle the enable_if attribute. Do 12237 // that here, so it will not hide previous -- and more relevant -- errors 12238 if (isa<MemberExpr>(NakedMemExpr)) { 12239 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12240 Diag(MemExprE->getLocStart(), 12241 diag::err_ovl_no_viable_member_function_in_call) 12242 << Method << Method->getSourceRange(); 12243 Diag(Method->getLocation(), 12244 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12245 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12246 return ExprError(); 12247 } 12248 } 12249 12250 if ((isa<CXXConstructorDecl>(CurContext) || 12251 isa<CXXDestructorDecl>(CurContext)) && 12252 TheCall->getMethodDecl()->isPure()) { 12253 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12254 12255 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12256 MemExpr->performsVirtualDispatch(getLangOpts())) { 12257 Diag(MemExpr->getLocStart(), 12258 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12259 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12260 << MD->getParent()->getDeclName(); 12261 12262 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12263 if (getLangOpts().AppleKext) 12264 Diag(MemExpr->getLocStart(), 12265 diag::note_pure_qualified_call_kext) 12266 << MD->getParent()->getDeclName() 12267 << MD->getDeclName(); 12268 } 12269 } 12270 12271 if (CXXDestructorDecl *DD = 12272 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12273 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12274 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() || 12275 getLangOpts().AppleKext; 12276 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12277 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12278 MemExpr->getMemberLoc()); 12279 } 12280 12281 return MaybeBindToTemporary(TheCall); 12282 } 12283 12284 /// BuildCallToObjectOfClassType - Build a call to an object of class 12285 /// type (C++ [over.call.object]), which can end up invoking an 12286 /// overloaded function call operator (@c operator()) or performing a 12287 /// user-defined conversion on the object argument. 12288 ExprResult 12289 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12290 SourceLocation LParenLoc, 12291 MultiExprArg Args, 12292 SourceLocation RParenLoc) { 12293 if (checkPlaceholderForOverload(*this, Obj)) 12294 return ExprError(); 12295 ExprResult Object = Obj; 12296 12297 UnbridgedCastsSet UnbridgedCasts; 12298 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12299 return ExprError(); 12300 12301 assert(Object.get()->getType()->isRecordType() && 12302 "Requires object type argument"); 12303 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12304 12305 // C++ [over.call.object]p1: 12306 // If the primary-expression E in the function call syntax 12307 // evaluates to a class object of type "cv T", then the set of 12308 // candidate functions includes at least the function call 12309 // operators of T. The function call operators of T are obtained by 12310 // ordinary lookup of the name operator() in the context of 12311 // (E).operator(). 12312 OverloadCandidateSet CandidateSet(LParenLoc, 12313 OverloadCandidateSet::CSK_Operator); 12314 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12315 12316 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12317 diag::err_incomplete_object_call, Object.get())) 12318 return true; 12319 12320 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12321 LookupQualifiedName(R, Record->getDecl()); 12322 R.suppressDiagnostics(); 12323 12324 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12325 Oper != OperEnd; ++Oper) { 12326 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12327 Object.get()->Classify(Context), 12328 Args, CandidateSet, 12329 /*SuppressUserConversions=*/ false); 12330 } 12331 12332 // C++ [over.call.object]p2: 12333 // In addition, for each (non-explicit in C++0x) conversion function 12334 // declared in T of the form 12335 // 12336 // operator conversion-type-id () cv-qualifier; 12337 // 12338 // where cv-qualifier is the same cv-qualification as, or a 12339 // greater cv-qualification than, cv, and where conversion-type-id 12340 // denotes the type "pointer to function of (P1,...,Pn) returning 12341 // R", or the type "reference to pointer to function of 12342 // (P1,...,Pn) returning R", or the type "reference to function 12343 // of (P1,...,Pn) returning R", a surrogate call function [...] 12344 // is also considered as a candidate function. Similarly, 12345 // surrogate call functions are added to the set of candidate 12346 // functions for each conversion function declared in an 12347 // accessible base class provided the function is not hidden 12348 // within T by another intervening declaration. 12349 const auto &Conversions = 12350 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12351 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12352 NamedDecl *D = *I; 12353 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12354 if (isa<UsingShadowDecl>(D)) 12355 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12356 12357 // Skip over templated conversion functions; they aren't 12358 // surrogates. 12359 if (isa<FunctionTemplateDecl>(D)) 12360 continue; 12361 12362 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12363 if (!Conv->isExplicit()) { 12364 // Strip the reference type (if any) and then the pointer type (if 12365 // any) to get down to what might be a function type. 12366 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12367 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12368 ConvType = ConvPtrType->getPointeeType(); 12369 12370 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12371 { 12372 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12373 Object.get(), Args, CandidateSet); 12374 } 12375 } 12376 } 12377 12378 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12379 12380 // Perform overload resolution. 12381 OverloadCandidateSet::iterator Best; 12382 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12383 Best)) { 12384 case OR_Success: 12385 // Overload resolution succeeded; we'll build the appropriate call 12386 // below. 12387 break; 12388 12389 case OR_No_Viable_Function: 12390 if (CandidateSet.empty()) 12391 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12392 << Object.get()->getType() << /*call*/ 1 12393 << Object.get()->getSourceRange(); 12394 else 12395 Diag(Object.get()->getLocStart(), 12396 diag::err_ovl_no_viable_object_call) 12397 << Object.get()->getType() << Object.get()->getSourceRange(); 12398 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12399 break; 12400 12401 case OR_Ambiguous: 12402 Diag(Object.get()->getLocStart(), 12403 diag::err_ovl_ambiguous_object_call) 12404 << Object.get()->getType() << Object.get()->getSourceRange(); 12405 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12406 break; 12407 12408 case OR_Deleted: 12409 Diag(Object.get()->getLocStart(), 12410 diag::err_ovl_deleted_object_call) 12411 << Best->Function->isDeleted() 12412 << Object.get()->getType() 12413 << getDeletedOrUnavailableSuffix(Best->Function) 12414 << Object.get()->getSourceRange(); 12415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12416 break; 12417 } 12418 12419 if (Best == CandidateSet.end()) 12420 return true; 12421 12422 UnbridgedCasts.restore(); 12423 12424 if (Best->Function == nullptr) { 12425 // Since there is no function declaration, this is one of the 12426 // surrogate candidates. Dig out the conversion function. 12427 CXXConversionDecl *Conv 12428 = cast<CXXConversionDecl>( 12429 Best->Conversions[0].UserDefined.ConversionFunction); 12430 12431 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12432 Best->FoundDecl); 12433 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12434 return ExprError(); 12435 assert(Conv == Best->FoundDecl.getDecl() && 12436 "Found Decl & conversion-to-functionptr should be same, right?!"); 12437 // We selected one of the surrogate functions that converts the 12438 // object parameter to a function pointer. Perform the conversion 12439 // on the object argument, then let ActOnCallExpr finish the job. 12440 12441 // Create an implicit member expr to refer to the conversion operator. 12442 // and then call it. 12443 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12444 Conv, HadMultipleCandidates); 12445 if (Call.isInvalid()) 12446 return ExprError(); 12447 // Record usage of conversion in an implicit cast. 12448 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12449 CK_UserDefinedConversion, Call.get(), 12450 nullptr, VK_RValue); 12451 12452 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12453 } 12454 12455 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12456 12457 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12458 // that calls this method, using Object for the implicit object 12459 // parameter and passing along the remaining arguments. 12460 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12461 12462 // An error diagnostic has already been printed when parsing the declaration. 12463 if (Method->isInvalidDecl()) 12464 return ExprError(); 12465 12466 const FunctionProtoType *Proto = 12467 Method->getType()->getAs<FunctionProtoType>(); 12468 12469 unsigned NumParams = Proto->getNumParams(); 12470 12471 DeclarationNameInfo OpLocInfo( 12472 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12473 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12474 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12475 HadMultipleCandidates, 12476 OpLocInfo.getLoc(), 12477 OpLocInfo.getInfo()); 12478 if (NewFn.isInvalid()) 12479 return true; 12480 12481 // Build the full argument list for the method call (the implicit object 12482 // parameter is placed at the beginning of the list). 12483 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12484 MethodArgs[0] = Object.get(); 12485 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12486 12487 // Once we've built TheCall, all of the expressions are properly 12488 // owned. 12489 QualType ResultTy = Method->getReturnType(); 12490 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12491 ResultTy = ResultTy.getNonLValueExprType(Context); 12492 12493 CXXOperatorCallExpr *TheCall = new (Context) 12494 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12495 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12496 ResultTy, VK, RParenLoc, false); 12497 MethodArgs.reset(); 12498 12499 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12500 return true; 12501 12502 // We may have default arguments. If so, we need to allocate more 12503 // slots in the call for them. 12504 if (Args.size() < NumParams) 12505 TheCall->setNumArgs(Context, NumParams + 1); 12506 12507 bool IsError = false; 12508 12509 // Initialize the implicit object parameter. 12510 ExprResult ObjRes = 12511 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12512 Best->FoundDecl, Method); 12513 if (ObjRes.isInvalid()) 12514 IsError = true; 12515 else 12516 Object = ObjRes; 12517 TheCall->setArg(0, Object.get()); 12518 12519 // Check the argument types. 12520 for (unsigned i = 0; i != NumParams; i++) { 12521 Expr *Arg; 12522 if (i < Args.size()) { 12523 Arg = Args[i]; 12524 12525 // Pass the argument. 12526 12527 ExprResult InputInit 12528 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12529 Context, 12530 Method->getParamDecl(i)), 12531 SourceLocation(), Arg); 12532 12533 IsError |= InputInit.isInvalid(); 12534 Arg = InputInit.getAs<Expr>(); 12535 } else { 12536 ExprResult DefArg 12537 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12538 if (DefArg.isInvalid()) { 12539 IsError = true; 12540 break; 12541 } 12542 12543 Arg = DefArg.getAs<Expr>(); 12544 } 12545 12546 TheCall->setArg(i + 1, Arg); 12547 } 12548 12549 // If this is a variadic call, handle args passed through "...". 12550 if (Proto->isVariadic()) { 12551 // Promote the arguments (C99 6.5.2.2p7). 12552 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12553 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12554 nullptr); 12555 IsError |= Arg.isInvalid(); 12556 TheCall->setArg(i + 1, Arg.get()); 12557 } 12558 } 12559 12560 if (IsError) return true; 12561 12562 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12563 12564 if (CheckFunctionCall(Method, TheCall, Proto)) 12565 return true; 12566 12567 return MaybeBindToTemporary(TheCall); 12568 } 12569 12570 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12571 /// (if one exists), where @c Base is an expression of class type and 12572 /// @c Member is the name of the member we're trying to find. 12573 ExprResult 12574 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12575 bool *NoArrowOperatorFound) { 12576 assert(Base->getType()->isRecordType() && 12577 "left-hand side must have class type"); 12578 12579 if (checkPlaceholderForOverload(*this, Base)) 12580 return ExprError(); 12581 12582 SourceLocation Loc = Base->getExprLoc(); 12583 12584 // C++ [over.ref]p1: 12585 // 12586 // [...] An expression x->m is interpreted as (x.operator->())->m 12587 // for a class object x of type T if T::operator->() exists and if 12588 // the operator is selected as the best match function by the 12589 // overload resolution mechanism (13.3). 12590 DeclarationName OpName = 12591 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12592 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12593 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12594 12595 if (RequireCompleteType(Loc, Base->getType(), 12596 diag::err_typecheck_incomplete_tag, Base)) 12597 return ExprError(); 12598 12599 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12600 LookupQualifiedName(R, BaseRecord->getDecl()); 12601 R.suppressDiagnostics(); 12602 12603 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12604 Oper != OperEnd; ++Oper) { 12605 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12606 None, CandidateSet, /*SuppressUserConversions=*/false); 12607 } 12608 12609 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12610 12611 // Perform overload resolution. 12612 OverloadCandidateSet::iterator Best; 12613 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12614 case OR_Success: 12615 // Overload resolution succeeded; we'll build the call below. 12616 break; 12617 12618 case OR_No_Viable_Function: 12619 if (CandidateSet.empty()) { 12620 QualType BaseType = Base->getType(); 12621 if (NoArrowOperatorFound) { 12622 // Report this specific error to the caller instead of emitting a 12623 // diagnostic, as requested. 12624 *NoArrowOperatorFound = true; 12625 return ExprError(); 12626 } 12627 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12628 << BaseType << Base->getSourceRange(); 12629 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12630 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12631 << FixItHint::CreateReplacement(OpLoc, "."); 12632 } 12633 } else 12634 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12635 << "operator->" << Base->getSourceRange(); 12636 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12637 return ExprError(); 12638 12639 case OR_Ambiguous: 12640 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12641 << "->" << Base->getType() << Base->getSourceRange(); 12642 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12643 return ExprError(); 12644 12645 case OR_Deleted: 12646 Diag(OpLoc, diag::err_ovl_deleted_oper) 12647 << Best->Function->isDeleted() 12648 << "->" 12649 << getDeletedOrUnavailableSuffix(Best->Function) 12650 << Base->getSourceRange(); 12651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12652 return ExprError(); 12653 } 12654 12655 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12656 12657 // Convert the object parameter. 12658 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12659 ExprResult BaseResult = 12660 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12661 Best->FoundDecl, Method); 12662 if (BaseResult.isInvalid()) 12663 return ExprError(); 12664 Base = BaseResult.get(); 12665 12666 // Build the operator call. 12667 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12668 HadMultipleCandidates, OpLoc); 12669 if (FnExpr.isInvalid()) 12670 return ExprError(); 12671 12672 QualType ResultTy = Method->getReturnType(); 12673 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12674 ResultTy = ResultTy.getNonLValueExprType(Context); 12675 CXXOperatorCallExpr *TheCall = 12676 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12677 Base, ResultTy, VK, OpLoc, false); 12678 12679 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12680 return ExprError(); 12681 12682 return MaybeBindToTemporary(TheCall); 12683 } 12684 12685 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12686 /// a literal operator described by the provided lookup results. 12687 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12688 DeclarationNameInfo &SuffixInfo, 12689 ArrayRef<Expr*> Args, 12690 SourceLocation LitEndLoc, 12691 TemplateArgumentListInfo *TemplateArgs) { 12692 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12693 12694 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12695 OverloadCandidateSet::CSK_Normal); 12696 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12697 /*SuppressUserConversions=*/true); 12698 12699 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12700 12701 // Perform overload resolution. This will usually be trivial, but might need 12702 // to perform substitutions for a literal operator template. 12703 OverloadCandidateSet::iterator Best; 12704 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12705 case OR_Success: 12706 case OR_Deleted: 12707 break; 12708 12709 case OR_No_Viable_Function: 12710 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12711 << R.getLookupName(); 12712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12713 return ExprError(); 12714 12715 case OR_Ambiguous: 12716 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12717 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12718 return ExprError(); 12719 } 12720 12721 FunctionDecl *FD = Best->Function; 12722 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12723 HadMultipleCandidates, 12724 SuffixInfo.getLoc(), 12725 SuffixInfo.getInfo()); 12726 if (Fn.isInvalid()) 12727 return true; 12728 12729 // Check the argument types. This should almost always be a no-op, except 12730 // that array-to-pointer decay is applied to string literals. 12731 Expr *ConvArgs[2]; 12732 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12733 ExprResult InputInit = PerformCopyInitialization( 12734 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12735 SourceLocation(), Args[ArgIdx]); 12736 if (InputInit.isInvalid()) 12737 return true; 12738 ConvArgs[ArgIdx] = InputInit.get(); 12739 } 12740 12741 QualType ResultTy = FD->getReturnType(); 12742 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12743 ResultTy = ResultTy.getNonLValueExprType(Context); 12744 12745 UserDefinedLiteral *UDL = 12746 new (Context) UserDefinedLiteral(Context, Fn.get(), 12747 llvm::makeArrayRef(ConvArgs, Args.size()), 12748 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12749 12750 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12751 return ExprError(); 12752 12753 if (CheckFunctionCall(FD, UDL, nullptr)) 12754 return ExprError(); 12755 12756 return MaybeBindToTemporary(UDL); 12757 } 12758 12759 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12760 /// given LookupResult is non-empty, it is assumed to describe a member which 12761 /// will be invoked. Otherwise, the function will be found via argument 12762 /// dependent lookup. 12763 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12764 /// otherwise CallExpr is set to ExprError() and some non-success value 12765 /// is returned. 12766 Sema::ForRangeStatus 12767 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12768 SourceLocation RangeLoc, 12769 const DeclarationNameInfo &NameInfo, 12770 LookupResult &MemberLookup, 12771 OverloadCandidateSet *CandidateSet, 12772 Expr *Range, ExprResult *CallExpr) { 12773 Scope *S = nullptr; 12774 12775 CandidateSet->clear(); 12776 if (!MemberLookup.empty()) { 12777 ExprResult MemberRef = 12778 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12779 /*IsPtr=*/false, CXXScopeSpec(), 12780 /*TemplateKWLoc=*/SourceLocation(), 12781 /*FirstQualifierInScope=*/nullptr, 12782 MemberLookup, 12783 /*TemplateArgs=*/nullptr, S); 12784 if (MemberRef.isInvalid()) { 12785 *CallExpr = ExprError(); 12786 return FRS_DiagnosticIssued; 12787 } 12788 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12789 if (CallExpr->isInvalid()) { 12790 *CallExpr = ExprError(); 12791 return FRS_DiagnosticIssued; 12792 } 12793 } else { 12794 UnresolvedSet<0> FoundNames; 12795 UnresolvedLookupExpr *Fn = 12796 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12797 NestedNameSpecifierLoc(), NameInfo, 12798 /*NeedsADL=*/true, /*Overloaded=*/false, 12799 FoundNames.begin(), FoundNames.end()); 12800 12801 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12802 CandidateSet, CallExpr); 12803 if (CandidateSet->empty() || CandidateSetError) { 12804 *CallExpr = ExprError(); 12805 return FRS_NoViableFunction; 12806 } 12807 OverloadCandidateSet::iterator Best; 12808 OverloadingResult OverloadResult = 12809 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12810 12811 if (OverloadResult == OR_No_Viable_Function) { 12812 *CallExpr = ExprError(); 12813 return FRS_NoViableFunction; 12814 } 12815 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12816 Loc, nullptr, CandidateSet, &Best, 12817 OverloadResult, 12818 /*AllowTypoCorrection=*/false); 12819 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12820 *CallExpr = ExprError(); 12821 return FRS_DiagnosticIssued; 12822 } 12823 } 12824 return FRS_Success; 12825 } 12826 12827 12828 /// FixOverloadedFunctionReference - E is an expression that refers to 12829 /// a C++ overloaded function (possibly with some parentheses and 12830 /// perhaps a '&' around it). We have resolved the overloaded function 12831 /// to the function declaration Fn, so patch up the expression E to 12832 /// refer (possibly indirectly) to Fn. Returns the new expr. 12833 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12834 FunctionDecl *Fn) { 12835 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12836 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12837 Found, Fn); 12838 if (SubExpr == PE->getSubExpr()) 12839 return PE; 12840 12841 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12842 } 12843 12844 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12845 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12846 Found, Fn); 12847 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12848 SubExpr->getType()) && 12849 "Implicit cast type cannot be determined from overload"); 12850 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12851 if (SubExpr == ICE->getSubExpr()) 12852 return ICE; 12853 12854 return ImplicitCastExpr::Create(Context, ICE->getType(), 12855 ICE->getCastKind(), 12856 SubExpr, nullptr, 12857 ICE->getValueKind()); 12858 } 12859 12860 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12861 assert(UnOp->getOpcode() == UO_AddrOf && 12862 "Can only take the address of an overloaded function"); 12863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12864 if (Method->isStatic()) { 12865 // Do nothing: static member functions aren't any different 12866 // from non-member functions. 12867 } else { 12868 // Fix the subexpression, which really has to be an 12869 // UnresolvedLookupExpr holding an overloaded member function 12870 // or template. 12871 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12872 Found, Fn); 12873 if (SubExpr == UnOp->getSubExpr()) 12874 return UnOp; 12875 12876 assert(isa<DeclRefExpr>(SubExpr) 12877 && "fixed to something other than a decl ref"); 12878 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12879 && "fixed to a member ref with no nested name qualifier"); 12880 12881 // We have taken the address of a pointer to member 12882 // function. Perform the computation here so that we get the 12883 // appropriate pointer to member type. 12884 QualType ClassType 12885 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12886 QualType MemPtrType 12887 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12888 12889 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12890 VK_RValue, OK_Ordinary, 12891 UnOp->getOperatorLoc()); 12892 } 12893 } 12894 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12895 Found, Fn); 12896 if (SubExpr == UnOp->getSubExpr()) 12897 return UnOp; 12898 12899 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12900 Context.getPointerType(SubExpr->getType()), 12901 VK_RValue, OK_Ordinary, 12902 UnOp->getOperatorLoc()); 12903 } 12904 12905 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12906 // FIXME: avoid copy. 12907 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12908 if (ULE->hasExplicitTemplateArgs()) { 12909 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12910 TemplateArgs = &TemplateArgsBuffer; 12911 } 12912 12913 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12914 ULE->getQualifierLoc(), 12915 ULE->getTemplateKeywordLoc(), 12916 Fn, 12917 /*enclosing*/ false, // FIXME? 12918 ULE->getNameLoc(), 12919 Fn->getType(), 12920 VK_LValue, 12921 Found.getDecl(), 12922 TemplateArgs); 12923 MarkDeclRefReferenced(DRE); 12924 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12925 return DRE; 12926 } 12927 12928 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12929 // FIXME: avoid copy. 12930 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12931 if (MemExpr->hasExplicitTemplateArgs()) { 12932 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12933 TemplateArgs = &TemplateArgsBuffer; 12934 } 12935 12936 Expr *Base; 12937 12938 // If we're filling in a static method where we used to have an 12939 // implicit member access, rewrite to a simple decl ref. 12940 if (MemExpr->isImplicitAccess()) { 12941 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12942 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12943 MemExpr->getQualifierLoc(), 12944 MemExpr->getTemplateKeywordLoc(), 12945 Fn, 12946 /*enclosing*/ false, 12947 MemExpr->getMemberLoc(), 12948 Fn->getType(), 12949 VK_LValue, 12950 Found.getDecl(), 12951 TemplateArgs); 12952 MarkDeclRefReferenced(DRE); 12953 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12954 return DRE; 12955 } else { 12956 SourceLocation Loc = MemExpr->getMemberLoc(); 12957 if (MemExpr->getQualifier()) 12958 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12959 CheckCXXThisCapture(Loc); 12960 Base = new (Context) CXXThisExpr(Loc, 12961 MemExpr->getBaseType(), 12962 /*isImplicit=*/true); 12963 } 12964 } else 12965 Base = MemExpr->getBase(); 12966 12967 ExprValueKind valueKind; 12968 QualType type; 12969 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12970 valueKind = VK_LValue; 12971 type = Fn->getType(); 12972 } else { 12973 valueKind = VK_RValue; 12974 type = Context.BoundMemberTy; 12975 } 12976 12977 MemberExpr *ME = MemberExpr::Create( 12978 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12979 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12980 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12981 OK_Ordinary); 12982 ME->setHadMultipleCandidates(true); 12983 MarkMemberReferenced(ME); 12984 return ME; 12985 } 12986 12987 llvm_unreachable("Invalid reference to overloaded function"); 12988 } 12989 12990 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12991 DeclAccessPair Found, 12992 FunctionDecl *Fn) { 12993 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12994 } 12995