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 297 // A conversion to an enumeration type is narrowing if the conversion to 298 // the underlying type is narrowing. This only arises for expressions of 299 // the form 'Enum{init}'. 300 if (auto *ET = ToType->getAs<EnumType>()) 301 ToType = ET->getDecl()->getIntegerType(); 302 303 switch (Second) { 304 // 'bool' is an integral type; dispatch to the right place to handle it. 305 case ICK_Boolean_Conversion: 306 if (FromType->isRealFloatingType()) 307 goto FloatingIntegralConversion; 308 if (FromType->isIntegralOrUnscopedEnumerationType()) 309 goto IntegralConversion; 310 // Boolean conversions can be from pointers and pointers to members 311 // [conv.bool], and those aren't considered narrowing conversions. 312 return NK_Not_Narrowing; 313 314 // -- from a floating-point type to an integer type, or 315 // 316 // -- from an integer type or unscoped enumeration type to a floating-point 317 // type, except where the source is a constant expression and the actual 318 // value after conversion will fit into the target type and will produce 319 // the original value when converted back to the original type, or 320 case ICK_Floating_Integral: 321 FloatingIntegralConversion: 322 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 323 return NK_Type_Narrowing; 324 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 325 llvm::APSInt IntConstantValue; 326 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 327 if (Initializer && 328 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 329 // Convert the integer to the floating type. 330 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 331 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 332 llvm::APFloat::rmNearestTiesToEven); 333 // And back. 334 llvm::APSInt ConvertedValue = IntConstantValue; 335 bool ignored; 336 Result.convertToInteger(ConvertedValue, 337 llvm::APFloat::rmTowardZero, &ignored); 338 // If the resulting value is different, this was a narrowing conversion. 339 if (IntConstantValue != ConvertedValue) { 340 ConstantValue = APValue(IntConstantValue); 341 ConstantType = Initializer->getType(); 342 return NK_Constant_Narrowing; 343 } 344 } else { 345 // Variables are always narrowings. 346 return NK_Variable_Narrowing; 347 } 348 } 349 return NK_Not_Narrowing; 350 351 // -- from long double to double or float, or from double to float, except 352 // where the source is a constant expression and the actual value after 353 // conversion is within the range of values that can be represented (even 354 // if it cannot be represented exactly), or 355 case ICK_Floating_Conversion: 356 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 357 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 358 // FromType is larger than ToType. 359 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 360 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 361 // Constant! 362 assert(ConstantValue.isFloat()); 363 llvm::APFloat FloatVal = ConstantValue.getFloat(); 364 // Convert the source value into the target type. 365 bool ignored; 366 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 367 Ctx.getFloatTypeSemantics(ToType), 368 llvm::APFloat::rmNearestTiesToEven, &ignored); 369 // If there was no overflow, the source value is within the range of 370 // values that can be represented. 371 if (ConvertStatus & llvm::APFloat::opOverflow) { 372 ConstantType = Initializer->getType(); 373 return NK_Constant_Narrowing; 374 } 375 } else { 376 return NK_Variable_Narrowing; 377 } 378 } 379 return NK_Not_Narrowing; 380 381 // -- from an integer type or unscoped enumeration type to an integer type 382 // that cannot represent all the values of the original type, except where 383 // the source is a constant expression and the actual value after 384 // conversion will fit into the target type and will produce the original 385 // value when converted back to the original type. 386 case ICK_Integral_Conversion: 387 IntegralConversion: { 388 assert(FromType->isIntegralOrUnscopedEnumerationType()); 389 assert(ToType->isIntegralOrUnscopedEnumerationType()); 390 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 391 const unsigned FromWidth = Ctx.getIntWidth(FromType); 392 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 393 const unsigned ToWidth = Ctx.getIntWidth(ToType); 394 395 if (FromWidth > ToWidth || 396 (FromWidth == ToWidth && FromSigned != ToSigned) || 397 (FromSigned && !ToSigned)) { 398 // Not all values of FromType can be represented in ToType. 399 llvm::APSInt InitializerValue; 400 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 401 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 402 // Such conversions on variables are always narrowing. 403 return NK_Variable_Narrowing; 404 } 405 bool Narrowing = false; 406 if (FromWidth < ToWidth) { 407 // Negative -> unsigned is narrowing. Otherwise, more bits is never 408 // narrowing. 409 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 410 Narrowing = true; 411 } else { 412 // Add a bit to the InitializerValue so we don't have to worry about 413 // signed vs. unsigned comparisons. 414 InitializerValue = InitializerValue.extend( 415 InitializerValue.getBitWidth() + 1); 416 // Convert the initializer to and from the target width and signed-ness. 417 llvm::APSInt ConvertedValue = InitializerValue; 418 ConvertedValue = ConvertedValue.trunc(ToWidth); 419 ConvertedValue.setIsSigned(ToSigned); 420 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 421 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 422 // If the result is different, this was a narrowing conversion. 423 if (ConvertedValue != InitializerValue) 424 Narrowing = true; 425 } 426 if (Narrowing) { 427 ConstantType = Initializer->getType(); 428 ConstantValue = APValue(InitializerValue); 429 return NK_Constant_Narrowing; 430 } 431 } 432 return NK_Not_Narrowing; 433 } 434 435 default: 436 // Other kinds of conversions are not narrowings. 437 return NK_Not_Narrowing; 438 } 439 } 440 441 /// dump - Print this standard conversion sequence to standard 442 /// error. Useful for debugging overloading issues. 443 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 444 raw_ostream &OS = llvm::errs(); 445 bool PrintedSomething = false; 446 if (First != ICK_Identity) { 447 OS << GetImplicitConversionName(First); 448 PrintedSomething = true; 449 } 450 451 if (Second != ICK_Identity) { 452 if (PrintedSomething) { 453 OS << " -> "; 454 } 455 OS << GetImplicitConversionName(Second); 456 457 if (CopyConstructor) { 458 OS << " (by copy constructor)"; 459 } else if (DirectBinding) { 460 OS << " (direct reference binding)"; 461 } else if (ReferenceBinding) { 462 OS << " (reference binding)"; 463 } 464 PrintedSomething = true; 465 } 466 467 if (Third != ICK_Identity) { 468 if (PrintedSomething) { 469 OS << " -> "; 470 } 471 OS << GetImplicitConversionName(Third); 472 PrintedSomething = true; 473 } 474 475 if (!PrintedSomething) { 476 OS << "No conversions required"; 477 } 478 } 479 480 /// dump - Print this user-defined conversion sequence to standard 481 /// error. Useful for debugging overloading issues. 482 void UserDefinedConversionSequence::dump() const { 483 raw_ostream &OS = llvm::errs(); 484 if (Before.First || Before.Second || Before.Third) { 485 Before.dump(); 486 OS << " -> "; 487 } 488 if (ConversionFunction) 489 OS << '\'' << *ConversionFunction << '\''; 490 else 491 OS << "aggregate initialization"; 492 if (After.First || After.Second || After.Third) { 493 OS << " -> "; 494 After.dump(); 495 } 496 } 497 498 /// dump - Print this implicit conversion sequence to standard 499 /// error. Useful for debugging overloading issues. 500 void ImplicitConversionSequence::dump() const { 501 raw_ostream &OS = llvm::errs(); 502 if (isStdInitializerListElement()) 503 OS << "Worst std::initializer_list element conversion: "; 504 switch (ConversionKind) { 505 case StandardConversion: 506 OS << "Standard conversion: "; 507 Standard.dump(); 508 break; 509 case UserDefinedConversion: 510 OS << "User-defined conversion: "; 511 UserDefined.dump(); 512 break; 513 case EllipsisConversion: 514 OS << "Ellipsis conversion"; 515 break; 516 case AmbiguousConversion: 517 OS << "Ambiguous conversion"; 518 break; 519 case BadConversion: 520 OS << "Bad conversion"; 521 break; 522 } 523 524 OS << "\n"; 525 } 526 527 void AmbiguousConversionSequence::construct() { 528 new (&conversions()) ConversionSet(); 529 } 530 531 void AmbiguousConversionSequence::destruct() { 532 conversions().~ConversionSet(); 533 } 534 535 void 536 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 537 FromTypePtr = O.FromTypePtr; 538 ToTypePtr = O.ToTypePtr; 539 new (&conversions()) ConversionSet(O.conversions()); 540 } 541 542 namespace { 543 // Structure used by DeductionFailureInfo to store 544 // template argument information. 545 struct DFIArguments { 546 TemplateArgument FirstArg; 547 TemplateArgument SecondArg; 548 }; 549 // Structure used by DeductionFailureInfo to store 550 // template parameter and template argument information. 551 struct DFIParamWithArguments : DFIArguments { 552 TemplateParameter Param; 553 }; 554 // Structure used by DeductionFailureInfo to store template argument 555 // information and the index of the problematic call argument. 556 struct DFIDeducedMismatchArgs : DFIArguments { 557 TemplateArgumentList *TemplateArgs; 558 unsigned CallArgIndex; 559 }; 560 } 561 562 /// \brief Convert from Sema's representation of template deduction information 563 /// to the form used in overload-candidate information. 564 DeductionFailureInfo 565 clang::MakeDeductionFailureInfo(ASTContext &Context, 566 Sema::TemplateDeductionResult TDK, 567 TemplateDeductionInfo &Info) { 568 DeductionFailureInfo Result; 569 Result.Result = static_cast<unsigned>(TDK); 570 Result.HasDiagnostic = false; 571 switch (TDK) { 572 case Sema::TDK_Success: 573 case Sema::TDK_Invalid: 574 case Sema::TDK_InstantiationDepth: 575 case Sema::TDK_TooManyArguments: 576 case Sema::TDK_TooFewArguments: 577 case Sema::TDK_MiscellaneousDeductionFailure: 578 Result.Data = nullptr; 579 break; 580 581 case Sema::TDK_Incomplete: 582 case Sema::TDK_InvalidExplicitArguments: 583 Result.Data = Info.Param.getOpaqueValue(); 584 break; 585 586 case Sema::TDK_DeducedMismatch: { 587 // FIXME: Should allocate from normal heap so that we can free this later. 588 auto *Saved = new (Context) DFIDeducedMismatchArgs; 589 Saved->FirstArg = Info.FirstArg; 590 Saved->SecondArg = Info.SecondArg; 591 Saved->TemplateArgs = Info.take(); 592 Saved->CallArgIndex = Info.CallArgIndex; 593 Result.Data = Saved; 594 break; 595 } 596 597 case Sema::TDK_NonDeducedMismatch: { 598 // FIXME: Should allocate from normal heap so that we can free this later. 599 DFIArguments *Saved = new (Context) DFIArguments; 600 Saved->FirstArg = Info.FirstArg; 601 Saved->SecondArg = Info.SecondArg; 602 Result.Data = Saved; 603 break; 604 } 605 606 case Sema::TDK_Inconsistent: 607 case Sema::TDK_Underqualified: { 608 // FIXME: Should allocate from normal heap so that we can free this later. 609 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 610 Saved->Param = Info.Param; 611 Saved->FirstArg = Info.FirstArg; 612 Saved->SecondArg = Info.SecondArg; 613 Result.Data = Saved; 614 break; 615 } 616 617 case Sema::TDK_SubstitutionFailure: 618 Result.Data = Info.take(); 619 if (Info.hasSFINAEDiagnostic()) { 620 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 621 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 622 Info.takeSFINAEDiagnostic(*Diag); 623 Result.HasDiagnostic = true; 624 } 625 break; 626 627 case Sema::TDK_FailedOverloadResolution: 628 Result.Data = Info.Expression; 629 break; 630 } 631 632 return Result; 633 } 634 635 void DeductionFailureInfo::Destroy() { 636 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 637 case Sema::TDK_Success: 638 case Sema::TDK_Invalid: 639 case Sema::TDK_InstantiationDepth: 640 case Sema::TDK_Incomplete: 641 case Sema::TDK_TooManyArguments: 642 case Sema::TDK_TooFewArguments: 643 case Sema::TDK_InvalidExplicitArguments: 644 case Sema::TDK_FailedOverloadResolution: 645 break; 646 647 case Sema::TDK_Inconsistent: 648 case Sema::TDK_Underqualified: 649 case Sema::TDK_DeducedMismatch: 650 case Sema::TDK_NonDeducedMismatch: 651 // FIXME: Destroy the data? 652 Data = nullptr; 653 break; 654 655 case Sema::TDK_SubstitutionFailure: 656 // FIXME: Destroy the template argument list? 657 Data = nullptr; 658 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 659 Diag->~PartialDiagnosticAt(); 660 HasDiagnostic = false; 661 } 662 break; 663 664 // Unhandled 665 case Sema::TDK_MiscellaneousDeductionFailure: 666 break; 667 } 668 } 669 670 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 671 if (HasDiagnostic) 672 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 673 return nullptr; 674 } 675 676 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 677 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 678 case Sema::TDK_Success: 679 case Sema::TDK_Invalid: 680 case Sema::TDK_InstantiationDepth: 681 case Sema::TDK_TooManyArguments: 682 case Sema::TDK_TooFewArguments: 683 case Sema::TDK_SubstitutionFailure: 684 case Sema::TDK_DeducedMismatch: 685 case Sema::TDK_NonDeducedMismatch: 686 case Sema::TDK_FailedOverloadResolution: 687 return TemplateParameter(); 688 689 case Sema::TDK_Incomplete: 690 case Sema::TDK_InvalidExplicitArguments: 691 return TemplateParameter::getFromOpaqueValue(Data); 692 693 case Sema::TDK_Inconsistent: 694 case Sema::TDK_Underqualified: 695 return static_cast<DFIParamWithArguments*>(Data)->Param; 696 697 // Unhandled 698 case Sema::TDK_MiscellaneousDeductionFailure: 699 break; 700 } 701 702 return TemplateParameter(); 703 } 704 705 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 707 case Sema::TDK_Success: 708 case Sema::TDK_Invalid: 709 case Sema::TDK_InstantiationDepth: 710 case Sema::TDK_TooManyArguments: 711 case Sema::TDK_TooFewArguments: 712 case Sema::TDK_Incomplete: 713 case Sema::TDK_InvalidExplicitArguments: 714 case Sema::TDK_Inconsistent: 715 case Sema::TDK_Underqualified: 716 case Sema::TDK_NonDeducedMismatch: 717 case Sema::TDK_FailedOverloadResolution: 718 return nullptr; 719 720 case Sema::TDK_DeducedMismatch: 721 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 722 723 case Sema::TDK_SubstitutionFailure: 724 return static_cast<TemplateArgumentList*>(Data); 725 726 // Unhandled 727 case Sema::TDK_MiscellaneousDeductionFailure: 728 break; 729 } 730 731 return nullptr; 732 } 733 734 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 735 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 736 case Sema::TDK_Success: 737 case Sema::TDK_Invalid: 738 case Sema::TDK_InstantiationDepth: 739 case Sema::TDK_Incomplete: 740 case Sema::TDK_TooManyArguments: 741 case Sema::TDK_TooFewArguments: 742 case Sema::TDK_InvalidExplicitArguments: 743 case Sema::TDK_SubstitutionFailure: 744 case Sema::TDK_FailedOverloadResolution: 745 return nullptr; 746 747 case Sema::TDK_Inconsistent: 748 case Sema::TDK_Underqualified: 749 case Sema::TDK_DeducedMismatch: 750 case Sema::TDK_NonDeducedMismatch: 751 return &static_cast<DFIArguments*>(Data)->FirstArg; 752 753 // Unhandled 754 case Sema::TDK_MiscellaneousDeductionFailure: 755 break; 756 } 757 758 return nullptr; 759 } 760 761 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 762 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 763 case Sema::TDK_Success: 764 case Sema::TDK_Invalid: 765 case Sema::TDK_InstantiationDepth: 766 case Sema::TDK_Incomplete: 767 case Sema::TDK_TooManyArguments: 768 case Sema::TDK_TooFewArguments: 769 case Sema::TDK_InvalidExplicitArguments: 770 case Sema::TDK_SubstitutionFailure: 771 case Sema::TDK_FailedOverloadResolution: 772 return nullptr; 773 774 case Sema::TDK_Inconsistent: 775 case Sema::TDK_Underqualified: 776 case Sema::TDK_DeducedMismatch: 777 case Sema::TDK_NonDeducedMismatch: 778 return &static_cast<DFIArguments*>(Data)->SecondArg; 779 780 // Unhandled 781 case Sema::TDK_MiscellaneousDeductionFailure: 782 break; 783 } 784 785 return nullptr; 786 } 787 788 Expr *DeductionFailureInfo::getExpr() { 789 if (static_cast<Sema::TemplateDeductionResult>(Result) == 790 Sema::TDK_FailedOverloadResolution) 791 return static_cast<Expr*>(Data); 792 793 return nullptr; 794 } 795 796 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 797 if (static_cast<Sema::TemplateDeductionResult>(Result) == 798 Sema::TDK_DeducedMismatch) 799 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 800 801 return llvm::None; 802 } 803 804 void OverloadCandidateSet::destroyCandidates() { 805 for (iterator i = begin(), e = end(); i != e; ++i) { 806 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 807 i->Conversions[ii].~ImplicitConversionSequence(); 808 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 809 i->DeductionFailure.Destroy(); 810 } 811 } 812 813 void OverloadCandidateSet::clear() { 814 destroyCandidates(); 815 NumInlineSequences = 0; 816 Candidates.clear(); 817 Functions.clear(); 818 } 819 820 namespace { 821 class UnbridgedCastsSet { 822 struct Entry { 823 Expr **Addr; 824 Expr *Saved; 825 }; 826 SmallVector<Entry, 2> Entries; 827 828 public: 829 void save(Sema &S, Expr *&E) { 830 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 831 Entry entry = { &E, E }; 832 Entries.push_back(entry); 833 E = S.stripARCUnbridgedCast(E); 834 } 835 836 void restore() { 837 for (SmallVectorImpl<Entry>::iterator 838 i = Entries.begin(), e = Entries.end(); i != e; ++i) 839 *i->Addr = i->Saved; 840 } 841 }; 842 } 843 844 /// checkPlaceholderForOverload - Do any interesting placeholder-like 845 /// preprocessing on the given expression. 846 /// 847 /// \param unbridgedCasts a collection to which to add unbridged casts; 848 /// without this, they will be immediately diagnosed as errors 849 /// 850 /// Return true on unrecoverable error. 851 static bool 852 checkPlaceholderForOverload(Sema &S, Expr *&E, 853 UnbridgedCastsSet *unbridgedCasts = nullptr) { 854 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 855 // We can't handle overloaded expressions here because overload 856 // resolution might reasonably tweak them. 857 if (placeholder->getKind() == BuiltinType::Overload) return false; 858 859 // If the context potentially accepts unbridged ARC casts, strip 860 // the unbridged cast and add it to the collection for later restoration. 861 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 862 unbridgedCasts) { 863 unbridgedCasts->save(S, E); 864 return false; 865 } 866 867 // Go ahead and check everything else. 868 ExprResult result = S.CheckPlaceholderExpr(E); 869 if (result.isInvalid()) 870 return true; 871 872 E = result.get(); 873 return false; 874 } 875 876 // Nothing to do. 877 return false; 878 } 879 880 /// checkArgPlaceholdersForOverload - Check a set of call operands for 881 /// placeholders. 882 static bool checkArgPlaceholdersForOverload(Sema &S, 883 MultiExprArg Args, 884 UnbridgedCastsSet &unbridged) { 885 for (unsigned i = 0, e = Args.size(); i != e; ++i) 886 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 887 return true; 888 889 return false; 890 } 891 892 // IsOverload - Determine whether the given New declaration is an 893 // overload of the declarations in Old. This routine returns false if 894 // New and Old cannot be overloaded, e.g., if New has the same 895 // signature as some function in Old (C++ 1.3.10) or if the Old 896 // declarations aren't functions (or function templates) at all. When 897 // it does return false, MatchedDecl will point to the decl that New 898 // cannot be overloaded with. This decl may be a UsingShadowDecl on 899 // top of the underlying declaration. 900 // 901 // Example: Given the following input: 902 // 903 // void f(int, float); // #1 904 // void f(int, int); // #2 905 // int f(int, int); // #3 906 // 907 // When we process #1, there is no previous declaration of "f", 908 // so IsOverload will not be used. 909 // 910 // When we process #2, Old contains only the FunctionDecl for #1. By 911 // comparing the parameter types, we see that #1 and #2 are overloaded 912 // (since they have different signatures), so this routine returns 913 // false; MatchedDecl is unchanged. 914 // 915 // When we process #3, Old is an overload set containing #1 and #2. We 916 // compare the signatures of #3 to #1 (they're overloaded, so we do 917 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 918 // identical (return types of functions are not part of the 919 // signature), IsOverload returns false and MatchedDecl will be set to 920 // point to the FunctionDecl for #2. 921 // 922 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 923 // into a class by a using declaration. The rules for whether to hide 924 // shadow declarations ignore some properties which otherwise figure 925 // into a function template's signature. 926 Sema::OverloadKind 927 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 928 NamedDecl *&Match, bool NewIsUsingDecl) { 929 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 930 I != E; ++I) { 931 NamedDecl *OldD = *I; 932 933 bool OldIsUsingDecl = false; 934 if (isa<UsingShadowDecl>(OldD)) { 935 OldIsUsingDecl = true; 936 937 // We can always introduce two using declarations into the same 938 // context, even if they have identical signatures. 939 if (NewIsUsingDecl) continue; 940 941 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 942 } 943 944 // A using-declaration does not conflict with another declaration 945 // if one of them is hidden. 946 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 947 continue; 948 949 // If either declaration was introduced by a using declaration, 950 // we'll need to use slightly different rules for matching. 951 // Essentially, these rules are the normal rules, except that 952 // function templates hide function templates with different 953 // return types or template parameter lists. 954 bool UseMemberUsingDeclRules = 955 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 956 !New->getFriendObjectKind(); 957 958 if (FunctionDecl *OldF = OldD->getAsFunction()) { 959 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 960 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 961 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 962 continue; 963 } 964 965 if (!isa<FunctionTemplateDecl>(OldD) && 966 !shouldLinkPossiblyHiddenDecl(*I, New)) 967 continue; 968 969 Match = *I; 970 return Ovl_Match; 971 } 972 } else if (isa<UsingDecl>(OldD)) { 973 // We can overload with these, which can show up when doing 974 // redeclaration checks for UsingDecls. 975 assert(Old.getLookupKind() == LookupUsingDeclName); 976 } else if (isa<TagDecl>(OldD)) { 977 // We can always overload with tags by hiding them. 978 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 979 // Optimistically assume that an unresolved using decl will 980 // overload; if it doesn't, we'll have to diagnose during 981 // template instantiation. 982 } else { 983 // (C++ 13p1): 984 // Only function declarations can be overloaded; object and type 985 // declarations cannot be overloaded. 986 Match = *I; 987 return Ovl_NonFunction; 988 } 989 } 990 991 return Ovl_Overload; 992 } 993 994 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 995 bool UseUsingDeclRules) { 996 // C++ [basic.start.main]p2: This function shall not be overloaded. 997 if (New->isMain()) 998 return false; 999 1000 // MSVCRT user defined entry points cannot be overloaded. 1001 if (New->isMSVCRTEntryPoint()) 1002 return false; 1003 1004 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1005 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1006 1007 // C++ [temp.fct]p2: 1008 // A function template can be overloaded with other function templates 1009 // and with normal (non-template) functions. 1010 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1011 return true; 1012 1013 // Is the function New an overload of the function Old? 1014 QualType OldQType = Context.getCanonicalType(Old->getType()); 1015 QualType NewQType = Context.getCanonicalType(New->getType()); 1016 1017 // Compare the signatures (C++ 1.3.10) of the two functions to 1018 // determine whether they are overloads. If we find any mismatch 1019 // in the signature, they are overloads. 1020 1021 // If either of these functions is a K&R-style function (no 1022 // prototype), then we consider them to have matching signatures. 1023 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1024 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1025 return false; 1026 1027 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1028 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1029 1030 // The signature of a function includes the types of its 1031 // parameters (C++ 1.3.10), which includes the presence or absence 1032 // of the ellipsis; see C++ DR 357). 1033 if (OldQType != NewQType && 1034 (OldType->getNumParams() != NewType->getNumParams() || 1035 OldType->isVariadic() != NewType->isVariadic() || 1036 !FunctionParamTypesAreEqual(OldType, NewType))) 1037 return true; 1038 1039 // C++ [temp.over.link]p4: 1040 // The signature of a function template consists of its function 1041 // signature, its return type and its template parameter list. The names 1042 // of the template parameters are significant only for establishing the 1043 // relationship between the template parameters and the rest of the 1044 // signature. 1045 // 1046 // We check the return type and template parameter lists for function 1047 // templates first; the remaining checks follow. 1048 // 1049 // However, we don't consider either of these when deciding whether 1050 // a member introduced by a shadow declaration is hidden. 1051 if (!UseUsingDeclRules && NewTemplate && 1052 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1053 OldTemplate->getTemplateParameters(), 1054 false, TPL_TemplateMatch) || 1055 OldType->getReturnType() != NewType->getReturnType())) 1056 return true; 1057 1058 // If the function is a class member, its signature includes the 1059 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1060 // 1061 // As part of this, also check whether one of the member functions 1062 // is static, in which case they are not overloads (C++ 1063 // 13.1p2). While not part of the definition of the signature, 1064 // this check is important to determine whether these functions 1065 // can be overloaded. 1066 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1067 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1068 if (OldMethod && NewMethod && 1069 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1070 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1071 if (!UseUsingDeclRules && 1072 (OldMethod->getRefQualifier() == RQ_None || 1073 NewMethod->getRefQualifier() == RQ_None)) { 1074 // C++0x [over.load]p2: 1075 // - Member function declarations with the same name and the same 1076 // parameter-type-list as well as member function template 1077 // declarations with the same name, the same parameter-type-list, and 1078 // the same template parameter lists cannot be overloaded if any of 1079 // them, but not all, have a ref-qualifier (8.3.5). 1080 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1081 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1082 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1083 } 1084 return true; 1085 } 1086 1087 // We may not have applied the implicit const for a constexpr member 1088 // function yet (because we haven't yet resolved whether this is a static 1089 // or non-static member function). Add it now, on the assumption that this 1090 // is a redeclaration of OldMethod. 1091 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1092 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1093 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1094 !isa<CXXConstructorDecl>(NewMethod)) 1095 NewQuals |= Qualifiers::Const; 1096 1097 // We do not allow overloading based off of '__restrict'. 1098 OldQuals &= ~Qualifiers::Restrict; 1099 NewQuals &= ~Qualifiers::Restrict; 1100 if (OldQuals != NewQuals) 1101 return true; 1102 } 1103 1104 // Though pass_object_size is placed on parameters and takes an argument, we 1105 // consider it to be a function-level modifier for the sake of function 1106 // identity. Either the function has one or more parameters with 1107 // pass_object_size or it doesn't. 1108 if (functionHasPassObjectSizeParams(New) != 1109 functionHasPassObjectSizeParams(Old)) 1110 return true; 1111 1112 // enable_if attributes are an order-sensitive part of the signature. 1113 for (specific_attr_iterator<EnableIfAttr> 1114 NewI = New->specific_attr_begin<EnableIfAttr>(), 1115 NewE = New->specific_attr_end<EnableIfAttr>(), 1116 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1117 OldE = Old->specific_attr_end<EnableIfAttr>(); 1118 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1119 if (NewI == NewE || OldI == OldE) 1120 return true; 1121 llvm::FoldingSetNodeID NewID, OldID; 1122 NewI->getCond()->Profile(NewID, Context, true); 1123 OldI->getCond()->Profile(OldID, Context, true); 1124 if (NewID != OldID) 1125 return true; 1126 } 1127 1128 if (getLangOpts().CUDA) { 1129 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1130 OldTarget = IdentifyCUDATarget(Old); 1131 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1132 return false; 1133 1134 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1135 1136 // Don't allow mixing of HD with other kinds. This guarantees that 1137 // we have only one viable function with this signature on any 1138 // side of CUDA compilation . 1139 // __global__ functions can't be overloaded based on attribute 1140 // difference because, like HD, they also exist on both sides. 1141 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1142 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1143 return false; 1144 1145 // Allow overloading of functions with same signature, but 1146 // different CUDA target attributes. 1147 return NewTarget != OldTarget; 1148 } 1149 1150 // The signatures match; this is not an overload. 1151 return false; 1152 } 1153 1154 /// \brief Checks availability of the function depending on the current 1155 /// function context. Inside an unavailable function, unavailability is ignored. 1156 /// 1157 /// \returns true if \arg FD is unavailable and current context is inside 1158 /// an available function, false otherwise. 1159 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1160 if (!FD->isUnavailable()) 1161 return false; 1162 1163 // Walk up the context of the caller. 1164 Decl *C = cast<Decl>(CurContext); 1165 do { 1166 if (C->isUnavailable()) 1167 return false; 1168 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1169 return true; 1170 } 1171 1172 /// \brief Tries a user-defined conversion from From to ToType. 1173 /// 1174 /// Produces an implicit conversion sequence for when a standard conversion 1175 /// is not an option. See TryImplicitConversion for more information. 1176 static ImplicitConversionSequence 1177 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1178 bool SuppressUserConversions, 1179 bool AllowExplicit, 1180 bool InOverloadResolution, 1181 bool CStyle, 1182 bool AllowObjCWritebackConversion, 1183 bool AllowObjCConversionOnExplicit) { 1184 ImplicitConversionSequence ICS; 1185 1186 if (SuppressUserConversions) { 1187 // We're not in the case above, so there is no conversion that 1188 // we can perform. 1189 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1190 return ICS; 1191 } 1192 1193 // Attempt user-defined conversion. 1194 OverloadCandidateSet Conversions(From->getExprLoc(), 1195 OverloadCandidateSet::CSK_Normal); 1196 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1197 Conversions, AllowExplicit, 1198 AllowObjCConversionOnExplicit)) { 1199 case OR_Success: 1200 case OR_Deleted: 1201 ICS.setUserDefined(); 1202 ICS.UserDefined.Before.setAsIdentityConversion(); 1203 // C++ [over.ics.user]p4: 1204 // A conversion of an expression of class type to the same class 1205 // type is given Exact Match rank, and a conversion of an 1206 // expression of class type to a base class of that type is 1207 // given Conversion rank, in spite of the fact that a copy 1208 // constructor (i.e., a user-defined conversion function) is 1209 // called for those cases. 1210 if (CXXConstructorDecl *Constructor 1211 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1212 QualType FromCanon 1213 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1214 QualType ToCanon 1215 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1216 if (Constructor->isCopyConstructor() && 1217 (FromCanon == ToCanon || 1218 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1219 // Turn this into a "standard" conversion sequence, so that it 1220 // gets ranked with standard conversion sequences. 1221 ICS.setStandard(); 1222 ICS.Standard.setAsIdentityConversion(); 1223 ICS.Standard.setFromType(From->getType()); 1224 ICS.Standard.setAllToTypes(ToType); 1225 ICS.Standard.CopyConstructor = Constructor; 1226 if (ToCanon != FromCanon) 1227 ICS.Standard.Second = ICK_Derived_To_Base; 1228 } 1229 } 1230 break; 1231 1232 case OR_Ambiguous: 1233 ICS.setAmbiguous(); 1234 ICS.Ambiguous.setFromType(From->getType()); 1235 ICS.Ambiguous.setToType(ToType); 1236 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1237 Cand != Conversions.end(); ++Cand) 1238 if (Cand->Viable) 1239 ICS.Ambiguous.addConversion(Cand->Function); 1240 break; 1241 1242 // Fall through. 1243 case OR_No_Viable_Function: 1244 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1245 break; 1246 } 1247 1248 return ICS; 1249 } 1250 1251 /// TryImplicitConversion - Attempt to perform an implicit conversion 1252 /// from the given expression (Expr) to the given type (ToType). This 1253 /// function returns an implicit conversion sequence that can be used 1254 /// to perform the initialization. Given 1255 /// 1256 /// void f(float f); 1257 /// void g(int i) { f(i); } 1258 /// 1259 /// this routine would produce an implicit conversion sequence to 1260 /// describe the initialization of f from i, which will be a standard 1261 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1262 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1263 // 1264 /// Note that this routine only determines how the conversion can be 1265 /// performed; it does not actually perform the conversion. As such, 1266 /// it will not produce any diagnostics if no conversion is available, 1267 /// but will instead return an implicit conversion sequence of kind 1268 /// "BadConversion". 1269 /// 1270 /// If @p SuppressUserConversions, then user-defined conversions are 1271 /// not permitted. 1272 /// If @p AllowExplicit, then explicit user-defined conversions are 1273 /// permitted. 1274 /// 1275 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1276 /// writeback conversion, which allows __autoreleasing id* parameters to 1277 /// be initialized with __strong id* or __weak id* arguments. 1278 static ImplicitConversionSequence 1279 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1280 bool SuppressUserConversions, 1281 bool AllowExplicit, 1282 bool InOverloadResolution, 1283 bool CStyle, 1284 bool AllowObjCWritebackConversion, 1285 bool AllowObjCConversionOnExplicit) { 1286 ImplicitConversionSequence ICS; 1287 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1288 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1289 ICS.setStandard(); 1290 return ICS; 1291 } 1292 1293 if (!S.getLangOpts().CPlusPlus) { 1294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1295 return ICS; 1296 } 1297 1298 // C++ [over.ics.user]p4: 1299 // A conversion of an expression of class type to the same class 1300 // type is given Exact Match rank, and a conversion of an 1301 // expression of class type to a base class of that type is 1302 // given Conversion rank, in spite of the fact that a copy/move 1303 // constructor (i.e., a user-defined conversion function) is 1304 // called for those cases. 1305 QualType FromType = From->getType(); 1306 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1307 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1308 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1309 ICS.setStandard(); 1310 ICS.Standard.setAsIdentityConversion(); 1311 ICS.Standard.setFromType(FromType); 1312 ICS.Standard.setAllToTypes(ToType); 1313 1314 // We don't actually check at this point whether there is a valid 1315 // copy/move constructor, since overloading just assumes that it 1316 // exists. When we actually perform initialization, we'll find the 1317 // appropriate constructor to copy the returned object, if needed. 1318 ICS.Standard.CopyConstructor = nullptr; 1319 1320 // Determine whether this is considered a derived-to-base conversion. 1321 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1322 ICS.Standard.Second = ICK_Derived_To_Base; 1323 1324 return ICS; 1325 } 1326 1327 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1328 AllowExplicit, InOverloadResolution, CStyle, 1329 AllowObjCWritebackConversion, 1330 AllowObjCConversionOnExplicit); 1331 } 1332 1333 ImplicitConversionSequence 1334 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1335 bool SuppressUserConversions, 1336 bool AllowExplicit, 1337 bool InOverloadResolution, 1338 bool CStyle, 1339 bool AllowObjCWritebackConversion) { 1340 return ::TryImplicitConversion(*this, From, ToType, 1341 SuppressUserConversions, AllowExplicit, 1342 InOverloadResolution, CStyle, 1343 AllowObjCWritebackConversion, 1344 /*AllowObjCConversionOnExplicit=*/false); 1345 } 1346 1347 /// PerformImplicitConversion - Perform an implicit conversion of the 1348 /// expression From to the type ToType. Returns the 1349 /// converted expression. Flavor is the kind of conversion we're 1350 /// performing, used in the error message. If @p AllowExplicit, 1351 /// explicit user-defined conversions are permitted. 1352 ExprResult 1353 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1354 AssignmentAction Action, bool AllowExplicit) { 1355 ImplicitConversionSequence ICS; 1356 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1357 } 1358 1359 ExprResult 1360 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1361 AssignmentAction Action, bool AllowExplicit, 1362 ImplicitConversionSequence& ICS) { 1363 if (checkPlaceholderForOverload(*this, From)) 1364 return ExprError(); 1365 1366 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1367 bool AllowObjCWritebackConversion 1368 = getLangOpts().ObjCAutoRefCount && 1369 (Action == AA_Passing || Action == AA_Sending); 1370 if (getLangOpts().ObjC1) 1371 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1372 ToType, From->getType(), From); 1373 ICS = ::TryImplicitConversion(*this, From, ToType, 1374 /*SuppressUserConversions=*/false, 1375 AllowExplicit, 1376 /*InOverloadResolution=*/false, 1377 /*CStyle=*/false, 1378 AllowObjCWritebackConversion, 1379 /*AllowObjCConversionOnExplicit=*/false); 1380 return PerformImplicitConversion(From, ToType, ICS, Action); 1381 } 1382 1383 /// \brief Determine whether the conversion from FromType to ToType is a valid 1384 /// conversion that strips "noreturn" off the nested function type. 1385 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1386 QualType &ResultTy) { 1387 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1388 return false; 1389 1390 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1391 // where F adds one of the following at most once: 1392 // - a pointer 1393 // - a member pointer 1394 // - a block pointer 1395 CanQualType CanTo = Context.getCanonicalType(ToType); 1396 CanQualType CanFrom = Context.getCanonicalType(FromType); 1397 Type::TypeClass TyClass = CanTo->getTypeClass(); 1398 if (TyClass != CanFrom->getTypeClass()) return false; 1399 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1400 if (TyClass == Type::Pointer) { 1401 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1402 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1403 } else if (TyClass == Type::BlockPointer) { 1404 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1405 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1406 } else if (TyClass == Type::MemberPointer) { 1407 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1408 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1409 } else { 1410 return false; 1411 } 1412 1413 TyClass = CanTo->getTypeClass(); 1414 if (TyClass != CanFrom->getTypeClass()) return false; 1415 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1416 return false; 1417 } 1418 1419 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1420 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1421 if (!EInfo.getNoReturn()) return false; 1422 1423 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1424 assert(QualType(FromFn, 0).isCanonical()); 1425 if (QualType(FromFn, 0) != CanTo) return false; 1426 1427 ResultTy = ToType; 1428 return true; 1429 } 1430 1431 /// \brief Determine whether the conversion from FromType to ToType is a valid 1432 /// vector conversion. 1433 /// 1434 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1435 /// conversion. 1436 static bool IsVectorConversion(Sema &S, QualType FromType, 1437 QualType ToType, ImplicitConversionKind &ICK) { 1438 // We need at least one of these types to be a vector type to have a vector 1439 // conversion. 1440 if (!ToType->isVectorType() && !FromType->isVectorType()) 1441 return false; 1442 1443 // Identical types require no conversions. 1444 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1445 return false; 1446 1447 // There are no conversions between extended vector types, only identity. 1448 if (ToType->isExtVectorType()) { 1449 // There are no conversions between extended vector types other than the 1450 // identity conversion. 1451 if (FromType->isExtVectorType()) 1452 return false; 1453 1454 // Vector splat from any arithmetic type to a vector. 1455 if (FromType->isArithmeticType()) { 1456 ICK = ICK_Vector_Splat; 1457 return true; 1458 } 1459 } 1460 1461 // We can perform the conversion between vector types in the following cases: 1462 // 1)vector types are equivalent AltiVec and GCC vector types 1463 // 2)lax vector conversions are permitted and the vector types are of the 1464 // same size 1465 if (ToType->isVectorType() && FromType->isVectorType()) { 1466 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1467 S.isLaxVectorConversion(FromType, ToType)) { 1468 ICK = ICK_Vector_Conversion; 1469 return true; 1470 } 1471 } 1472 1473 return false; 1474 } 1475 1476 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1477 bool InOverloadResolution, 1478 StandardConversionSequence &SCS, 1479 bool CStyle); 1480 1481 /// IsStandardConversion - Determines whether there is a standard 1482 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1483 /// expression From to the type ToType. Standard conversion sequences 1484 /// only consider non-class types; for conversions that involve class 1485 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1486 /// contain the standard conversion sequence required to perform this 1487 /// conversion and this routine will return true. Otherwise, this 1488 /// routine will return false and the value of SCS is unspecified. 1489 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1490 bool InOverloadResolution, 1491 StandardConversionSequence &SCS, 1492 bool CStyle, 1493 bool AllowObjCWritebackConversion) { 1494 QualType FromType = From->getType(); 1495 1496 // Standard conversions (C++ [conv]) 1497 SCS.setAsIdentityConversion(); 1498 SCS.IncompatibleObjC = false; 1499 SCS.setFromType(FromType); 1500 SCS.CopyConstructor = nullptr; 1501 1502 // There are no standard conversions for class types in C++, so 1503 // abort early. When overloading in C, however, we do permit them. 1504 if (S.getLangOpts().CPlusPlus && 1505 (FromType->isRecordType() || ToType->isRecordType())) 1506 return false; 1507 1508 // The first conversion can be an lvalue-to-rvalue conversion, 1509 // array-to-pointer conversion, or function-to-pointer conversion 1510 // (C++ 4p1). 1511 1512 if (FromType == S.Context.OverloadTy) { 1513 DeclAccessPair AccessPair; 1514 if (FunctionDecl *Fn 1515 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1516 AccessPair)) { 1517 // We were able to resolve the address of the overloaded function, 1518 // so we can convert to the type of that function. 1519 FromType = Fn->getType(); 1520 SCS.setFromType(FromType); 1521 1522 // we can sometimes resolve &foo<int> regardless of ToType, so check 1523 // if the type matches (identity) or we are converting to bool 1524 if (!S.Context.hasSameUnqualifiedType( 1525 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1526 QualType resultTy; 1527 // if the function type matches except for [[noreturn]], it's ok 1528 if (!S.IsNoReturnConversion(FromType, 1529 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1530 // otherwise, only a boolean conversion is standard 1531 if (!ToType->isBooleanType()) 1532 return false; 1533 } 1534 1535 // Check if the "from" expression is taking the address of an overloaded 1536 // function and recompute the FromType accordingly. Take advantage of the 1537 // fact that non-static member functions *must* have such an address-of 1538 // expression. 1539 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1540 if (Method && !Method->isStatic()) { 1541 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1542 "Non-unary operator on non-static member address"); 1543 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1544 == UO_AddrOf && 1545 "Non-address-of operator on non-static member address"); 1546 const Type *ClassType 1547 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1548 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1549 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1550 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1551 UO_AddrOf && 1552 "Non-address-of operator for overloaded function expression"); 1553 FromType = S.Context.getPointerType(FromType); 1554 } 1555 1556 // Check that we've computed the proper type after overload resolution. 1557 assert(S.Context.hasSameType( 1558 FromType, 1559 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1560 } else { 1561 return false; 1562 } 1563 } 1564 // Lvalue-to-rvalue conversion (C++11 4.1): 1565 // A glvalue (3.10) of a non-function, non-array type T can 1566 // be converted to a prvalue. 1567 bool argIsLValue = From->isGLValue(); 1568 if (argIsLValue && 1569 !FromType->isFunctionType() && !FromType->isArrayType() && 1570 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1571 SCS.First = ICK_Lvalue_To_Rvalue; 1572 1573 // C11 6.3.2.1p2: 1574 // ... if the lvalue has atomic type, the value has the non-atomic version 1575 // of the type of the lvalue ... 1576 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1577 FromType = Atomic->getValueType(); 1578 1579 // If T is a non-class type, the type of the rvalue is the 1580 // cv-unqualified version of T. Otherwise, the type of the rvalue 1581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1582 // just strip the qualifiers because they don't matter. 1583 FromType = FromType.getUnqualifiedType(); 1584 } else if (FromType->isArrayType()) { 1585 // Array-to-pointer conversion (C++ 4.2) 1586 SCS.First = ICK_Array_To_Pointer; 1587 1588 // An lvalue or rvalue of type "array of N T" or "array of unknown 1589 // bound of T" can be converted to an rvalue of type "pointer to 1590 // T" (C++ 4.2p1). 1591 FromType = S.Context.getArrayDecayedType(FromType); 1592 1593 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1594 // This conversion is deprecated in C++03 (D.4) 1595 SCS.DeprecatedStringLiteralToCharPtr = true; 1596 1597 // For the purpose of ranking in overload resolution 1598 // (13.3.3.1.1), this conversion is considered an 1599 // array-to-pointer conversion followed by a qualification 1600 // conversion (4.4). (C++ 4.2p2) 1601 SCS.Second = ICK_Identity; 1602 SCS.Third = ICK_Qualification; 1603 SCS.QualificationIncludesObjCLifetime = false; 1604 SCS.setAllToTypes(FromType); 1605 return true; 1606 } 1607 } else if (FromType->isFunctionType() && argIsLValue) { 1608 // Function-to-pointer conversion (C++ 4.3). 1609 SCS.First = ICK_Function_To_Pointer; 1610 1611 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1612 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1613 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1614 return false; 1615 1616 // An lvalue of function type T can be converted to an rvalue of 1617 // type "pointer to T." The result is a pointer to the 1618 // function. (C++ 4.3p1). 1619 FromType = S.Context.getPointerType(FromType); 1620 } else { 1621 // We don't require any conversions for the first step. 1622 SCS.First = ICK_Identity; 1623 } 1624 SCS.setToType(0, FromType); 1625 1626 // The second conversion can be an integral promotion, floating 1627 // point promotion, integral conversion, floating point conversion, 1628 // floating-integral conversion, pointer conversion, 1629 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1630 // For overloading in C, this can also be a "compatible-type" 1631 // conversion. 1632 bool IncompatibleObjC = false; 1633 ImplicitConversionKind SecondICK = ICK_Identity; 1634 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1635 // The unqualified versions of the types are the same: there's no 1636 // conversion to do. 1637 SCS.Second = ICK_Identity; 1638 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1639 // Integral promotion (C++ 4.5). 1640 SCS.Second = ICK_Integral_Promotion; 1641 FromType = ToType.getUnqualifiedType(); 1642 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1643 // Floating point promotion (C++ 4.6). 1644 SCS.Second = ICK_Floating_Promotion; 1645 FromType = ToType.getUnqualifiedType(); 1646 } else if (S.IsComplexPromotion(FromType, ToType)) { 1647 // Complex promotion (Clang extension) 1648 SCS.Second = ICK_Complex_Promotion; 1649 FromType = ToType.getUnqualifiedType(); 1650 } else if (ToType->isBooleanType() && 1651 (FromType->isArithmeticType() || 1652 FromType->isAnyPointerType() || 1653 FromType->isBlockPointerType() || 1654 FromType->isMemberPointerType() || 1655 FromType->isNullPtrType())) { 1656 // Boolean conversions (C++ 4.12). 1657 SCS.Second = ICK_Boolean_Conversion; 1658 FromType = S.Context.BoolTy; 1659 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1660 ToType->isIntegralType(S.Context)) { 1661 // Integral conversions (C++ 4.7). 1662 SCS.Second = ICK_Integral_Conversion; 1663 FromType = ToType.getUnqualifiedType(); 1664 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1665 // Complex conversions (C99 6.3.1.6) 1666 SCS.Second = ICK_Complex_Conversion; 1667 FromType = ToType.getUnqualifiedType(); 1668 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1669 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1670 // Complex-real conversions (C99 6.3.1.7) 1671 SCS.Second = ICK_Complex_Real; 1672 FromType = ToType.getUnqualifiedType(); 1673 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1674 // Floating point conversions (C++ 4.8). 1675 SCS.Second = ICK_Floating_Conversion; 1676 FromType = ToType.getUnqualifiedType(); 1677 } else if ((FromType->isRealFloatingType() && 1678 ToType->isIntegralType(S.Context)) || 1679 (FromType->isIntegralOrUnscopedEnumerationType() && 1680 ToType->isRealFloatingType())) { 1681 // Floating-integral conversions (C++ 4.9). 1682 SCS.Second = ICK_Floating_Integral; 1683 FromType = ToType.getUnqualifiedType(); 1684 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1685 SCS.Second = ICK_Block_Pointer_Conversion; 1686 } else if (AllowObjCWritebackConversion && 1687 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1688 SCS.Second = ICK_Writeback_Conversion; 1689 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1690 FromType, IncompatibleObjC)) { 1691 // Pointer conversions (C++ 4.10). 1692 SCS.Second = ICK_Pointer_Conversion; 1693 SCS.IncompatibleObjC = IncompatibleObjC; 1694 FromType = FromType.getUnqualifiedType(); 1695 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1696 InOverloadResolution, FromType)) { 1697 // Pointer to member conversions (4.11). 1698 SCS.Second = ICK_Pointer_Member; 1699 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1700 SCS.Second = SecondICK; 1701 FromType = ToType.getUnqualifiedType(); 1702 } else if (!S.getLangOpts().CPlusPlus && 1703 S.Context.typesAreCompatible(ToType, FromType)) { 1704 // Compatible conversions (Clang extension for C function overloading) 1705 SCS.Second = ICK_Compatible_Conversion; 1706 FromType = ToType.getUnqualifiedType(); 1707 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1708 // Treat a conversion that strips "noreturn" as an identity conversion. 1709 SCS.Second = ICK_NoReturn_Adjustment; 1710 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1711 InOverloadResolution, 1712 SCS, CStyle)) { 1713 SCS.Second = ICK_TransparentUnionConversion; 1714 FromType = ToType; 1715 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1716 CStyle)) { 1717 // tryAtomicConversion has updated the standard conversion sequence 1718 // appropriately. 1719 return true; 1720 } else if (ToType->isEventT() && 1721 From->isIntegerConstantExpr(S.getASTContext()) && 1722 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1723 SCS.Second = ICK_Zero_Event_Conversion; 1724 FromType = ToType; 1725 } else { 1726 // No second conversion required. 1727 SCS.Second = ICK_Identity; 1728 } 1729 SCS.setToType(1, FromType); 1730 1731 QualType CanonFrom; 1732 QualType CanonTo; 1733 // The third conversion can be a qualification conversion (C++ 4p1). 1734 bool ObjCLifetimeConversion; 1735 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1736 ObjCLifetimeConversion)) { 1737 SCS.Third = ICK_Qualification; 1738 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1739 FromType = ToType; 1740 CanonFrom = S.Context.getCanonicalType(FromType); 1741 CanonTo = S.Context.getCanonicalType(ToType); 1742 } else { 1743 // No conversion required 1744 SCS.Third = ICK_Identity; 1745 1746 // C++ [over.best.ics]p6: 1747 // [...] Any difference in top-level cv-qualification is 1748 // subsumed by the initialization itself and does not constitute 1749 // a conversion. [...] 1750 CanonFrom = S.Context.getCanonicalType(FromType); 1751 CanonTo = S.Context.getCanonicalType(ToType); 1752 if (CanonFrom.getLocalUnqualifiedType() 1753 == CanonTo.getLocalUnqualifiedType() && 1754 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1755 FromType = ToType; 1756 CanonFrom = CanonTo; 1757 } 1758 } 1759 SCS.setToType(2, FromType); 1760 1761 if (CanonFrom == CanonTo) 1762 return true; 1763 1764 // If we have not converted the argument type to the parameter type, 1765 // this is a bad conversion sequence, unless we're resolving an overload in C. 1766 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1767 return false; 1768 1769 ExprResult ER = ExprResult{From}; 1770 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1771 /*Diagnose=*/false, 1772 /*DiagnoseCFAudited=*/false, 1773 /*ConvertRHS=*/false); 1774 if (Conv != Sema::Compatible) 1775 return false; 1776 1777 SCS.setAllToTypes(ToType); 1778 // We need to set all three because we want this conversion to rank terribly, 1779 // and we don't know what conversions it may overlap with. 1780 SCS.First = ICK_C_Only_Conversion; 1781 SCS.Second = ICK_C_Only_Conversion; 1782 SCS.Third = ICK_C_Only_Conversion; 1783 return true; 1784 } 1785 1786 static bool 1787 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1788 QualType &ToType, 1789 bool InOverloadResolution, 1790 StandardConversionSequence &SCS, 1791 bool CStyle) { 1792 1793 const RecordType *UT = ToType->getAsUnionType(); 1794 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1795 return false; 1796 // The field to initialize within the transparent union. 1797 RecordDecl *UD = UT->getDecl(); 1798 // It's compatible if the expression matches any of the fields. 1799 for (const auto *it : UD->fields()) { 1800 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1801 CStyle, /*ObjCWritebackConversion=*/false)) { 1802 ToType = it->getType(); 1803 return true; 1804 } 1805 } 1806 return false; 1807 } 1808 1809 /// IsIntegralPromotion - Determines whether the conversion from the 1810 /// expression From (whose potentially-adjusted type is FromType) to 1811 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1812 /// sets PromotedType to the promoted type. 1813 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1814 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1815 // All integers are built-in. 1816 if (!To) { 1817 return false; 1818 } 1819 1820 // An rvalue of type char, signed char, unsigned char, short int, or 1821 // unsigned short int can be converted to an rvalue of type int if 1822 // int can represent all the values of the source type; otherwise, 1823 // the source rvalue can be converted to an rvalue of type unsigned 1824 // int (C++ 4.5p1). 1825 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1826 !FromType->isEnumeralType()) { 1827 if (// We can promote any signed, promotable integer type to an int 1828 (FromType->isSignedIntegerType() || 1829 // We can promote any unsigned integer type whose size is 1830 // less than int to an int. 1831 (!FromType->isSignedIntegerType() && 1832 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1833 return To->getKind() == BuiltinType::Int; 1834 } 1835 1836 return To->getKind() == BuiltinType::UInt; 1837 } 1838 1839 // C++11 [conv.prom]p3: 1840 // A prvalue of an unscoped enumeration type whose underlying type is not 1841 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1842 // following types that can represent all the values of the enumeration 1843 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1844 // unsigned int, long int, unsigned long int, long long int, or unsigned 1845 // long long int. If none of the types in that list can represent all the 1846 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1847 // type can be converted to an rvalue a prvalue of the extended integer type 1848 // with lowest integer conversion rank (4.13) greater than the rank of long 1849 // long in which all the values of the enumeration can be represented. If 1850 // there are two such extended types, the signed one is chosen. 1851 // C++11 [conv.prom]p4: 1852 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1853 // can be converted to a prvalue of its underlying type. Moreover, if 1854 // integral promotion can be applied to its underlying type, a prvalue of an 1855 // unscoped enumeration type whose underlying type is fixed can also be 1856 // converted to a prvalue of the promoted underlying type. 1857 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1858 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1859 // provided for a scoped enumeration. 1860 if (FromEnumType->getDecl()->isScoped()) 1861 return false; 1862 1863 // We can perform an integral promotion to the underlying type of the enum, 1864 // even if that's not the promoted type. Note that the check for promoting 1865 // the underlying type is based on the type alone, and does not consider 1866 // the bitfield-ness of the actual source expression. 1867 if (FromEnumType->getDecl()->isFixed()) { 1868 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1869 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1870 IsIntegralPromotion(nullptr, Underlying, ToType); 1871 } 1872 1873 // We have already pre-calculated the promotion type, so this is trivial. 1874 if (ToType->isIntegerType() && 1875 isCompleteType(From->getLocStart(), FromType)) 1876 return Context.hasSameUnqualifiedType( 1877 ToType, FromEnumType->getDecl()->getPromotionType()); 1878 } 1879 1880 // C++0x [conv.prom]p2: 1881 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1882 // to an rvalue a prvalue of the first of the following types that can 1883 // represent all the values of its underlying type: int, unsigned int, 1884 // long int, unsigned long int, long long int, or unsigned long long int. 1885 // If none of the types in that list can represent all the values of its 1886 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1887 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1888 // type. 1889 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1890 ToType->isIntegerType()) { 1891 // Determine whether the type we're converting from is signed or 1892 // unsigned. 1893 bool FromIsSigned = FromType->isSignedIntegerType(); 1894 uint64_t FromSize = Context.getTypeSize(FromType); 1895 1896 // The types we'll try to promote to, in the appropriate 1897 // order. Try each of these types. 1898 QualType PromoteTypes[6] = { 1899 Context.IntTy, Context.UnsignedIntTy, 1900 Context.LongTy, Context.UnsignedLongTy , 1901 Context.LongLongTy, Context.UnsignedLongLongTy 1902 }; 1903 for (int Idx = 0; Idx < 6; ++Idx) { 1904 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1905 if (FromSize < ToSize || 1906 (FromSize == ToSize && 1907 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1908 // We found the type that we can promote to. If this is the 1909 // type we wanted, we have a promotion. Otherwise, no 1910 // promotion. 1911 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1912 } 1913 } 1914 } 1915 1916 // An rvalue for an integral bit-field (9.6) can be converted to an 1917 // rvalue of type int if int can represent all the values of the 1918 // bit-field; otherwise, it can be converted to unsigned int if 1919 // unsigned int can represent all the values of the bit-field. If 1920 // the bit-field is larger yet, no integral promotion applies to 1921 // it. If the bit-field has an enumerated type, it is treated as any 1922 // other value of that type for promotion purposes (C++ 4.5p3). 1923 // FIXME: We should delay checking of bit-fields until we actually perform the 1924 // conversion. 1925 if (From) { 1926 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1927 llvm::APSInt BitWidth; 1928 if (FromType->isIntegralType(Context) && 1929 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1930 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1931 ToSize = Context.getTypeSize(ToType); 1932 1933 // Are we promoting to an int from a bitfield that fits in an int? 1934 if (BitWidth < ToSize || 1935 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1936 return To->getKind() == BuiltinType::Int; 1937 } 1938 1939 // Are we promoting to an unsigned int from an unsigned bitfield 1940 // that fits into an unsigned int? 1941 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1942 return To->getKind() == BuiltinType::UInt; 1943 } 1944 1945 return false; 1946 } 1947 } 1948 } 1949 1950 // An rvalue of type bool can be converted to an rvalue of type int, 1951 // with false becoming zero and true becoming one (C++ 4.5p4). 1952 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1953 return true; 1954 } 1955 1956 return false; 1957 } 1958 1959 /// IsFloatingPointPromotion - Determines whether the conversion from 1960 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1961 /// returns true and sets PromotedType to the promoted type. 1962 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1963 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1964 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1965 /// An rvalue of type float can be converted to an rvalue of type 1966 /// double. (C++ 4.6p1). 1967 if (FromBuiltin->getKind() == BuiltinType::Float && 1968 ToBuiltin->getKind() == BuiltinType::Double) 1969 return true; 1970 1971 // C99 6.3.1.5p1: 1972 // When a float is promoted to double or long double, or a 1973 // double is promoted to long double [...]. 1974 if (!getLangOpts().CPlusPlus && 1975 (FromBuiltin->getKind() == BuiltinType::Float || 1976 FromBuiltin->getKind() == BuiltinType::Double) && 1977 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1978 return true; 1979 1980 // Half can be promoted to float. 1981 if (!getLangOpts().NativeHalfType && 1982 FromBuiltin->getKind() == BuiltinType::Half && 1983 ToBuiltin->getKind() == BuiltinType::Float) 1984 return true; 1985 } 1986 1987 return false; 1988 } 1989 1990 /// \brief Determine if a conversion is a complex promotion. 1991 /// 1992 /// A complex promotion is defined as a complex -> complex conversion 1993 /// where the conversion between the underlying real types is a 1994 /// floating-point or integral promotion. 1995 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1996 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1997 if (!FromComplex) 1998 return false; 1999 2000 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2001 if (!ToComplex) 2002 return false; 2003 2004 return IsFloatingPointPromotion(FromComplex->getElementType(), 2005 ToComplex->getElementType()) || 2006 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2007 ToComplex->getElementType()); 2008 } 2009 2010 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2011 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2012 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2013 /// if non-empty, will be a pointer to ToType that may or may not have 2014 /// the right set of qualifiers on its pointee. 2015 /// 2016 static QualType 2017 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2018 QualType ToPointee, QualType ToType, 2019 ASTContext &Context, 2020 bool StripObjCLifetime = false) { 2021 assert((FromPtr->getTypeClass() == Type::Pointer || 2022 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2023 "Invalid similarly-qualified pointer type"); 2024 2025 /// Conversions to 'id' subsume cv-qualifier conversions. 2026 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2027 return ToType.getUnqualifiedType(); 2028 2029 QualType CanonFromPointee 2030 = Context.getCanonicalType(FromPtr->getPointeeType()); 2031 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2032 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2033 2034 if (StripObjCLifetime) 2035 Quals.removeObjCLifetime(); 2036 2037 // Exact qualifier match -> return the pointer type we're converting to. 2038 if (CanonToPointee.getLocalQualifiers() == Quals) { 2039 // ToType is exactly what we need. Return it. 2040 if (!ToType.isNull()) 2041 return ToType.getUnqualifiedType(); 2042 2043 // Build a pointer to ToPointee. It has the right qualifiers 2044 // already. 2045 if (isa<ObjCObjectPointerType>(ToType)) 2046 return Context.getObjCObjectPointerType(ToPointee); 2047 return Context.getPointerType(ToPointee); 2048 } 2049 2050 // Just build a canonical type that has the right qualifiers. 2051 QualType QualifiedCanonToPointee 2052 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2053 2054 if (isa<ObjCObjectPointerType>(ToType)) 2055 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2056 return Context.getPointerType(QualifiedCanonToPointee); 2057 } 2058 2059 static bool isNullPointerConstantForConversion(Expr *Expr, 2060 bool InOverloadResolution, 2061 ASTContext &Context) { 2062 // Handle value-dependent integral null pointer constants correctly. 2063 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2064 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2065 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2066 return !InOverloadResolution; 2067 2068 return Expr->isNullPointerConstant(Context, 2069 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2070 : Expr::NPC_ValueDependentIsNull); 2071 } 2072 2073 /// IsPointerConversion - Determines whether the conversion of the 2074 /// expression From, which has the (possibly adjusted) type FromType, 2075 /// can be converted to the type ToType via a pointer conversion (C++ 2076 /// 4.10). If so, returns true and places the converted type (that 2077 /// might differ from ToType in its cv-qualifiers at some level) into 2078 /// ConvertedType. 2079 /// 2080 /// This routine also supports conversions to and from block pointers 2081 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2082 /// pointers to interfaces. FIXME: Once we've determined the 2083 /// appropriate overloading rules for Objective-C, we may want to 2084 /// split the Objective-C checks into a different routine; however, 2085 /// GCC seems to consider all of these conversions to be pointer 2086 /// conversions, so for now they live here. IncompatibleObjC will be 2087 /// set if the conversion is an allowed Objective-C conversion that 2088 /// should result in a warning. 2089 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2090 bool InOverloadResolution, 2091 QualType& ConvertedType, 2092 bool &IncompatibleObjC) { 2093 IncompatibleObjC = false; 2094 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2095 IncompatibleObjC)) 2096 return true; 2097 2098 // Conversion from a null pointer constant to any Objective-C pointer type. 2099 if (ToType->isObjCObjectPointerType() && 2100 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2101 ConvertedType = ToType; 2102 return true; 2103 } 2104 2105 // Blocks: Block pointers can be converted to void*. 2106 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2107 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2108 ConvertedType = ToType; 2109 return true; 2110 } 2111 // Blocks: A null pointer constant can be converted to a block 2112 // pointer type. 2113 if (ToType->isBlockPointerType() && 2114 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2115 ConvertedType = ToType; 2116 return true; 2117 } 2118 2119 // If the left-hand-side is nullptr_t, the right side can be a null 2120 // pointer constant. 2121 if (ToType->isNullPtrType() && 2122 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2123 ConvertedType = ToType; 2124 return true; 2125 } 2126 2127 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2128 if (!ToTypePtr) 2129 return false; 2130 2131 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2132 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2133 ConvertedType = ToType; 2134 return true; 2135 } 2136 2137 // Beyond this point, both types need to be pointers 2138 // , including objective-c pointers. 2139 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2140 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2141 !getLangOpts().ObjCAutoRefCount) { 2142 ConvertedType = BuildSimilarlyQualifiedPointerType( 2143 FromType->getAs<ObjCObjectPointerType>(), 2144 ToPointeeType, 2145 ToType, Context); 2146 return true; 2147 } 2148 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2149 if (!FromTypePtr) 2150 return false; 2151 2152 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2153 2154 // If the unqualified pointee types are the same, this can't be a 2155 // pointer conversion, so don't do all of the work below. 2156 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2157 return false; 2158 2159 // An rvalue of type "pointer to cv T," where T is an object type, 2160 // can be converted to an rvalue of type "pointer to cv void" (C++ 2161 // 4.10p2). 2162 if (FromPointeeType->isIncompleteOrObjectType() && 2163 ToPointeeType->isVoidType()) { 2164 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2165 ToPointeeType, 2166 ToType, Context, 2167 /*StripObjCLifetime=*/true); 2168 return true; 2169 } 2170 2171 // MSVC allows implicit function to void* type conversion. 2172 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2173 ToPointeeType->isVoidType()) { 2174 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2175 ToPointeeType, 2176 ToType, Context); 2177 return true; 2178 } 2179 2180 // When we're overloading in C, we allow a special kind of pointer 2181 // conversion for compatible-but-not-identical pointee types. 2182 if (!getLangOpts().CPlusPlus && 2183 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2184 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2185 ToPointeeType, 2186 ToType, Context); 2187 return true; 2188 } 2189 2190 // C++ [conv.ptr]p3: 2191 // 2192 // An rvalue of type "pointer to cv D," where D is a class type, 2193 // can be converted to an rvalue of type "pointer to cv B," where 2194 // B is a base class (clause 10) of D. If B is an inaccessible 2195 // (clause 11) or ambiguous (10.2) base class of D, a program that 2196 // necessitates this conversion is ill-formed. The result of the 2197 // conversion is a pointer to the base class sub-object of the 2198 // derived class object. The null pointer value is converted to 2199 // the null pointer value of the destination type. 2200 // 2201 // Note that we do not check for ambiguity or inaccessibility 2202 // here. That is handled by CheckPointerConversion. 2203 if (getLangOpts().CPlusPlus && 2204 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2205 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2206 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2208 ToPointeeType, 2209 ToType, Context); 2210 return true; 2211 } 2212 2213 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2214 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2215 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2216 ToPointeeType, 2217 ToType, Context); 2218 return true; 2219 } 2220 2221 return false; 2222 } 2223 2224 /// \brief Adopt the given qualifiers for the given type. 2225 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2226 Qualifiers TQs = T.getQualifiers(); 2227 2228 // Check whether qualifiers already match. 2229 if (TQs == Qs) 2230 return T; 2231 2232 if (Qs.compatiblyIncludes(TQs)) 2233 return Context.getQualifiedType(T, Qs); 2234 2235 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2236 } 2237 2238 /// isObjCPointerConversion - Determines whether this is an 2239 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2240 /// with the same arguments and return values. 2241 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2242 QualType& ConvertedType, 2243 bool &IncompatibleObjC) { 2244 if (!getLangOpts().ObjC1) 2245 return false; 2246 2247 // The set of qualifiers on the type we're converting from. 2248 Qualifiers FromQualifiers = FromType.getQualifiers(); 2249 2250 // First, we handle all conversions on ObjC object pointer types. 2251 const ObjCObjectPointerType* ToObjCPtr = 2252 ToType->getAs<ObjCObjectPointerType>(); 2253 const ObjCObjectPointerType *FromObjCPtr = 2254 FromType->getAs<ObjCObjectPointerType>(); 2255 2256 if (ToObjCPtr && FromObjCPtr) { 2257 // If the pointee types are the same (ignoring qualifications), 2258 // then this is not a pointer conversion. 2259 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2260 FromObjCPtr->getPointeeType())) 2261 return false; 2262 2263 // Conversion between Objective-C pointers. 2264 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2265 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2266 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2267 if (getLangOpts().CPlusPlus && LHS && RHS && 2268 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2269 FromObjCPtr->getPointeeType())) 2270 return false; 2271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2272 ToObjCPtr->getPointeeType(), 2273 ToType, Context); 2274 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2275 return true; 2276 } 2277 2278 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2279 // Okay: this is some kind of implicit downcast of Objective-C 2280 // interfaces, which is permitted. However, we're going to 2281 // complain about it. 2282 IncompatibleObjC = true; 2283 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2284 ToObjCPtr->getPointeeType(), 2285 ToType, Context); 2286 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2287 return true; 2288 } 2289 } 2290 // Beyond this point, both types need to be C pointers or block pointers. 2291 QualType ToPointeeType; 2292 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2293 ToPointeeType = ToCPtr->getPointeeType(); 2294 else if (const BlockPointerType *ToBlockPtr = 2295 ToType->getAs<BlockPointerType>()) { 2296 // Objective C++: We're able to convert from a pointer to any object 2297 // to a block pointer type. 2298 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2299 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2300 return true; 2301 } 2302 ToPointeeType = ToBlockPtr->getPointeeType(); 2303 } 2304 else if (FromType->getAs<BlockPointerType>() && 2305 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2306 // Objective C++: We're able to convert from a block pointer type to a 2307 // pointer to any object. 2308 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2309 return true; 2310 } 2311 else 2312 return false; 2313 2314 QualType FromPointeeType; 2315 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2316 FromPointeeType = FromCPtr->getPointeeType(); 2317 else if (const BlockPointerType *FromBlockPtr = 2318 FromType->getAs<BlockPointerType>()) 2319 FromPointeeType = FromBlockPtr->getPointeeType(); 2320 else 2321 return false; 2322 2323 // If we have pointers to pointers, recursively check whether this 2324 // is an Objective-C conversion. 2325 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2326 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2327 IncompatibleObjC)) { 2328 // We always complain about this conversion. 2329 IncompatibleObjC = true; 2330 ConvertedType = Context.getPointerType(ConvertedType); 2331 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2332 return true; 2333 } 2334 // Allow conversion of pointee being objective-c pointer to another one; 2335 // as in I* to id. 2336 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2337 ToPointeeType->getAs<ObjCObjectPointerType>() && 2338 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2339 IncompatibleObjC)) { 2340 2341 ConvertedType = Context.getPointerType(ConvertedType); 2342 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2343 return true; 2344 } 2345 2346 // If we have pointers to functions or blocks, check whether the only 2347 // differences in the argument and result types are in Objective-C 2348 // pointer conversions. If so, we permit the conversion (but 2349 // complain about it). 2350 const FunctionProtoType *FromFunctionType 2351 = FromPointeeType->getAs<FunctionProtoType>(); 2352 const FunctionProtoType *ToFunctionType 2353 = ToPointeeType->getAs<FunctionProtoType>(); 2354 if (FromFunctionType && ToFunctionType) { 2355 // If the function types are exactly the same, this isn't an 2356 // Objective-C pointer conversion. 2357 if (Context.getCanonicalType(FromPointeeType) 2358 == Context.getCanonicalType(ToPointeeType)) 2359 return false; 2360 2361 // Perform the quick checks that will tell us whether these 2362 // function types are obviously different. 2363 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2364 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2365 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2366 return false; 2367 2368 bool HasObjCConversion = false; 2369 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2370 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2371 // Okay, the types match exactly. Nothing to do. 2372 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2373 ToFunctionType->getReturnType(), 2374 ConvertedType, IncompatibleObjC)) { 2375 // Okay, we have an Objective-C pointer conversion. 2376 HasObjCConversion = true; 2377 } else { 2378 // Function types are too different. Abort. 2379 return false; 2380 } 2381 2382 // Check argument types. 2383 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2384 ArgIdx != NumArgs; ++ArgIdx) { 2385 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2386 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2387 if (Context.getCanonicalType(FromArgType) 2388 == Context.getCanonicalType(ToArgType)) { 2389 // Okay, the types match exactly. Nothing to do. 2390 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2391 ConvertedType, IncompatibleObjC)) { 2392 // Okay, we have an Objective-C pointer conversion. 2393 HasObjCConversion = true; 2394 } else { 2395 // Argument types are too different. Abort. 2396 return false; 2397 } 2398 } 2399 2400 if (HasObjCConversion) { 2401 // We had an Objective-C conversion. Allow this pointer 2402 // conversion, but complain about it. 2403 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2404 IncompatibleObjC = true; 2405 return true; 2406 } 2407 } 2408 2409 return false; 2410 } 2411 2412 /// \brief Determine whether this is an Objective-C writeback conversion, 2413 /// used for parameter passing when performing automatic reference counting. 2414 /// 2415 /// \param FromType The type we're converting form. 2416 /// 2417 /// \param ToType The type we're converting to. 2418 /// 2419 /// \param ConvertedType The type that will be produced after applying 2420 /// this conversion. 2421 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2422 QualType &ConvertedType) { 2423 if (!getLangOpts().ObjCAutoRefCount || 2424 Context.hasSameUnqualifiedType(FromType, ToType)) 2425 return false; 2426 2427 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2428 QualType ToPointee; 2429 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2430 ToPointee = ToPointer->getPointeeType(); 2431 else 2432 return false; 2433 2434 Qualifiers ToQuals = ToPointee.getQualifiers(); 2435 if (!ToPointee->isObjCLifetimeType() || 2436 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2437 !ToQuals.withoutObjCLifetime().empty()) 2438 return false; 2439 2440 // Argument must be a pointer to __strong to __weak. 2441 QualType FromPointee; 2442 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2443 FromPointee = FromPointer->getPointeeType(); 2444 else 2445 return false; 2446 2447 Qualifiers FromQuals = FromPointee.getQualifiers(); 2448 if (!FromPointee->isObjCLifetimeType() || 2449 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2450 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2451 return false; 2452 2453 // Make sure that we have compatible qualifiers. 2454 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2455 if (!ToQuals.compatiblyIncludes(FromQuals)) 2456 return false; 2457 2458 // Remove qualifiers from the pointee type we're converting from; they 2459 // aren't used in the compatibility check belong, and we'll be adding back 2460 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2461 FromPointee = FromPointee.getUnqualifiedType(); 2462 2463 // The unqualified form of the pointee types must be compatible. 2464 ToPointee = ToPointee.getUnqualifiedType(); 2465 bool IncompatibleObjC; 2466 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2467 FromPointee = ToPointee; 2468 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2469 IncompatibleObjC)) 2470 return false; 2471 2472 /// \brief Construct the type we're converting to, which is a pointer to 2473 /// __autoreleasing pointee. 2474 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2475 ConvertedType = Context.getPointerType(FromPointee); 2476 return true; 2477 } 2478 2479 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2480 QualType& ConvertedType) { 2481 QualType ToPointeeType; 2482 if (const BlockPointerType *ToBlockPtr = 2483 ToType->getAs<BlockPointerType>()) 2484 ToPointeeType = ToBlockPtr->getPointeeType(); 2485 else 2486 return false; 2487 2488 QualType FromPointeeType; 2489 if (const BlockPointerType *FromBlockPtr = 2490 FromType->getAs<BlockPointerType>()) 2491 FromPointeeType = FromBlockPtr->getPointeeType(); 2492 else 2493 return false; 2494 // We have pointer to blocks, check whether the only 2495 // differences in the argument and result types are in Objective-C 2496 // pointer conversions. If so, we permit the conversion. 2497 2498 const FunctionProtoType *FromFunctionType 2499 = FromPointeeType->getAs<FunctionProtoType>(); 2500 const FunctionProtoType *ToFunctionType 2501 = ToPointeeType->getAs<FunctionProtoType>(); 2502 2503 if (!FromFunctionType || !ToFunctionType) 2504 return false; 2505 2506 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2507 return true; 2508 2509 // Perform the quick checks that will tell us whether these 2510 // function types are obviously different. 2511 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2512 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2513 return false; 2514 2515 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2516 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2517 if (FromEInfo != ToEInfo) 2518 return false; 2519 2520 bool IncompatibleObjC = false; 2521 if (Context.hasSameType(FromFunctionType->getReturnType(), 2522 ToFunctionType->getReturnType())) { 2523 // Okay, the types match exactly. Nothing to do. 2524 } else { 2525 QualType RHS = FromFunctionType->getReturnType(); 2526 QualType LHS = ToFunctionType->getReturnType(); 2527 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2528 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2529 LHS = LHS.getUnqualifiedType(); 2530 2531 if (Context.hasSameType(RHS,LHS)) { 2532 // OK exact match. 2533 } else if (isObjCPointerConversion(RHS, LHS, 2534 ConvertedType, IncompatibleObjC)) { 2535 if (IncompatibleObjC) 2536 return false; 2537 // Okay, we have an Objective-C pointer conversion. 2538 } 2539 else 2540 return false; 2541 } 2542 2543 // Check argument types. 2544 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2545 ArgIdx != NumArgs; ++ArgIdx) { 2546 IncompatibleObjC = false; 2547 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2548 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2549 if (Context.hasSameType(FromArgType, ToArgType)) { 2550 // Okay, the types match exactly. Nothing to do. 2551 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2552 ConvertedType, IncompatibleObjC)) { 2553 if (IncompatibleObjC) 2554 return false; 2555 // Okay, we have an Objective-C pointer conversion. 2556 } else 2557 // Argument types are too different. Abort. 2558 return false; 2559 } 2560 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2561 ToFunctionType)) 2562 return false; 2563 2564 ConvertedType = ToType; 2565 return true; 2566 } 2567 2568 enum { 2569 ft_default, 2570 ft_different_class, 2571 ft_parameter_arity, 2572 ft_parameter_mismatch, 2573 ft_return_type, 2574 ft_qualifer_mismatch 2575 }; 2576 2577 /// Attempts to get the FunctionProtoType from a Type. Handles 2578 /// MemberFunctionPointers properly. 2579 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2580 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2581 return FPT; 2582 2583 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2584 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2585 2586 return nullptr; 2587 } 2588 2589 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2590 /// function types. Catches different number of parameter, mismatch in 2591 /// parameter types, and different return types. 2592 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2593 QualType FromType, QualType ToType) { 2594 // If either type is not valid, include no extra info. 2595 if (FromType.isNull() || ToType.isNull()) { 2596 PDiag << ft_default; 2597 return; 2598 } 2599 2600 // Get the function type from the pointers. 2601 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2602 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2603 *ToMember = ToType->getAs<MemberPointerType>(); 2604 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2605 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2606 << QualType(FromMember->getClass(), 0); 2607 return; 2608 } 2609 FromType = FromMember->getPointeeType(); 2610 ToType = ToMember->getPointeeType(); 2611 } 2612 2613 if (FromType->isPointerType()) 2614 FromType = FromType->getPointeeType(); 2615 if (ToType->isPointerType()) 2616 ToType = ToType->getPointeeType(); 2617 2618 // Remove references. 2619 FromType = FromType.getNonReferenceType(); 2620 ToType = ToType.getNonReferenceType(); 2621 2622 // Don't print extra info for non-specialized template functions. 2623 if (FromType->isInstantiationDependentType() && 2624 !FromType->getAs<TemplateSpecializationType>()) { 2625 PDiag << ft_default; 2626 return; 2627 } 2628 2629 // No extra info for same types. 2630 if (Context.hasSameType(FromType, ToType)) { 2631 PDiag << ft_default; 2632 return; 2633 } 2634 2635 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2636 *ToFunction = tryGetFunctionProtoType(ToType); 2637 2638 // Both types need to be function types. 2639 if (!FromFunction || !ToFunction) { 2640 PDiag << ft_default; 2641 return; 2642 } 2643 2644 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2645 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2646 << FromFunction->getNumParams(); 2647 return; 2648 } 2649 2650 // Handle different parameter types. 2651 unsigned ArgPos; 2652 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2653 PDiag << ft_parameter_mismatch << ArgPos + 1 2654 << ToFunction->getParamType(ArgPos) 2655 << FromFunction->getParamType(ArgPos); 2656 return; 2657 } 2658 2659 // Handle different return type. 2660 if (!Context.hasSameType(FromFunction->getReturnType(), 2661 ToFunction->getReturnType())) { 2662 PDiag << ft_return_type << ToFunction->getReturnType() 2663 << FromFunction->getReturnType(); 2664 return; 2665 } 2666 2667 unsigned FromQuals = FromFunction->getTypeQuals(), 2668 ToQuals = ToFunction->getTypeQuals(); 2669 if (FromQuals != ToQuals) { 2670 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2671 return; 2672 } 2673 2674 // Unable to find a difference, so add no extra info. 2675 PDiag << ft_default; 2676 } 2677 2678 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2679 /// for equality of their argument types. Caller has already checked that 2680 /// they have same number of arguments. If the parameters are different, 2681 /// ArgPos will have the parameter index of the first different parameter. 2682 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2683 const FunctionProtoType *NewType, 2684 unsigned *ArgPos) { 2685 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2686 N = NewType->param_type_begin(), 2687 E = OldType->param_type_end(); 2688 O && (O != E); ++O, ++N) { 2689 if (!Context.hasSameType(O->getUnqualifiedType(), 2690 N->getUnqualifiedType())) { 2691 if (ArgPos) 2692 *ArgPos = O - OldType->param_type_begin(); 2693 return false; 2694 } 2695 } 2696 return true; 2697 } 2698 2699 /// CheckPointerConversion - Check the pointer conversion from the 2700 /// expression From to the type ToType. This routine checks for 2701 /// ambiguous or inaccessible derived-to-base pointer 2702 /// conversions for which IsPointerConversion has already returned 2703 /// true. It returns true and produces a diagnostic if there was an 2704 /// error, or returns false otherwise. 2705 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2706 CastKind &Kind, 2707 CXXCastPath& BasePath, 2708 bool IgnoreBaseAccess, 2709 bool Diagnose) { 2710 QualType FromType = From->getType(); 2711 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2712 2713 Kind = CK_BitCast; 2714 2715 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2716 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2717 Expr::NPCK_ZeroExpression) { 2718 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2719 DiagRuntimeBehavior(From->getExprLoc(), From, 2720 PDiag(diag::warn_impcast_bool_to_null_pointer) 2721 << ToType << From->getSourceRange()); 2722 else if (!isUnevaluatedContext()) 2723 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2724 << ToType << From->getSourceRange(); 2725 } 2726 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2727 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2728 QualType FromPointeeType = FromPtrType->getPointeeType(), 2729 ToPointeeType = ToPtrType->getPointeeType(); 2730 2731 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2732 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2733 // We must have a derived-to-base conversion. Check an 2734 // ambiguous or inaccessible conversion. 2735 unsigned InaccessibleID = 0; 2736 unsigned AmbigiousID = 0; 2737 if (Diagnose) { 2738 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2739 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2740 } 2741 if (CheckDerivedToBaseConversion( 2742 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2743 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2744 &BasePath, IgnoreBaseAccess)) 2745 return true; 2746 2747 // The conversion was successful. 2748 Kind = CK_DerivedToBase; 2749 } 2750 2751 if (Diagnose && !IsCStyleOrFunctionalCast && 2752 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2753 assert(getLangOpts().MSVCCompat && 2754 "this should only be possible with MSVCCompat!"); 2755 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2756 << From->getSourceRange(); 2757 } 2758 } 2759 } else if (const ObjCObjectPointerType *ToPtrType = 2760 ToType->getAs<ObjCObjectPointerType>()) { 2761 if (const ObjCObjectPointerType *FromPtrType = 2762 FromType->getAs<ObjCObjectPointerType>()) { 2763 // Objective-C++ conversions are always okay. 2764 // FIXME: We should have a different class of conversions for the 2765 // Objective-C++ implicit conversions. 2766 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2767 return false; 2768 } else if (FromType->isBlockPointerType()) { 2769 Kind = CK_BlockPointerToObjCPointerCast; 2770 } else { 2771 Kind = CK_CPointerToObjCPointerCast; 2772 } 2773 } else if (ToType->isBlockPointerType()) { 2774 if (!FromType->isBlockPointerType()) 2775 Kind = CK_AnyPointerToBlockPointerCast; 2776 } 2777 2778 // We shouldn't fall into this case unless it's valid for other 2779 // reasons. 2780 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2781 Kind = CK_NullToPointer; 2782 2783 return false; 2784 } 2785 2786 /// IsMemberPointerConversion - Determines whether the conversion of the 2787 /// expression From, which has the (possibly adjusted) type FromType, can be 2788 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2789 /// If so, returns true and places the converted type (that might differ from 2790 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2791 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2792 QualType ToType, 2793 bool InOverloadResolution, 2794 QualType &ConvertedType) { 2795 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2796 if (!ToTypePtr) 2797 return false; 2798 2799 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2800 if (From->isNullPointerConstant(Context, 2801 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2802 : Expr::NPC_ValueDependentIsNull)) { 2803 ConvertedType = ToType; 2804 return true; 2805 } 2806 2807 // Otherwise, both types have to be member pointers. 2808 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2809 if (!FromTypePtr) 2810 return false; 2811 2812 // A pointer to member of B can be converted to a pointer to member of D, 2813 // where D is derived from B (C++ 4.11p2). 2814 QualType FromClass(FromTypePtr->getClass(), 0); 2815 QualType ToClass(ToTypePtr->getClass(), 0); 2816 2817 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2818 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2819 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2820 ToClass.getTypePtr()); 2821 return true; 2822 } 2823 2824 return false; 2825 } 2826 2827 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2828 /// expression From to the type ToType. This routine checks for ambiguous or 2829 /// virtual or inaccessible base-to-derived member pointer conversions 2830 /// for which IsMemberPointerConversion has already returned true. It returns 2831 /// true and produces a diagnostic if there was an error, or returns false 2832 /// otherwise. 2833 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2834 CastKind &Kind, 2835 CXXCastPath &BasePath, 2836 bool IgnoreBaseAccess) { 2837 QualType FromType = From->getType(); 2838 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2839 if (!FromPtrType) { 2840 // This must be a null pointer to member pointer conversion 2841 assert(From->isNullPointerConstant(Context, 2842 Expr::NPC_ValueDependentIsNull) && 2843 "Expr must be null pointer constant!"); 2844 Kind = CK_NullToMemberPointer; 2845 return false; 2846 } 2847 2848 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2849 assert(ToPtrType && "No member pointer cast has a target type " 2850 "that is not a member pointer."); 2851 2852 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2853 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2854 2855 // FIXME: What about dependent types? 2856 assert(FromClass->isRecordType() && "Pointer into non-class."); 2857 assert(ToClass->isRecordType() && "Pointer into non-class."); 2858 2859 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2860 /*DetectVirtual=*/true); 2861 bool DerivationOkay = 2862 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2863 assert(DerivationOkay && 2864 "Should not have been called if derivation isn't OK."); 2865 (void)DerivationOkay; 2866 2867 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2868 getUnqualifiedType())) { 2869 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2870 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2871 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2872 return true; 2873 } 2874 2875 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2876 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2877 << FromClass << ToClass << QualType(VBase, 0) 2878 << From->getSourceRange(); 2879 return true; 2880 } 2881 2882 if (!IgnoreBaseAccess) 2883 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2884 Paths.front(), 2885 diag::err_downcast_from_inaccessible_base); 2886 2887 // Must be a base to derived member conversion. 2888 BuildBasePathArray(Paths, BasePath); 2889 Kind = CK_BaseToDerivedMemberPointer; 2890 return false; 2891 } 2892 2893 /// Determine whether the lifetime conversion between the two given 2894 /// qualifiers sets is nontrivial. 2895 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2896 Qualifiers ToQuals) { 2897 // Converting anything to const __unsafe_unretained is trivial. 2898 if (ToQuals.hasConst() && 2899 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2900 return false; 2901 2902 return true; 2903 } 2904 2905 /// IsQualificationConversion - Determines whether the conversion from 2906 /// an rvalue of type FromType to ToType is a qualification conversion 2907 /// (C++ 4.4). 2908 /// 2909 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2910 /// when the qualification conversion involves a change in the Objective-C 2911 /// object lifetime. 2912 bool 2913 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2914 bool CStyle, bool &ObjCLifetimeConversion) { 2915 FromType = Context.getCanonicalType(FromType); 2916 ToType = Context.getCanonicalType(ToType); 2917 ObjCLifetimeConversion = false; 2918 2919 // If FromType and ToType are the same type, this is not a 2920 // qualification conversion. 2921 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2922 return false; 2923 2924 // (C++ 4.4p4): 2925 // A conversion can add cv-qualifiers at levels other than the first 2926 // in multi-level pointers, subject to the following rules: [...] 2927 bool PreviousToQualsIncludeConst = true; 2928 bool UnwrappedAnyPointer = false; 2929 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2930 // Within each iteration of the loop, we check the qualifiers to 2931 // determine if this still looks like a qualification 2932 // conversion. Then, if all is well, we unwrap one more level of 2933 // pointers or pointers-to-members and do it all again 2934 // until there are no more pointers or pointers-to-members left to 2935 // unwrap. 2936 UnwrappedAnyPointer = true; 2937 2938 Qualifiers FromQuals = FromType.getQualifiers(); 2939 Qualifiers ToQuals = ToType.getQualifiers(); 2940 2941 // Objective-C ARC: 2942 // Check Objective-C lifetime conversions. 2943 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2944 UnwrappedAnyPointer) { 2945 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2946 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2947 ObjCLifetimeConversion = true; 2948 FromQuals.removeObjCLifetime(); 2949 ToQuals.removeObjCLifetime(); 2950 } else { 2951 // Qualification conversions cannot cast between different 2952 // Objective-C lifetime qualifiers. 2953 return false; 2954 } 2955 } 2956 2957 // Allow addition/removal of GC attributes but not changing GC attributes. 2958 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2959 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2960 FromQuals.removeObjCGCAttr(); 2961 ToQuals.removeObjCGCAttr(); 2962 } 2963 2964 // -- for every j > 0, if const is in cv 1,j then const is in cv 2965 // 2,j, and similarly for volatile. 2966 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2967 return false; 2968 2969 // -- if the cv 1,j and cv 2,j are different, then const is in 2970 // every cv for 0 < k < j. 2971 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2972 && !PreviousToQualsIncludeConst) 2973 return false; 2974 2975 // Keep track of whether all prior cv-qualifiers in the "to" type 2976 // include const. 2977 PreviousToQualsIncludeConst 2978 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2979 } 2980 2981 // We are left with FromType and ToType being the pointee types 2982 // after unwrapping the original FromType and ToType the same number 2983 // of types. If we unwrapped any pointers, and if FromType and 2984 // ToType have the same unqualified type (since we checked 2985 // qualifiers above), then this is a qualification conversion. 2986 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2987 } 2988 2989 /// \brief - Determine whether this is a conversion from a scalar type to an 2990 /// atomic type. 2991 /// 2992 /// If successful, updates \c SCS's second and third steps in the conversion 2993 /// sequence to finish the conversion. 2994 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2995 bool InOverloadResolution, 2996 StandardConversionSequence &SCS, 2997 bool CStyle) { 2998 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2999 if (!ToAtomic) 3000 return false; 3001 3002 StandardConversionSequence InnerSCS; 3003 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3004 InOverloadResolution, InnerSCS, 3005 CStyle, /*AllowObjCWritebackConversion=*/false)) 3006 return false; 3007 3008 SCS.Second = InnerSCS.Second; 3009 SCS.setToType(1, InnerSCS.getToType(1)); 3010 SCS.Third = InnerSCS.Third; 3011 SCS.QualificationIncludesObjCLifetime 3012 = InnerSCS.QualificationIncludesObjCLifetime; 3013 SCS.setToType(2, InnerSCS.getToType(2)); 3014 return true; 3015 } 3016 3017 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3018 CXXConstructorDecl *Constructor, 3019 QualType Type) { 3020 const FunctionProtoType *CtorType = 3021 Constructor->getType()->getAs<FunctionProtoType>(); 3022 if (CtorType->getNumParams() > 0) { 3023 QualType FirstArg = CtorType->getParamType(0); 3024 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3025 return true; 3026 } 3027 return false; 3028 } 3029 3030 static OverloadingResult 3031 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3032 CXXRecordDecl *To, 3033 UserDefinedConversionSequence &User, 3034 OverloadCandidateSet &CandidateSet, 3035 bool AllowExplicit) { 3036 DeclContext::lookup_result R = S.LookupConstructors(To); 3037 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3038 Con != ConEnd; ++Con) { 3039 NamedDecl *D = *Con; 3040 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3041 3042 // Find the constructor (which may be a template). 3043 CXXConstructorDecl *Constructor = nullptr; 3044 FunctionTemplateDecl *ConstructorTmpl 3045 = dyn_cast<FunctionTemplateDecl>(D); 3046 if (ConstructorTmpl) 3047 Constructor 3048 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3049 else 3050 Constructor = cast<CXXConstructorDecl>(D); 3051 3052 bool Usable = !Constructor->isInvalidDecl() && 3053 S.isInitListConstructor(Constructor) && 3054 (AllowExplicit || !Constructor->isExplicit()); 3055 if (Usable) { 3056 // If the first argument is (a reference to) the target type, 3057 // suppress conversions. 3058 bool SuppressUserConversions = 3059 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 3060 if (ConstructorTmpl) 3061 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3062 /*ExplicitArgs*/ nullptr, 3063 From, CandidateSet, 3064 SuppressUserConversions); 3065 else 3066 S.AddOverloadCandidate(Constructor, FoundDecl, 3067 From, CandidateSet, 3068 SuppressUserConversions); 3069 } 3070 } 3071 3072 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3073 3074 OverloadCandidateSet::iterator Best; 3075 switch (auto Result = 3076 CandidateSet.BestViableFunction(S, From->getLocStart(), 3077 Best, true)) { 3078 case OR_Deleted: 3079 case OR_Success: { 3080 // Record the standard conversion we used and the conversion function. 3081 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3082 QualType ThisType = Constructor->getThisType(S.Context); 3083 // Initializer lists don't have conversions as such. 3084 User.Before.setAsIdentityConversion(); 3085 User.HadMultipleCandidates = HadMultipleCandidates; 3086 User.ConversionFunction = Constructor; 3087 User.FoundConversionFunction = Best->FoundDecl; 3088 User.After.setAsIdentityConversion(); 3089 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3090 User.After.setAllToTypes(ToType); 3091 return Result; 3092 } 3093 3094 case OR_No_Viable_Function: 3095 return OR_No_Viable_Function; 3096 case OR_Ambiguous: 3097 return OR_Ambiguous; 3098 } 3099 3100 llvm_unreachable("Invalid OverloadResult!"); 3101 } 3102 3103 /// Determines whether there is a user-defined conversion sequence 3104 /// (C++ [over.ics.user]) that converts expression From to the type 3105 /// ToType. If such a conversion exists, User will contain the 3106 /// user-defined conversion sequence that performs such a conversion 3107 /// and this routine will return true. Otherwise, this routine returns 3108 /// false and User is unspecified. 3109 /// 3110 /// \param AllowExplicit true if the conversion should consider C++0x 3111 /// "explicit" conversion functions as well as non-explicit conversion 3112 /// functions (C++0x [class.conv.fct]p2). 3113 /// 3114 /// \param AllowObjCConversionOnExplicit true if the conversion should 3115 /// allow an extra Objective-C pointer conversion on uses of explicit 3116 /// constructors. Requires \c AllowExplicit to also be set. 3117 static OverloadingResult 3118 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3119 UserDefinedConversionSequence &User, 3120 OverloadCandidateSet &CandidateSet, 3121 bool AllowExplicit, 3122 bool AllowObjCConversionOnExplicit) { 3123 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3124 3125 // Whether we will only visit constructors. 3126 bool ConstructorsOnly = false; 3127 3128 // If the type we are conversion to is a class type, enumerate its 3129 // constructors. 3130 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3131 // C++ [over.match.ctor]p1: 3132 // When objects of class type are direct-initialized (8.5), or 3133 // copy-initialized from an expression of the same or a 3134 // derived class type (8.5), overload resolution selects the 3135 // constructor. [...] For copy-initialization, the candidate 3136 // functions are all the converting constructors (12.3.1) of 3137 // that class. The argument list is the expression-list within 3138 // the parentheses of the initializer. 3139 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3140 (From->getType()->getAs<RecordType>() && 3141 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3142 ConstructorsOnly = true; 3143 3144 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3145 // We're not going to find any constructors. 3146 } else if (CXXRecordDecl *ToRecordDecl 3147 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3148 3149 Expr **Args = &From; 3150 unsigned NumArgs = 1; 3151 bool ListInitializing = false; 3152 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3153 // But first, see if there is an init-list-constructor that will work. 3154 OverloadingResult Result = IsInitializerListConstructorConversion( 3155 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3156 if (Result != OR_No_Viable_Function) 3157 return Result; 3158 // Never mind. 3159 CandidateSet.clear(); 3160 3161 // If we're list-initializing, we pass the individual elements as 3162 // arguments, not the entire list. 3163 Args = InitList->getInits(); 3164 NumArgs = InitList->getNumInits(); 3165 ListInitializing = true; 3166 } 3167 3168 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3169 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3170 Con != ConEnd; ++Con) { 3171 NamedDecl *D = *Con; 3172 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3173 3174 // Find the constructor (which may be a template). 3175 CXXConstructorDecl *Constructor = nullptr; 3176 FunctionTemplateDecl *ConstructorTmpl 3177 = dyn_cast<FunctionTemplateDecl>(D); 3178 if (ConstructorTmpl) 3179 Constructor 3180 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3181 else 3182 Constructor = cast<CXXConstructorDecl>(D); 3183 3184 bool Usable = !Constructor->isInvalidDecl(); 3185 if (ListInitializing) 3186 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3187 else 3188 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3189 if (Usable) { 3190 bool SuppressUserConversions = !ConstructorsOnly; 3191 if (SuppressUserConversions && ListInitializing) { 3192 SuppressUserConversions = false; 3193 if (NumArgs == 1) { 3194 // If the first argument is (a reference to) the target type, 3195 // suppress conversions. 3196 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3197 S.Context, Constructor, ToType); 3198 } 3199 } 3200 if (ConstructorTmpl) 3201 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3202 /*ExplicitArgs*/ nullptr, 3203 llvm::makeArrayRef(Args, NumArgs), 3204 CandidateSet, SuppressUserConversions); 3205 else 3206 // Allow one user-defined conversion when user specifies a 3207 // From->ToType conversion via an static cast (c-style, etc). 3208 S.AddOverloadCandidate(Constructor, FoundDecl, 3209 llvm::makeArrayRef(Args, NumArgs), 3210 CandidateSet, SuppressUserConversions); 3211 } 3212 } 3213 } 3214 } 3215 3216 // Enumerate conversion functions, if we're allowed to. 3217 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3218 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3219 // No conversion functions from incomplete types. 3220 } else if (const RecordType *FromRecordType 3221 = From->getType()->getAs<RecordType>()) { 3222 if (CXXRecordDecl *FromRecordDecl 3223 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3224 // Add all of the conversion functions as candidates. 3225 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3226 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3227 DeclAccessPair FoundDecl = I.getPair(); 3228 NamedDecl *D = FoundDecl.getDecl(); 3229 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3230 if (isa<UsingShadowDecl>(D)) 3231 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3232 3233 CXXConversionDecl *Conv; 3234 FunctionTemplateDecl *ConvTemplate; 3235 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3236 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3237 else 3238 Conv = cast<CXXConversionDecl>(D); 3239 3240 if (AllowExplicit || !Conv->isExplicit()) { 3241 if (ConvTemplate) 3242 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3243 ActingContext, From, ToType, 3244 CandidateSet, 3245 AllowObjCConversionOnExplicit); 3246 else 3247 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3248 From, ToType, CandidateSet, 3249 AllowObjCConversionOnExplicit); 3250 } 3251 } 3252 } 3253 } 3254 3255 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3256 3257 OverloadCandidateSet::iterator Best; 3258 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3259 Best, true)) { 3260 case OR_Success: 3261 case OR_Deleted: 3262 // Record the standard conversion we used and the conversion function. 3263 if (CXXConstructorDecl *Constructor 3264 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3265 // C++ [over.ics.user]p1: 3266 // If the user-defined conversion is specified by a 3267 // constructor (12.3.1), the initial standard conversion 3268 // sequence converts the source type to the type required by 3269 // the argument of the constructor. 3270 // 3271 QualType ThisType = Constructor->getThisType(S.Context); 3272 if (isa<InitListExpr>(From)) { 3273 // Initializer lists don't have conversions as such. 3274 User.Before.setAsIdentityConversion(); 3275 } else { 3276 if (Best->Conversions[0].isEllipsis()) 3277 User.EllipsisConversion = true; 3278 else { 3279 User.Before = Best->Conversions[0].Standard; 3280 User.EllipsisConversion = false; 3281 } 3282 } 3283 User.HadMultipleCandidates = HadMultipleCandidates; 3284 User.ConversionFunction = Constructor; 3285 User.FoundConversionFunction = Best->FoundDecl; 3286 User.After.setAsIdentityConversion(); 3287 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3288 User.After.setAllToTypes(ToType); 3289 return Result; 3290 } 3291 if (CXXConversionDecl *Conversion 3292 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3293 // C++ [over.ics.user]p1: 3294 // 3295 // [...] If the user-defined conversion is specified by a 3296 // conversion function (12.3.2), the initial standard 3297 // conversion sequence converts the source type to the 3298 // implicit object parameter of the conversion function. 3299 User.Before = Best->Conversions[0].Standard; 3300 User.HadMultipleCandidates = HadMultipleCandidates; 3301 User.ConversionFunction = Conversion; 3302 User.FoundConversionFunction = Best->FoundDecl; 3303 User.EllipsisConversion = false; 3304 3305 // C++ [over.ics.user]p2: 3306 // The second standard conversion sequence converts the 3307 // result of the user-defined conversion to the target type 3308 // for the sequence. Since an implicit conversion sequence 3309 // is an initialization, the special rules for 3310 // initialization by user-defined conversion apply when 3311 // selecting the best user-defined conversion for a 3312 // user-defined conversion sequence (see 13.3.3 and 3313 // 13.3.3.1). 3314 User.After = Best->FinalConversion; 3315 return Result; 3316 } 3317 llvm_unreachable("Not a constructor or conversion function?"); 3318 3319 case OR_No_Viable_Function: 3320 return OR_No_Viable_Function; 3321 3322 case OR_Ambiguous: 3323 return OR_Ambiguous; 3324 } 3325 3326 llvm_unreachable("Invalid OverloadResult!"); 3327 } 3328 3329 bool 3330 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3331 ImplicitConversionSequence ICS; 3332 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3333 OverloadCandidateSet::CSK_Normal); 3334 OverloadingResult OvResult = 3335 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3336 CandidateSet, false, false); 3337 if (OvResult == OR_Ambiguous) 3338 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3339 << From->getType() << ToType << From->getSourceRange(); 3340 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3341 if (!RequireCompleteType(From->getLocStart(), ToType, 3342 diag::err_typecheck_nonviable_condition_incomplete, 3343 From->getType(), From->getSourceRange())) 3344 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3345 << false << From->getType() << From->getSourceRange() << ToType; 3346 } else 3347 return false; 3348 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3349 return true; 3350 } 3351 3352 /// \brief Compare the user-defined conversion functions or constructors 3353 /// of two user-defined conversion sequences to determine whether any ordering 3354 /// is possible. 3355 static ImplicitConversionSequence::CompareKind 3356 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3357 FunctionDecl *Function2) { 3358 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3359 return ImplicitConversionSequence::Indistinguishable; 3360 3361 // Objective-C++: 3362 // If both conversion functions are implicitly-declared conversions from 3363 // a lambda closure type to a function pointer and a block pointer, 3364 // respectively, always prefer the conversion to a function pointer, 3365 // because the function pointer is more lightweight and is more likely 3366 // to keep code working. 3367 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3368 if (!Conv1) 3369 return ImplicitConversionSequence::Indistinguishable; 3370 3371 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3372 if (!Conv2) 3373 return ImplicitConversionSequence::Indistinguishable; 3374 3375 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3376 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3377 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3378 if (Block1 != Block2) 3379 return Block1 ? ImplicitConversionSequence::Worse 3380 : ImplicitConversionSequence::Better; 3381 } 3382 3383 return ImplicitConversionSequence::Indistinguishable; 3384 } 3385 3386 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3387 const ImplicitConversionSequence &ICS) { 3388 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3389 (ICS.isUserDefined() && 3390 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3391 } 3392 3393 /// CompareImplicitConversionSequences - Compare two implicit 3394 /// conversion sequences to determine whether one is better than the 3395 /// other or if they are indistinguishable (C++ 13.3.3.2). 3396 static ImplicitConversionSequence::CompareKind 3397 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3398 const ImplicitConversionSequence& ICS1, 3399 const ImplicitConversionSequence& ICS2) 3400 { 3401 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3402 // conversion sequences (as defined in 13.3.3.1) 3403 // -- a standard conversion sequence (13.3.3.1.1) is a better 3404 // conversion sequence than a user-defined conversion sequence or 3405 // an ellipsis conversion sequence, and 3406 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3407 // conversion sequence than an ellipsis conversion sequence 3408 // (13.3.3.1.3). 3409 // 3410 // C++0x [over.best.ics]p10: 3411 // For the purpose of ranking implicit conversion sequences as 3412 // described in 13.3.3.2, the ambiguous conversion sequence is 3413 // treated as a user-defined sequence that is indistinguishable 3414 // from any other user-defined conversion sequence. 3415 3416 // String literal to 'char *' conversion has been deprecated in C++03. It has 3417 // been removed from C++11. We still accept this conversion, if it happens at 3418 // the best viable function. Otherwise, this conversion is considered worse 3419 // than ellipsis conversion. Consider this as an extension; this is not in the 3420 // standard. For example: 3421 // 3422 // int &f(...); // #1 3423 // void f(char*); // #2 3424 // void g() { int &r = f("foo"); } 3425 // 3426 // In C++03, we pick #2 as the best viable function. 3427 // In C++11, we pick #1 as the best viable function, because ellipsis 3428 // conversion is better than string-literal to char* conversion (since there 3429 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3430 // convert arguments, #2 would be the best viable function in C++11. 3431 // If the best viable function has this conversion, a warning will be issued 3432 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3433 3434 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3435 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3436 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3437 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3438 ? ImplicitConversionSequence::Worse 3439 : ImplicitConversionSequence::Better; 3440 3441 if (ICS1.getKindRank() < ICS2.getKindRank()) 3442 return ImplicitConversionSequence::Better; 3443 if (ICS2.getKindRank() < ICS1.getKindRank()) 3444 return ImplicitConversionSequence::Worse; 3445 3446 // The following checks require both conversion sequences to be of 3447 // the same kind. 3448 if (ICS1.getKind() != ICS2.getKind()) 3449 return ImplicitConversionSequence::Indistinguishable; 3450 3451 ImplicitConversionSequence::CompareKind Result = 3452 ImplicitConversionSequence::Indistinguishable; 3453 3454 // Two implicit conversion sequences of the same form are 3455 // indistinguishable conversion sequences unless one of the 3456 // following rules apply: (C++ 13.3.3.2p3): 3457 3458 // List-initialization sequence L1 is a better conversion sequence than 3459 // list-initialization sequence L2 if: 3460 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3461 // if not that, 3462 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3463 // and N1 is smaller than N2., 3464 // even if one of the other rules in this paragraph would otherwise apply. 3465 if (!ICS1.isBad()) { 3466 if (ICS1.isStdInitializerListElement() && 3467 !ICS2.isStdInitializerListElement()) 3468 return ImplicitConversionSequence::Better; 3469 if (!ICS1.isStdInitializerListElement() && 3470 ICS2.isStdInitializerListElement()) 3471 return ImplicitConversionSequence::Worse; 3472 } 3473 3474 if (ICS1.isStandard()) 3475 // Standard conversion sequence S1 is a better conversion sequence than 3476 // standard conversion sequence S2 if [...] 3477 Result = CompareStandardConversionSequences(S, Loc, 3478 ICS1.Standard, ICS2.Standard); 3479 else if (ICS1.isUserDefined()) { 3480 // User-defined conversion sequence U1 is a better conversion 3481 // sequence than another user-defined conversion sequence U2 if 3482 // they contain the same user-defined conversion function or 3483 // constructor and if the second standard conversion sequence of 3484 // U1 is better than the second standard conversion sequence of 3485 // U2 (C++ 13.3.3.2p3). 3486 if (ICS1.UserDefined.ConversionFunction == 3487 ICS2.UserDefined.ConversionFunction) 3488 Result = CompareStandardConversionSequences(S, Loc, 3489 ICS1.UserDefined.After, 3490 ICS2.UserDefined.After); 3491 else 3492 Result = compareConversionFunctions(S, 3493 ICS1.UserDefined.ConversionFunction, 3494 ICS2.UserDefined.ConversionFunction); 3495 } 3496 3497 return Result; 3498 } 3499 3500 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3501 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3502 Qualifiers Quals; 3503 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3504 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3505 } 3506 3507 return Context.hasSameUnqualifiedType(T1, T2); 3508 } 3509 3510 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3511 // determine if one is a proper subset of the other. 3512 static ImplicitConversionSequence::CompareKind 3513 compareStandardConversionSubsets(ASTContext &Context, 3514 const StandardConversionSequence& SCS1, 3515 const StandardConversionSequence& SCS2) { 3516 ImplicitConversionSequence::CompareKind Result 3517 = ImplicitConversionSequence::Indistinguishable; 3518 3519 // the identity conversion sequence is considered to be a subsequence of 3520 // any non-identity conversion sequence 3521 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3522 return ImplicitConversionSequence::Better; 3523 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3524 return ImplicitConversionSequence::Worse; 3525 3526 if (SCS1.Second != SCS2.Second) { 3527 if (SCS1.Second == ICK_Identity) 3528 Result = ImplicitConversionSequence::Better; 3529 else if (SCS2.Second == ICK_Identity) 3530 Result = ImplicitConversionSequence::Worse; 3531 else 3532 return ImplicitConversionSequence::Indistinguishable; 3533 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3534 return ImplicitConversionSequence::Indistinguishable; 3535 3536 if (SCS1.Third == SCS2.Third) { 3537 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3538 : ImplicitConversionSequence::Indistinguishable; 3539 } 3540 3541 if (SCS1.Third == ICK_Identity) 3542 return Result == ImplicitConversionSequence::Worse 3543 ? ImplicitConversionSequence::Indistinguishable 3544 : ImplicitConversionSequence::Better; 3545 3546 if (SCS2.Third == ICK_Identity) 3547 return Result == ImplicitConversionSequence::Better 3548 ? ImplicitConversionSequence::Indistinguishable 3549 : ImplicitConversionSequence::Worse; 3550 3551 return ImplicitConversionSequence::Indistinguishable; 3552 } 3553 3554 /// \brief Determine whether one of the given reference bindings is better 3555 /// than the other based on what kind of bindings they are. 3556 static bool 3557 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3558 const StandardConversionSequence &SCS2) { 3559 // C++0x [over.ics.rank]p3b4: 3560 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3561 // implicit object parameter of a non-static member function declared 3562 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3563 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3564 // lvalue reference to a function lvalue and S2 binds an rvalue 3565 // reference*. 3566 // 3567 // FIXME: Rvalue references. We're going rogue with the above edits, 3568 // because the semantics in the current C++0x working paper (N3225 at the 3569 // time of this writing) break the standard definition of std::forward 3570 // and std::reference_wrapper when dealing with references to functions. 3571 // Proposed wording changes submitted to CWG for consideration. 3572 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3573 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3574 return false; 3575 3576 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3577 SCS2.IsLvalueReference) || 3578 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3579 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3580 } 3581 3582 /// CompareStandardConversionSequences - Compare two standard 3583 /// conversion sequences to determine whether one is better than the 3584 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3585 static ImplicitConversionSequence::CompareKind 3586 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3587 const StandardConversionSequence& SCS1, 3588 const StandardConversionSequence& SCS2) 3589 { 3590 // Standard conversion sequence S1 is a better conversion sequence 3591 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3592 3593 // -- S1 is a proper subsequence of S2 (comparing the conversion 3594 // sequences in the canonical form defined by 13.3.3.1.1, 3595 // excluding any Lvalue Transformation; the identity conversion 3596 // sequence is considered to be a subsequence of any 3597 // non-identity conversion sequence) or, if not that, 3598 if (ImplicitConversionSequence::CompareKind CK 3599 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3600 return CK; 3601 3602 // -- the rank of S1 is better than the rank of S2 (by the rules 3603 // defined below), or, if not that, 3604 ImplicitConversionRank Rank1 = SCS1.getRank(); 3605 ImplicitConversionRank Rank2 = SCS2.getRank(); 3606 if (Rank1 < Rank2) 3607 return ImplicitConversionSequence::Better; 3608 else if (Rank2 < Rank1) 3609 return ImplicitConversionSequence::Worse; 3610 3611 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3612 // are indistinguishable unless one of the following rules 3613 // applies: 3614 3615 // A conversion that is not a conversion of a pointer, or 3616 // pointer to member, to bool is better than another conversion 3617 // that is such a conversion. 3618 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3619 return SCS2.isPointerConversionToBool() 3620 ? ImplicitConversionSequence::Better 3621 : ImplicitConversionSequence::Worse; 3622 3623 // C++ [over.ics.rank]p4b2: 3624 // 3625 // If class B is derived directly or indirectly from class A, 3626 // conversion of B* to A* is better than conversion of B* to 3627 // void*, and conversion of A* to void* is better than conversion 3628 // of B* to void*. 3629 bool SCS1ConvertsToVoid 3630 = SCS1.isPointerConversionToVoidPointer(S.Context); 3631 bool SCS2ConvertsToVoid 3632 = SCS2.isPointerConversionToVoidPointer(S.Context); 3633 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3634 // Exactly one of the conversion sequences is a conversion to 3635 // a void pointer; it's the worse conversion. 3636 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3637 : ImplicitConversionSequence::Worse; 3638 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3639 // Neither conversion sequence converts to a void pointer; compare 3640 // their derived-to-base conversions. 3641 if (ImplicitConversionSequence::CompareKind DerivedCK 3642 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3643 return DerivedCK; 3644 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3645 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3646 // Both conversion sequences are conversions to void 3647 // pointers. Compare the source types to determine if there's an 3648 // inheritance relationship in their sources. 3649 QualType FromType1 = SCS1.getFromType(); 3650 QualType FromType2 = SCS2.getFromType(); 3651 3652 // Adjust the types we're converting from via the array-to-pointer 3653 // conversion, if we need to. 3654 if (SCS1.First == ICK_Array_To_Pointer) 3655 FromType1 = S.Context.getArrayDecayedType(FromType1); 3656 if (SCS2.First == ICK_Array_To_Pointer) 3657 FromType2 = S.Context.getArrayDecayedType(FromType2); 3658 3659 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3660 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3661 3662 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3663 return ImplicitConversionSequence::Better; 3664 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3665 return ImplicitConversionSequence::Worse; 3666 3667 // Objective-C++: If one interface is more specific than the 3668 // other, it is the better one. 3669 const ObjCObjectPointerType* FromObjCPtr1 3670 = FromType1->getAs<ObjCObjectPointerType>(); 3671 const ObjCObjectPointerType* FromObjCPtr2 3672 = FromType2->getAs<ObjCObjectPointerType>(); 3673 if (FromObjCPtr1 && FromObjCPtr2) { 3674 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3675 FromObjCPtr2); 3676 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3677 FromObjCPtr1); 3678 if (AssignLeft != AssignRight) { 3679 return AssignLeft? ImplicitConversionSequence::Better 3680 : ImplicitConversionSequence::Worse; 3681 } 3682 } 3683 } 3684 3685 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3686 // bullet 3). 3687 if (ImplicitConversionSequence::CompareKind QualCK 3688 = CompareQualificationConversions(S, SCS1, SCS2)) 3689 return QualCK; 3690 3691 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3692 // Check for a better reference binding based on the kind of bindings. 3693 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3694 return ImplicitConversionSequence::Better; 3695 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3696 return ImplicitConversionSequence::Worse; 3697 3698 // C++ [over.ics.rank]p3b4: 3699 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3700 // which the references refer are the same type except for 3701 // top-level cv-qualifiers, and the type to which the reference 3702 // initialized by S2 refers is more cv-qualified than the type 3703 // to which the reference initialized by S1 refers. 3704 QualType T1 = SCS1.getToType(2); 3705 QualType T2 = SCS2.getToType(2); 3706 T1 = S.Context.getCanonicalType(T1); 3707 T2 = S.Context.getCanonicalType(T2); 3708 Qualifiers T1Quals, T2Quals; 3709 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3710 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3711 if (UnqualT1 == UnqualT2) { 3712 // Objective-C++ ARC: If the references refer to objects with different 3713 // lifetimes, prefer bindings that don't change lifetime. 3714 if (SCS1.ObjCLifetimeConversionBinding != 3715 SCS2.ObjCLifetimeConversionBinding) { 3716 return SCS1.ObjCLifetimeConversionBinding 3717 ? ImplicitConversionSequence::Worse 3718 : ImplicitConversionSequence::Better; 3719 } 3720 3721 // If the type is an array type, promote the element qualifiers to the 3722 // type for comparison. 3723 if (isa<ArrayType>(T1) && T1Quals) 3724 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3725 if (isa<ArrayType>(T2) && T2Quals) 3726 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3727 if (T2.isMoreQualifiedThan(T1)) 3728 return ImplicitConversionSequence::Better; 3729 else if (T1.isMoreQualifiedThan(T2)) 3730 return ImplicitConversionSequence::Worse; 3731 } 3732 } 3733 3734 // In Microsoft mode, prefer an integral conversion to a 3735 // floating-to-integral conversion if the integral conversion 3736 // is between types of the same size. 3737 // For example: 3738 // void f(float); 3739 // void f(int); 3740 // int main { 3741 // long a; 3742 // f(a); 3743 // } 3744 // Here, MSVC will call f(int) instead of generating a compile error 3745 // as clang will do in standard mode. 3746 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3747 SCS2.Second == ICK_Floating_Integral && 3748 S.Context.getTypeSize(SCS1.getFromType()) == 3749 S.Context.getTypeSize(SCS1.getToType(2))) 3750 return ImplicitConversionSequence::Better; 3751 3752 return ImplicitConversionSequence::Indistinguishable; 3753 } 3754 3755 /// CompareQualificationConversions - Compares two standard conversion 3756 /// sequences to determine whether they can be ranked based on their 3757 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3758 static ImplicitConversionSequence::CompareKind 3759 CompareQualificationConversions(Sema &S, 3760 const StandardConversionSequence& SCS1, 3761 const StandardConversionSequence& SCS2) { 3762 // C++ 13.3.3.2p3: 3763 // -- S1 and S2 differ only in their qualification conversion and 3764 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3765 // cv-qualification signature of type T1 is a proper subset of 3766 // the cv-qualification signature of type T2, and S1 is not the 3767 // deprecated string literal array-to-pointer conversion (4.2). 3768 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3769 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3770 return ImplicitConversionSequence::Indistinguishable; 3771 3772 // FIXME: the example in the standard doesn't use a qualification 3773 // conversion (!) 3774 QualType T1 = SCS1.getToType(2); 3775 QualType T2 = SCS2.getToType(2); 3776 T1 = S.Context.getCanonicalType(T1); 3777 T2 = S.Context.getCanonicalType(T2); 3778 Qualifiers T1Quals, T2Quals; 3779 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3780 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3781 3782 // If the types are the same, we won't learn anything by unwrapped 3783 // them. 3784 if (UnqualT1 == UnqualT2) 3785 return ImplicitConversionSequence::Indistinguishable; 3786 3787 // If the type is an array type, promote the element qualifiers to the type 3788 // for comparison. 3789 if (isa<ArrayType>(T1) && T1Quals) 3790 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3791 if (isa<ArrayType>(T2) && T2Quals) 3792 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3793 3794 ImplicitConversionSequence::CompareKind Result 3795 = ImplicitConversionSequence::Indistinguishable; 3796 3797 // Objective-C++ ARC: 3798 // Prefer qualification conversions not involving a change in lifetime 3799 // to qualification conversions that do not change lifetime. 3800 if (SCS1.QualificationIncludesObjCLifetime != 3801 SCS2.QualificationIncludesObjCLifetime) { 3802 Result = SCS1.QualificationIncludesObjCLifetime 3803 ? ImplicitConversionSequence::Worse 3804 : ImplicitConversionSequence::Better; 3805 } 3806 3807 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3808 // Within each iteration of the loop, we check the qualifiers to 3809 // determine if this still looks like a qualification 3810 // conversion. Then, if all is well, we unwrap one more level of 3811 // pointers or pointers-to-members and do it all again 3812 // until there are no more pointers or pointers-to-members left 3813 // to unwrap. This essentially mimics what 3814 // IsQualificationConversion does, but here we're checking for a 3815 // strict subset of qualifiers. 3816 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3817 // The qualifiers are the same, so this doesn't tell us anything 3818 // about how the sequences rank. 3819 ; 3820 else if (T2.isMoreQualifiedThan(T1)) { 3821 // T1 has fewer qualifiers, so it could be the better sequence. 3822 if (Result == ImplicitConversionSequence::Worse) 3823 // Neither has qualifiers that are a subset of the other's 3824 // qualifiers. 3825 return ImplicitConversionSequence::Indistinguishable; 3826 3827 Result = ImplicitConversionSequence::Better; 3828 } else if (T1.isMoreQualifiedThan(T2)) { 3829 // T2 has fewer qualifiers, so it could be the better sequence. 3830 if (Result == ImplicitConversionSequence::Better) 3831 // Neither has qualifiers that are a subset of the other's 3832 // qualifiers. 3833 return ImplicitConversionSequence::Indistinguishable; 3834 3835 Result = ImplicitConversionSequence::Worse; 3836 } else { 3837 // Qualifiers are disjoint. 3838 return ImplicitConversionSequence::Indistinguishable; 3839 } 3840 3841 // If the types after this point are equivalent, we're done. 3842 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3843 break; 3844 } 3845 3846 // Check that the winning standard conversion sequence isn't using 3847 // the deprecated string literal array to pointer conversion. 3848 switch (Result) { 3849 case ImplicitConversionSequence::Better: 3850 if (SCS1.DeprecatedStringLiteralToCharPtr) 3851 Result = ImplicitConversionSequence::Indistinguishable; 3852 break; 3853 3854 case ImplicitConversionSequence::Indistinguishable: 3855 break; 3856 3857 case ImplicitConversionSequence::Worse: 3858 if (SCS2.DeprecatedStringLiteralToCharPtr) 3859 Result = ImplicitConversionSequence::Indistinguishable; 3860 break; 3861 } 3862 3863 return Result; 3864 } 3865 3866 /// CompareDerivedToBaseConversions - Compares two standard conversion 3867 /// sequences to determine whether they can be ranked based on their 3868 /// various kinds of derived-to-base conversions (C++ 3869 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3870 /// conversions between Objective-C interface types. 3871 static ImplicitConversionSequence::CompareKind 3872 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3873 const StandardConversionSequence& SCS1, 3874 const StandardConversionSequence& SCS2) { 3875 QualType FromType1 = SCS1.getFromType(); 3876 QualType ToType1 = SCS1.getToType(1); 3877 QualType FromType2 = SCS2.getFromType(); 3878 QualType ToType2 = SCS2.getToType(1); 3879 3880 // Adjust the types we're converting from via the array-to-pointer 3881 // conversion, if we need to. 3882 if (SCS1.First == ICK_Array_To_Pointer) 3883 FromType1 = S.Context.getArrayDecayedType(FromType1); 3884 if (SCS2.First == ICK_Array_To_Pointer) 3885 FromType2 = S.Context.getArrayDecayedType(FromType2); 3886 3887 // Canonicalize all of the types. 3888 FromType1 = S.Context.getCanonicalType(FromType1); 3889 ToType1 = S.Context.getCanonicalType(ToType1); 3890 FromType2 = S.Context.getCanonicalType(FromType2); 3891 ToType2 = S.Context.getCanonicalType(ToType2); 3892 3893 // C++ [over.ics.rank]p4b3: 3894 // 3895 // If class B is derived directly or indirectly from class A and 3896 // class C is derived directly or indirectly from B, 3897 // 3898 // Compare based on pointer conversions. 3899 if (SCS1.Second == ICK_Pointer_Conversion && 3900 SCS2.Second == ICK_Pointer_Conversion && 3901 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3902 FromType1->isPointerType() && FromType2->isPointerType() && 3903 ToType1->isPointerType() && ToType2->isPointerType()) { 3904 QualType FromPointee1 3905 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3906 QualType ToPointee1 3907 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3908 QualType FromPointee2 3909 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3910 QualType ToPointee2 3911 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3912 3913 // -- conversion of C* to B* is better than conversion of C* to A*, 3914 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3915 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3916 return ImplicitConversionSequence::Better; 3917 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3918 return ImplicitConversionSequence::Worse; 3919 } 3920 3921 // -- conversion of B* to A* is better than conversion of C* to A*, 3922 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3923 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3924 return ImplicitConversionSequence::Better; 3925 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3926 return ImplicitConversionSequence::Worse; 3927 } 3928 } else if (SCS1.Second == ICK_Pointer_Conversion && 3929 SCS2.Second == ICK_Pointer_Conversion) { 3930 const ObjCObjectPointerType *FromPtr1 3931 = FromType1->getAs<ObjCObjectPointerType>(); 3932 const ObjCObjectPointerType *FromPtr2 3933 = FromType2->getAs<ObjCObjectPointerType>(); 3934 const ObjCObjectPointerType *ToPtr1 3935 = ToType1->getAs<ObjCObjectPointerType>(); 3936 const ObjCObjectPointerType *ToPtr2 3937 = ToType2->getAs<ObjCObjectPointerType>(); 3938 3939 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3940 // Apply the same conversion ranking rules for Objective-C pointer types 3941 // that we do for C++ pointers to class types. However, we employ the 3942 // Objective-C pseudo-subtyping relationship used for assignment of 3943 // Objective-C pointer types. 3944 bool FromAssignLeft 3945 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3946 bool FromAssignRight 3947 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3948 bool ToAssignLeft 3949 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3950 bool ToAssignRight 3951 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3952 3953 // A conversion to an a non-id object pointer type or qualified 'id' 3954 // type is better than a conversion to 'id'. 3955 if (ToPtr1->isObjCIdType() && 3956 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3957 return ImplicitConversionSequence::Worse; 3958 if (ToPtr2->isObjCIdType() && 3959 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3960 return ImplicitConversionSequence::Better; 3961 3962 // A conversion to a non-id object pointer type is better than a 3963 // conversion to a qualified 'id' type 3964 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3965 return ImplicitConversionSequence::Worse; 3966 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3967 return ImplicitConversionSequence::Better; 3968 3969 // A conversion to an a non-Class object pointer type or qualified 'Class' 3970 // type is better than a conversion to 'Class'. 3971 if (ToPtr1->isObjCClassType() && 3972 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3973 return ImplicitConversionSequence::Worse; 3974 if (ToPtr2->isObjCClassType() && 3975 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3976 return ImplicitConversionSequence::Better; 3977 3978 // A conversion to a non-Class object pointer type is better than a 3979 // conversion to a qualified 'Class' type. 3980 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3981 return ImplicitConversionSequence::Worse; 3982 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3983 return ImplicitConversionSequence::Better; 3984 3985 // -- "conversion of C* to B* is better than conversion of C* to A*," 3986 if (S.Context.hasSameType(FromType1, FromType2) && 3987 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3988 (ToAssignLeft != ToAssignRight)) 3989 return ToAssignLeft? ImplicitConversionSequence::Worse 3990 : ImplicitConversionSequence::Better; 3991 3992 // -- "conversion of B* to A* is better than conversion of C* to A*," 3993 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3994 (FromAssignLeft != FromAssignRight)) 3995 return FromAssignLeft? ImplicitConversionSequence::Better 3996 : ImplicitConversionSequence::Worse; 3997 } 3998 } 3999 4000 // Ranking of member-pointer types. 4001 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4002 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4003 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4004 const MemberPointerType * FromMemPointer1 = 4005 FromType1->getAs<MemberPointerType>(); 4006 const MemberPointerType * ToMemPointer1 = 4007 ToType1->getAs<MemberPointerType>(); 4008 const MemberPointerType * FromMemPointer2 = 4009 FromType2->getAs<MemberPointerType>(); 4010 const MemberPointerType * ToMemPointer2 = 4011 ToType2->getAs<MemberPointerType>(); 4012 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4013 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4014 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4015 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4016 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4017 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4018 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4019 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4020 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4021 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4022 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4023 return ImplicitConversionSequence::Worse; 4024 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4025 return ImplicitConversionSequence::Better; 4026 } 4027 // conversion of B::* to C::* is better than conversion of A::* to C::* 4028 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4029 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4030 return ImplicitConversionSequence::Better; 4031 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4032 return ImplicitConversionSequence::Worse; 4033 } 4034 } 4035 4036 if (SCS1.Second == ICK_Derived_To_Base) { 4037 // -- conversion of C to B is better than conversion of C to A, 4038 // -- binding of an expression of type C to a reference of type 4039 // B& is better than binding an expression of type C to a 4040 // reference of type A&, 4041 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4042 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4043 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4044 return ImplicitConversionSequence::Better; 4045 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4046 return ImplicitConversionSequence::Worse; 4047 } 4048 4049 // -- conversion of B to A is better than conversion of C to A. 4050 // -- binding of an expression of type B to a reference of type 4051 // A& is better than binding an expression of type C to a 4052 // reference of type A&, 4053 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4054 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4055 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4056 return ImplicitConversionSequence::Better; 4057 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4058 return ImplicitConversionSequence::Worse; 4059 } 4060 } 4061 4062 return ImplicitConversionSequence::Indistinguishable; 4063 } 4064 4065 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4066 /// C++ class. 4067 static bool isTypeValid(QualType T) { 4068 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4069 return !Record->isInvalidDecl(); 4070 4071 return true; 4072 } 4073 4074 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4075 /// determine whether they are reference-related, 4076 /// reference-compatible, reference-compatible with added 4077 /// qualification, or incompatible, for use in C++ initialization by 4078 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4079 /// type, and the first type (T1) is the pointee type of the reference 4080 /// type being initialized. 4081 Sema::ReferenceCompareResult 4082 Sema::CompareReferenceRelationship(SourceLocation Loc, 4083 QualType OrigT1, QualType OrigT2, 4084 bool &DerivedToBase, 4085 bool &ObjCConversion, 4086 bool &ObjCLifetimeConversion) { 4087 assert(!OrigT1->isReferenceType() && 4088 "T1 must be the pointee type of the reference type"); 4089 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4090 4091 QualType T1 = Context.getCanonicalType(OrigT1); 4092 QualType T2 = Context.getCanonicalType(OrigT2); 4093 Qualifiers T1Quals, T2Quals; 4094 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4095 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4096 4097 // C++ [dcl.init.ref]p4: 4098 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4099 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4100 // T1 is a base class of T2. 4101 DerivedToBase = false; 4102 ObjCConversion = false; 4103 ObjCLifetimeConversion = false; 4104 if (UnqualT1 == UnqualT2) { 4105 // Nothing to do. 4106 } else if (isCompleteType(Loc, OrigT2) && 4107 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4108 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4109 DerivedToBase = true; 4110 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4111 UnqualT2->isObjCObjectOrInterfaceType() && 4112 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4113 ObjCConversion = true; 4114 else 4115 return Ref_Incompatible; 4116 4117 // At this point, we know that T1 and T2 are reference-related (at 4118 // least). 4119 4120 // If the type is an array type, promote the element qualifiers to the type 4121 // for comparison. 4122 if (isa<ArrayType>(T1) && T1Quals) 4123 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4124 if (isa<ArrayType>(T2) && T2Quals) 4125 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4126 4127 // C++ [dcl.init.ref]p4: 4128 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4129 // reference-related to T2 and cv1 is the same cv-qualification 4130 // as, or greater cv-qualification than, cv2. For purposes of 4131 // overload resolution, cases for which cv1 is greater 4132 // cv-qualification than cv2 are identified as 4133 // reference-compatible with added qualification (see 13.3.3.2). 4134 // 4135 // Note that we also require equivalence of Objective-C GC and address-space 4136 // qualifiers when performing these computations, so that e.g., an int in 4137 // address space 1 is not reference-compatible with an int in address 4138 // space 2. 4139 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4140 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4141 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4142 ObjCLifetimeConversion = true; 4143 4144 T1Quals.removeObjCLifetime(); 4145 T2Quals.removeObjCLifetime(); 4146 } 4147 4148 if (T1Quals == T2Quals) 4149 return Ref_Compatible; 4150 else if (T1Quals.compatiblyIncludes(T2Quals)) 4151 return Ref_Compatible_With_Added_Qualification; 4152 else 4153 return Ref_Related; 4154 } 4155 4156 /// \brief Look for a user-defined conversion to an value reference-compatible 4157 /// with DeclType. Return true if something definite is found. 4158 static bool 4159 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4160 QualType DeclType, SourceLocation DeclLoc, 4161 Expr *Init, QualType T2, bool AllowRvalues, 4162 bool AllowExplicit) { 4163 assert(T2->isRecordType() && "Can only find conversions of record types."); 4164 CXXRecordDecl *T2RecordDecl 4165 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4166 4167 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4168 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4169 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4170 NamedDecl *D = *I; 4171 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4172 if (isa<UsingShadowDecl>(D)) 4173 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4174 4175 FunctionTemplateDecl *ConvTemplate 4176 = dyn_cast<FunctionTemplateDecl>(D); 4177 CXXConversionDecl *Conv; 4178 if (ConvTemplate) 4179 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4180 else 4181 Conv = cast<CXXConversionDecl>(D); 4182 4183 // If this is an explicit conversion, and we're not allowed to consider 4184 // explicit conversions, skip it. 4185 if (!AllowExplicit && Conv->isExplicit()) 4186 continue; 4187 4188 if (AllowRvalues) { 4189 bool DerivedToBase = false; 4190 bool ObjCConversion = false; 4191 bool ObjCLifetimeConversion = false; 4192 4193 // If we are initializing an rvalue reference, don't permit conversion 4194 // functions that return lvalues. 4195 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4196 const ReferenceType *RefType 4197 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4198 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4199 continue; 4200 } 4201 4202 if (!ConvTemplate && 4203 S.CompareReferenceRelationship( 4204 DeclLoc, 4205 Conv->getConversionType().getNonReferenceType() 4206 .getUnqualifiedType(), 4207 DeclType.getNonReferenceType().getUnqualifiedType(), 4208 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4209 Sema::Ref_Incompatible) 4210 continue; 4211 } else { 4212 // If the conversion function doesn't return a reference type, 4213 // it can't be considered for this conversion. An rvalue reference 4214 // is only acceptable if its referencee is a function type. 4215 4216 const ReferenceType *RefType = 4217 Conv->getConversionType()->getAs<ReferenceType>(); 4218 if (!RefType || 4219 (!RefType->isLValueReferenceType() && 4220 !RefType->getPointeeType()->isFunctionType())) 4221 continue; 4222 } 4223 4224 if (ConvTemplate) 4225 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4226 Init, DeclType, CandidateSet, 4227 /*AllowObjCConversionOnExplicit=*/false); 4228 else 4229 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4230 DeclType, CandidateSet, 4231 /*AllowObjCConversionOnExplicit=*/false); 4232 } 4233 4234 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4235 4236 OverloadCandidateSet::iterator Best; 4237 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4238 case OR_Success: 4239 // C++ [over.ics.ref]p1: 4240 // 4241 // [...] If the parameter binds directly to the result of 4242 // applying a conversion function to the argument 4243 // expression, the implicit conversion sequence is a 4244 // user-defined conversion sequence (13.3.3.1.2), with the 4245 // second standard conversion sequence either an identity 4246 // conversion or, if the conversion function returns an 4247 // entity of a type that is a derived class of the parameter 4248 // type, a derived-to-base Conversion. 4249 if (!Best->FinalConversion.DirectBinding) 4250 return false; 4251 4252 ICS.setUserDefined(); 4253 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4254 ICS.UserDefined.After = Best->FinalConversion; 4255 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4256 ICS.UserDefined.ConversionFunction = Best->Function; 4257 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4258 ICS.UserDefined.EllipsisConversion = false; 4259 assert(ICS.UserDefined.After.ReferenceBinding && 4260 ICS.UserDefined.After.DirectBinding && 4261 "Expected a direct reference binding!"); 4262 return true; 4263 4264 case OR_Ambiguous: 4265 ICS.setAmbiguous(); 4266 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4267 Cand != CandidateSet.end(); ++Cand) 4268 if (Cand->Viable) 4269 ICS.Ambiguous.addConversion(Cand->Function); 4270 return true; 4271 4272 case OR_No_Viable_Function: 4273 case OR_Deleted: 4274 // There was no suitable conversion, or we found a deleted 4275 // conversion; continue with other checks. 4276 return false; 4277 } 4278 4279 llvm_unreachable("Invalid OverloadResult!"); 4280 } 4281 4282 /// \brief Compute an implicit conversion sequence for reference 4283 /// initialization. 4284 static ImplicitConversionSequence 4285 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4286 SourceLocation DeclLoc, 4287 bool SuppressUserConversions, 4288 bool AllowExplicit) { 4289 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4290 4291 // Most paths end in a failed conversion. 4292 ImplicitConversionSequence ICS; 4293 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4294 4295 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4296 QualType T2 = Init->getType(); 4297 4298 // If the initializer is the address of an overloaded function, try 4299 // to resolve the overloaded function. If all goes well, T2 is the 4300 // type of the resulting function. 4301 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4302 DeclAccessPair Found; 4303 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4304 false, Found)) 4305 T2 = Fn->getType(); 4306 } 4307 4308 // Compute some basic properties of the types and the initializer. 4309 bool isRValRef = DeclType->isRValueReferenceType(); 4310 bool DerivedToBase = false; 4311 bool ObjCConversion = false; 4312 bool ObjCLifetimeConversion = false; 4313 Expr::Classification InitCategory = Init->Classify(S.Context); 4314 Sema::ReferenceCompareResult RefRelationship 4315 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4316 ObjCConversion, ObjCLifetimeConversion); 4317 4318 4319 // C++0x [dcl.init.ref]p5: 4320 // A reference to type "cv1 T1" is initialized by an expression 4321 // of type "cv2 T2" as follows: 4322 4323 // -- If reference is an lvalue reference and the initializer expression 4324 if (!isRValRef) { 4325 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4326 // reference-compatible with "cv2 T2," or 4327 // 4328 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4329 if (InitCategory.isLValue() && 4330 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4331 // C++ [over.ics.ref]p1: 4332 // When a parameter of reference type binds directly (8.5.3) 4333 // to an argument expression, the implicit conversion sequence 4334 // is the identity conversion, unless the argument expression 4335 // has a type that is a derived class of the parameter type, 4336 // in which case the implicit conversion sequence is a 4337 // derived-to-base Conversion (13.3.3.1). 4338 ICS.setStandard(); 4339 ICS.Standard.First = ICK_Identity; 4340 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4341 : ObjCConversion? ICK_Compatible_Conversion 4342 : ICK_Identity; 4343 ICS.Standard.Third = ICK_Identity; 4344 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4345 ICS.Standard.setToType(0, T2); 4346 ICS.Standard.setToType(1, T1); 4347 ICS.Standard.setToType(2, T1); 4348 ICS.Standard.ReferenceBinding = true; 4349 ICS.Standard.DirectBinding = true; 4350 ICS.Standard.IsLvalueReference = !isRValRef; 4351 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4352 ICS.Standard.BindsToRvalue = false; 4353 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4354 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4355 ICS.Standard.CopyConstructor = nullptr; 4356 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4357 4358 // Nothing more to do: the inaccessibility/ambiguity check for 4359 // derived-to-base conversions is suppressed when we're 4360 // computing the implicit conversion sequence (C++ 4361 // [over.best.ics]p2). 4362 return ICS; 4363 } 4364 4365 // -- has a class type (i.e., T2 is a class type), where T1 is 4366 // not reference-related to T2, and can be implicitly 4367 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4368 // is reference-compatible with "cv3 T3" 92) (this 4369 // conversion is selected by enumerating the applicable 4370 // conversion functions (13.3.1.6) and choosing the best 4371 // one through overload resolution (13.3)), 4372 if (!SuppressUserConversions && T2->isRecordType() && 4373 S.isCompleteType(DeclLoc, T2) && 4374 RefRelationship == Sema::Ref_Incompatible) { 4375 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4376 Init, T2, /*AllowRvalues=*/false, 4377 AllowExplicit)) 4378 return ICS; 4379 } 4380 } 4381 4382 // -- Otherwise, the reference shall be an lvalue reference to a 4383 // non-volatile const type (i.e., cv1 shall be const), or the reference 4384 // shall be an rvalue reference. 4385 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4386 return ICS; 4387 4388 // -- If the initializer expression 4389 // 4390 // -- is an xvalue, class prvalue, array prvalue or function 4391 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4392 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4393 (InitCategory.isXValue() || 4394 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4395 (InitCategory.isLValue() && T2->isFunctionType()))) { 4396 ICS.setStandard(); 4397 ICS.Standard.First = ICK_Identity; 4398 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4399 : ObjCConversion? ICK_Compatible_Conversion 4400 : ICK_Identity; 4401 ICS.Standard.Third = ICK_Identity; 4402 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4403 ICS.Standard.setToType(0, T2); 4404 ICS.Standard.setToType(1, T1); 4405 ICS.Standard.setToType(2, T1); 4406 ICS.Standard.ReferenceBinding = true; 4407 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4408 // binding unless we're binding to a class prvalue. 4409 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4410 // allow the use of rvalue references in C++98/03 for the benefit of 4411 // standard library implementors; therefore, we need the xvalue check here. 4412 ICS.Standard.DirectBinding = 4413 S.getLangOpts().CPlusPlus11 || 4414 !(InitCategory.isPRValue() || T2->isRecordType()); 4415 ICS.Standard.IsLvalueReference = !isRValRef; 4416 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4417 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4418 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4419 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4420 ICS.Standard.CopyConstructor = nullptr; 4421 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4422 return ICS; 4423 } 4424 4425 // -- has a class type (i.e., T2 is a class type), where T1 is not 4426 // reference-related to T2, and can be implicitly converted to 4427 // an xvalue, class prvalue, or function lvalue of type 4428 // "cv3 T3", where "cv1 T1" is reference-compatible with 4429 // "cv3 T3", 4430 // 4431 // then the reference is bound to the value of the initializer 4432 // expression in the first case and to the result of the conversion 4433 // in the second case (or, in either case, to an appropriate base 4434 // class subobject). 4435 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4436 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4437 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4438 Init, T2, /*AllowRvalues=*/true, 4439 AllowExplicit)) { 4440 // In the second case, if the reference is an rvalue reference 4441 // and the second standard conversion sequence of the 4442 // user-defined conversion sequence includes an lvalue-to-rvalue 4443 // conversion, the program is ill-formed. 4444 if (ICS.isUserDefined() && isRValRef && 4445 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4446 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4447 4448 return ICS; 4449 } 4450 4451 // A temporary of function type cannot be created; don't even try. 4452 if (T1->isFunctionType()) 4453 return ICS; 4454 4455 // -- Otherwise, a temporary of type "cv1 T1" is created and 4456 // initialized from the initializer expression using the 4457 // rules for a non-reference copy initialization (8.5). The 4458 // reference is then bound to the temporary. If T1 is 4459 // reference-related to T2, cv1 must be the same 4460 // cv-qualification as, or greater cv-qualification than, 4461 // cv2; otherwise, the program is ill-formed. 4462 if (RefRelationship == Sema::Ref_Related) { 4463 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4464 // we would be reference-compatible or reference-compatible with 4465 // added qualification. But that wasn't the case, so the reference 4466 // initialization fails. 4467 // 4468 // Note that we only want to check address spaces and cvr-qualifiers here. 4469 // ObjC GC and lifetime qualifiers aren't important. 4470 Qualifiers T1Quals = T1.getQualifiers(); 4471 Qualifiers T2Quals = T2.getQualifiers(); 4472 T1Quals.removeObjCGCAttr(); 4473 T1Quals.removeObjCLifetime(); 4474 T2Quals.removeObjCGCAttr(); 4475 T2Quals.removeObjCLifetime(); 4476 if (!T1Quals.compatiblyIncludes(T2Quals)) 4477 return ICS; 4478 } 4479 4480 // If at least one of the types is a class type, the types are not 4481 // related, and we aren't allowed any user conversions, the 4482 // reference binding fails. This case is important for breaking 4483 // recursion, since TryImplicitConversion below will attempt to 4484 // create a temporary through the use of a copy constructor. 4485 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4486 (T1->isRecordType() || T2->isRecordType())) 4487 return ICS; 4488 4489 // If T1 is reference-related to T2 and the reference is an rvalue 4490 // reference, the initializer expression shall not be an lvalue. 4491 if (RefRelationship >= Sema::Ref_Related && 4492 isRValRef && Init->Classify(S.Context).isLValue()) 4493 return ICS; 4494 4495 // C++ [over.ics.ref]p2: 4496 // When a parameter of reference type is not bound directly to 4497 // an argument expression, the conversion sequence is the one 4498 // required to convert the argument expression to the 4499 // underlying type of the reference according to 4500 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4501 // to copy-initializing a temporary of the underlying type with 4502 // the argument expression. Any difference in top-level 4503 // cv-qualification is subsumed by the initialization itself 4504 // and does not constitute a conversion. 4505 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4506 /*AllowExplicit=*/false, 4507 /*InOverloadResolution=*/false, 4508 /*CStyle=*/false, 4509 /*AllowObjCWritebackConversion=*/false, 4510 /*AllowObjCConversionOnExplicit=*/false); 4511 4512 // Of course, that's still a reference binding. 4513 if (ICS.isStandard()) { 4514 ICS.Standard.ReferenceBinding = true; 4515 ICS.Standard.IsLvalueReference = !isRValRef; 4516 ICS.Standard.BindsToFunctionLvalue = false; 4517 ICS.Standard.BindsToRvalue = true; 4518 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4519 ICS.Standard.ObjCLifetimeConversionBinding = false; 4520 } else if (ICS.isUserDefined()) { 4521 const ReferenceType *LValRefType = 4522 ICS.UserDefined.ConversionFunction->getReturnType() 4523 ->getAs<LValueReferenceType>(); 4524 4525 // C++ [over.ics.ref]p3: 4526 // Except for an implicit object parameter, for which see 13.3.1, a 4527 // standard conversion sequence cannot be formed if it requires [...] 4528 // binding an rvalue reference to an lvalue other than a function 4529 // lvalue. 4530 // Note that the function case is not possible here. 4531 if (DeclType->isRValueReferenceType() && LValRefType) { 4532 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4533 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4534 // reference to an rvalue! 4535 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4536 return ICS; 4537 } 4538 4539 ICS.UserDefined.Before.setAsIdentityConversion(); 4540 ICS.UserDefined.After.ReferenceBinding = true; 4541 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4542 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4543 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4544 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4545 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4546 } 4547 4548 return ICS; 4549 } 4550 4551 static ImplicitConversionSequence 4552 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4553 bool SuppressUserConversions, 4554 bool InOverloadResolution, 4555 bool AllowObjCWritebackConversion, 4556 bool AllowExplicit = false); 4557 4558 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4559 /// initializer list From. 4560 static ImplicitConversionSequence 4561 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4562 bool SuppressUserConversions, 4563 bool InOverloadResolution, 4564 bool AllowObjCWritebackConversion) { 4565 // C++11 [over.ics.list]p1: 4566 // When an argument is an initializer list, it is not an expression and 4567 // special rules apply for converting it to a parameter type. 4568 4569 ImplicitConversionSequence Result; 4570 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4571 4572 // We need a complete type for what follows. Incomplete types can never be 4573 // initialized from init lists. 4574 if (!S.isCompleteType(From->getLocStart(), ToType)) 4575 return Result; 4576 4577 // Per DR1467: 4578 // If the parameter type is a class X and the initializer list has a single 4579 // element of type cv U, where U is X or a class derived from X, the 4580 // implicit conversion sequence is the one required to convert the element 4581 // to the parameter type. 4582 // 4583 // Otherwise, if the parameter type is a character array [... ] 4584 // and the initializer list has a single element that is an 4585 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4586 // implicit conversion sequence is the identity conversion. 4587 if (From->getNumInits() == 1) { 4588 if (ToType->isRecordType()) { 4589 QualType InitType = From->getInit(0)->getType(); 4590 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4591 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4592 return TryCopyInitialization(S, From->getInit(0), ToType, 4593 SuppressUserConversions, 4594 InOverloadResolution, 4595 AllowObjCWritebackConversion); 4596 } 4597 // FIXME: Check the other conditions here: array of character type, 4598 // initializer is a string literal. 4599 if (ToType->isArrayType()) { 4600 InitializedEntity Entity = 4601 InitializedEntity::InitializeParameter(S.Context, ToType, 4602 /*Consumed=*/false); 4603 if (S.CanPerformCopyInitialization(Entity, From)) { 4604 Result.setStandard(); 4605 Result.Standard.setAsIdentityConversion(); 4606 Result.Standard.setFromType(ToType); 4607 Result.Standard.setAllToTypes(ToType); 4608 return Result; 4609 } 4610 } 4611 } 4612 4613 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4614 // C++11 [over.ics.list]p2: 4615 // If the parameter type is std::initializer_list<X> or "array of X" and 4616 // all the elements can be implicitly converted to X, the implicit 4617 // conversion sequence is the worst conversion necessary to convert an 4618 // element of the list to X. 4619 // 4620 // C++14 [over.ics.list]p3: 4621 // Otherwise, if the parameter type is "array of N X", if the initializer 4622 // list has exactly N elements or if it has fewer than N elements and X is 4623 // default-constructible, and if all the elements of the initializer list 4624 // can be implicitly converted to X, the implicit conversion sequence is 4625 // the worst conversion necessary to convert an element of the list to X. 4626 // 4627 // FIXME: We're missing a lot of these checks. 4628 bool toStdInitializerList = false; 4629 QualType X; 4630 if (ToType->isArrayType()) 4631 X = S.Context.getAsArrayType(ToType)->getElementType(); 4632 else 4633 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4634 if (!X.isNull()) { 4635 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4636 Expr *Init = From->getInit(i); 4637 ImplicitConversionSequence ICS = 4638 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4639 InOverloadResolution, 4640 AllowObjCWritebackConversion); 4641 // If a single element isn't convertible, fail. 4642 if (ICS.isBad()) { 4643 Result = ICS; 4644 break; 4645 } 4646 // Otherwise, look for the worst conversion. 4647 if (Result.isBad() || 4648 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4649 Result) == 4650 ImplicitConversionSequence::Worse) 4651 Result = ICS; 4652 } 4653 4654 // For an empty list, we won't have computed any conversion sequence. 4655 // Introduce the identity conversion sequence. 4656 if (From->getNumInits() == 0) { 4657 Result.setStandard(); 4658 Result.Standard.setAsIdentityConversion(); 4659 Result.Standard.setFromType(ToType); 4660 Result.Standard.setAllToTypes(ToType); 4661 } 4662 4663 Result.setStdInitializerListElement(toStdInitializerList); 4664 return Result; 4665 } 4666 4667 // C++14 [over.ics.list]p4: 4668 // C++11 [over.ics.list]p3: 4669 // Otherwise, if the parameter is a non-aggregate class X and overload 4670 // resolution chooses a single best constructor [...] the implicit 4671 // conversion sequence is a user-defined conversion sequence. If multiple 4672 // constructors are viable but none is better than the others, the 4673 // implicit conversion sequence is a user-defined conversion sequence. 4674 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4675 // This function can deal with initializer lists. 4676 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4677 /*AllowExplicit=*/false, 4678 InOverloadResolution, /*CStyle=*/false, 4679 AllowObjCWritebackConversion, 4680 /*AllowObjCConversionOnExplicit=*/false); 4681 } 4682 4683 // C++14 [over.ics.list]p5: 4684 // C++11 [over.ics.list]p4: 4685 // Otherwise, if the parameter has an aggregate type which can be 4686 // initialized from the initializer list [...] the implicit conversion 4687 // sequence is a user-defined conversion sequence. 4688 if (ToType->isAggregateType()) { 4689 // Type is an aggregate, argument is an init list. At this point it comes 4690 // down to checking whether the initialization works. 4691 // FIXME: Find out whether this parameter is consumed or not. 4692 InitializedEntity Entity = 4693 InitializedEntity::InitializeParameter(S.Context, ToType, 4694 /*Consumed=*/false); 4695 if (S.CanPerformCopyInitialization(Entity, From)) { 4696 Result.setUserDefined(); 4697 Result.UserDefined.Before.setAsIdentityConversion(); 4698 // Initializer lists don't have a type. 4699 Result.UserDefined.Before.setFromType(QualType()); 4700 Result.UserDefined.Before.setAllToTypes(QualType()); 4701 4702 Result.UserDefined.After.setAsIdentityConversion(); 4703 Result.UserDefined.After.setFromType(ToType); 4704 Result.UserDefined.After.setAllToTypes(ToType); 4705 Result.UserDefined.ConversionFunction = nullptr; 4706 } 4707 return Result; 4708 } 4709 4710 // C++14 [over.ics.list]p6: 4711 // C++11 [over.ics.list]p5: 4712 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4713 if (ToType->isReferenceType()) { 4714 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4715 // mention initializer lists in any way. So we go by what list- 4716 // initialization would do and try to extrapolate from that. 4717 4718 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4719 4720 // If the initializer list has a single element that is reference-related 4721 // to the parameter type, we initialize the reference from that. 4722 if (From->getNumInits() == 1) { 4723 Expr *Init = From->getInit(0); 4724 4725 QualType T2 = Init->getType(); 4726 4727 // If the initializer is the address of an overloaded function, try 4728 // to resolve the overloaded function. If all goes well, T2 is the 4729 // type of the resulting function. 4730 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4731 DeclAccessPair Found; 4732 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4733 Init, ToType, false, Found)) 4734 T2 = Fn->getType(); 4735 } 4736 4737 // Compute some basic properties of the types and the initializer. 4738 bool dummy1 = false; 4739 bool dummy2 = false; 4740 bool dummy3 = false; 4741 Sema::ReferenceCompareResult RefRelationship 4742 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4743 dummy2, dummy3); 4744 4745 if (RefRelationship >= Sema::Ref_Related) { 4746 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4747 SuppressUserConversions, 4748 /*AllowExplicit=*/false); 4749 } 4750 } 4751 4752 // Otherwise, we bind the reference to a temporary created from the 4753 // initializer list. 4754 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4755 InOverloadResolution, 4756 AllowObjCWritebackConversion); 4757 if (Result.isFailure()) 4758 return Result; 4759 assert(!Result.isEllipsis() && 4760 "Sub-initialization cannot result in ellipsis conversion."); 4761 4762 // Can we even bind to a temporary? 4763 if (ToType->isRValueReferenceType() || 4764 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4765 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4766 Result.UserDefined.After; 4767 SCS.ReferenceBinding = true; 4768 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4769 SCS.BindsToRvalue = true; 4770 SCS.BindsToFunctionLvalue = false; 4771 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4772 SCS.ObjCLifetimeConversionBinding = false; 4773 } else 4774 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4775 From, ToType); 4776 return Result; 4777 } 4778 4779 // C++14 [over.ics.list]p7: 4780 // C++11 [over.ics.list]p6: 4781 // Otherwise, if the parameter type is not a class: 4782 if (!ToType->isRecordType()) { 4783 // - if the initializer list has one element that is not itself an 4784 // initializer list, the implicit conversion sequence is the one 4785 // required to convert the element to the parameter type. 4786 unsigned NumInits = From->getNumInits(); 4787 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4788 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4789 SuppressUserConversions, 4790 InOverloadResolution, 4791 AllowObjCWritebackConversion); 4792 // - if the initializer list has no elements, the implicit conversion 4793 // sequence is the identity conversion. 4794 else if (NumInits == 0) { 4795 Result.setStandard(); 4796 Result.Standard.setAsIdentityConversion(); 4797 Result.Standard.setFromType(ToType); 4798 Result.Standard.setAllToTypes(ToType); 4799 } 4800 return Result; 4801 } 4802 4803 // C++14 [over.ics.list]p8: 4804 // C++11 [over.ics.list]p7: 4805 // In all cases other than those enumerated above, no conversion is possible 4806 return Result; 4807 } 4808 4809 /// TryCopyInitialization - Try to copy-initialize a value of type 4810 /// ToType from the expression From. Return the implicit conversion 4811 /// sequence required to pass this argument, which may be a bad 4812 /// conversion sequence (meaning that the argument cannot be passed to 4813 /// a parameter of this type). If @p SuppressUserConversions, then we 4814 /// do not permit any user-defined conversion sequences. 4815 static ImplicitConversionSequence 4816 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4817 bool SuppressUserConversions, 4818 bool InOverloadResolution, 4819 bool AllowObjCWritebackConversion, 4820 bool AllowExplicit) { 4821 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4822 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4823 InOverloadResolution,AllowObjCWritebackConversion); 4824 4825 if (ToType->isReferenceType()) 4826 return TryReferenceInit(S, From, ToType, 4827 /*FIXME:*/From->getLocStart(), 4828 SuppressUserConversions, 4829 AllowExplicit); 4830 4831 return TryImplicitConversion(S, From, ToType, 4832 SuppressUserConversions, 4833 /*AllowExplicit=*/false, 4834 InOverloadResolution, 4835 /*CStyle=*/false, 4836 AllowObjCWritebackConversion, 4837 /*AllowObjCConversionOnExplicit=*/false); 4838 } 4839 4840 static bool TryCopyInitialization(const CanQualType FromQTy, 4841 const CanQualType ToQTy, 4842 Sema &S, 4843 SourceLocation Loc, 4844 ExprValueKind FromVK) { 4845 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4846 ImplicitConversionSequence ICS = 4847 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4848 4849 return !ICS.isBad(); 4850 } 4851 4852 /// TryObjectArgumentInitialization - Try to initialize the object 4853 /// parameter of the given member function (@c Method) from the 4854 /// expression @p From. 4855 static ImplicitConversionSequence 4856 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4857 Expr::Classification FromClassification, 4858 CXXMethodDecl *Method, 4859 CXXRecordDecl *ActingContext) { 4860 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4861 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4862 // const volatile object. 4863 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4864 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4865 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4866 4867 // Set up the conversion sequence as a "bad" conversion, to allow us 4868 // to exit early. 4869 ImplicitConversionSequence ICS; 4870 4871 // We need to have an object of class type. 4872 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4873 FromType = PT->getPointeeType(); 4874 4875 // When we had a pointer, it's implicitly dereferenced, so we 4876 // better have an lvalue. 4877 assert(FromClassification.isLValue()); 4878 } 4879 4880 assert(FromType->isRecordType()); 4881 4882 // C++0x [over.match.funcs]p4: 4883 // For non-static member functions, the type of the implicit object 4884 // parameter is 4885 // 4886 // - "lvalue reference to cv X" for functions declared without a 4887 // ref-qualifier or with the & ref-qualifier 4888 // - "rvalue reference to cv X" for functions declared with the && 4889 // ref-qualifier 4890 // 4891 // where X is the class of which the function is a member and cv is the 4892 // cv-qualification on the member function declaration. 4893 // 4894 // However, when finding an implicit conversion sequence for the argument, we 4895 // are not allowed to create temporaries or perform user-defined conversions 4896 // (C++ [over.match.funcs]p5). We perform a simplified version of 4897 // reference binding here, that allows class rvalues to bind to 4898 // non-constant references. 4899 4900 // First check the qualifiers. 4901 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4902 if (ImplicitParamType.getCVRQualifiers() 4903 != FromTypeCanon.getLocalCVRQualifiers() && 4904 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4905 ICS.setBad(BadConversionSequence::bad_qualifiers, 4906 FromType, ImplicitParamType); 4907 return ICS; 4908 } 4909 4910 // Check that we have either the same type or a derived type. It 4911 // affects the conversion rank. 4912 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4913 ImplicitConversionKind SecondKind; 4914 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4915 SecondKind = ICK_Identity; 4916 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4917 SecondKind = ICK_Derived_To_Base; 4918 else { 4919 ICS.setBad(BadConversionSequence::unrelated_class, 4920 FromType, ImplicitParamType); 4921 return ICS; 4922 } 4923 4924 // Check the ref-qualifier. 4925 switch (Method->getRefQualifier()) { 4926 case RQ_None: 4927 // Do nothing; we don't care about lvalueness or rvalueness. 4928 break; 4929 4930 case RQ_LValue: 4931 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4932 // non-const lvalue reference cannot bind to an rvalue 4933 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4934 ImplicitParamType); 4935 return ICS; 4936 } 4937 break; 4938 4939 case RQ_RValue: 4940 if (!FromClassification.isRValue()) { 4941 // rvalue reference cannot bind to an lvalue 4942 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4943 ImplicitParamType); 4944 return ICS; 4945 } 4946 break; 4947 } 4948 4949 // Success. Mark this as a reference binding. 4950 ICS.setStandard(); 4951 ICS.Standard.setAsIdentityConversion(); 4952 ICS.Standard.Second = SecondKind; 4953 ICS.Standard.setFromType(FromType); 4954 ICS.Standard.setAllToTypes(ImplicitParamType); 4955 ICS.Standard.ReferenceBinding = true; 4956 ICS.Standard.DirectBinding = true; 4957 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4958 ICS.Standard.BindsToFunctionLvalue = false; 4959 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4960 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4961 = (Method->getRefQualifier() == RQ_None); 4962 return ICS; 4963 } 4964 4965 /// PerformObjectArgumentInitialization - Perform initialization of 4966 /// the implicit object parameter for the given Method with the given 4967 /// expression. 4968 ExprResult 4969 Sema::PerformObjectArgumentInitialization(Expr *From, 4970 NestedNameSpecifier *Qualifier, 4971 NamedDecl *FoundDecl, 4972 CXXMethodDecl *Method) { 4973 QualType FromRecordType, DestType; 4974 QualType ImplicitParamRecordType = 4975 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4976 4977 Expr::Classification FromClassification; 4978 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4979 FromRecordType = PT->getPointeeType(); 4980 DestType = Method->getThisType(Context); 4981 FromClassification = Expr::Classification::makeSimpleLValue(); 4982 } else { 4983 FromRecordType = From->getType(); 4984 DestType = ImplicitParamRecordType; 4985 FromClassification = From->Classify(Context); 4986 } 4987 4988 // Note that we always use the true parent context when performing 4989 // the actual argument initialization. 4990 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4991 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4992 Method->getParent()); 4993 if (ICS.isBad()) { 4994 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4995 Qualifiers FromQs = FromRecordType.getQualifiers(); 4996 Qualifiers ToQs = DestType.getQualifiers(); 4997 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4998 if (CVR) { 4999 Diag(From->getLocStart(), 5000 diag::err_member_function_call_bad_cvr) 5001 << Method->getDeclName() << FromRecordType << (CVR - 1) 5002 << From->getSourceRange(); 5003 Diag(Method->getLocation(), diag::note_previous_decl) 5004 << Method->getDeclName(); 5005 return ExprError(); 5006 } 5007 } 5008 5009 return Diag(From->getLocStart(), 5010 diag::err_implicit_object_parameter_init) 5011 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5012 } 5013 5014 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5015 ExprResult FromRes = 5016 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5017 if (FromRes.isInvalid()) 5018 return ExprError(); 5019 From = FromRes.get(); 5020 } 5021 5022 if (!Context.hasSameType(From->getType(), DestType)) 5023 From = ImpCastExprToType(From, DestType, CK_NoOp, 5024 From->getValueKind()).get(); 5025 return From; 5026 } 5027 5028 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5029 /// expression From to bool (C++0x [conv]p3). 5030 static ImplicitConversionSequence 5031 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5032 return TryImplicitConversion(S, From, S.Context.BoolTy, 5033 /*SuppressUserConversions=*/false, 5034 /*AllowExplicit=*/true, 5035 /*InOverloadResolution=*/false, 5036 /*CStyle=*/false, 5037 /*AllowObjCWritebackConversion=*/false, 5038 /*AllowObjCConversionOnExplicit=*/false); 5039 } 5040 5041 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5042 /// of the expression From to bool (C++0x [conv]p3). 5043 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5044 if (checkPlaceholderForOverload(*this, From)) 5045 return ExprError(); 5046 5047 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5048 if (!ICS.isBad()) 5049 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5050 5051 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5052 return Diag(From->getLocStart(), 5053 diag::err_typecheck_bool_condition) 5054 << From->getType() << From->getSourceRange(); 5055 return ExprError(); 5056 } 5057 5058 /// Check that the specified conversion is permitted in a converted constant 5059 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5060 /// is acceptable. 5061 static bool CheckConvertedConstantConversions(Sema &S, 5062 StandardConversionSequence &SCS) { 5063 // Since we know that the target type is an integral or unscoped enumeration 5064 // type, most conversion kinds are impossible. All possible First and Third 5065 // conversions are fine. 5066 switch (SCS.Second) { 5067 case ICK_Identity: 5068 case ICK_NoReturn_Adjustment: 5069 case ICK_Integral_Promotion: 5070 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5071 return true; 5072 5073 case ICK_Boolean_Conversion: 5074 // Conversion from an integral or unscoped enumeration type to bool is 5075 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5076 // conversion, so we allow it in a converted constant expression. 5077 // 5078 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5079 // a lot of popular code. We should at least add a warning for this 5080 // (non-conforming) extension. 5081 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5082 SCS.getToType(2)->isBooleanType(); 5083 5084 case ICK_Pointer_Conversion: 5085 case ICK_Pointer_Member: 5086 // C++1z: null pointer conversions and null member pointer conversions are 5087 // only permitted if the source type is std::nullptr_t. 5088 return SCS.getFromType()->isNullPtrType(); 5089 5090 case ICK_Floating_Promotion: 5091 case ICK_Complex_Promotion: 5092 case ICK_Floating_Conversion: 5093 case ICK_Complex_Conversion: 5094 case ICK_Floating_Integral: 5095 case ICK_Compatible_Conversion: 5096 case ICK_Derived_To_Base: 5097 case ICK_Vector_Conversion: 5098 case ICK_Vector_Splat: 5099 case ICK_Complex_Real: 5100 case ICK_Block_Pointer_Conversion: 5101 case ICK_TransparentUnionConversion: 5102 case ICK_Writeback_Conversion: 5103 case ICK_Zero_Event_Conversion: 5104 case ICK_C_Only_Conversion: 5105 return false; 5106 5107 case ICK_Lvalue_To_Rvalue: 5108 case ICK_Array_To_Pointer: 5109 case ICK_Function_To_Pointer: 5110 llvm_unreachable("found a first conversion kind in Second"); 5111 5112 case ICK_Qualification: 5113 llvm_unreachable("found a third conversion kind in Second"); 5114 5115 case ICK_Num_Conversion_Kinds: 5116 break; 5117 } 5118 5119 llvm_unreachable("unknown conversion kind"); 5120 } 5121 5122 /// CheckConvertedConstantExpression - Check that the expression From is a 5123 /// converted constant expression of type T, perform the conversion and produce 5124 /// the converted expression, per C++11 [expr.const]p3. 5125 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5126 QualType T, APValue &Value, 5127 Sema::CCEKind CCE, 5128 bool RequireInt) { 5129 assert(S.getLangOpts().CPlusPlus11 && 5130 "converted constant expression outside C++11"); 5131 5132 if (checkPlaceholderForOverload(S, From)) 5133 return ExprError(); 5134 5135 // C++1z [expr.const]p3: 5136 // A converted constant expression of type T is an expression, 5137 // implicitly converted to type T, where the converted 5138 // expression is a constant expression and the implicit conversion 5139 // sequence contains only [... list of conversions ...]. 5140 ImplicitConversionSequence ICS = 5141 TryCopyInitialization(S, From, T, 5142 /*SuppressUserConversions=*/false, 5143 /*InOverloadResolution=*/false, 5144 /*AllowObjcWritebackConversion=*/false, 5145 /*AllowExplicit=*/false); 5146 StandardConversionSequence *SCS = nullptr; 5147 switch (ICS.getKind()) { 5148 case ImplicitConversionSequence::StandardConversion: 5149 SCS = &ICS.Standard; 5150 break; 5151 case ImplicitConversionSequence::UserDefinedConversion: 5152 // We are converting to a non-class type, so the Before sequence 5153 // must be trivial. 5154 SCS = &ICS.UserDefined.After; 5155 break; 5156 case ImplicitConversionSequence::AmbiguousConversion: 5157 case ImplicitConversionSequence::BadConversion: 5158 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5159 return S.Diag(From->getLocStart(), 5160 diag::err_typecheck_converted_constant_expression) 5161 << From->getType() << From->getSourceRange() << T; 5162 return ExprError(); 5163 5164 case ImplicitConversionSequence::EllipsisConversion: 5165 llvm_unreachable("ellipsis conversion in converted constant expression"); 5166 } 5167 5168 // Check that we would only use permitted conversions. 5169 if (!CheckConvertedConstantConversions(S, *SCS)) { 5170 return S.Diag(From->getLocStart(), 5171 diag::err_typecheck_converted_constant_expression_disallowed) 5172 << From->getType() << From->getSourceRange() << T; 5173 } 5174 // [...] and where the reference binding (if any) binds directly. 5175 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5176 return S.Diag(From->getLocStart(), 5177 diag::err_typecheck_converted_constant_expression_indirect) 5178 << From->getType() << From->getSourceRange() << T; 5179 } 5180 5181 ExprResult Result = 5182 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5183 if (Result.isInvalid()) 5184 return Result; 5185 5186 // Check for a narrowing implicit conversion. 5187 APValue PreNarrowingValue; 5188 QualType PreNarrowingType; 5189 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5190 PreNarrowingType)) { 5191 case NK_Variable_Narrowing: 5192 // Implicit conversion to a narrower type, and the value is not a constant 5193 // expression. We'll diagnose this in a moment. 5194 case NK_Not_Narrowing: 5195 break; 5196 5197 case NK_Constant_Narrowing: 5198 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5199 << CCE << /*Constant*/1 5200 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5201 break; 5202 5203 case NK_Type_Narrowing: 5204 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5205 << CCE << /*Constant*/0 << From->getType() << T; 5206 break; 5207 } 5208 5209 // Check the expression is a constant expression. 5210 SmallVector<PartialDiagnosticAt, 8> Notes; 5211 Expr::EvalResult Eval; 5212 Eval.Diag = &Notes; 5213 5214 if ((T->isReferenceType() 5215 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5216 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5217 (RequireInt && !Eval.Val.isInt())) { 5218 // The expression can't be folded, so we can't keep it at this position in 5219 // the AST. 5220 Result = ExprError(); 5221 } else { 5222 Value = Eval.Val; 5223 5224 if (Notes.empty()) { 5225 // It's a constant expression. 5226 return Result; 5227 } 5228 } 5229 5230 // It's not a constant expression. Produce an appropriate diagnostic. 5231 if (Notes.size() == 1 && 5232 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5233 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5234 else { 5235 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5236 << CCE << From->getSourceRange(); 5237 for (unsigned I = 0; I < Notes.size(); ++I) 5238 S.Diag(Notes[I].first, Notes[I].second); 5239 } 5240 return ExprError(); 5241 } 5242 5243 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5244 APValue &Value, CCEKind CCE) { 5245 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5246 } 5247 5248 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5249 llvm::APSInt &Value, 5250 CCEKind CCE) { 5251 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5252 5253 APValue V; 5254 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5255 if (!R.isInvalid()) 5256 Value = V.getInt(); 5257 return R; 5258 } 5259 5260 5261 /// dropPointerConversions - If the given standard conversion sequence 5262 /// involves any pointer conversions, remove them. This may change 5263 /// the result type of the conversion sequence. 5264 static void dropPointerConversion(StandardConversionSequence &SCS) { 5265 if (SCS.Second == ICK_Pointer_Conversion) { 5266 SCS.Second = ICK_Identity; 5267 SCS.Third = ICK_Identity; 5268 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5269 } 5270 } 5271 5272 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5273 /// convert the expression From to an Objective-C pointer type. 5274 static ImplicitConversionSequence 5275 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5276 // Do an implicit conversion to 'id'. 5277 QualType Ty = S.Context.getObjCIdType(); 5278 ImplicitConversionSequence ICS 5279 = TryImplicitConversion(S, From, Ty, 5280 // FIXME: Are these flags correct? 5281 /*SuppressUserConversions=*/false, 5282 /*AllowExplicit=*/true, 5283 /*InOverloadResolution=*/false, 5284 /*CStyle=*/false, 5285 /*AllowObjCWritebackConversion=*/false, 5286 /*AllowObjCConversionOnExplicit=*/true); 5287 5288 // Strip off any final conversions to 'id'. 5289 switch (ICS.getKind()) { 5290 case ImplicitConversionSequence::BadConversion: 5291 case ImplicitConversionSequence::AmbiguousConversion: 5292 case ImplicitConversionSequence::EllipsisConversion: 5293 break; 5294 5295 case ImplicitConversionSequence::UserDefinedConversion: 5296 dropPointerConversion(ICS.UserDefined.After); 5297 break; 5298 5299 case ImplicitConversionSequence::StandardConversion: 5300 dropPointerConversion(ICS.Standard); 5301 break; 5302 } 5303 5304 return ICS; 5305 } 5306 5307 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5308 /// conversion of the expression From to an Objective-C pointer type. 5309 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5310 if (checkPlaceholderForOverload(*this, From)) 5311 return ExprError(); 5312 5313 QualType Ty = Context.getObjCIdType(); 5314 ImplicitConversionSequence ICS = 5315 TryContextuallyConvertToObjCPointer(*this, From); 5316 if (!ICS.isBad()) 5317 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5318 return ExprError(); 5319 } 5320 5321 /// Determine whether the provided type is an integral type, or an enumeration 5322 /// type of a permitted flavor. 5323 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5324 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5325 : T->isIntegralOrUnscopedEnumerationType(); 5326 } 5327 5328 static ExprResult 5329 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5330 Sema::ContextualImplicitConverter &Converter, 5331 QualType T, UnresolvedSetImpl &ViableConversions) { 5332 5333 if (Converter.Suppress) 5334 return ExprError(); 5335 5336 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5337 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5338 CXXConversionDecl *Conv = 5339 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5340 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5341 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5342 } 5343 return From; 5344 } 5345 5346 static bool 5347 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5348 Sema::ContextualImplicitConverter &Converter, 5349 QualType T, bool HadMultipleCandidates, 5350 UnresolvedSetImpl &ExplicitConversions) { 5351 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5352 DeclAccessPair Found = ExplicitConversions[0]; 5353 CXXConversionDecl *Conversion = 5354 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5355 5356 // The user probably meant to invoke the given explicit 5357 // conversion; use it. 5358 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5359 std::string TypeStr; 5360 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5361 5362 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5363 << FixItHint::CreateInsertion(From->getLocStart(), 5364 "static_cast<" + TypeStr + ">(") 5365 << FixItHint::CreateInsertion( 5366 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5367 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5368 5369 // If we aren't in a SFINAE context, build a call to the 5370 // explicit conversion function. 5371 if (SemaRef.isSFINAEContext()) 5372 return true; 5373 5374 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5375 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5376 HadMultipleCandidates); 5377 if (Result.isInvalid()) 5378 return true; 5379 // Record usage of conversion in an implicit cast. 5380 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5381 CK_UserDefinedConversion, Result.get(), 5382 nullptr, Result.get()->getValueKind()); 5383 } 5384 return false; 5385 } 5386 5387 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5388 Sema::ContextualImplicitConverter &Converter, 5389 QualType T, bool HadMultipleCandidates, 5390 DeclAccessPair &Found) { 5391 CXXConversionDecl *Conversion = 5392 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5393 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5394 5395 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5396 if (!Converter.SuppressConversion) { 5397 if (SemaRef.isSFINAEContext()) 5398 return true; 5399 5400 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5401 << From->getSourceRange(); 5402 } 5403 5404 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5405 HadMultipleCandidates); 5406 if (Result.isInvalid()) 5407 return true; 5408 // Record usage of conversion in an implicit cast. 5409 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5410 CK_UserDefinedConversion, Result.get(), 5411 nullptr, Result.get()->getValueKind()); 5412 return false; 5413 } 5414 5415 static ExprResult finishContextualImplicitConversion( 5416 Sema &SemaRef, SourceLocation Loc, Expr *From, 5417 Sema::ContextualImplicitConverter &Converter) { 5418 if (!Converter.match(From->getType()) && !Converter.Suppress) 5419 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5420 << From->getSourceRange(); 5421 5422 return SemaRef.DefaultLvalueConversion(From); 5423 } 5424 5425 static void 5426 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5427 UnresolvedSetImpl &ViableConversions, 5428 OverloadCandidateSet &CandidateSet) { 5429 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5430 DeclAccessPair FoundDecl = ViableConversions[I]; 5431 NamedDecl *D = FoundDecl.getDecl(); 5432 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5433 if (isa<UsingShadowDecl>(D)) 5434 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5435 5436 CXXConversionDecl *Conv; 5437 FunctionTemplateDecl *ConvTemplate; 5438 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5439 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5440 else 5441 Conv = cast<CXXConversionDecl>(D); 5442 5443 if (ConvTemplate) 5444 SemaRef.AddTemplateConversionCandidate( 5445 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5446 /*AllowObjCConversionOnExplicit=*/false); 5447 else 5448 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5449 ToType, CandidateSet, 5450 /*AllowObjCConversionOnExplicit=*/false); 5451 } 5452 } 5453 5454 /// \brief Attempt to convert the given expression to a type which is accepted 5455 /// by the given converter. 5456 /// 5457 /// This routine will attempt to convert an expression of class type to a 5458 /// type accepted by the specified converter. In C++11 and before, the class 5459 /// must have a single non-explicit conversion function converting to a matching 5460 /// type. In C++1y, there can be multiple such conversion functions, but only 5461 /// one target type. 5462 /// 5463 /// \param Loc The source location of the construct that requires the 5464 /// conversion. 5465 /// 5466 /// \param From The expression we're converting from. 5467 /// 5468 /// \param Converter Used to control and diagnose the conversion process. 5469 /// 5470 /// \returns The expression, converted to an integral or enumeration type if 5471 /// successful. 5472 ExprResult Sema::PerformContextualImplicitConversion( 5473 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5474 // We can't perform any more checking for type-dependent expressions. 5475 if (From->isTypeDependent()) 5476 return From; 5477 5478 // Process placeholders immediately. 5479 if (From->hasPlaceholderType()) { 5480 ExprResult result = CheckPlaceholderExpr(From); 5481 if (result.isInvalid()) 5482 return result; 5483 From = result.get(); 5484 } 5485 5486 // If the expression already has a matching type, we're golden. 5487 QualType T = From->getType(); 5488 if (Converter.match(T)) 5489 return DefaultLvalueConversion(From); 5490 5491 // FIXME: Check for missing '()' if T is a function type? 5492 5493 // We can only perform contextual implicit conversions on objects of class 5494 // type. 5495 const RecordType *RecordTy = T->getAs<RecordType>(); 5496 if (!RecordTy || !getLangOpts().CPlusPlus) { 5497 if (!Converter.Suppress) 5498 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5499 return From; 5500 } 5501 5502 // We must have a complete class type. 5503 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5504 ContextualImplicitConverter &Converter; 5505 Expr *From; 5506 5507 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5508 : Converter(Converter), From(From) {} 5509 5510 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5511 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5512 } 5513 } IncompleteDiagnoser(Converter, From); 5514 5515 if (Converter.Suppress ? !isCompleteType(Loc, T) 5516 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5517 return From; 5518 5519 // Look for a conversion to an integral or enumeration type. 5520 UnresolvedSet<4> 5521 ViableConversions; // These are *potentially* viable in C++1y. 5522 UnresolvedSet<4> ExplicitConversions; 5523 const auto &Conversions = 5524 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5525 5526 bool HadMultipleCandidates = 5527 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5528 5529 // To check that there is only one target type, in C++1y: 5530 QualType ToType; 5531 bool HasUniqueTargetType = true; 5532 5533 // Collect explicit or viable (potentially in C++1y) conversions. 5534 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5535 NamedDecl *D = (*I)->getUnderlyingDecl(); 5536 CXXConversionDecl *Conversion; 5537 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5538 if (ConvTemplate) { 5539 if (getLangOpts().CPlusPlus14) 5540 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5541 else 5542 continue; // C++11 does not consider conversion operator templates(?). 5543 } else 5544 Conversion = cast<CXXConversionDecl>(D); 5545 5546 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5547 "Conversion operator templates are considered potentially " 5548 "viable in C++1y"); 5549 5550 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5551 if (Converter.match(CurToType) || ConvTemplate) { 5552 5553 if (Conversion->isExplicit()) { 5554 // FIXME: For C++1y, do we need this restriction? 5555 // cf. diagnoseNoViableConversion() 5556 if (!ConvTemplate) 5557 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5558 } else { 5559 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5560 if (ToType.isNull()) 5561 ToType = CurToType.getUnqualifiedType(); 5562 else if (HasUniqueTargetType && 5563 (CurToType.getUnqualifiedType() != ToType)) 5564 HasUniqueTargetType = false; 5565 } 5566 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5567 } 5568 } 5569 } 5570 5571 if (getLangOpts().CPlusPlus14) { 5572 // C++1y [conv]p6: 5573 // ... An expression e of class type E appearing in such a context 5574 // is said to be contextually implicitly converted to a specified 5575 // type T and is well-formed if and only if e can be implicitly 5576 // converted to a type T that is determined as follows: E is searched 5577 // for conversion functions whose return type is cv T or reference to 5578 // cv T such that T is allowed by the context. There shall be 5579 // exactly one such T. 5580 5581 // If no unique T is found: 5582 if (ToType.isNull()) { 5583 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5584 HadMultipleCandidates, 5585 ExplicitConversions)) 5586 return ExprError(); 5587 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5588 } 5589 5590 // If more than one unique Ts are found: 5591 if (!HasUniqueTargetType) 5592 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5593 ViableConversions); 5594 5595 // If one unique T is found: 5596 // First, build a candidate set from the previously recorded 5597 // potentially viable conversions. 5598 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5599 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5600 CandidateSet); 5601 5602 // Then, perform overload resolution over the candidate set. 5603 OverloadCandidateSet::iterator Best; 5604 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5605 case OR_Success: { 5606 // Apply this conversion. 5607 DeclAccessPair Found = 5608 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5609 if (recordConversion(*this, Loc, From, Converter, T, 5610 HadMultipleCandidates, Found)) 5611 return ExprError(); 5612 break; 5613 } 5614 case OR_Ambiguous: 5615 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5616 ViableConversions); 5617 case OR_No_Viable_Function: 5618 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5619 HadMultipleCandidates, 5620 ExplicitConversions)) 5621 return ExprError(); 5622 // fall through 'OR_Deleted' case. 5623 case OR_Deleted: 5624 // We'll complain below about a non-integral condition type. 5625 break; 5626 } 5627 } else { 5628 switch (ViableConversions.size()) { 5629 case 0: { 5630 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5631 HadMultipleCandidates, 5632 ExplicitConversions)) 5633 return ExprError(); 5634 5635 // We'll complain below about a non-integral condition type. 5636 break; 5637 } 5638 case 1: { 5639 // Apply this conversion. 5640 DeclAccessPair Found = ViableConversions[0]; 5641 if (recordConversion(*this, Loc, From, Converter, T, 5642 HadMultipleCandidates, Found)) 5643 return ExprError(); 5644 break; 5645 } 5646 default: 5647 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5648 ViableConversions); 5649 } 5650 } 5651 5652 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5653 } 5654 5655 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5656 /// an acceptable non-member overloaded operator for a call whose 5657 /// arguments have types T1 (and, if non-empty, T2). This routine 5658 /// implements the check in C++ [over.match.oper]p3b2 concerning 5659 /// enumeration types. 5660 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5661 FunctionDecl *Fn, 5662 ArrayRef<Expr *> Args) { 5663 QualType T1 = Args[0]->getType(); 5664 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5665 5666 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5667 return true; 5668 5669 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5670 return true; 5671 5672 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5673 if (Proto->getNumParams() < 1) 5674 return false; 5675 5676 if (T1->isEnumeralType()) { 5677 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5678 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5679 return true; 5680 } 5681 5682 if (Proto->getNumParams() < 2) 5683 return false; 5684 5685 if (!T2.isNull() && T2->isEnumeralType()) { 5686 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5687 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5688 return true; 5689 } 5690 5691 return false; 5692 } 5693 5694 /// AddOverloadCandidate - Adds the given function to the set of 5695 /// candidate functions, using the given function call arguments. If 5696 /// @p SuppressUserConversions, then don't allow user-defined 5697 /// conversions via constructors or conversion operators. 5698 /// 5699 /// \param PartialOverloading true if we are performing "partial" overloading 5700 /// based on an incomplete set of function arguments. This feature is used by 5701 /// code completion. 5702 void 5703 Sema::AddOverloadCandidate(FunctionDecl *Function, 5704 DeclAccessPair FoundDecl, 5705 ArrayRef<Expr *> Args, 5706 OverloadCandidateSet &CandidateSet, 5707 bool SuppressUserConversions, 5708 bool PartialOverloading, 5709 bool AllowExplicit) { 5710 const FunctionProtoType *Proto 5711 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5712 assert(Proto && "Functions without a prototype cannot be overloaded"); 5713 assert(!Function->getDescribedFunctionTemplate() && 5714 "Use AddTemplateOverloadCandidate for function templates"); 5715 5716 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5717 if (!isa<CXXConstructorDecl>(Method)) { 5718 // If we get here, it's because we're calling a member function 5719 // that is named without a member access expression (e.g., 5720 // "this->f") that was either written explicitly or created 5721 // implicitly. This can happen with a qualified call to a member 5722 // function, e.g., X::f(). We use an empty type for the implied 5723 // object argument (C++ [over.call.func]p3), and the acting context 5724 // is irrelevant. 5725 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5726 QualType(), Expr::Classification::makeSimpleLValue(), 5727 Args, CandidateSet, SuppressUserConversions, 5728 PartialOverloading); 5729 return; 5730 } 5731 // We treat a constructor like a non-member function, since its object 5732 // argument doesn't participate in overload resolution. 5733 } 5734 5735 if (!CandidateSet.isNewCandidate(Function)) 5736 return; 5737 5738 // C++ [over.match.oper]p3: 5739 // if no operand has a class type, only those non-member functions in the 5740 // lookup set that have a first parameter of type T1 or "reference to 5741 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5742 // is a right operand) a second parameter of type T2 or "reference to 5743 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5744 // candidate functions. 5745 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5746 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5747 return; 5748 5749 // C++11 [class.copy]p11: [DR1402] 5750 // A defaulted move constructor that is defined as deleted is ignored by 5751 // overload resolution. 5752 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5753 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5754 Constructor->isMoveConstructor()) 5755 return; 5756 5757 // Overload resolution is always an unevaluated context. 5758 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5759 5760 // Add this candidate 5761 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5762 Candidate.FoundDecl = FoundDecl; 5763 Candidate.Function = Function; 5764 Candidate.Viable = true; 5765 Candidate.IsSurrogate = false; 5766 Candidate.IgnoreObjectArgument = false; 5767 Candidate.ExplicitCallArguments = Args.size(); 5768 5769 if (Constructor) { 5770 // C++ [class.copy]p3: 5771 // A member function template is never instantiated to perform the copy 5772 // of a class object to an object of its class type. 5773 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5774 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5775 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5776 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5777 ClassType))) { 5778 Candidate.Viable = false; 5779 Candidate.FailureKind = ovl_fail_illegal_constructor; 5780 return; 5781 } 5782 } 5783 5784 unsigned NumParams = Proto->getNumParams(); 5785 5786 // (C++ 13.3.2p2): A candidate function having fewer than m 5787 // parameters is viable only if it has an ellipsis in its parameter 5788 // list (8.3.5). 5789 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5790 !Proto->isVariadic()) { 5791 Candidate.Viable = false; 5792 Candidate.FailureKind = ovl_fail_too_many_arguments; 5793 return; 5794 } 5795 5796 // (C++ 13.3.2p2): A candidate function having more than m parameters 5797 // is viable only if the (m+1)st parameter has a default argument 5798 // (8.3.6). For the purposes of overload resolution, the 5799 // parameter list is truncated on the right, so that there are 5800 // exactly m parameters. 5801 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5802 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5803 // Not enough arguments. 5804 Candidate.Viable = false; 5805 Candidate.FailureKind = ovl_fail_too_few_arguments; 5806 return; 5807 } 5808 5809 // (CUDA B.1): Check for invalid calls between targets. 5810 if (getLangOpts().CUDA) 5811 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5812 // Skip the check for callers that are implicit members, because in this 5813 // case we may not yet know what the member's target is; the target is 5814 // inferred for the member automatically, based on the bases and fields of 5815 // the class. 5816 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5817 Candidate.Viable = false; 5818 Candidate.FailureKind = ovl_fail_bad_target; 5819 return; 5820 } 5821 5822 // Determine the implicit conversion sequences for each of the 5823 // arguments. 5824 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5825 if (ArgIdx < NumParams) { 5826 // (C++ 13.3.2p3): for F to be a viable function, there shall 5827 // exist for each argument an implicit conversion sequence 5828 // (13.3.3.1) that converts that argument to the corresponding 5829 // parameter of F. 5830 QualType ParamType = Proto->getParamType(ArgIdx); 5831 Candidate.Conversions[ArgIdx] 5832 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5833 SuppressUserConversions, 5834 /*InOverloadResolution=*/true, 5835 /*AllowObjCWritebackConversion=*/ 5836 getLangOpts().ObjCAutoRefCount, 5837 AllowExplicit); 5838 if (Candidate.Conversions[ArgIdx].isBad()) { 5839 Candidate.Viable = false; 5840 Candidate.FailureKind = ovl_fail_bad_conversion; 5841 return; 5842 } 5843 } else { 5844 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5845 // argument for which there is no corresponding parameter is 5846 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5847 Candidate.Conversions[ArgIdx].setEllipsis(); 5848 } 5849 } 5850 5851 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5852 Candidate.Viable = false; 5853 Candidate.FailureKind = ovl_fail_enable_if; 5854 Candidate.DeductionFailure.Data = FailedAttr; 5855 return; 5856 } 5857 } 5858 5859 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5860 bool IsInstance) { 5861 SmallVector<ObjCMethodDecl*, 4> Methods; 5862 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5863 return nullptr; 5864 5865 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5866 bool Match = true; 5867 ObjCMethodDecl *Method = Methods[b]; 5868 unsigned NumNamedArgs = Sel.getNumArgs(); 5869 // Method might have more arguments than selector indicates. This is due 5870 // to addition of c-style arguments in method. 5871 if (Method->param_size() > NumNamedArgs) 5872 NumNamedArgs = Method->param_size(); 5873 if (Args.size() < NumNamedArgs) 5874 continue; 5875 5876 for (unsigned i = 0; i < NumNamedArgs; i++) { 5877 // We can't do any type-checking on a type-dependent argument. 5878 if (Args[i]->isTypeDependent()) { 5879 Match = false; 5880 break; 5881 } 5882 5883 ParmVarDecl *param = Method->parameters()[i]; 5884 Expr *argExpr = Args[i]; 5885 assert(argExpr && "SelectBestMethod(): missing expression"); 5886 5887 // Strip the unbridged-cast placeholder expression off unless it's 5888 // a consumed argument. 5889 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5890 !param->hasAttr<CFConsumedAttr>()) 5891 argExpr = stripARCUnbridgedCast(argExpr); 5892 5893 // If the parameter is __unknown_anytype, move on to the next method. 5894 if (param->getType() == Context.UnknownAnyTy) { 5895 Match = false; 5896 break; 5897 } 5898 5899 ImplicitConversionSequence ConversionState 5900 = TryCopyInitialization(*this, argExpr, param->getType(), 5901 /*SuppressUserConversions*/false, 5902 /*InOverloadResolution=*/true, 5903 /*AllowObjCWritebackConversion=*/ 5904 getLangOpts().ObjCAutoRefCount, 5905 /*AllowExplicit*/false); 5906 if (ConversionState.isBad()) { 5907 Match = false; 5908 break; 5909 } 5910 } 5911 // Promote additional arguments to variadic methods. 5912 if (Match && Method->isVariadic()) { 5913 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5914 if (Args[i]->isTypeDependent()) { 5915 Match = false; 5916 break; 5917 } 5918 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5919 nullptr); 5920 if (Arg.isInvalid()) { 5921 Match = false; 5922 break; 5923 } 5924 } 5925 } else { 5926 // Check for extra arguments to non-variadic methods. 5927 if (Args.size() != NumNamedArgs) 5928 Match = false; 5929 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5930 // Special case when selectors have no argument. In this case, select 5931 // one with the most general result type of 'id'. 5932 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5933 QualType ReturnT = Methods[b]->getReturnType(); 5934 if (ReturnT->isObjCIdType()) 5935 return Methods[b]; 5936 } 5937 } 5938 } 5939 5940 if (Match) 5941 return Method; 5942 } 5943 return nullptr; 5944 } 5945 5946 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5947 // enable_if is order-sensitive. As a result, we need to reverse things 5948 // sometimes. Size of 4 elements is arbitrary. 5949 static SmallVector<EnableIfAttr *, 4> 5950 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5951 SmallVector<EnableIfAttr *, 4> Result; 5952 if (!Function->hasAttrs()) 5953 return Result; 5954 5955 const auto &FuncAttrs = Function->getAttrs(); 5956 for (Attr *Attr : FuncAttrs) 5957 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5958 Result.push_back(EnableIf); 5959 5960 std::reverse(Result.begin(), Result.end()); 5961 return Result; 5962 } 5963 5964 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5965 bool MissingImplicitThis) { 5966 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5967 if (EnableIfAttrs.empty()) 5968 return nullptr; 5969 5970 SFINAETrap Trap(*this); 5971 SmallVector<Expr *, 16> ConvertedArgs; 5972 bool InitializationFailed = false; 5973 bool ContainsValueDependentExpr = false; 5974 5975 // Convert the arguments. 5976 for (unsigned I = 0, E = Args.size(); I != E; ++I) { 5977 ExprResult R; 5978 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5979 !cast<CXXMethodDecl>(Function)->isStatic() && 5980 !isa<CXXConstructorDecl>(Function)) { 5981 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5982 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5983 Method, Method); 5984 } else { 5985 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 5986 Context, Function->getParamDecl(I)), 5987 SourceLocation(), Args[I]); 5988 } 5989 5990 if (R.isInvalid()) { 5991 InitializationFailed = true; 5992 break; 5993 } 5994 5995 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5996 ConvertedArgs.push_back(R.get()); 5997 } 5998 5999 if (InitializationFailed || Trap.hasErrorOccurred()) 6000 return EnableIfAttrs[0]; 6001 6002 // Push default arguments if needed. 6003 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6004 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6005 ParmVarDecl *P = Function->getParamDecl(i); 6006 ExprResult R = PerformCopyInitialization( 6007 InitializedEntity::InitializeParameter(Context, 6008 Function->getParamDecl(i)), 6009 SourceLocation(), 6010 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6011 : P->getDefaultArg()); 6012 if (R.isInvalid()) { 6013 InitializationFailed = true; 6014 break; 6015 } 6016 ContainsValueDependentExpr |= R.get()->isValueDependent(); 6017 ConvertedArgs.push_back(R.get()); 6018 } 6019 6020 if (InitializationFailed || Trap.hasErrorOccurred()) 6021 return EnableIfAttrs[0]; 6022 } 6023 6024 for (auto *EIA : EnableIfAttrs) { 6025 APValue Result; 6026 if (EIA->getCond()->isValueDependent()) { 6027 // Don't even try now, we'll examine it after instantiation. 6028 continue; 6029 } 6030 6031 if (!EIA->getCond()->EvaluateWithSubstitution( 6032 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 6033 if (!ContainsValueDependentExpr) 6034 return EIA; 6035 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 6036 return EIA; 6037 } 6038 } 6039 return nullptr; 6040 } 6041 6042 /// \brief Add all of the function declarations in the given function set to 6043 /// the overload candidate set. 6044 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6045 ArrayRef<Expr *> Args, 6046 OverloadCandidateSet& CandidateSet, 6047 TemplateArgumentListInfo *ExplicitTemplateArgs, 6048 bool SuppressUserConversions, 6049 bool PartialOverloading) { 6050 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6051 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6052 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6053 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6054 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6055 cast<CXXMethodDecl>(FD)->getParent(), 6056 Args[0]->getType(), Args[0]->Classify(Context), 6057 Args.slice(1), CandidateSet, 6058 SuppressUserConversions, PartialOverloading); 6059 else 6060 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6061 SuppressUserConversions, PartialOverloading); 6062 } else { 6063 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6064 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6065 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6066 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6067 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6068 ExplicitTemplateArgs, 6069 Args[0]->getType(), 6070 Args[0]->Classify(Context), Args.slice(1), 6071 CandidateSet, SuppressUserConversions, 6072 PartialOverloading); 6073 else 6074 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6075 ExplicitTemplateArgs, Args, 6076 CandidateSet, SuppressUserConversions, 6077 PartialOverloading); 6078 } 6079 } 6080 } 6081 6082 /// AddMethodCandidate - Adds a named decl (which is some kind of 6083 /// method) as a method candidate to the given overload set. 6084 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6085 QualType ObjectType, 6086 Expr::Classification ObjectClassification, 6087 ArrayRef<Expr *> Args, 6088 OverloadCandidateSet& CandidateSet, 6089 bool SuppressUserConversions) { 6090 NamedDecl *Decl = FoundDecl.getDecl(); 6091 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6092 6093 if (isa<UsingShadowDecl>(Decl)) 6094 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6095 6096 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6097 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6098 "Expected a member function template"); 6099 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6100 /*ExplicitArgs*/ nullptr, 6101 ObjectType, ObjectClassification, 6102 Args, CandidateSet, 6103 SuppressUserConversions); 6104 } else { 6105 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6106 ObjectType, ObjectClassification, 6107 Args, 6108 CandidateSet, SuppressUserConversions); 6109 } 6110 } 6111 6112 /// AddMethodCandidate - Adds the given C++ member function to the set 6113 /// of candidate functions, using the given function call arguments 6114 /// and the object argument (@c Object). For example, in a call 6115 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6116 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6117 /// allow user-defined conversions via constructors or conversion 6118 /// operators. 6119 void 6120 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6121 CXXRecordDecl *ActingContext, QualType ObjectType, 6122 Expr::Classification ObjectClassification, 6123 ArrayRef<Expr *> Args, 6124 OverloadCandidateSet &CandidateSet, 6125 bool SuppressUserConversions, 6126 bool PartialOverloading) { 6127 const FunctionProtoType *Proto 6128 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6129 assert(Proto && "Methods without a prototype cannot be overloaded"); 6130 assert(!isa<CXXConstructorDecl>(Method) && 6131 "Use AddOverloadCandidate for constructors"); 6132 6133 if (!CandidateSet.isNewCandidate(Method)) 6134 return; 6135 6136 // C++11 [class.copy]p23: [DR1402] 6137 // A defaulted move assignment operator that is defined as deleted is 6138 // ignored by overload resolution. 6139 if (Method->isDefaulted() && Method->isDeleted() && 6140 Method->isMoveAssignmentOperator()) 6141 return; 6142 6143 // Overload resolution is always an unevaluated context. 6144 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6145 6146 // Add this candidate 6147 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6148 Candidate.FoundDecl = FoundDecl; 6149 Candidate.Function = Method; 6150 Candidate.IsSurrogate = false; 6151 Candidate.IgnoreObjectArgument = false; 6152 Candidate.ExplicitCallArguments = Args.size(); 6153 6154 unsigned NumParams = Proto->getNumParams(); 6155 6156 // (C++ 13.3.2p2): A candidate function having fewer than m 6157 // parameters is viable only if it has an ellipsis in its parameter 6158 // list (8.3.5). 6159 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6160 !Proto->isVariadic()) { 6161 Candidate.Viable = false; 6162 Candidate.FailureKind = ovl_fail_too_many_arguments; 6163 return; 6164 } 6165 6166 // (C++ 13.3.2p2): A candidate function having more than m parameters 6167 // is viable only if the (m+1)st parameter has a default argument 6168 // (8.3.6). For the purposes of overload resolution, the 6169 // parameter list is truncated on the right, so that there are 6170 // exactly m parameters. 6171 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6172 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6173 // Not enough arguments. 6174 Candidate.Viable = false; 6175 Candidate.FailureKind = ovl_fail_too_few_arguments; 6176 return; 6177 } 6178 6179 Candidate.Viable = true; 6180 6181 if (Method->isStatic() || ObjectType.isNull()) 6182 // The implicit object argument is ignored. 6183 Candidate.IgnoreObjectArgument = true; 6184 else { 6185 // Determine the implicit conversion sequence for the object 6186 // parameter. 6187 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6188 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6189 Method, ActingContext); 6190 if (Candidate.Conversions[0].isBad()) { 6191 Candidate.Viable = false; 6192 Candidate.FailureKind = ovl_fail_bad_conversion; 6193 return; 6194 } 6195 } 6196 6197 // (CUDA B.1): Check for invalid calls between targets. 6198 if (getLangOpts().CUDA) 6199 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6200 if (CheckCUDATarget(Caller, Method)) { 6201 Candidate.Viable = false; 6202 Candidate.FailureKind = ovl_fail_bad_target; 6203 return; 6204 } 6205 6206 // Determine the implicit conversion sequences for each of the 6207 // arguments. 6208 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6209 if (ArgIdx < NumParams) { 6210 // (C++ 13.3.2p3): for F to be a viable function, there shall 6211 // exist for each argument an implicit conversion sequence 6212 // (13.3.3.1) that converts that argument to the corresponding 6213 // parameter of F. 6214 QualType ParamType = Proto->getParamType(ArgIdx); 6215 Candidate.Conversions[ArgIdx + 1] 6216 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6217 SuppressUserConversions, 6218 /*InOverloadResolution=*/true, 6219 /*AllowObjCWritebackConversion=*/ 6220 getLangOpts().ObjCAutoRefCount); 6221 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6222 Candidate.Viable = false; 6223 Candidate.FailureKind = ovl_fail_bad_conversion; 6224 return; 6225 } 6226 } else { 6227 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6228 // argument for which there is no corresponding parameter is 6229 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6230 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6231 } 6232 } 6233 6234 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6235 Candidate.Viable = false; 6236 Candidate.FailureKind = ovl_fail_enable_if; 6237 Candidate.DeductionFailure.Data = FailedAttr; 6238 return; 6239 } 6240 } 6241 6242 /// \brief Add a C++ member function template as a candidate to the candidate 6243 /// set, using template argument deduction to produce an appropriate member 6244 /// function template specialization. 6245 void 6246 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6247 DeclAccessPair FoundDecl, 6248 CXXRecordDecl *ActingContext, 6249 TemplateArgumentListInfo *ExplicitTemplateArgs, 6250 QualType ObjectType, 6251 Expr::Classification ObjectClassification, 6252 ArrayRef<Expr *> Args, 6253 OverloadCandidateSet& CandidateSet, 6254 bool SuppressUserConversions, 6255 bool PartialOverloading) { 6256 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6257 return; 6258 6259 // C++ [over.match.funcs]p7: 6260 // In each case where a candidate is a function template, candidate 6261 // function template specializations are generated using template argument 6262 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6263 // candidate functions in the usual way.113) A given name can refer to one 6264 // or more function templates and also to a set of overloaded non-template 6265 // functions. In such a case, the candidate functions generated from each 6266 // function template are combined with the set of non-template candidate 6267 // functions. 6268 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6269 FunctionDecl *Specialization = nullptr; 6270 if (TemplateDeductionResult Result 6271 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6272 Specialization, Info, PartialOverloading)) { 6273 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6274 Candidate.FoundDecl = FoundDecl; 6275 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6276 Candidate.Viable = false; 6277 Candidate.FailureKind = ovl_fail_bad_deduction; 6278 Candidate.IsSurrogate = false; 6279 Candidate.IgnoreObjectArgument = false; 6280 Candidate.ExplicitCallArguments = Args.size(); 6281 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6282 Info); 6283 return; 6284 } 6285 6286 // Add the function template specialization produced by template argument 6287 // deduction as a candidate. 6288 assert(Specialization && "Missing member function template specialization?"); 6289 assert(isa<CXXMethodDecl>(Specialization) && 6290 "Specialization is not a member function?"); 6291 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6292 ActingContext, ObjectType, ObjectClassification, Args, 6293 CandidateSet, SuppressUserConversions, PartialOverloading); 6294 } 6295 6296 /// \brief Add a C++ function template specialization as a candidate 6297 /// in the candidate set, using template argument deduction to produce 6298 /// an appropriate function template specialization. 6299 void 6300 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6301 DeclAccessPair FoundDecl, 6302 TemplateArgumentListInfo *ExplicitTemplateArgs, 6303 ArrayRef<Expr *> Args, 6304 OverloadCandidateSet& CandidateSet, 6305 bool SuppressUserConversions, 6306 bool PartialOverloading) { 6307 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6308 return; 6309 6310 // C++ [over.match.funcs]p7: 6311 // In each case where a candidate is a function template, candidate 6312 // function template specializations are generated using template argument 6313 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6314 // candidate functions in the usual way.113) A given name can refer to one 6315 // or more function templates and also to a set of overloaded non-template 6316 // functions. In such a case, the candidate functions generated from each 6317 // function template are combined with the set of non-template candidate 6318 // functions. 6319 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6320 FunctionDecl *Specialization = nullptr; 6321 if (TemplateDeductionResult Result 6322 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6323 Specialization, Info, PartialOverloading)) { 6324 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6325 Candidate.FoundDecl = FoundDecl; 6326 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6327 Candidate.Viable = false; 6328 Candidate.FailureKind = ovl_fail_bad_deduction; 6329 Candidate.IsSurrogate = false; 6330 Candidate.IgnoreObjectArgument = false; 6331 Candidate.ExplicitCallArguments = Args.size(); 6332 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6333 Info); 6334 return; 6335 } 6336 6337 // Add the function template specialization produced by template argument 6338 // deduction as a candidate. 6339 assert(Specialization && "Missing function template specialization?"); 6340 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6341 SuppressUserConversions, PartialOverloading); 6342 } 6343 6344 /// Determine whether this is an allowable conversion from the result 6345 /// of an explicit conversion operator to the expected type, per C++ 6346 /// [over.match.conv]p1 and [over.match.ref]p1. 6347 /// 6348 /// \param ConvType The return type of the conversion function. 6349 /// 6350 /// \param ToType The type we are converting to. 6351 /// 6352 /// \param AllowObjCPointerConversion Allow a conversion from one 6353 /// Objective-C pointer to another. 6354 /// 6355 /// \returns true if the conversion is allowable, false otherwise. 6356 static bool isAllowableExplicitConversion(Sema &S, 6357 QualType ConvType, QualType ToType, 6358 bool AllowObjCPointerConversion) { 6359 QualType ToNonRefType = ToType.getNonReferenceType(); 6360 6361 // Easy case: the types are the same. 6362 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6363 return true; 6364 6365 // Allow qualification conversions. 6366 bool ObjCLifetimeConversion; 6367 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6368 ObjCLifetimeConversion)) 6369 return true; 6370 6371 // If we're not allowed to consider Objective-C pointer conversions, 6372 // we're done. 6373 if (!AllowObjCPointerConversion) 6374 return false; 6375 6376 // Is this an Objective-C pointer conversion? 6377 bool IncompatibleObjC = false; 6378 QualType ConvertedType; 6379 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6380 IncompatibleObjC); 6381 } 6382 6383 /// AddConversionCandidate - Add a C++ conversion function as a 6384 /// candidate in the candidate set (C++ [over.match.conv], 6385 /// C++ [over.match.copy]). From is the expression we're converting from, 6386 /// and ToType is the type that we're eventually trying to convert to 6387 /// (which may or may not be the same type as the type that the 6388 /// conversion function produces). 6389 void 6390 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6391 DeclAccessPair FoundDecl, 6392 CXXRecordDecl *ActingContext, 6393 Expr *From, QualType ToType, 6394 OverloadCandidateSet& CandidateSet, 6395 bool AllowObjCConversionOnExplicit) { 6396 assert(!Conversion->getDescribedFunctionTemplate() && 6397 "Conversion function templates use AddTemplateConversionCandidate"); 6398 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6399 if (!CandidateSet.isNewCandidate(Conversion)) 6400 return; 6401 6402 // If the conversion function has an undeduced return type, trigger its 6403 // deduction now. 6404 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6405 if (DeduceReturnType(Conversion, From->getExprLoc())) 6406 return; 6407 ConvType = Conversion->getConversionType().getNonReferenceType(); 6408 } 6409 6410 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6411 // operator is only a candidate if its return type is the target type or 6412 // can be converted to the target type with a qualification conversion. 6413 if (Conversion->isExplicit() && 6414 !isAllowableExplicitConversion(*this, ConvType, ToType, 6415 AllowObjCConversionOnExplicit)) 6416 return; 6417 6418 // Overload resolution is always an unevaluated context. 6419 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6420 6421 // Add this candidate 6422 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6423 Candidate.FoundDecl = FoundDecl; 6424 Candidate.Function = Conversion; 6425 Candidate.IsSurrogate = false; 6426 Candidate.IgnoreObjectArgument = false; 6427 Candidate.FinalConversion.setAsIdentityConversion(); 6428 Candidate.FinalConversion.setFromType(ConvType); 6429 Candidate.FinalConversion.setAllToTypes(ToType); 6430 Candidate.Viable = true; 6431 Candidate.ExplicitCallArguments = 1; 6432 6433 // C++ [over.match.funcs]p4: 6434 // For conversion functions, the function is considered to be a member of 6435 // the class of the implicit implied object argument for the purpose of 6436 // defining the type of the implicit object parameter. 6437 // 6438 // Determine the implicit conversion sequence for the implicit 6439 // object parameter. 6440 QualType ImplicitParamType = From->getType(); 6441 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6442 ImplicitParamType = FromPtrType->getPointeeType(); 6443 CXXRecordDecl *ConversionContext 6444 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6445 6446 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6447 *this, CandidateSet.getLocation(), From->getType(), 6448 From->Classify(Context), Conversion, ConversionContext); 6449 6450 if (Candidate.Conversions[0].isBad()) { 6451 Candidate.Viable = false; 6452 Candidate.FailureKind = ovl_fail_bad_conversion; 6453 return; 6454 } 6455 6456 // We won't go through a user-defined type conversion function to convert a 6457 // derived to base as such conversions are given Conversion Rank. They only 6458 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6459 QualType FromCanon 6460 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6461 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6462 if (FromCanon == ToCanon || 6463 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6464 Candidate.Viable = false; 6465 Candidate.FailureKind = ovl_fail_trivial_conversion; 6466 return; 6467 } 6468 6469 // To determine what the conversion from the result of calling the 6470 // conversion function to the type we're eventually trying to 6471 // convert to (ToType), we need to synthesize a call to the 6472 // conversion function and attempt copy initialization from it. This 6473 // makes sure that we get the right semantics with respect to 6474 // lvalues/rvalues and the type. Fortunately, we can allocate this 6475 // call on the stack and we don't need its arguments to be 6476 // well-formed. 6477 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6478 VK_LValue, From->getLocStart()); 6479 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6480 Context.getPointerType(Conversion->getType()), 6481 CK_FunctionToPointerDecay, 6482 &ConversionRef, VK_RValue); 6483 6484 QualType ConversionType = Conversion->getConversionType(); 6485 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6486 Candidate.Viable = false; 6487 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6488 return; 6489 } 6490 6491 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6492 6493 // Note that it is safe to allocate CallExpr on the stack here because 6494 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6495 // allocator). 6496 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6497 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6498 From->getLocStart()); 6499 ImplicitConversionSequence ICS = 6500 TryCopyInitialization(*this, &Call, ToType, 6501 /*SuppressUserConversions=*/true, 6502 /*InOverloadResolution=*/false, 6503 /*AllowObjCWritebackConversion=*/false); 6504 6505 switch (ICS.getKind()) { 6506 case ImplicitConversionSequence::StandardConversion: 6507 Candidate.FinalConversion = ICS.Standard; 6508 6509 // C++ [over.ics.user]p3: 6510 // If the user-defined conversion is specified by a specialization of a 6511 // conversion function template, the second standard conversion sequence 6512 // shall have exact match rank. 6513 if (Conversion->getPrimaryTemplate() && 6514 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6515 Candidate.Viable = false; 6516 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6517 return; 6518 } 6519 6520 // C++0x [dcl.init.ref]p5: 6521 // In the second case, if the reference is an rvalue reference and 6522 // the second standard conversion sequence of the user-defined 6523 // conversion sequence includes an lvalue-to-rvalue conversion, the 6524 // program is ill-formed. 6525 if (ToType->isRValueReferenceType() && 6526 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6527 Candidate.Viable = false; 6528 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6529 return; 6530 } 6531 break; 6532 6533 case ImplicitConversionSequence::BadConversion: 6534 Candidate.Viable = false; 6535 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6536 return; 6537 6538 default: 6539 llvm_unreachable( 6540 "Can only end up with a standard conversion sequence or failure"); 6541 } 6542 6543 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6544 Candidate.Viable = false; 6545 Candidate.FailureKind = ovl_fail_enable_if; 6546 Candidate.DeductionFailure.Data = FailedAttr; 6547 return; 6548 } 6549 } 6550 6551 /// \brief Adds a conversion function template specialization 6552 /// candidate to the overload set, using template argument deduction 6553 /// to deduce the template arguments of the conversion function 6554 /// template from the type that we are converting to (C++ 6555 /// [temp.deduct.conv]). 6556 void 6557 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6558 DeclAccessPair FoundDecl, 6559 CXXRecordDecl *ActingDC, 6560 Expr *From, QualType ToType, 6561 OverloadCandidateSet &CandidateSet, 6562 bool AllowObjCConversionOnExplicit) { 6563 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6564 "Only conversion function templates permitted here"); 6565 6566 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6567 return; 6568 6569 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6570 CXXConversionDecl *Specialization = nullptr; 6571 if (TemplateDeductionResult Result 6572 = DeduceTemplateArguments(FunctionTemplate, ToType, 6573 Specialization, Info)) { 6574 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6575 Candidate.FoundDecl = FoundDecl; 6576 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6577 Candidate.Viable = false; 6578 Candidate.FailureKind = ovl_fail_bad_deduction; 6579 Candidate.IsSurrogate = false; 6580 Candidate.IgnoreObjectArgument = false; 6581 Candidate.ExplicitCallArguments = 1; 6582 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6583 Info); 6584 return; 6585 } 6586 6587 // Add the conversion function template specialization produced by 6588 // template argument deduction as a candidate. 6589 assert(Specialization && "Missing function template specialization?"); 6590 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6591 CandidateSet, AllowObjCConversionOnExplicit); 6592 } 6593 6594 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6595 /// converts the given @c Object to a function pointer via the 6596 /// conversion function @c Conversion, and then attempts to call it 6597 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6598 /// the type of function that we'll eventually be calling. 6599 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6600 DeclAccessPair FoundDecl, 6601 CXXRecordDecl *ActingContext, 6602 const FunctionProtoType *Proto, 6603 Expr *Object, 6604 ArrayRef<Expr *> Args, 6605 OverloadCandidateSet& CandidateSet) { 6606 if (!CandidateSet.isNewCandidate(Conversion)) 6607 return; 6608 6609 // Overload resolution is always an unevaluated context. 6610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6611 6612 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6613 Candidate.FoundDecl = FoundDecl; 6614 Candidate.Function = nullptr; 6615 Candidate.Surrogate = Conversion; 6616 Candidate.Viable = true; 6617 Candidate.IsSurrogate = true; 6618 Candidate.IgnoreObjectArgument = false; 6619 Candidate.ExplicitCallArguments = Args.size(); 6620 6621 // Determine the implicit conversion sequence for the implicit 6622 // object parameter. 6623 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6624 *this, CandidateSet.getLocation(), Object->getType(), 6625 Object->Classify(Context), Conversion, ActingContext); 6626 if (ObjectInit.isBad()) { 6627 Candidate.Viable = false; 6628 Candidate.FailureKind = ovl_fail_bad_conversion; 6629 Candidate.Conversions[0] = ObjectInit; 6630 return; 6631 } 6632 6633 // The first conversion is actually a user-defined conversion whose 6634 // first conversion is ObjectInit's standard conversion (which is 6635 // effectively a reference binding). Record it as such. 6636 Candidate.Conversions[0].setUserDefined(); 6637 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6638 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6639 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6640 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6641 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6642 Candidate.Conversions[0].UserDefined.After 6643 = Candidate.Conversions[0].UserDefined.Before; 6644 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6645 6646 // Find the 6647 unsigned NumParams = Proto->getNumParams(); 6648 6649 // (C++ 13.3.2p2): A candidate function having fewer than m 6650 // parameters is viable only if it has an ellipsis in its parameter 6651 // list (8.3.5). 6652 if (Args.size() > NumParams && !Proto->isVariadic()) { 6653 Candidate.Viable = false; 6654 Candidate.FailureKind = ovl_fail_too_many_arguments; 6655 return; 6656 } 6657 6658 // Function types don't have any default arguments, so just check if 6659 // we have enough arguments. 6660 if (Args.size() < NumParams) { 6661 // Not enough arguments. 6662 Candidate.Viable = false; 6663 Candidate.FailureKind = ovl_fail_too_few_arguments; 6664 return; 6665 } 6666 6667 // Determine the implicit conversion sequences for each of the 6668 // arguments. 6669 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6670 if (ArgIdx < NumParams) { 6671 // (C++ 13.3.2p3): for F to be a viable function, there shall 6672 // exist for each argument an implicit conversion sequence 6673 // (13.3.3.1) that converts that argument to the corresponding 6674 // parameter of F. 6675 QualType ParamType = Proto->getParamType(ArgIdx); 6676 Candidate.Conversions[ArgIdx + 1] 6677 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6678 /*SuppressUserConversions=*/false, 6679 /*InOverloadResolution=*/false, 6680 /*AllowObjCWritebackConversion=*/ 6681 getLangOpts().ObjCAutoRefCount); 6682 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6683 Candidate.Viable = false; 6684 Candidate.FailureKind = ovl_fail_bad_conversion; 6685 return; 6686 } 6687 } else { 6688 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6689 // argument for which there is no corresponding parameter is 6690 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6691 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6692 } 6693 } 6694 6695 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6696 Candidate.Viable = false; 6697 Candidate.FailureKind = ovl_fail_enable_if; 6698 Candidate.DeductionFailure.Data = FailedAttr; 6699 return; 6700 } 6701 } 6702 6703 /// \brief Add overload candidates for overloaded operators that are 6704 /// member functions. 6705 /// 6706 /// Add the overloaded operator candidates that are member functions 6707 /// for the operator Op that was used in an operator expression such 6708 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6709 /// CandidateSet will store the added overload candidates. (C++ 6710 /// [over.match.oper]). 6711 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6712 SourceLocation OpLoc, 6713 ArrayRef<Expr *> Args, 6714 OverloadCandidateSet& CandidateSet, 6715 SourceRange OpRange) { 6716 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6717 6718 // C++ [over.match.oper]p3: 6719 // For a unary operator @ with an operand of a type whose 6720 // cv-unqualified version is T1, and for a binary operator @ with 6721 // a left operand of a type whose cv-unqualified version is T1 and 6722 // a right operand of a type whose cv-unqualified version is T2, 6723 // three sets of candidate functions, designated member 6724 // candidates, non-member candidates and built-in candidates, are 6725 // constructed as follows: 6726 QualType T1 = Args[0]->getType(); 6727 6728 // -- If T1 is a complete class type or a class currently being 6729 // defined, the set of member candidates is the result of the 6730 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6731 // the set of member candidates is empty. 6732 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6733 // Complete the type if it can be completed. 6734 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6735 return; 6736 // If the type is neither complete nor being defined, bail out now. 6737 if (!T1Rec->getDecl()->getDefinition()) 6738 return; 6739 6740 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6741 LookupQualifiedName(Operators, T1Rec->getDecl()); 6742 Operators.suppressDiagnostics(); 6743 6744 for (LookupResult::iterator Oper = Operators.begin(), 6745 OperEnd = Operators.end(); 6746 Oper != OperEnd; 6747 ++Oper) 6748 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6749 Args[0]->Classify(Context), 6750 Args.slice(1), 6751 CandidateSet, 6752 /* SuppressUserConversions = */ false); 6753 } 6754 } 6755 6756 /// AddBuiltinCandidate - Add a candidate for a built-in 6757 /// operator. ResultTy and ParamTys are the result and parameter types 6758 /// of the built-in candidate, respectively. Args and NumArgs are the 6759 /// arguments being passed to the candidate. IsAssignmentOperator 6760 /// should be true when this built-in candidate is an assignment 6761 /// operator. NumContextualBoolArguments is the number of arguments 6762 /// (at the beginning of the argument list) that will be contextually 6763 /// converted to bool. 6764 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6765 ArrayRef<Expr *> Args, 6766 OverloadCandidateSet& CandidateSet, 6767 bool IsAssignmentOperator, 6768 unsigned NumContextualBoolArguments) { 6769 // Overload resolution is always an unevaluated context. 6770 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6771 6772 // Add this candidate 6773 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6774 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6775 Candidate.Function = nullptr; 6776 Candidate.IsSurrogate = false; 6777 Candidate.IgnoreObjectArgument = false; 6778 Candidate.BuiltinTypes.ResultTy = ResultTy; 6779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6780 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6781 6782 // Determine the implicit conversion sequences for each of the 6783 // arguments. 6784 Candidate.Viable = true; 6785 Candidate.ExplicitCallArguments = Args.size(); 6786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6787 // C++ [over.match.oper]p4: 6788 // For the built-in assignment operators, conversions of the 6789 // left operand are restricted as follows: 6790 // -- no temporaries are introduced to hold the left operand, and 6791 // -- no user-defined conversions are applied to the left 6792 // operand to achieve a type match with the left-most 6793 // parameter of a built-in candidate. 6794 // 6795 // We block these conversions by turning off user-defined 6796 // conversions, since that is the only way that initialization of 6797 // a reference to a non-class type can occur from something that 6798 // is not of the same type. 6799 if (ArgIdx < NumContextualBoolArguments) { 6800 assert(ParamTys[ArgIdx] == Context.BoolTy && 6801 "Contextual conversion to bool requires bool type"); 6802 Candidate.Conversions[ArgIdx] 6803 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6804 } else { 6805 Candidate.Conversions[ArgIdx] 6806 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6807 ArgIdx == 0 && IsAssignmentOperator, 6808 /*InOverloadResolution=*/false, 6809 /*AllowObjCWritebackConversion=*/ 6810 getLangOpts().ObjCAutoRefCount); 6811 } 6812 if (Candidate.Conversions[ArgIdx].isBad()) { 6813 Candidate.Viable = false; 6814 Candidate.FailureKind = ovl_fail_bad_conversion; 6815 break; 6816 } 6817 } 6818 } 6819 6820 namespace { 6821 6822 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6823 /// candidate operator functions for built-in operators (C++ 6824 /// [over.built]). The types are separated into pointer types and 6825 /// enumeration types. 6826 class BuiltinCandidateTypeSet { 6827 /// TypeSet - A set of types. 6828 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6829 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6830 6831 /// PointerTypes - The set of pointer types that will be used in the 6832 /// built-in candidates. 6833 TypeSet PointerTypes; 6834 6835 /// MemberPointerTypes - The set of member pointer types that will be 6836 /// used in the built-in candidates. 6837 TypeSet MemberPointerTypes; 6838 6839 /// EnumerationTypes - The set of enumeration types that will be 6840 /// used in the built-in candidates. 6841 TypeSet EnumerationTypes; 6842 6843 /// \brief The set of vector types that will be used in the built-in 6844 /// candidates. 6845 TypeSet VectorTypes; 6846 6847 /// \brief A flag indicating non-record types are viable candidates 6848 bool HasNonRecordTypes; 6849 6850 /// \brief A flag indicating whether either arithmetic or enumeration types 6851 /// were present in the candidate set. 6852 bool HasArithmeticOrEnumeralTypes; 6853 6854 /// \brief A flag indicating whether the nullptr type was present in the 6855 /// candidate set. 6856 bool HasNullPtrType; 6857 6858 /// Sema - The semantic analysis instance where we are building the 6859 /// candidate type set. 6860 Sema &SemaRef; 6861 6862 /// Context - The AST context in which we will build the type sets. 6863 ASTContext &Context; 6864 6865 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6866 const Qualifiers &VisibleQuals); 6867 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6868 6869 public: 6870 /// iterator - Iterates through the types that are part of the set. 6871 typedef TypeSet::iterator iterator; 6872 6873 BuiltinCandidateTypeSet(Sema &SemaRef) 6874 : HasNonRecordTypes(false), 6875 HasArithmeticOrEnumeralTypes(false), 6876 HasNullPtrType(false), 6877 SemaRef(SemaRef), 6878 Context(SemaRef.Context) { } 6879 6880 void AddTypesConvertedFrom(QualType Ty, 6881 SourceLocation Loc, 6882 bool AllowUserConversions, 6883 bool AllowExplicitConversions, 6884 const Qualifiers &VisibleTypeConversionsQuals); 6885 6886 /// pointer_begin - First pointer type found; 6887 iterator pointer_begin() { return PointerTypes.begin(); } 6888 6889 /// pointer_end - Past the last pointer type found; 6890 iterator pointer_end() { return PointerTypes.end(); } 6891 6892 /// member_pointer_begin - First member pointer type found; 6893 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6894 6895 /// member_pointer_end - Past the last member pointer type found; 6896 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6897 6898 /// enumeration_begin - First enumeration type found; 6899 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6900 6901 /// enumeration_end - Past the last enumeration type found; 6902 iterator enumeration_end() { return EnumerationTypes.end(); } 6903 6904 iterator vector_begin() { return VectorTypes.begin(); } 6905 iterator vector_end() { return VectorTypes.end(); } 6906 6907 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6908 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6909 bool hasNullPtrType() const { return HasNullPtrType; } 6910 }; 6911 6912 } // end anonymous namespace 6913 6914 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6915 /// the set of pointer types along with any more-qualified variants of 6916 /// that type. For example, if @p Ty is "int const *", this routine 6917 /// will add "int const *", "int const volatile *", "int const 6918 /// restrict *", and "int const volatile restrict *" to the set of 6919 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6920 /// false otherwise. 6921 /// 6922 /// FIXME: what to do about extended qualifiers? 6923 bool 6924 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6925 const Qualifiers &VisibleQuals) { 6926 6927 // Insert this type. 6928 if (!PointerTypes.insert(Ty)) 6929 return false; 6930 6931 QualType PointeeTy; 6932 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6933 bool buildObjCPtr = false; 6934 if (!PointerTy) { 6935 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6936 PointeeTy = PTy->getPointeeType(); 6937 buildObjCPtr = true; 6938 } else { 6939 PointeeTy = PointerTy->getPointeeType(); 6940 } 6941 6942 // Don't add qualified variants of arrays. For one, they're not allowed 6943 // (the qualifier would sink to the element type), and for another, the 6944 // only overload situation where it matters is subscript or pointer +- int, 6945 // and those shouldn't have qualifier variants anyway. 6946 if (PointeeTy->isArrayType()) 6947 return true; 6948 6949 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6950 bool hasVolatile = VisibleQuals.hasVolatile(); 6951 bool hasRestrict = VisibleQuals.hasRestrict(); 6952 6953 // Iterate through all strict supersets of BaseCVR. 6954 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6955 if ((CVR | BaseCVR) != CVR) continue; 6956 // Skip over volatile if no volatile found anywhere in the types. 6957 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6958 6959 // Skip over restrict if no restrict found anywhere in the types, or if 6960 // the type cannot be restrict-qualified. 6961 if ((CVR & Qualifiers::Restrict) && 6962 (!hasRestrict || 6963 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6964 continue; 6965 6966 // Build qualified pointee type. 6967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6968 6969 // Build qualified pointer type. 6970 QualType QPointerTy; 6971 if (!buildObjCPtr) 6972 QPointerTy = Context.getPointerType(QPointeeTy); 6973 else 6974 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6975 6976 // Insert qualified pointer type. 6977 PointerTypes.insert(QPointerTy); 6978 } 6979 6980 return true; 6981 } 6982 6983 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6984 /// to the set of pointer types along with any more-qualified variants of 6985 /// that type. For example, if @p Ty is "int const *", this routine 6986 /// will add "int const *", "int const volatile *", "int const 6987 /// restrict *", and "int const volatile restrict *" to the set of 6988 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6989 /// false otherwise. 6990 /// 6991 /// FIXME: what to do about extended qualifiers? 6992 bool 6993 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6994 QualType Ty) { 6995 // Insert this type. 6996 if (!MemberPointerTypes.insert(Ty)) 6997 return false; 6998 6999 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7000 assert(PointerTy && "type was not a member pointer type!"); 7001 7002 QualType PointeeTy = PointerTy->getPointeeType(); 7003 // Don't add qualified variants of arrays. For one, they're not allowed 7004 // (the qualifier would sink to the element type), and for another, the 7005 // only overload situation where it matters is subscript or pointer +- int, 7006 // and those shouldn't have qualifier variants anyway. 7007 if (PointeeTy->isArrayType()) 7008 return true; 7009 const Type *ClassTy = PointerTy->getClass(); 7010 7011 // Iterate through all strict supersets of the pointee type's CVR 7012 // qualifiers. 7013 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7014 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7015 if ((CVR | BaseCVR) != CVR) continue; 7016 7017 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7018 MemberPointerTypes.insert( 7019 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7020 } 7021 7022 return true; 7023 } 7024 7025 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7026 /// Ty can be implicit converted to the given set of @p Types. We're 7027 /// primarily interested in pointer types and enumeration types. We also 7028 /// take member pointer types, for the conditional operator. 7029 /// AllowUserConversions is true if we should look at the conversion 7030 /// functions of a class type, and AllowExplicitConversions if we 7031 /// should also include the explicit conversion functions of a class 7032 /// type. 7033 void 7034 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7035 SourceLocation Loc, 7036 bool AllowUserConversions, 7037 bool AllowExplicitConversions, 7038 const Qualifiers &VisibleQuals) { 7039 // Only deal with canonical types. 7040 Ty = Context.getCanonicalType(Ty); 7041 7042 // Look through reference types; they aren't part of the type of an 7043 // expression for the purposes of conversions. 7044 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7045 Ty = RefTy->getPointeeType(); 7046 7047 // If we're dealing with an array type, decay to the pointer. 7048 if (Ty->isArrayType()) 7049 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7050 7051 // Otherwise, we don't care about qualifiers on the type. 7052 Ty = Ty.getLocalUnqualifiedType(); 7053 7054 // Flag if we ever add a non-record type. 7055 const RecordType *TyRec = Ty->getAs<RecordType>(); 7056 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7057 7058 // Flag if we encounter an arithmetic type. 7059 HasArithmeticOrEnumeralTypes = 7060 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7061 7062 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7063 PointerTypes.insert(Ty); 7064 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7065 // Insert our type, and its more-qualified variants, into the set 7066 // of types. 7067 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7068 return; 7069 } else if (Ty->isMemberPointerType()) { 7070 // Member pointers are far easier, since the pointee can't be converted. 7071 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7072 return; 7073 } else if (Ty->isEnumeralType()) { 7074 HasArithmeticOrEnumeralTypes = true; 7075 EnumerationTypes.insert(Ty); 7076 } else if (Ty->isVectorType()) { 7077 // We treat vector types as arithmetic types in many contexts as an 7078 // extension. 7079 HasArithmeticOrEnumeralTypes = true; 7080 VectorTypes.insert(Ty); 7081 } else if (Ty->isNullPtrType()) { 7082 HasNullPtrType = true; 7083 } else if (AllowUserConversions && TyRec) { 7084 // No conversion functions in incomplete types. 7085 if (!SemaRef.isCompleteType(Loc, Ty)) 7086 return; 7087 7088 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7089 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7090 if (isa<UsingShadowDecl>(D)) 7091 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7092 7093 // Skip conversion function templates; they don't tell us anything 7094 // about which builtin types we can convert to. 7095 if (isa<FunctionTemplateDecl>(D)) 7096 continue; 7097 7098 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7099 if (AllowExplicitConversions || !Conv->isExplicit()) { 7100 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7101 VisibleQuals); 7102 } 7103 } 7104 } 7105 } 7106 7107 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7108 /// the volatile- and non-volatile-qualified assignment operators for the 7109 /// given type to the candidate set. 7110 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7111 QualType T, 7112 ArrayRef<Expr *> Args, 7113 OverloadCandidateSet &CandidateSet) { 7114 QualType ParamTypes[2]; 7115 7116 // T& operator=(T&, T) 7117 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7118 ParamTypes[1] = T; 7119 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7120 /*IsAssignmentOperator=*/true); 7121 7122 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7123 // volatile T& operator=(volatile T&, T) 7124 ParamTypes[0] 7125 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7126 ParamTypes[1] = T; 7127 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7128 /*IsAssignmentOperator=*/true); 7129 } 7130 } 7131 7132 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7133 /// if any, found in visible type conversion functions found in ArgExpr's type. 7134 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7135 Qualifiers VRQuals; 7136 const RecordType *TyRec; 7137 if (const MemberPointerType *RHSMPType = 7138 ArgExpr->getType()->getAs<MemberPointerType>()) 7139 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7140 else 7141 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7142 if (!TyRec) { 7143 // Just to be safe, assume the worst case. 7144 VRQuals.addVolatile(); 7145 VRQuals.addRestrict(); 7146 return VRQuals; 7147 } 7148 7149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7150 if (!ClassDecl->hasDefinition()) 7151 return VRQuals; 7152 7153 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7154 if (isa<UsingShadowDecl>(D)) 7155 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7156 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7157 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7158 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7159 CanTy = ResTypeRef->getPointeeType(); 7160 // Need to go down the pointer/mempointer chain and add qualifiers 7161 // as see them. 7162 bool done = false; 7163 while (!done) { 7164 if (CanTy.isRestrictQualified()) 7165 VRQuals.addRestrict(); 7166 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7167 CanTy = ResTypePtr->getPointeeType(); 7168 else if (const MemberPointerType *ResTypeMPtr = 7169 CanTy->getAs<MemberPointerType>()) 7170 CanTy = ResTypeMPtr->getPointeeType(); 7171 else 7172 done = true; 7173 if (CanTy.isVolatileQualified()) 7174 VRQuals.addVolatile(); 7175 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7176 return VRQuals; 7177 } 7178 } 7179 } 7180 return VRQuals; 7181 } 7182 7183 namespace { 7184 7185 /// \brief Helper class to manage the addition of builtin operator overload 7186 /// candidates. It provides shared state and utility methods used throughout 7187 /// the process, as well as a helper method to add each group of builtin 7188 /// operator overloads from the standard to a candidate set. 7189 class BuiltinOperatorOverloadBuilder { 7190 // Common instance state available to all overload candidate addition methods. 7191 Sema &S; 7192 ArrayRef<Expr *> Args; 7193 Qualifiers VisibleTypeConversionsQuals; 7194 bool HasArithmeticOrEnumeralCandidateType; 7195 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7196 OverloadCandidateSet &CandidateSet; 7197 7198 // Define some constants used to index and iterate over the arithemetic types 7199 // provided via the getArithmeticType() method below. 7200 // The "promoted arithmetic types" are the arithmetic 7201 // types are that preserved by promotion (C++ [over.built]p2). 7202 static const unsigned FirstIntegralType = 3; 7203 static const unsigned LastIntegralType = 20; 7204 static const unsigned FirstPromotedIntegralType = 3, 7205 LastPromotedIntegralType = 11; 7206 static const unsigned FirstPromotedArithmeticType = 0, 7207 LastPromotedArithmeticType = 11; 7208 static const unsigned NumArithmeticTypes = 20; 7209 7210 /// \brief Get the canonical type for a given arithmetic type index. 7211 CanQualType getArithmeticType(unsigned index) { 7212 assert(index < NumArithmeticTypes); 7213 static CanQualType ASTContext::* const 7214 ArithmeticTypes[NumArithmeticTypes] = { 7215 // Start of promoted types. 7216 &ASTContext::FloatTy, 7217 &ASTContext::DoubleTy, 7218 &ASTContext::LongDoubleTy, 7219 7220 // Start of integral types. 7221 &ASTContext::IntTy, 7222 &ASTContext::LongTy, 7223 &ASTContext::LongLongTy, 7224 &ASTContext::Int128Ty, 7225 &ASTContext::UnsignedIntTy, 7226 &ASTContext::UnsignedLongTy, 7227 &ASTContext::UnsignedLongLongTy, 7228 &ASTContext::UnsignedInt128Ty, 7229 // End of promoted types. 7230 7231 &ASTContext::BoolTy, 7232 &ASTContext::CharTy, 7233 &ASTContext::WCharTy, 7234 &ASTContext::Char16Ty, 7235 &ASTContext::Char32Ty, 7236 &ASTContext::SignedCharTy, 7237 &ASTContext::ShortTy, 7238 &ASTContext::UnsignedCharTy, 7239 &ASTContext::UnsignedShortTy, 7240 // End of integral types. 7241 // FIXME: What about complex? What about half? 7242 }; 7243 return S.Context.*ArithmeticTypes[index]; 7244 } 7245 7246 /// \brief Gets the canonical type resulting from the usual arithemetic 7247 /// converions for the given arithmetic types. 7248 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7249 // Accelerator table for performing the usual arithmetic conversions. 7250 // The rules are basically: 7251 // - if either is floating-point, use the wider floating-point 7252 // - if same signedness, use the higher rank 7253 // - if same size, use unsigned of the higher rank 7254 // - use the larger type 7255 // These rules, together with the axiom that higher ranks are 7256 // never smaller, are sufficient to precompute all of these results 7257 // *except* when dealing with signed types of higher rank. 7258 // (we could precompute SLL x UI for all known platforms, but it's 7259 // better not to make any assumptions). 7260 // We assume that int128 has a higher rank than long long on all platforms. 7261 enum PromotedType { 7262 Dep=-1, 7263 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7264 }; 7265 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7266 [LastPromotedArithmeticType] = { 7267 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7268 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7269 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7270 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7271 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7272 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7273 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7274 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7275 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7276 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7277 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7278 }; 7279 7280 assert(L < LastPromotedArithmeticType); 7281 assert(R < LastPromotedArithmeticType); 7282 int Idx = ConversionsTable[L][R]; 7283 7284 // Fast path: the table gives us a concrete answer. 7285 if (Idx != Dep) return getArithmeticType(Idx); 7286 7287 // Slow path: we need to compare widths. 7288 // An invariant is that the signed type has higher rank. 7289 CanQualType LT = getArithmeticType(L), 7290 RT = getArithmeticType(R); 7291 unsigned LW = S.Context.getIntWidth(LT), 7292 RW = S.Context.getIntWidth(RT); 7293 7294 // If they're different widths, use the signed type. 7295 if (LW > RW) return LT; 7296 else if (LW < RW) return RT; 7297 7298 // Otherwise, use the unsigned type of the signed type's rank. 7299 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7300 assert(L == SLL || R == SLL); 7301 return S.Context.UnsignedLongLongTy; 7302 } 7303 7304 /// \brief Helper method to factor out the common pattern of adding overloads 7305 /// for '++' and '--' builtin operators. 7306 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7307 bool HasVolatile, 7308 bool HasRestrict) { 7309 QualType ParamTypes[2] = { 7310 S.Context.getLValueReferenceType(CandidateTy), 7311 S.Context.IntTy 7312 }; 7313 7314 // Non-volatile version. 7315 if (Args.size() == 1) 7316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7317 else 7318 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7319 7320 // Use a heuristic to reduce number of builtin candidates in the set: 7321 // add volatile version only if there are conversions to a volatile type. 7322 if (HasVolatile) { 7323 ParamTypes[0] = 7324 S.Context.getLValueReferenceType( 7325 S.Context.getVolatileType(CandidateTy)); 7326 if (Args.size() == 1) 7327 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7328 else 7329 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7330 } 7331 7332 // Add restrict version only if there are conversions to a restrict type 7333 // and our candidate type is a non-restrict-qualified pointer. 7334 if (HasRestrict && CandidateTy->isAnyPointerType() && 7335 !CandidateTy.isRestrictQualified()) { 7336 ParamTypes[0] 7337 = S.Context.getLValueReferenceType( 7338 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7339 if (Args.size() == 1) 7340 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7341 else 7342 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7343 7344 if (HasVolatile) { 7345 ParamTypes[0] 7346 = S.Context.getLValueReferenceType( 7347 S.Context.getCVRQualifiedType(CandidateTy, 7348 (Qualifiers::Volatile | 7349 Qualifiers::Restrict))); 7350 if (Args.size() == 1) 7351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7352 else 7353 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7354 } 7355 } 7356 7357 } 7358 7359 public: 7360 BuiltinOperatorOverloadBuilder( 7361 Sema &S, ArrayRef<Expr *> Args, 7362 Qualifiers VisibleTypeConversionsQuals, 7363 bool HasArithmeticOrEnumeralCandidateType, 7364 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7365 OverloadCandidateSet &CandidateSet) 7366 : S(S), Args(Args), 7367 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7368 HasArithmeticOrEnumeralCandidateType( 7369 HasArithmeticOrEnumeralCandidateType), 7370 CandidateTypes(CandidateTypes), 7371 CandidateSet(CandidateSet) { 7372 // Validate some of our static helper constants in debug builds. 7373 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7374 "Invalid first promoted integral type"); 7375 assert(getArithmeticType(LastPromotedIntegralType - 1) 7376 == S.Context.UnsignedInt128Ty && 7377 "Invalid last promoted integral type"); 7378 assert(getArithmeticType(FirstPromotedArithmeticType) 7379 == S.Context.FloatTy && 7380 "Invalid first promoted arithmetic type"); 7381 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7382 == S.Context.UnsignedInt128Ty && 7383 "Invalid last promoted arithmetic type"); 7384 } 7385 7386 // C++ [over.built]p3: 7387 // 7388 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7389 // is either volatile or empty, there exist candidate operator 7390 // functions of the form 7391 // 7392 // VQ T& operator++(VQ T&); 7393 // T operator++(VQ T&, int); 7394 // 7395 // C++ [over.built]p4: 7396 // 7397 // For every pair (T, VQ), where T is an arithmetic type other 7398 // than bool, and VQ is either volatile or empty, there exist 7399 // candidate operator functions of the form 7400 // 7401 // VQ T& operator--(VQ T&); 7402 // T operator--(VQ T&, int); 7403 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7404 if (!HasArithmeticOrEnumeralCandidateType) 7405 return; 7406 7407 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7408 Arith < NumArithmeticTypes; ++Arith) { 7409 addPlusPlusMinusMinusStyleOverloads( 7410 getArithmeticType(Arith), 7411 VisibleTypeConversionsQuals.hasVolatile(), 7412 VisibleTypeConversionsQuals.hasRestrict()); 7413 } 7414 } 7415 7416 // C++ [over.built]p5: 7417 // 7418 // For every pair (T, VQ), where T is a cv-qualified or 7419 // cv-unqualified object type, and VQ is either volatile or 7420 // empty, there exist candidate operator functions of the form 7421 // 7422 // T*VQ& operator++(T*VQ&); 7423 // T*VQ& operator--(T*VQ&); 7424 // T* operator++(T*VQ&, int); 7425 // T* operator--(T*VQ&, int); 7426 void addPlusPlusMinusMinusPointerOverloads() { 7427 for (BuiltinCandidateTypeSet::iterator 7428 Ptr = CandidateTypes[0].pointer_begin(), 7429 PtrEnd = CandidateTypes[0].pointer_end(); 7430 Ptr != PtrEnd; ++Ptr) { 7431 // Skip pointer types that aren't pointers to object types. 7432 if (!(*Ptr)->getPointeeType()->isObjectType()) 7433 continue; 7434 7435 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7436 (!(*Ptr).isVolatileQualified() && 7437 VisibleTypeConversionsQuals.hasVolatile()), 7438 (!(*Ptr).isRestrictQualified() && 7439 VisibleTypeConversionsQuals.hasRestrict())); 7440 } 7441 } 7442 7443 // C++ [over.built]p6: 7444 // For every cv-qualified or cv-unqualified object type T, there 7445 // exist candidate operator functions of the form 7446 // 7447 // T& operator*(T*); 7448 // 7449 // C++ [over.built]p7: 7450 // For every function type T that does not have cv-qualifiers or a 7451 // ref-qualifier, there exist candidate operator functions of the form 7452 // T& operator*(T*); 7453 void addUnaryStarPointerOverloads() { 7454 for (BuiltinCandidateTypeSet::iterator 7455 Ptr = CandidateTypes[0].pointer_begin(), 7456 PtrEnd = CandidateTypes[0].pointer_end(); 7457 Ptr != PtrEnd; ++Ptr) { 7458 QualType ParamTy = *Ptr; 7459 QualType PointeeTy = ParamTy->getPointeeType(); 7460 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7461 continue; 7462 7463 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7464 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7465 continue; 7466 7467 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7468 &ParamTy, Args, CandidateSet); 7469 } 7470 } 7471 7472 // C++ [over.built]p9: 7473 // For every promoted arithmetic type T, there exist candidate 7474 // operator functions of the form 7475 // 7476 // T operator+(T); 7477 // T operator-(T); 7478 void addUnaryPlusOrMinusArithmeticOverloads() { 7479 if (!HasArithmeticOrEnumeralCandidateType) 7480 return; 7481 7482 for (unsigned Arith = FirstPromotedArithmeticType; 7483 Arith < LastPromotedArithmeticType; ++Arith) { 7484 QualType ArithTy = getArithmeticType(Arith); 7485 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7486 } 7487 7488 // Extension: We also add these operators for vector types. 7489 for (BuiltinCandidateTypeSet::iterator 7490 Vec = CandidateTypes[0].vector_begin(), 7491 VecEnd = CandidateTypes[0].vector_end(); 7492 Vec != VecEnd; ++Vec) { 7493 QualType VecTy = *Vec; 7494 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7495 } 7496 } 7497 7498 // C++ [over.built]p8: 7499 // For every type T, there exist candidate operator functions of 7500 // the form 7501 // 7502 // T* operator+(T*); 7503 void addUnaryPlusPointerOverloads() { 7504 for (BuiltinCandidateTypeSet::iterator 7505 Ptr = CandidateTypes[0].pointer_begin(), 7506 PtrEnd = CandidateTypes[0].pointer_end(); 7507 Ptr != PtrEnd; ++Ptr) { 7508 QualType ParamTy = *Ptr; 7509 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7510 } 7511 } 7512 7513 // C++ [over.built]p10: 7514 // For every promoted integral type T, there exist candidate 7515 // operator functions of the form 7516 // 7517 // T operator~(T); 7518 void addUnaryTildePromotedIntegralOverloads() { 7519 if (!HasArithmeticOrEnumeralCandidateType) 7520 return; 7521 7522 for (unsigned Int = FirstPromotedIntegralType; 7523 Int < LastPromotedIntegralType; ++Int) { 7524 QualType IntTy = getArithmeticType(Int); 7525 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7526 } 7527 7528 // Extension: We also add this operator for vector types. 7529 for (BuiltinCandidateTypeSet::iterator 7530 Vec = CandidateTypes[0].vector_begin(), 7531 VecEnd = CandidateTypes[0].vector_end(); 7532 Vec != VecEnd; ++Vec) { 7533 QualType VecTy = *Vec; 7534 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7535 } 7536 } 7537 7538 // C++ [over.match.oper]p16: 7539 // For every pointer to member type T, there exist candidate operator 7540 // functions of the form 7541 // 7542 // bool operator==(T,T); 7543 // bool operator!=(T,T); 7544 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7545 /// Set of (canonical) types that we've already handled. 7546 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7547 7548 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7549 for (BuiltinCandidateTypeSet::iterator 7550 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7551 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7552 MemPtr != MemPtrEnd; 7553 ++MemPtr) { 7554 // Don't add the same builtin candidate twice. 7555 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7556 continue; 7557 7558 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7559 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7560 } 7561 } 7562 } 7563 7564 // C++ [over.built]p15: 7565 // 7566 // For every T, where T is an enumeration type, a pointer type, or 7567 // std::nullptr_t, there exist candidate operator functions of the form 7568 // 7569 // bool operator<(T, T); 7570 // bool operator>(T, T); 7571 // bool operator<=(T, T); 7572 // bool operator>=(T, T); 7573 // bool operator==(T, T); 7574 // bool operator!=(T, T); 7575 void addRelationalPointerOrEnumeralOverloads() { 7576 // C++ [over.match.oper]p3: 7577 // [...]the built-in candidates include all of the candidate operator 7578 // functions defined in 13.6 that, compared to the given operator, [...] 7579 // do not have the same parameter-type-list as any non-template non-member 7580 // candidate. 7581 // 7582 // Note that in practice, this only affects enumeration types because there 7583 // aren't any built-in candidates of record type, and a user-defined operator 7584 // must have an operand of record or enumeration type. Also, the only other 7585 // overloaded operator with enumeration arguments, operator=, 7586 // cannot be overloaded for enumeration types, so this is the only place 7587 // where we must suppress candidates like this. 7588 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7589 UserDefinedBinaryOperators; 7590 7591 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7592 if (CandidateTypes[ArgIdx].enumeration_begin() != 7593 CandidateTypes[ArgIdx].enumeration_end()) { 7594 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7595 CEnd = CandidateSet.end(); 7596 C != CEnd; ++C) { 7597 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7598 continue; 7599 7600 if (C->Function->isFunctionTemplateSpecialization()) 7601 continue; 7602 7603 QualType FirstParamType = 7604 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7605 QualType SecondParamType = 7606 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7607 7608 // Skip if either parameter isn't of enumeral type. 7609 if (!FirstParamType->isEnumeralType() || 7610 !SecondParamType->isEnumeralType()) 7611 continue; 7612 7613 // Add this operator to the set of known user-defined operators. 7614 UserDefinedBinaryOperators.insert( 7615 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7616 S.Context.getCanonicalType(SecondParamType))); 7617 } 7618 } 7619 } 7620 7621 /// Set of (canonical) types that we've already handled. 7622 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7623 7624 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7625 for (BuiltinCandidateTypeSet::iterator 7626 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7627 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7628 Ptr != PtrEnd; ++Ptr) { 7629 // Don't add the same builtin candidate twice. 7630 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7631 continue; 7632 7633 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7634 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7635 } 7636 for (BuiltinCandidateTypeSet::iterator 7637 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7638 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7639 Enum != EnumEnd; ++Enum) { 7640 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7641 7642 // Don't add the same builtin candidate twice, or if a user defined 7643 // candidate exists. 7644 if (!AddedTypes.insert(CanonType).second || 7645 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7646 CanonType))) 7647 continue; 7648 7649 QualType ParamTypes[2] = { *Enum, *Enum }; 7650 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7651 } 7652 7653 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7654 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7655 if (AddedTypes.insert(NullPtrTy).second && 7656 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7657 NullPtrTy))) { 7658 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7659 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7660 CandidateSet); 7661 } 7662 } 7663 } 7664 } 7665 7666 // C++ [over.built]p13: 7667 // 7668 // For every cv-qualified or cv-unqualified object type T 7669 // there exist candidate operator functions of the form 7670 // 7671 // T* operator+(T*, ptrdiff_t); 7672 // T& operator[](T*, ptrdiff_t); [BELOW] 7673 // T* operator-(T*, ptrdiff_t); 7674 // T* operator+(ptrdiff_t, T*); 7675 // T& operator[](ptrdiff_t, T*); [BELOW] 7676 // 7677 // C++ [over.built]p14: 7678 // 7679 // For every T, where T is a pointer to object type, there 7680 // exist candidate operator functions of the form 7681 // 7682 // ptrdiff_t operator-(T, T); 7683 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7684 /// Set of (canonical) types that we've already handled. 7685 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7686 7687 for (int Arg = 0; Arg < 2; ++Arg) { 7688 QualType AsymmetricParamTypes[2] = { 7689 S.Context.getPointerDiffType(), 7690 S.Context.getPointerDiffType(), 7691 }; 7692 for (BuiltinCandidateTypeSet::iterator 7693 Ptr = CandidateTypes[Arg].pointer_begin(), 7694 PtrEnd = CandidateTypes[Arg].pointer_end(); 7695 Ptr != PtrEnd; ++Ptr) { 7696 QualType PointeeTy = (*Ptr)->getPointeeType(); 7697 if (!PointeeTy->isObjectType()) 7698 continue; 7699 7700 AsymmetricParamTypes[Arg] = *Ptr; 7701 if (Arg == 0 || Op == OO_Plus) { 7702 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7703 // T* operator+(ptrdiff_t, T*); 7704 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7705 } 7706 if (Op == OO_Minus) { 7707 // ptrdiff_t operator-(T, T); 7708 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7709 continue; 7710 7711 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7712 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7713 Args, CandidateSet); 7714 } 7715 } 7716 } 7717 } 7718 7719 // C++ [over.built]p12: 7720 // 7721 // For every pair of promoted arithmetic types L and R, there 7722 // exist candidate operator functions of the form 7723 // 7724 // LR operator*(L, R); 7725 // LR operator/(L, R); 7726 // LR operator+(L, R); 7727 // LR operator-(L, R); 7728 // bool operator<(L, R); 7729 // bool operator>(L, R); 7730 // bool operator<=(L, R); 7731 // bool operator>=(L, R); 7732 // bool operator==(L, R); 7733 // bool operator!=(L, R); 7734 // 7735 // where LR is the result of the usual arithmetic conversions 7736 // between types L and R. 7737 // 7738 // C++ [over.built]p24: 7739 // 7740 // For every pair of promoted arithmetic types L and R, there exist 7741 // candidate operator functions of the form 7742 // 7743 // LR operator?(bool, L, R); 7744 // 7745 // where LR is the result of the usual arithmetic conversions 7746 // between types L and R. 7747 // Our candidates ignore the first parameter. 7748 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7749 if (!HasArithmeticOrEnumeralCandidateType) 7750 return; 7751 7752 for (unsigned Left = FirstPromotedArithmeticType; 7753 Left < LastPromotedArithmeticType; ++Left) { 7754 for (unsigned Right = FirstPromotedArithmeticType; 7755 Right < LastPromotedArithmeticType; ++Right) { 7756 QualType LandR[2] = { getArithmeticType(Left), 7757 getArithmeticType(Right) }; 7758 QualType Result = 7759 isComparison ? S.Context.BoolTy 7760 : getUsualArithmeticConversions(Left, Right); 7761 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7762 } 7763 } 7764 7765 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7766 // conditional operator for vector types. 7767 for (BuiltinCandidateTypeSet::iterator 7768 Vec1 = CandidateTypes[0].vector_begin(), 7769 Vec1End = CandidateTypes[0].vector_end(); 7770 Vec1 != Vec1End; ++Vec1) { 7771 for (BuiltinCandidateTypeSet::iterator 7772 Vec2 = CandidateTypes[1].vector_begin(), 7773 Vec2End = CandidateTypes[1].vector_end(); 7774 Vec2 != Vec2End; ++Vec2) { 7775 QualType LandR[2] = { *Vec1, *Vec2 }; 7776 QualType Result = S.Context.BoolTy; 7777 if (!isComparison) { 7778 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7779 Result = *Vec1; 7780 else 7781 Result = *Vec2; 7782 } 7783 7784 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7785 } 7786 } 7787 } 7788 7789 // C++ [over.built]p17: 7790 // 7791 // For every pair of promoted integral types L and R, there 7792 // exist candidate operator functions of the form 7793 // 7794 // LR operator%(L, R); 7795 // LR operator&(L, R); 7796 // LR operator^(L, R); 7797 // LR operator|(L, R); 7798 // L operator<<(L, R); 7799 // L operator>>(L, R); 7800 // 7801 // where LR is the result of the usual arithmetic conversions 7802 // between types L and R. 7803 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7804 if (!HasArithmeticOrEnumeralCandidateType) 7805 return; 7806 7807 for (unsigned Left = FirstPromotedIntegralType; 7808 Left < LastPromotedIntegralType; ++Left) { 7809 for (unsigned Right = FirstPromotedIntegralType; 7810 Right < LastPromotedIntegralType; ++Right) { 7811 QualType LandR[2] = { getArithmeticType(Left), 7812 getArithmeticType(Right) }; 7813 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7814 ? LandR[0] 7815 : getUsualArithmeticConversions(Left, Right); 7816 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7817 } 7818 } 7819 } 7820 7821 // C++ [over.built]p20: 7822 // 7823 // For every pair (T, VQ), where T is an enumeration or 7824 // pointer to member type and VQ is either volatile or 7825 // empty, there exist candidate operator functions of the form 7826 // 7827 // VQ T& operator=(VQ T&, T); 7828 void addAssignmentMemberPointerOrEnumeralOverloads() { 7829 /// Set of (canonical) types that we've already handled. 7830 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7831 7832 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7833 for (BuiltinCandidateTypeSet::iterator 7834 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7835 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7836 Enum != EnumEnd; ++Enum) { 7837 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7838 continue; 7839 7840 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7841 } 7842 7843 for (BuiltinCandidateTypeSet::iterator 7844 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7845 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7846 MemPtr != MemPtrEnd; ++MemPtr) { 7847 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7848 continue; 7849 7850 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7851 } 7852 } 7853 } 7854 7855 // C++ [over.built]p19: 7856 // 7857 // For every pair (T, VQ), where T is any type and VQ is either 7858 // volatile or empty, there exist candidate operator functions 7859 // of the form 7860 // 7861 // T*VQ& operator=(T*VQ&, T*); 7862 // 7863 // C++ [over.built]p21: 7864 // 7865 // For every pair (T, VQ), where T is a cv-qualified or 7866 // cv-unqualified object type and VQ is either volatile or 7867 // empty, there exist candidate operator functions of the form 7868 // 7869 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7870 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7871 void addAssignmentPointerOverloads(bool isEqualOp) { 7872 /// Set of (canonical) types that we've already handled. 7873 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7874 7875 for (BuiltinCandidateTypeSet::iterator 7876 Ptr = CandidateTypes[0].pointer_begin(), 7877 PtrEnd = CandidateTypes[0].pointer_end(); 7878 Ptr != PtrEnd; ++Ptr) { 7879 // If this is operator=, keep track of the builtin candidates we added. 7880 if (isEqualOp) 7881 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7882 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7883 continue; 7884 7885 // non-volatile version 7886 QualType ParamTypes[2] = { 7887 S.Context.getLValueReferenceType(*Ptr), 7888 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7889 }; 7890 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7891 /*IsAssigmentOperator=*/ isEqualOp); 7892 7893 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7894 VisibleTypeConversionsQuals.hasVolatile(); 7895 if (NeedVolatile) { 7896 // volatile version 7897 ParamTypes[0] = 7898 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7900 /*IsAssigmentOperator=*/isEqualOp); 7901 } 7902 7903 if (!(*Ptr).isRestrictQualified() && 7904 VisibleTypeConversionsQuals.hasRestrict()) { 7905 // restrict version 7906 ParamTypes[0] 7907 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7909 /*IsAssigmentOperator=*/isEqualOp); 7910 7911 if (NeedVolatile) { 7912 // volatile restrict version 7913 ParamTypes[0] 7914 = S.Context.getLValueReferenceType( 7915 S.Context.getCVRQualifiedType(*Ptr, 7916 (Qualifiers::Volatile | 7917 Qualifiers::Restrict))); 7918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7919 /*IsAssigmentOperator=*/isEqualOp); 7920 } 7921 } 7922 } 7923 7924 if (isEqualOp) { 7925 for (BuiltinCandidateTypeSet::iterator 7926 Ptr = CandidateTypes[1].pointer_begin(), 7927 PtrEnd = CandidateTypes[1].pointer_end(); 7928 Ptr != PtrEnd; ++Ptr) { 7929 // Make sure we don't add the same candidate twice. 7930 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7931 continue; 7932 7933 QualType ParamTypes[2] = { 7934 S.Context.getLValueReferenceType(*Ptr), 7935 *Ptr, 7936 }; 7937 7938 // non-volatile version 7939 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7940 /*IsAssigmentOperator=*/true); 7941 7942 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7943 VisibleTypeConversionsQuals.hasVolatile(); 7944 if (NeedVolatile) { 7945 // volatile version 7946 ParamTypes[0] = 7947 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7949 /*IsAssigmentOperator=*/true); 7950 } 7951 7952 if (!(*Ptr).isRestrictQualified() && 7953 VisibleTypeConversionsQuals.hasRestrict()) { 7954 // restrict version 7955 ParamTypes[0] 7956 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7957 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7958 /*IsAssigmentOperator=*/true); 7959 7960 if (NeedVolatile) { 7961 // volatile restrict version 7962 ParamTypes[0] 7963 = S.Context.getLValueReferenceType( 7964 S.Context.getCVRQualifiedType(*Ptr, 7965 (Qualifiers::Volatile | 7966 Qualifiers::Restrict))); 7967 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7968 /*IsAssigmentOperator=*/true); 7969 } 7970 } 7971 } 7972 } 7973 } 7974 7975 // C++ [over.built]p18: 7976 // 7977 // For every triple (L, VQ, R), where L is an arithmetic type, 7978 // VQ is either volatile or empty, and R is a promoted 7979 // arithmetic type, there exist candidate operator functions of 7980 // the form 7981 // 7982 // VQ L& operator=(VQ L&, R); 7983 // VQ L& operator*=(VQ L&, R); 7984 // VQ L& operator/=(VQ L&, R); 7985 // VQ L& operator+=(VQ L&, R); 7986 // VQ L& operator-=(VQ L&, R); 7987 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7988 if (!HasArithmeticOrEnumeralCandidateType) 7989 return; 7990 7991 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7992 for (unsigned Right = FirstPromotedArithmeticType; 7993 Right < LastPromotedArithmeticType; ++Right) { 7994 QualType ParamTypes[2]; 7995 ParamTypes[1] = getArithmeticType(Right); 7996 7997 // Add this built-in operator as a candidate (VQ is empty). 7998 ParamTypes[0] = 7999 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8001 /*IsAssigmentOperator=*/isEqualOp); 8002 8003 // Add this built-in operator as a candidate (VQ is 'volatile'). 8004 if (VisibleTypeConversionsQuals.hasVolatile()) { 8005 ParamTypes[0] = 8006 S.Context.getVolatileType(getArithmeticType(Left)); 8007 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8009 /*IsAssigmentOperator=*/isEqualOp); 8010 } 8011 } 8012 } 8013 8014 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8015 for (BuiltinCandidateTypeSet::iterator 8016 Vec1 = CandidateTypes[0].vector_begin(), 8017 Vec1End = CandidateTypes[0].vector_end(); 8018 Vec1 != Vec1End; ++Vec1) { 8019 for (BuiltinCandidateTypeSet::iterator 8020 Vec2 = CandidateTypes[1].vector_begin(), 8021 Vec2End = CandidateTypes[1].vector_end(); 8022 Vec2 != Vec2End; ++Vec2) { 8023 QualType ParamTypes[2]; 8024 ParamTypes[1] = *Vec2; 8025 // Add this built-in operator as a candidate (VQ is empty). 8026 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8027 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8028 /*IsAssigmentOperator=*/isEqualOp); 8029 8030 // Add this built-in operator as a candidate (VQ is 'volatile'). 8031 if (VisibleTypeConversionsQuals.hasVolatile()) { 8032 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8033 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8035 /*IsAssigmentOperator=*/isEqualOp); 8036 } 8037 } 8038 } 8039 } 8040 8041 // C++ [over.built]p22: 8042 // 8043 // For every triple (L, VQ, R), where L is an integral type, VQ 8044 // is either volatile or empty, and R is a promoted integral 8045 // type, there exist candidate operator functions of the form 8046 // 8047 // VQ L& operator%=(VQ L&, R); 8048 // VQ L& operator<<=(VQ L&, R); 8049 // VQ L& operator>>=(VQ L&, R); 8050 // VQ L& operator&=(VQ L&, R); 8051 // VQ L& operator^=(VQ L&, R); 8052 // VQ L& operator|=(VQ L&, R); 8053 void addAssignmentIntegralOverloads() { 8054 if (!HasArithmeticOrEnumeralCandidateType) 8055 return; 8056 8057 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8058 for (unsigned Right = FirstPromotedIntegralType; 8059 Right < LastPromotedIntegralType; ++Right) { 8060 QualType ParamTypes[2]; 8061 ParamTypes[1] = getArithmeticType(Right); 8062 8063 // Add this built-in operator as a candidate (VQ is empty). 8064 ParamTypes[0] = 8065 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8067 if (VisibleTypeConversionsQuals.hasVolatile()) { 8068 // Add this built-in operator as a candidate (VQ is 'volatile'). 8069 ParamTypes[0] = getArithmeticType(Left); 8070 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8071 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8072 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8073 } 8074 } 8075 } 8076 } 8077 8078 // C++ [over.operator]p23: 8079 // 8080 // There also exist candidate operator functions of the form 8081 // 8082 // bool operator!(bool); 8083 // bool operator&&(bool, bool); 8084 // bool operator||(bool, bool); 8085 void addExclaimOverload() { 8086 QualType ParamTy = S.Context.BoolTy; 8087 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8088 /*IsAssignmentOperator=*/false, 8089 /*NumContextualBoolArguments=*/1); 8090 } 8091 void addAmpAmpOrPipePipeOverload() { 8092 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8093 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8094 /*IsAssignmentOperator=*/false, 8095 /*NumContextualBoolArguments=*/2); 8096 } 8097 8098 // C++ [over.built]p13: 8099 // 8100 // For every cv-qualified or cv-unqualified object type T there 8101 // exist candidate operator functions of the form 8102 // 8103 // T* operator+(T*, ptrdiff_t); [ABOVE] 8104 // T& operator[](T*, ptrdiff_t); 8105 // T* operator-(T*, ptrdiff_t); [ABOVE] 8106 // T* operator+(ptrdiff_t, T*); [ABOVE] 8107 // T& operator[](ptrdiff_t, T*); 8108 void addSubscriptOverloads() { 8109 for (BuiltinCandidateTypeSet::iterator 8110 Ptr = CandidateTypes[0].pointer_begin(), 8111 PtrEnd = CandidateTypes[0].pointer_end(); 8112 Ptr != PtrEnd; ++Ptr) { 8113 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8114 QualType PointeeType = (*Ptr)->getPointeeType(); 8115 if (!PointeeType->isObjectType()) 8116 continue; 8117 8118 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8119 8120 // T& operator[](T*, ptrdiff_t) 8121 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8122 } 8123 8124 for (BuiltinCandidateTypeSet::iterator 8125 Ptr = CandidateTypes[1].pointer_begin(), 8126 PtrEnd = CandidateTypes[1].pointer_end(); 8127 Ptr != PtrEnd; ++Ptr) { 8128 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8129 QualType PointeeType = (*Ptr)->getPointeeType(); 8130 if (!PointeeType->isObjectType()) 8131 continue; 8132 8133 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8134 8135 // T& operator[](ptrdiff_t, T*) 8136 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8137 } 8138 } 8139 8140 // C++ [over.built]p11: 8141 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8142 // C1 is the same type as C2 or is a derived class of C2, T is an object 8143 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8144 // there exist candidate operator functions of the form 8145 // 8146 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8147 // 8148 // where CV12 is the union of CV1 and CV2. 8149 void addArrowStarOverloads() { 8150 for (BuiltinCandidateTypeSet::iterator 8151 Ptr = CandidateTypes[0].pointer_begin(), 8152 PtrEnd = CandidateTypes[0].pointer_end(); 8153 Ptr != PtrEnd; ++Ptr) { 8154 QualType C1Ty = (*Ptr); 8155 QualType C1; 8156 QualifierCollector Q1; 8157 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8158 if (!isa<RecordType>(C1)) 8159 continue; 8160 // heuristic to reduce number of builtin candidates in the set. 8161 // Add volatile/restrict version only if there are conversions to a 8162 // volatile/restrict type. 8163 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8164 continue; 8165 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8166 continue; 8167 for (BuiltinCandidateTypeSet::iterator 8168 MemPtr = CandidateTypes[1].member_pointer_begin(), 8169 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8170 MemPtr != MemPtrEnd; ++MemPtr) { 8171 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8172 QualType C2 = QualType(mptr->getClass(), 0); 8173 C2 = C2.getUnqualifiedType(); 8174 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8175 break; 8176 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8177 // build CV12 T& 8178 QualType T = mptr->getPointeeType(); 8179 if (!VisibleTypeConversionsQuals.hasVolatile() && 8180 T.isVolatileQualified()) 8181 continue; 8182 if (!VisibleTypeConversionsQuals.hasRestrict() && 8183 T.isRestrictQualified()) 8184 continue; 8185 T = Q1.apply(S.Context, T); 8186 QualType ResultTy = S.Context.getLValueReferenceType(T); 8187 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8188 } 8189 } 8190 } 8191 8192 // Note that we don't consider the first argument, since it has been 8193 // contextually converted to bool long ago. The candidates below are 8194 // therefore added as binary. 8195 // 8196 // C++ [over.built]p25: 8197 // For every type T, where T is a pointer, pointer-to-member, or scoped 8198 // enumeration type, there exist candidate operator functions of the form 8199 // 8200 // T operator?(bool, T, T); 8201 // 8202 void addConditionalOperatorOverloads() { 8203 /// Set of (canonical) types that we've already handled. 8204 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8205 8206 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8207 for (BuiltinCandidateTypeSet::iterator 8208 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8209 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8210 Ptr != PtrEnd; ++Ptr) { 8211 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8212 continue; 8213 8214 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8215 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8216 } 8217 8218 for (BuiltinCandidateTypeSet::iterator 8219 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8220 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8221 MemPtr != MemPtrEnd; ++MemPtr) { 8222 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8223 continue; 8224 8225 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8226 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8227 } 8228 8229 if (S.getLangOpts().CPlusPlus11) { 8230 for (BuiltinCandidateTypeSet::iterator 8231 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8232 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8233 Enum != EnumEnd; ++Enum) { 8234 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8235 continue; 8236 8237 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8238 continue; 8239 8240 QualType ParamTypes[2] = { *Enum, *Enum }; 8241 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8242 } 8243 } 8244 } 8245 } 8246 }; 8247 8248 } // end anonymous namespace 8249 8250 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8251 /// operator overloads to the candidate set (C++ [over.built]), based 8252 /// on the operator @p Op and the arguments given. For example, if the 8253 /// operator is a binary '+', this routine might add "int 8254 /// operator+(int, int)" to cover integer addition. 8255 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8256 SourceLocation OpLoc, 8257 ArrayRef<Expr *> Args, 8258 OverloadCandidateSet &CandidateSet) { 8259 // Find all of the types that the arguments can convert to, but only 8260 // if the operator we're looking at has built-in operator candidates 8261 // that make use of these types. Also record whether we encounter non-record 8262 // candidate types or either arithmetic or enumeral candidate types. 8263 Qualifiers VisibleTypeConversionsQuals; 8264 VisibleTypeConversionsQuals.addConst(); 8265 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8266 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8267 8268 bool HasNonRecordCandidateType = false; 8269 bool HasArithmeticOrEnumeralCandidateType = false; 8270 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8271 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8272 CandidateTypes.emplace_back(*this); 8273 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8274 OpLoc, 8275 true, 8276 (Op == OO_Exclaim || 8277 Op == OO_AmpAmp || 8278 Op == OO_PipePipe), 8279 VisibleTypeConversionsQuals); 8280 HasNonRecordCandidateType = HasNonRecordCandidateType || 8281 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8282 HasArithmeticOrEnumeralCandidateType = 8283 HasArithmeticOrEnumeralCandidateType || 8284 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8285 } 8286 8287 // Exit early when no non-record types have been added to the candidate set 8288 // for any of the arguments to the operator. 8289 // 8290 // We can't exit early for !, ||, or &&, since there we have always have 8291 // 'bool' overloads. 8292 if (!HasNonRecordCandidateType && 8293 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8294 return; 8295 8296 // Setup an object to manage the common state for building overloads. 8297 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8298 VisibleTypeConversionsQuals, 8299 HasArithmeticOrEnumeralCandidateType, 8300 CandidateTypes, CandidateSet); 8301 8302 // Dispatch over the operation to add in only those overloads which apply. 8303 switch (Op) { 8304 case OO_None: 8305 case NUM_OVERLOADED_OPERATORS: 8306 llvm_unreachable("Expected an overloaded operator"); 8307 8308 case OO_New: 8309 case OO_Delete: 8310 case OO_Array_New: 8311 case OO_Array_Delete: 8312 case OO_Call: 8313 llvm_unreachable( 8314 "Special operators don't use AddBuiltinOperatorCandidates"); 8315 8316 case OO_Comma: 8317 case OO_Arrow: 8318 case OO_Coawait: 8319 // C++ [over.match.oper]p3: 8320 // -- For the operator ',', the unary operator '&', the 8321 // operator '->', or the operator 'co_await', the 8322 // built-in candidates set is empty. 8323 break; 8324 8325 case OO_Plus: // '+' is either unary or binary 8326 if (Args.size() == 1) 8327 OpBuilder.addUnaryPlusPointerOverloads(); 8328 // Fall through. 8329 8330 case OO_Minus: // '-' is either unary or binary 8331 if (Args.size() == 1) { 8332 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8333 } else { 8334 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8336 } 8337 break; 8338 8339 case OO_Star: // '*' is either unary or binary 8340 if (Args.size() == 1) 8341 OpBuilder.addUnaryStarPointerOverloads(); 8342 else 8343 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8344 break; 8345 8346 case OO_Slash: 8347 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8348 break; 8349 8350 case OO_PlusPlus: 8351 case OO_MinusMinus: 8352 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8353 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8354 break; 8355 8356 case OO_EqualEqual: 8357 case OO_ExclaimEqual: 8358 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8359 // Fall through. 8360 8361 case OO_Less: 8362 case OO_Greater: 8363 case OO_LessEqual: 8364 case OO_GreaterEqual: 8365 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8366 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8367 break; 8368 8369 case OO_Percent: 8370 case OO_Caret: 8371 case OO_Pipe: 8372 case OO_LessLess: 8373 case OO_GreaterGreater: 8374 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8375 break; 8376 8377 case OO_Amp: // '&' is either unary or binary 8378 if (Args.size() == 1) 8379 // C++ [over.match.oper]p3: 8380 // -- For the operator ',', the unary operator '&', or the 8381 // operator '->', the built-in candidates set is empty. 8382 break; 8383 8384 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8385 break; 8386 8387 case OO_Tilde: 8388 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8389 break; 8390 8391 case OO_Equal: 8392 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8393 // Fall through. 8394 8395 case OO_PlusEqual: 8396 case OO_MinusEqual: 8397 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8398 // Fall through. 8399 8400 case OO_StarEqual: 8401 case OO_SlashEqual: 8402 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8403 break; 8404 8405 case OO_PercentEqual: 8406 case OO_LessLessEqual: 8407 case OO_GreaterGreaterEqual: 8408 case OO_AmpEqual: 8409 case OO_CaretEqual: 8410 case OO_PipeEqual: 8411 OpBuilder.addAssignmentIntegralOverloads(); 8412 break; 8413 8414 case OO_Exclaim: 8415 OpBuilder.addExclaimOverload(); 8416 break; 8417 8418 case OO_AmpAmp: 8419 case OO_PipePipe: 8420 OpBuilder.addAmpAmpOrPipePipeOverload(); 8421 break; 8422 8423 case OO_Subscript: 8424 OpBuilder.addSubscriptOverloads(); 8425 break; 8426 8427 case OO_ArrowStar: 8428 OpBuilder.addArrowStarOverloads(); 8429 break; 8430 8431 case OO_Conditional: 8432 OpBuilder.addConditionalOperatorOverloads(); 8433 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8434 break; 8435 } 8436 } 8437 8438 /// \brief Add function candidates found via argument-dependent lookup 8439 /// to the set of overloading candidates. 8440 /// 8441 /// This routine performs argument-dependent name lookup based on the 8442 /// given function name (which may also be an operator name) and adds 8443 /// all of the overload candidates found by ADL to the overload 8444 /// candidate set (C++ [basic.lookup.argdep]). 8445 void 8446 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8447 SourceLocation Loc, 8448 ArrayRef<Expr *> Args, 8449 TemplateArgumentListInfo *ExplicitTemplateArgs, 8450 OverloadCandidateSet& CandidateSet, 8451 bool PartialOverloading) { 8452 ADLResult Fns; 8453 8454 // FIXME: This approach for uniquing ADL results (and removing 8455 // redundant candidates from the set) relies on pointer-equality, 8456 // which means we need to key off the canonical decl. However, 8457 // always going back to the canonical decl might not get us the 8458 // right set of default arguments. What default arguments are 8459 // we supposed to consider on ADL candidates, anyway? 8460 8461 // FIXME: Pass in the explicit template arguments? 8462 ArgumentDependentLookup(Name, Loc, Args, Fns); 8463 8464 // Erase all of the candidates we already knew about. 8465 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8466 CandEnd = CandidateSet.end(); 8467 Cand != CandEnd; ++Cand) 8468 if (Cand->Function) { 8469 Fns.erase(Cand->Function); 8470 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8471 Fns.erase(FunTmpl); 8472 } 8473 8474 // For each of the ADL candidates we found, add it to the overload 8475 // set. 8476 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8477 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8478 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8479 if (ExplicitTemplateArgs) 8480 continue; 8481 8482 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8483 PartialOverloading); 8484 } else 8485 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8486 FoundDecl, ExplicitTemplateArgs, 8487 Args, CandidateSet, PartialOverloading); 8488 } 8489 } 8490 8491 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8492 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8493 // on Cand1 and Cand2 have conditions that evaluate to true. 8494 // 8495 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8496 // Cand1's first N enable_if attributes have precisely the same conditions as 8497 // Cand2's first N enable_if attributes (where N = the number of enable_if 8498 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8499 static bool hasBetterEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8500 const FunctionDecl *Cand2) { 8501 8502 // FIXME: The next several lines are just 8503 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8504 // instead of reverse order which is how they're stored in the AST. 8505 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8506 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8507 8508 // Candidate 1 is better if it has strictly more attributes and 8509 // the common sequence is identical. 8510 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8511 return false; 8512 8513 auto Cand1I = Cand1Attrs.begin(); 8514 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8515 for (auto &Cand2A : Cand2Attrs) { 8516 Cand1ID.clear(); 8517 Cand2ID.clear(); 8518 8519 auto &Cand1A = *Cand1I++; 8520 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8521 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8522 if (Cand1ID != Cand2ID) 8523 return false; 8524 } 8525 8526 return true; 8527 } 8528 8529 /// isBetterOverloadCandidate - Determines whether the first overload 8530 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8531 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8532 const OverloadCandidate &Cand2, 8533 SourceLocation Loc, 8534 bool UserDefinedConversion) { 8535 // Define viable functions to be better candidates than non-viable 8536 // functions. 8537 if (!Cand2.Viable) 8538 return Cand1.Viable; 8539 else if (!Cand1.Viable) 8540 return false; 8541 8542 // C++ [over.match.best]p1: 8543 // 8544 // -- if F is a static member function, ICS1(F) is defined such 8545 // that ICS1(F) is neither better nor worse than ICS1(G) for 8546 // any function G, and, symmetrically, ICS1(G) is neither 8547 // better nor worse than ICS1(F). 8548 unsigned StartArg = 0; 8549 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8550 StartArg = 1; 8551 8552 // C++ [over.match.best]p1: 8553 // A viable function F1 is defined to be a better function than another 8554 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8555 // conversion sequence than ICSi(F2), and then... 8556 unsigned NumArgs = Cand1.NumConversions; 8557 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8558 bool HasBetterConversion = false; 8559 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8560 switch (CompareImplicitConversionSequences(S, Loc, 8561 Cand1.Conversions[ArgIdx], 8562 Cand2.Conversions[ArgIdx])) { 8563 case ImplicitConversionSequence::Better: 8564 // Cand1 has a better conversion sequence. 8565 HasBetterConversion = true; 8566 break; 8567 8568 case ImplicitConversionSequence::Worse: 8569 // Cand1 can't be better than Cand2. 8570 return false; 8571 8572 case ImplicitConversionSequence::Indistinguishable: 8573 // Do nothing. 8574 break; 8575 } 8576 } 8577 8578 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8579 // ICSj(F2), or, if not that, 8580 if (HasBetterConversion) 8581 return true; 8582 8583 // -- the context is an initialization by user-defined conversion 8584 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8585 // from the return type of F1 to the destination type (i.e., 8586 // the type of the entity being initialized) is a better 8587 // conversion sequence than the standard conversion sequence 8588 // from the return type of F2 to the destination type. 8589 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8590 isa<CXXConversionDecl>(Cand1.Function) && 8591 isa<CXXConversionDecl>(Cand2.Function)) { 8592 // First check whether we prefer one of the conversion functions over the 8593 // other. This only distinguishes the results in non-standard, extension 8594 // cases such as the conversion from a lambda closure type to a function 8595 // pointer or block. 8596 ImplicitConversionSequence::CompareKind Result = 8597 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8598 if (Result == ImplicitConversionSequence::Indistinguishable) 8599 Result = CompareStandardConversionSequences(S, Loc, 8600 Cand1.FinalConversion, 8601 Cand2.FinalConversion); 8602 8603 if (Result != ImplicitConversionSequence::Indistinguishable) 8604 return Result == ImplicitConversionSequence::Better; 8605 8606 // FIXME: Compare kind of reference binding if conversion functions 8607 // convert to a reference type used in direct reference binding, per 8608 // C++14 [over.match.best]p1 section 2 bullet 3. 8609 } 8610 8611 // -- F1 is a non-template function and F2 is a function template 8612 // specialization, or, if not that, 8613 bool Cand1IsSpecialization = Cand1.Function && 8614 Cand1.Function->getPrimaryTemplate(); 8615 bool Cand2IsSpecialization = Cand2.Function && 8616 Cand2.Function->getPrimaryTemplate(); 8617 if (Cand1IsSpecialization != Cand2IsSpecialization) 8618 return Cand2IsSpecialization; 8619 8620 // -- F1 and F2 are function template specializations, and the function 8621 // template for F1 is more specialized than the template for F2 8622 // according to the partial ordering rules described in 14.5.5.2, or, 8623 // if not that, 8624 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8625 if (FunctionTemplateDecl *BetterTemplate 8626 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8627 Cand2.Function->getPrimaryTemplate(), 8628 Loc, 8629 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8630 : TPOC_Call, 8631 Cand1.ExplicitCallArguments, 8632 Cand2.ExplicitCallArguments)) 8633 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8634 } 8635 8636 // Check for enable_if value-based overload resolution. 8637 if (Cand1.Function && Cand2.Function && 8638 (Cand1.Function->hasAttr<EnableIfAttr>() || 8639 Cand2.Function->hasAttr<EnableIfAttr>())) 8640 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8641 8642 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8643 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8644 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8645 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8646 } 8647 8648 bool HasPS1 = Cand1.Function != nullptr && 8649 functionHasPassObjectSizeParams(Cand1.Function); 8650 bool HasPS2 = Cand2.Function != nullptr && 8651 functionHasPassObjectSizeParams(Cand2.Function); 8652 return HasPS1 != HasPS2 && HasPS1; 8653 } 8654 8655 /// Determine whether two declarations are "equivalent" for the purposes of 8656 /// name lookup and overload resolution. This applies when the same internal/no 8657 /// linkage entity is defined by two modules (probably by textually including 8658 /// the same header). In such a case, we don't consider the declarations to 8659 /// declare the same entity, but we also don't want lookups with both 8660 /// declarations visible to be ambiguous in some cases (this happens when using 8661 /// a modularized libstdc++). 8662 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8663 const NamedDecl *B) { 8664 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8665 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8666 if (!VA || !VB) 8667 return false; 8668 8669 // The declarations must be declaring the same name as an internal linkage 8670 // entity in different modules. 8671 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8672 VB->getDeclContext()->getRedeclContext()) || 8673 getOwningModule(const_cast<ValueDecl *>(VA)) == 8674 getOwningModule(const_cast<ValueDecl *>(VB)) || 8675 VA->isExternallyVisible() || VB->isExternallyVisible()) 8676 return false; 8677 8678 // Check that the declarations appear to be equivalent. 8679 // 8680 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8681 // For constants and functions, we should check the initializer or body is 8682 // the same. For non-constant variables, we shouldn't allow it at all. 8683 if (Context.hasSameType(VA->getType(), VB->getType())) 8684 return true; 8685 8686 // Enum constants within unnamed enumerations will have different types, but 8687 // may still be similar enough to be interchangeable for our purposes. 8688 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8689 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8690 // Only handle anonymous enums. If the enumerations were named and 8691 // equivalent, they would have been merged to the same type. 8692 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8693 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8694 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8695 !Context.hasSameType(EnumA->getIntegerType(), 8696 EnumB->getIntegerType())) 8697 return false; 8698 // Allow this only if the value is the same for both enumerators. 8699 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8700 } 8701 } 8702 8703 // Nothing else is sufficiently similar. 8704 return false; 8705 } 8706 8707 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8708 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8709 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8710 8711 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8712 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8713 << !M << (M ? M->getFullModuleName() : ""); 8714 8715 for (auto *E : Equiv) { 8716 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8717 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8718 << !M << (M ? M->getFullModuleName() : ""); 8719 } 8720 } 8721 8722 /// \brief Computes the best viable function (C++ 13.3.3) 8723 /// within an overload candidate set. 8724 /// 8725 /// \param Loc The location of the function name (or operator symbol) for 8726 /// which overload resolution occurs. 8727 /// 8728 /// \param Best If overload resolution was successful or found a deleted 8729 /// function, \p Best points to the candidate function found. 8730 /// 8731 /// \returns The result of overload resolution. 8732 OverloadingResult 8733 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8734 iterator &Best, 8735 bool UserDefinedConversion) { 8736 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8737 std::transform(begin(), end(), std::back_inserter(Candidates), 8738 [](OverloadCandidate &Cand) { return &Cand; }); 8739 8740 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA 8741 // but accepted by both clang and NVCC. However during a particular 8742 // compilation mode only one call variant is viable. We need to 8743 // exclude non-viable overload candidates from consideration based 8744 // only on their host/device attributes. Specifically, if one 8745 // candidate call is WrongSide and the other is SameSide, we ignore 8746 // the WrongSide candidate. 8747 if (S.getLangOpts().CUDA) { 8748 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8749 bool ContainsSameSideCandidate = 8750 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8751 return Cand->Function && 8752 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8753 Sema::CFP_SameSide; 8754 }); 8755 if (ContainsSameSideCandidate) { 8756 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8757 return Cand->Function && 8758 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8759 Sema::CFP_WrongSide; 8760 }; 8761 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8762 IsWrongSideCandidate), 8763 Candidates.end()); 8764 } 8765 } 8766 8767 // Find the best viable function. 8768 Best = end(); 8769 for (auto *Cand : Candidates) 8770 if (Cand->Viable) 8771 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8772 UserDefinedConversion)) 8773 Best = Cand; 8774 8775 // If we didn't find any viable functions, abort. 8776 if (Best == end()) 8777 return OR_No_Viable_Function; 8778 8779 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8780 8781 // Make sure that this function is better than every other viable 8782 // function. If not, we have an ambiguity. 8783 for (auto *Cand : Candidates) { 8784 if (Cand->Viable && 8785 Cand != Best && 8786 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8787 UserDefinedConversion)) { 8788 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8789 Cand->Function)) { 8790 EquivalentCands.push_back(Cand->Function); 8791 continue; 8792 } 8793 8794 Best = end(); 8795 return OR_Ambiguous; 8796 } 8797 } 8798 8799 // Best is the best viable function. 8800 if (Best->Function && 8801 (Best->Function->isDeleted() || 8802 S.isFunctionConsideredUnavailable(Best->Function))) 8803 return OR_Deleted; 8804 8805 if (!EquivalentCands.empty()) 8806 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8807 EquivalentCands); 8808 8809 return OR_Success; 8810 } 8811 8812 namespace { 8813 8814 enum OverloadCandidateKind { 8815 oc_function, 8816 oc_method, 8817 oc_constructor, 8818 oc_function_template, 8819 oc_method_template, 8820 oc_constructor_template, 8821 oc_implicit_default_constructor, 8822 oc_implicit_copy_constructor, 8823 oc_implicit_move_constructor, 8824 oc_implicit_copy_assignment, 8825 oc_implicit_move_assignment, 8826 oc_implicit_inherited_constructor 8827 }; 8828 8829 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8830 FunctionDecl *Fn, 8831 std::string &Description) { 8832 bool isTemplate = false; 8833 8834 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8835 isTemplate = true; 8836 Description = S.getTemplateArgumentBindingsText( 8837 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8838 } 8839 8840 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8841 if (!Ctor->isImplicit()) 8842 return isTemplate ? oc_constructor_template : oc_constructor; 8843 8844 if (Ctor->getInheritedConstructor()) 8845 return oc_implicit_inherited_constructor; 8846 8847 if (Ctor->isDefaultConstructor()) 8848 return oc_implicit_default_constructor; 8849 8850 if (Ctor->isMoveConstructor()) 8851 return oc_implicit_move_constructor; 8852 8853 assert(Ctor->isCopyConstructor() && 8854 "unexpected sort of implicit constructor"); 8855 return oc_implicit_copy_constructor; 8856 } 8857 8858 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8859 // This actually gets spelled 'candidate function' for now, but 8860 // it doesn't hurt to split it out. 8861 if (!Meth->isImplicit()) 8862 return isTemplate ? oc_method_template : oc_method; 8863 8864 if (Meth->isMoveAssignmentOperator()) 8865 return oc_implicit_move_assignment; 8866 8867 if (Meth->isCopyAssignmentOperator()) 8868 return oc_implicit_copy_assignment; 8869 8870 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8871 return oc_method; 8872 } 8873 8874 return isTemplate ? oc_function_template : oc_function; 8875 } 8876 8877 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8878 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8879 if (!Ctor) return; 8880 8881 Ctor = Ctor->getInheritedConstructor(); 8882 if (!Ctor) return; 8883 8884 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8885 } 8886 8887 } // end anonymous namespace 8888 8889 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8890 const FunctionDecl *FD) { 8891 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8892 bool AlwaysTrue; 8893 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8894 return false; 8895 if (!AlwaysTrue) 8896 return false; 8897 } 8898 return true; 8899 } 8900 8901 /// \brief Returns true if we can take the address of the function. 8902 /// 8903 /// \param Complain - If true, we'll emit a diagnostic 8904 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8905 /// we in overload resolution? 8906 /// \param Loc - The location of the statement we're complaining about. Ignored 8907 /// if we're not complaining, or if we're in overload resolution. 8908 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8909 bool Complain, 8910 bool InOverloadResolution, 8911 SourceLocation Loc) { 8912 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8913 if (Complain) { 8914 if (InOverloadResolution) 8915 S.Diag(FD->getLocStart(), 8916 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8917 else 8918 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8919 } 8920 return false; 8921 } 8922 8923 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8924 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8925 if (I == FD->param_end()) 8926 return true; 8927 8928 if (Complain) { 8929 // Add one to ParamNo because it's user-facing 8930 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8931 if (InOverloadResolution) 8932 S.Diag(FD->getLocation(), 8933 diag::note_ovl_candidate_has_pass_object_size_params) 8934 << ParamNo; 8935 else 8936 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8937 << FD << ParamNo; 8938 } 8939 return false; 8940 } 8941 8942 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8943 const FunctionDecl *FD) { 8944 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8945 /*InOverloadResolution=*/true, 8946 /*Loc=*/SourceLocation()); 8947 } 8948 8949 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8950 bool Complain, 8951 SourceLocation Loc) { 8952 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8953 /*InOverloadResolution=*/false, 8954 Loc); 8955 } 8956 8957 // Notes the location of an overload candidate. 8958 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8959 bool TakingAddress) { 8960 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8961 return; 8962 8963 std::string FnDesc; 8964 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8965 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8966 << (unsigned) K << FnDesc; 8967 8968 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8969 Diag(Fn->getLocation(), PD); 8970 MaybeEmitInheritedConstructorNote(*this, Fn); 8971 } 8972 8973 // Notes the location of all overload candidates designated through 8974 // OverloadedExpr 8975 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8976 bool TakingAddress) { 8977 assert(OverloadedExpr->getType() == Context.OverloadTy); 8978 8979 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8980 OverloadExpr *OvlExpr = Ovl.Expression; 8981 8982 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8983 IEnd = OvlExpr->decls_end(); 8984 I != IEnd; ++I) { 8985 if (FunctionTemplateDecl *FunTmpl = 8986 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8987 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8988 TakingAddress); 8989 } else if (FunctionDecl *Fun 8990 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8991 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8992 } 8993 } 8994 } 8995 8996 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8997 /// "lead" diagnostic; it will be given two arguments, the source and 8998 /// target types of the conversion. 8999 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9000 Sema &S, 9001 SourceLocation CaretLoc, 9002 const PartialDiagnostic &PDiag) const { 9003 S.Diag(CaretLoc, PDiag) 9004 << Ambiguous.getFromType() << Ambiguous.getToType(); 9005 // FIXME: The note limiting machinery is borrowed from 9006 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9007 // refactoring here. 9008 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9009 unsigned CandsShown = 0; 9010 AmbiguousConversionSequence::const_iterator I, E; 9011 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9012 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9013 break; 9014 ++CandsShown; 9015 S.NoteOverloadCandidate(*I); 9016 } 9017 if (I != E) 9018 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9019 } 9020 9021 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9022 unsigned I, bool TakingCandidateAddress) { 9023 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9024 assert(Conv.isBad()); 9025 assert(Cand->Function && "for now, candidate must be a function"); 9026 FunctionDecl *Fn = Cand->Function; 9027 9028 // There's a conversion slot for the object argument if this is a 9029 // non-constructor method. Note that 'I' corresponds the 9030 // conversion-slot index. 9031 bool isObjectArgument = false; 9032 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9033 if (I == 0) 9034 isObjectArgument = true; 9035 else 9036 I--; 9037 } 9038 9039 std::string FnDesc; 9040 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9041 9042 Expr *FromExpr = Conv.Bad.FromExpr; 9043 QualType FromTy = Conv.Bad.getFromType(); 9044 QualType ToTy = Conv.Bad.getToType(); 9045 9046 if (FromTy == S.Context.OverloadTy) { 9047 assert(FromExpr && "overload set argument came from implicit argument?"); 9048 Expr *E = FromExpr->IgnoreParens(); 9049 if (isa<UnaryOperator>(E)) 9050 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9051 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9052 9053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9054 << (unsigned) FnKind << FnDesc 9055 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9056 << ToTy << Name << I+1; 9057 MaybeEmitInheritedConstructorNote(S, Fn); 9058 return; 9059 } 9060 9061 // Do some hand-waving analysis to see if the non-viability is due 9062 // to a qualifier mismatch. 9063 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9064 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9065 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9066 CToTy = RT->getPointeeType(); 9067 else { 9068 // TODO: detect and diagnose the full richness of const mismatches. 9069 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9070 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9071 CFromTy = FromPT->getPointeeType(); 9072 CToTy = ToPT->getPointeeType(); 9073 } 9074 } 9075 9076 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9077 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9078 Qualifiers FromQs = CFromTy.getQualifiers(); 9079 Qualifiers ToQs = CToTy.getQualifiers(); 9080 9081 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9083 << (unsigned) FnKind << FnDesc 9084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9085 << FromTy 9086 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9087 << (unsigned) isObjectArgument << I+1; 9088 MaybeEmitInheritedConstructorNote(S, Fn); 9089 return; 9090 } 9091 9092 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9094 << (unsigned) FnKind << FnDesc 9095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9096 << FromTy 9097 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9098 << (unsigned) isObjectArgument << I+1; 9099 MaybeEmitInheritedConstructorNote(S, Fn); 9100 return; 9101 } 9102 9103 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9105 << (unsigned) FnKind << FnDesc 9106 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9107 << FromTy 9108 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9109 << (unsigned) isObjectArgument << I+1; 9110 MaybeEmitInheritedConstructorNote(S, Fn); 9111 return; 9112 } 9113 9114 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9115 assert(CVR && "unexpected qualifiers mismatch"); 9116 9117 if (isObjectArgument) { 9118 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9119 << (unsigned) FnKind << FnDesc 9120 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9121 << FromTy << (CVR - 1); 9122 } else { 9123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9124 << (unsigned) FnKind << FnDesc 9125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9126 << FromTy << (CVR - 1) << I+1; 9127 } 9128 MaybeEmitInheritedConstructorNote(S, Fn); 9129 return; 9130 } 9131 9132 // Special diagnostic for failure to convert an initializer list, since 9133 // telling the user that it has type void is not useful. 9134 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9136 << (unsigned) FnKind << FnDesc 9137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9139 MaybeEmitInheritedConstructorNote(S, Fn); 9140 return; 9141 } 9142 9143 // Diagnose references or pointers to incomplete types differently, 9144 // since it's far from impossible that the incompleteness triggered 9145 // the failure. 9146 QualType TempFromTy = FromTy.getNonReferenceType(); 9147 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9148 TempFromTy = PTy->getPointeeType(); 9149 if (TempFromTy->isIncompleteType()) { 9150 // Emit the generic diagnostic and, optionally, add the hints to it. 9151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9152 << (unsigned) FnKind << FnDesc 9153 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9154 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9155 << (unsigned) (Cand->Fix.Kind); 9156 9157 MaybeEmitInheritedConstructorNote(S, Fn); 9158 return; 9159 } 9160 9161 // Diagnose base -> derived pointer conversions. 9162 unsigned BaseToDerivedConversion = 0; 9163 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9164 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9165 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9166 FromPtrTy->getPointeeType()) && 9167 !FromPtrTy->getPointeeType()->isIncompleteType() && 9168 !ToPtrTy->getPointeeType()->isIncompleteType() && 9169 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9170 FromPtrTy->getPointeeType())) 9171 BaseToDerivedConversion = 1; 9172 } 9173 } else if (const ObjCObjectPointerType *FromPtrTy 9174 = FromTy->getAs<ObjCObjectPointerType>()) { 9175 if (const ObjCObjectPointerType *ToPtrTy 9176 = ToTy->getAs<ObjCObjectPointerType>()) 9177 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9178 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9179 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9180 FromPtrTy->getPointeeType()) && 9181 FromIface->isSuperClassOf(ToIface)) 9182 BaseToDerivedConversion = 2; 9183 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9184 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9185 !FromTy->isIncompleteType() && 9186 !ToRefTy->getPointeeType()->isIncompleteType() && 9187 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9188 BaseToDerivedConversion = 3; 9189 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9190 ToTy.getNonReferenceType().getCanonicalType() == 9191 FromTy.getNonReferenceType().getCanonicalType()) { 9192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9193 << (unsigned) FnKind << FnDesc 9194 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9195 << (unsigned) isObjectArgument << I + 1; 9196 MaybeEmitInheritedConstructorNote(S, Fn); 9197 return; 9198 } 9199 } 9200 9201 if (BaseToDerivedConversion) { 9202 S.Diag(Fn->getLocation(), 9203 diag::note_ovl_candidate_bad_base_to_derived_conv) 9204 << (unsigned) FnKind << FnDesc 9205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9206 << (BaseToDerivedConversion - 1) 9207 << FromTy << ToTy << I+1; 9208 MaybeEmitInheritedConstructorNote(S, Fn); 9209 return; 9210 } 9211 9212 if (isa<ObjCObjectPointerType>(CFromTy) && 9213 isa<PointerType>(CToTy)) { 9214 Qualifiers FromQs = CFromTy.getQualifiers(); 9215 Qualifiers ToQs = CToTy.getQualifiers(); 9216 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9218 << (unsigned) FnKind << FnDesc 9219 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9220 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9221 MaybeEmitInheritedConstructorNote(S, Fn); 9222 return; 9223 } 9224 } 9225 9226 if (TakingCandidateAddress && 9227 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9228 return; 9229 9230 // Emit the generic diagnostic and, optionally, add the hints to it. 9231 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9232 FDiag << (unsigned) FnKind << FnDesc 9233 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9234 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9235 << (unsigned) (Cand->Fix.Kind); 9236 9237 // If we can fix the conversion, suggest the FixIts. 9238 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9239 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9240 FDiag << *HI; 9241 S.Diag(Fn->getLocation(), FDiag); 9242 9243 MaybeEmitInheritedConstructorNote(S, Fn); 9244 } 9245 9246 /// Additional arity mismatch diagnosis specific to a function overload 9247 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9248 /// over a candidate in any candidate set. 9249 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9250 unsigned NumArgs) { 9251 FunctionDecl *Fn = Cand->Function; 9252 unsigned MinParams = Fn->getMinRequiredArguments(); 9253 9254 // With invalid overloaded operators, it's possible that we think we 9255 // have an arity mismatch when in fact it looks like we have the 9256 // right number of arguments, because only overloaded operators have 9257 // the weird behavior of overloading member and non-member functions. 9258 // Just don't report anything. 9259 if (Fn->isInvalidDecl() && 9260 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9261 return true; 9262 9263 if (NumArgs < MinParams) { 9264 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9265 (Cand->FailureKind == ovl_fail_bad_deduction && 9266 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9267 } else { 9268 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9269 (Cand->FailureKind == ovl_fail_bad_deduction && 9270 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9271 } 9272 9273 return false; 9274 } 9275 9276 /// General arity mismatch diagnosis over a candidate in a candidate set. 9277 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9278 assert(isa<FunctionDecl>(D) && 9279 "The templated declaration should at least be a function" 9280 " when diagnosing bad template argument deduction due to too many" 9281 " or too few arguments"); 9282 9283 FunctionDecl *Fn = cast<FunctionDecl>(D); 9284 9285 // TODO: treat calls to a missing default constructor as a special case 9286 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9287 unsigned MinParams = Fn->getMinRequiredArguments(); 9288 9289 // at least / at most / exactly 9290 unsigned mode, modeCount; 9291 if (NumFormalArgs < MinParams) { 9292 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9293 FnTy->isTemplateVariadic()) 9294 mode = 0; // "at least" 9295 else 9296 mode = 2; // "exactly" 9297 modeCount = MinParams; 9298 } else { 9299 if (MinParams != FnTy->getNumParams()) 9300 mode = 1; // "at most" 9301 else 9302 mode = 2; // "exactly" 9303 modeCount = FnTy->getNumParams(); 9304 } 9305 9306 std::string Description; 9307 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9308 9309 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9310 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9311 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9312 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9313 else 9314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9315 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9316 << mode << modeCount << NumFormalArgs; 9317 MaybeEmitInheritedConstructorNote(S, Fn); 9318 } 9319 9320 /// Arity mismatch diagnosis specific to a function overload candidate. 9321 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9322 unsigned NumFormalArgs) { 9323 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9324 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9325 } 9326 9327 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9329 return FD->getDescribedFunctionTemplate(); 9330 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9331 return RD->getDescribedClassTemplate(); 9332 9333 llvm_unreachable("Unsupported: Getting the described template declaration" 9334 " for bad deduction diagnosis"); 9335 } 9336 9337 /// Diagnose a failed template-argument deduction. 9338 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9339 DeductionFailureInfo &DeductionFailure, 9340 unsigned NumArgs, 9341 bool TakingCandidateAddress) { 9342 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9343 NamedDecl *ParamD; 9344 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9345 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9346 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9347 switch (DeductionFailure.Result) { 9348 case Sema::TDK_Success: 9349 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9350 9351 case Sema::TDK_Incomplete: { 9352 assert(ParamD && "no parameter found for incomplete deduction result"); 9353 S.Diag(Templated->getLocation(), 9354 diag::note_ovl_candidate_incomplete_deduction) 9355 << ParamD->getDeclName(); 9356 MaybeEmitInheritedConstructorNote(S, Templated); 9357 return; 9358 } 9359 9360 case Sema::TDK_Underqualified: { 9361 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9362 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9363 9364 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9365 9366 // Param will have been canonicalized, but it should just be a 9367 // qualified version of ParamD, so move the qualifiers to that. 9368 QualifierCollector Qs; 9369 Qs.strip(Param); 9370 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9371 assert(S.Context.hasSameType(Param, NonCanonParam)); 9372 9373 // Arg has also been canonicalized, but there's nothing we can do 9374 // about that. It also doesn't matter as much, because it won't 9375 // have any template parameters in it (because deduction isn't 9376 // done on dependent types). 9377 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9378 9379 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9380 << ParamD->getDeclName() << Arg << NonCanonParam; 9381 MaybeEmitInheritedConstructorNote(S, Templated); 9382 return; 9383 } 9384 9385 case Sema::TDK_Inconsistent: { 9386 assert(ParamD && "no parameter found for inconsistent deduction result"); 9387 int which = 0; 9388 if (isa<TemplateTypeParmDecl>(ParamD)) 9389 which = 0; 9390 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9391 which = 1; 9392 else { 9393 which = 2; 9394 } 9395 9396 S.Diag(Templated->getLocation(), 9397 diag::note_ovl_candidate_inconsistent_deduction) 9398 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9399 << *DeductionFailure.getSecondArg(); 9400 MaybeEmitInheritedConstructorNote(S, Templated); 9401 return; 9402 } 9403 9404 case Sema::TDK_InvalidExplicitArguments: 9405 assert(ParamD && "no parameter found for invalid explicit arguments"); 9406 if (ParamD->getDeclName()) 9407 S.Diag(Templated->getLocation(), 9408 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9409 << ParamD->getDeclName(); 9410 else { 9411 int index = 0; 9412 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9413 index = TTP->getIndex(); 9414 else if (NonTypeTemplateParmDecl *NTTP 9415 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9416 index = NTTP->getIndex(); 9417 else 9418 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9419 S.Diag(Templated->getLocation(), 9420 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9421 << (index + 1); 9422 } 9423 MaybeEmitInheritedConstructorNote(S, Templated); 9424 return; 9425 9426 case Sema::TDK_TooManyArguments: 9427 case Sema::TDK_TooFewArguments: 9428 DiagnoseArityMismatch(S, Templated, NumArgs); 9429 return; 9430 9431 case Sema::TDK_InstantiationDepth: 9432 S.Diag(Templated->getLocation(), 9433 diag::note_ovl_candidate_instantiation_depth); 9434 MaybeEmitInheritedConstructorNote(S, Templated); 9435 return; 9436 9437 case Sema::TDK_SubstitutionFailure: { 9438 // Format the template argument list into the argument string. 9439 SmallString<128> TemplateArgString; 9440 if (TemplateArgumentList *Args = 9441 DeductionFailure.getTemplateArgumentList()) { 9442 TemplateArgString = " "; 9443 TemplateArgString += S.getTemplateArgumentBindingsText( 9444 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9445 } 9446 9447 // If this candidate was disabled by enable_if, say so. 9448 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9449 if (PDiag && PDiag->second.getDiagID() == 9450 diag::err_typename_nested_not_found_enable_if) { 9451 // FIXME: Use the source range of the condition, and the fully-qualified 9452 // name of the enable_if template. These are both present in PDiag. 9453 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9454 << "'enable_if'" << TemplateArgString; 9455 return; 9456 } 9457 9458 // Format the SFINAE diagnostic into the argument string. 9459 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9460 // formatted message in another diagnostic. 9461 SmallString<128> SFINAEArgString; 9462 SourceRange R; 9463 if (PDiag) { 9464 SFINAEArgString = ": "; 9465 R = SourceRange(PDiag->first, PDiag->first); 9466 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9467 } 9468 9469 S.Diag(Templated->getLocation(), 9470 diag::note_ovl_candidate_substitution_failure) 9471 << TemplateArgString << SFINAEArgString << R; 9472 MaybeEmitInheritedConstructorNote(S, Templated); 9473 return; 9474 } 9475 9476 case Sema::TDK_FailedOverloadResolution: { 9477 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9478 S.Diag(Templated->getLocation(), 9479 diag::note_ovl_candidate_failed_overload_resolution) 9480 << R.Expression->getName(); 9481 return; 9482 } 9483 9484 case Sema::TDK_DeducedMismatch: { 9485 // Format the template argument list into the argument string. 9486 SmallString<128> TemplateArgString; 9487 if (TemplateArgumentList *Args = 9488 DeductionFailure.getTemplateArgumentList()) { 9489 TemplateArgString = " "; 9490 TemplateArgString += S.getTemplateArgumentBindingsText( 9491 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9492 } 9493 9494 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9495 << (*DeductionFailure.getCallArgIndex() + 1) 9496 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9497 << TemplateArgString; 9498 break; 9499 } 9500 9501 case Sema::TDK_NonDeducedMismatch: { 9502 // FIXME: Provide a source location to indicate what we couldn't match. 9503 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9504 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9505 if (FirstTA.getKind() == TemplateArgument::Template && 9506 SecondTA.getKind() == TemplateArgument::Template) { 9507 TemplateName FirstTN = FirstTA.getAsTemplate(); 9508 TemplateName SecondTN = SecondTA.getAsTemplate(); 9509 if (FirstTN.getKind() == TemplateName::Template && 9510 SecondTN.getKind() == TemplateName::Template) { 9511 if (FirstTN.getAsTemplateDecl()->getName() == 9512 SecondTN.getAsTemplateDecl()->getName()) { 9513 // FIXME: This fixes a bad diagnostic where both templates are named 9514 // the same. This particular case is a bit difficult since: 9515 // 1) It is passed as a string to the diagnostic printer. 9516 // 2) The diagnostic printer only attempts to find a better 9517 // name for types, not decls. 9518 // Ideally, this should folded into the diagnostic printer. 9519 S.Diag(Templated->getLocation(), 9520 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9521 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9522 return; 9523 } 9524 } 9525 } 9526 9527 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9528 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9529 return; 9530 9531 // FIXME: For generic lambda parameters, check if the function is a lambda 9532 // call operator, and if so, emit a prettier and more informative 9533 // diagnostic that mentions 'auto' and lambda in addition to 9534 // (or instead of?) the canonical template type parameters. 9535 S.Diag(Templated->getLocation(), 9536 diag::note_ovl_candidate_non_deduced_mismatch) 9537 << FirstTA << SecondTA; 9538 return; 9539 } 9540 // TODO: diagnose these individually, then kill off 9541 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9542 case Sema::TDK_MiscellaneousDeductionFailure: 9543 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9544 MaybeEmitInheritedConstructorNote(S, Templated); 9545 return; 9546 } 9547 } 9548 9549 /// Diagnose a failed template-argument deduction, for function calls. 9550 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9551 unsigned NumArgs, 9552 bool TakingCandidateAddress) { 9553 unsigned TDK = Cand->DeductionFailure.Result; 9554 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9555 if (CheckArityMismatch(S, Cand, NumArgs)) 9556 return; 9557 } 9558 DiagnoseBadDeduction(S, Cand->Function, // pattern 9559 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9560 } 9561 9562 /// CUDA: diagnose an invalid call across targets. 9563 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9564 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9565 FunctionDecl *Callee = Cand->Function; 9566 9567 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9568 CalleeTarget = S.IdentifyCUDATarget(Callee); 9569 9570 std::string FnDesc; 9571 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9572 9573 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9574 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9575 9576 // This could be an implicit constructor for which we could not infer the 9577 // target due to a collsion. Diagnose that case. 9578 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9579 if (Meth != nullptr && Meth->isImplicit()) { 9580 CXXRecordDecl *ParentClass = Meth->getParent(); 9581 Sema::CXXSpecialMember CSM; 9582 9583 switch (FnKind) { 9584 default: 9585 return; 9586 case oc_implicit_default_constructor: 9587 CSM = Sema::CXXDefaultConstructor; 9588 break; 9589 case oc_implicit_copy_constructor: 9590 CSM = Sema::CXXCopyConstructor; 9591 break; 9592 case oc_implicit_move_constructor: 9593 CSM = Sema::CXXMoveConstructor; 9594 break; 9595 case oc_implicit_copy_assignment: 9596 CSM = Sema::CXXCopyAssignment; 9597 break; 9598 case oc_implicit_move_assignment: 9599 CSM = Sema::CXXMoveAssignment; 9600 break; 9601 }; 9602 9603 bool ConstRHS = false; 9604 if (Meth->getNumParams()) { 9605 if (const ReferenceType *RT = 9606 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9607 ConstRHS = RT->getPointeeType().isConstQualified(); 9608 } 9609 } 9610 9611 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9612 /* ConstRHS */ ConstRHS, 9613 /* Diagnose */ true); 9614 } 9615 } 9616 9617 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9618 FunctionDecl *Callee = Cand->Function; 9619 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9620 9621 S.Diag(Callee->getLocation(), 9622 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9623 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9624 } 9625 9626 /// Generates a 'note' diagnostic for an overload candidate. We've 9627 /// already generated a primary error at the call site. 9628 /// 9629 /// It really does need to be a single diagnostic with its caret 9630 /// pointed at the candidate declaration. Yes, this creates some 9631 /// major challenges of technical writing. Yes, this makes pointing 9632 /// out problems with specific arguments quite awkward. It's still 9633 /// better than generating twenty screens of text for every failed 9634 /// overload. 9635 /// 9636 /// It would be great to be able to express per-candidate problems 9637 /// more richly for those diagnostic clients that cared, but we'd 9638 /// still have to be just as careful with the default diagnostics. 9639 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9640 unsigned NumArgs, 9641 bool TakingCandidateAddress) { 9642 FunctionDecl *Fn = Cand->Function; 9643 9644 // Note deleted candidates, but only if they're viable. 9645 if (Cand->Viable && (Fn->isDeleted() || 9646 S.isFunctionConsideredUnavailable(Fn))) { 9647 std::string FnDesc; 9648 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9649 9650 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9651 << FnKind << FnDesc 9652 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9653 MaybeEmitInheritedConstructorNote(S, Fn); 9654 return; 9655 } 9656 9657 // We don't really have anything else to say about viable candidates. 9658 if (Cand->Viable) { 9659 S.NoteOverloadCandidate(Fn); 9660 return; 9661 } 9662 9663 switch (Cand->FailureKind) { 9664 case ovl_fail_too_many_arguments: 9665 case ovl_fail_too_few_arguments: 9666 return DiagnoseArityMismatch(S, Cand, NumArgs); 9667 9668 case ovl_fail_bad_deduction: 9669 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9670 9671 case ovl_fail_illegal_constructor: { 9672 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9673 << (Fn->getPrimaryTemplate() ? 1 : 0); 9674 MaybeEmitInheritedConstructorNote(S, Fn); 9675 return; 9676 } 9677 9678 case ovl_fail_trivial_conversion: 9679 case ovl_fail_bad_final_conversion: 9680 case ovl_fail_final_conversion_not_exact: 9681 return S.NoteOverloadCandidate(Fn); 9682 9683 case ovl_fail_bad_conversion: { 9684 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9685 for (unsigned N = Cand->NumConversions; I != N; ++I) 9686 if (Cand->Conversions[I].isBad()) 9687 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9688 9689 // FIXME: this currently happens when we're called from SemaInit 9690 // when user-conversion overload fails. Figure out how to handle 9691 // those conditions and diagnose them well. 9692 return S.NoteOverloadCandidate(Fn); 9693 } 9694 9695 case ovl_fail_bad_target: 9696 return DiagnoseBadTarget(S, Cand); 9697 9698 case ovl_fail_enable_if: 9699 return DiagnoseFailedEnableIfAttr(S, Cand); 9700 9701 case ovl_fail_addr_not_available: { 9702 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9703 (void)Available; 9704 assert(!Available); 9705 break; 9706 } 9707 } 9708 } 9709 9710 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9711 // Desugar the type of the surrogate down to a function type, 9712 // retaining as many typedefs as possible while still showing 9713 // the function type (and, therefore, its parameter types). 9714 QualType FnType = Cand->Surrogate->getConversionType(); 9715 bool isLValueReference = false; 9716 bool isRValueReference = false; 9717 bool isPointer = false; 9718 if (const LValueReferenceType *FnTypeRef = 9719 FnType->getAs<LValueReferenceType>()) { 9720 FnType = FnTypeRef->getPointeeType(); 9721 isLValueReference = true; 9722 } else if (const RValueReferenceType *FnTypeRef = 9723 FnType->getAs<RValueReferenceType>()) { 9724 FnType = FnTypeRef->getPointeeType(); 9725 isRValueReference = true; 9726 } 9727 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9728 FnType = FnTypePtr->getPointeeType(); 9729 isPointer = true; 9730 } 9731 // Desugar down to a function type. 9732 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9733 // Reconstruct the pointer/reference as appropriate. 9734 if (isPointer) FnType = S.Context.getPointerType(FnType); 9735 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9736 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9737 9738 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9739 << FnType; 9740 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9741 } 9742 9743 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9744 SourceLocation OpLoc, 9745 OverloadCandidate *Cand) { 9746 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9747 std::string TypeStr("operator"); 9748 TypeStr += Opc; 9749 TypeStr += "("; 9750 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9751 if (Cand->NumConversions == 1) { 9752 TypeStr += ")"; 9753 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9754 } else { 9755 TypeStr += ", "; 9756 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9757 TypeStr += ")"; 9758 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9759 } 9760 } 9761 9762 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9763 OverloadCandidate *Cand) { 9764 unsigned NoOperands = Cand->NumConversions; 9765 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9766 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9767 if (ICS.isBad()) break; // all meaningless after first invalid 9768 if (!ICS.isAmbiguous()) continue; 9769 9770 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9771 S.PDiag(diag::note_ambiguous_type_conversion)); 9772 } 9773 } 9774 9775 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9776 if (Cand->Function) 9777 return Cand->Function->getLocation(); 9778 if (Cand->IsSurrogate) 9779 return Cand->Surrogate->getLocation(); 9780 return SourceLocation(); 9781 } 9782 9783 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9784 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9785 case Sema::TDK_Success: 9786 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9787 9788 case Sema::TDK_Invalid: 9789 case Sema::TDK_Incomplete: 9790 return 1; 9791 9792 case Sema::TDK_Underqualified: 9793 case Sema::TDK_Inconsistent: 9794 return 2; 9795 9796 case Sema::TDK_SubstitutionFailure: 9797 case Sema::TDK_DeducedMismatch: 9798 case Sema::TDK_NonDeducedMismatch: 9799 case Sema::TDK_MiscellaneousDeductionFailure: 9800 return 3; 9801 9802 case Sema::TDK_InstantiationDepth: 9803 case Sema::TDK_FailedOverloadResolution: 9804 return 4; 9805 9806 case Sema::TDK_InvalidExplicitArguments: 9807 return 5; 9808 9809 case Sema::TDK_TooManyArguments: 9810 case Sema::TDK_TooFewArguments: 9811 return 6; 9812 } 9813 llvm_unreachable("Unhandled deduction result"); 9814 } 9815 9816 namespace { 9817 struct CompareOverloadCandidatesForDisplay { 9818 Sema &S; 9819 SourceLocation Loc; 9820 size_t NumArgs; 9821 9822 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9823 : S(S), NumArgs(nArgs) {} 9824 9825 bool operator()(const OverloadCandidate *L, 9826 const OverloadCandidate *R) { 9827 // Fast-path this check. 9828 if (L == R) return false; 9829 9830 // Order first by viability. 9831 if (L->Viable) { 9832 if (!R->Viable) return true; 9833 9834 // TODO: introduce a tri-valued comparison for overload 9835 // candidates. Would be more worthwhile if we had a sort 9836 // that could exploit it. 9837 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9838 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9839 } else if (R->Viable) 9840 return false; 9841 9842 assert(L->Viable == R->Viable); 9843 9844 // Criteria by which we can sort non-viable candidates: 9845 if (!L->Viable) { 9846 // 1. Arity mismatches come after other candidates. 9847 if (L->FailureKind == ovl_fail_too_many_arguments || 9848 L->FailureKind == ovl_fail_too_few_arguments) { 9849 if (R->FailureKind == ovl_fail_too_many_arguments || 9850 R->FailureKind == ovl_fail_too_few_arguments) { 9851 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9852 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9853 if (LDist == RDist) { 9854 if (L->FailureKind == R->FailureKind) 9855 // Sort non-surrogates before surrogates. 9856 return !L->IsSurrogate && R->IsSurrogate; 9857 // Sort candidates requiring fewer parameters than there were 9858 // arguments given after candidates requiring more parameters 9859 // than there were arguments given. 9860 return L->FailureKind == ovl_fail_too_many_arguments; 9861 } 9862 return LDist < RDist; 9863 } 9864 return false; 9865 } 9866 if (R->FailureKind == ovl_fail_too_many_arguments || 9867 R->FailureKind == ovl_fail_too_few_arguments) 9868 return true; 9869 9870 // 2. Bad conversions come first and are ordered by the number 9871 // of bad conversions and quality of good conversions. 9872 if (L->FailureKind == ovl_fail_bad_conversion) { 9873 if (R->FailureKind != ovl_fail_bad_conversion) 9874 return true; 9875 9876 // The conversion that can be fixed with a smaller number of changes, 9877 // comes first. 9878 unsigned numLFixes = L->Fix.NumConversionsFixed; 9879 unsigned numRFixes = R->Fix.NumConversionsFixed; 9880 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9881 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9882 if (numLFixes != numRFixes) { 9883 return numLFixes < numRFixes; 9884 } 9885 9886 // If there's any ordering between the defined conversions... 9887 // FIXME: this might not be transitive. 9888 assert(L->NumConversions == R->NumConversions); 9889 9890 int leftBetter = 0; 9891 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9892 for (unsigned E = L->NumConversions; I != E; ++I) { 9893 switch (CompareImplicitConversionSequences(S, Loc, 9894 L->Conversions[I], 9895 R->Conversions[I])) { 9896 case ImplicitConversionSequence::Better: 9897 leftBetter++; 9898 break; 9899 9900 case ImplicitConversionSequence::Worse: 9901 leftBetter--; 9902 break; 9903 9904 case ImplicitConversionSequence::Indistinguishable: 9905 break; 9906 } 9907 } 9908 if (leftBetter > 0) return true; 9909 if (leftBetter < 0) return false; 9910 9911 } else if (R->FailureKind == ovl_fail_bad_conversion) 9912 return false; 9913 9914 if (L->FailureKind == ovl_fail_bad_deduction) { 9915 if (R->FailureKind != ovl_fail_bad_deduction) 9916 return true; 9917 9918 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9919 return RankDeductionFailure(L->DeductionFailure) 9920 < RankDeductionFailure(R->DeductionFailure); 9921 } else if (R->FailureKind == ovl_fail_bad_deduction) 9922 return false; 9923 9924 // TODO: others? 9925 } 9926 9927 // Sort everything else by location. 9928 SourceLocation LLoc = GetLocationForCandidate(L); 9929 SourceLocation RLoc = GetLocationForCandidate(R); 9930 9931 // Put candidates without locations (e.g. builtins) at the end. 9932 if (LLoc.isInvalid()) return false; 9933 if (RLoc.isInvalid()) return true; 9934 9935 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9936 } 9937 }; 9938 } 9939 9940 /// CompleteNonViableCandidate - Normally, overload resolution only 9941 /// computes up to the first. Produces the FixIt set if possible. 9942 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9943 ArrayRef<Expr *> Args) { 9944 assert(!Cand->Viable); 9945 9946 // Don't do anything on failures other than bad conversion. 9947 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9948 9949 // We only want the FixIts if all the arguments can be corrected. 9950 bool Unfixable = false; 9951 // Use a implicit copy initialization to check conversion fixes. 9952 Cand->Fix.setConversionChecker(TryCopyInitialization); 9953 9954 // Skip forward to the first bad conversion. 9955 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9956 unsigned ConvCount = Cand->NumConversions; 9957 while (true) { 9958 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9959 ConvIdx++; 9960 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9961 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9962 break; 9963 } 9964 } 9965 9966 if (ConvIdx == ConvCount) 9967 return; 9968 9969 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9970 "remaining conversion is initialized?"); 9971 9972 // FIXME: this should probably be preserved from the overload 9973 // operation somehow. 9974 bool SuppressUserConversions = false; 9975 9976 const FunctionProtoType* Proto; 9977 unsigned ArgIdx = ConvIdx; 9978 9979 if (Cand->IsSurrogate) { 9980 QualType ConvType 9981 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9982 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9983 ConvType = ConvPtrType->getPointeeType(); 9984 Proto = ConvType->getAs<FunctionProtoType>(); 9985 ArgIdx--; 9986 } else if (Cand->Function) { 9987 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9988 if (isa<CXXMethodDecl>(Cand->Function) && 9989 !isa<CXXConstructorDecl>(Cand->Function)) 9990 ArgIdx--; 9991 } else { 9992 // Builtin binary operator with a bad first conversion. 9993 assert(ConvCount <= 3); 9994 for (; ConvIdx != ConvCount; ++ConvIdx) 9995 Cand->Conversions[ConvIdx] 9996 = TryCopyInitialization(S, Args[ConvIdx], 9997 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9998 SuppressUserConversions, 9999 /*InOverloadResolution*/ true, 10000 /*AllowObjCWritebackConversion=*/ 10001 S.getLangOpts().ObjCAutoRefCount); 10002 return; 10003 } 10004 10005 // Fill in the rest of the conversions. 10006 unsigned NumParams = Proto->getNumParams(); 10007 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10008 if (ArgIdx < NumParams) { 10009 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10010 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10011 /*InOverloadResolution=*/true, 10012 /*AllowObjCWritebackConversion=*/ 10013 S.getLangOpts().ObjCAutoRefCount); 10014 // Store the FixIt in the candidate if it exists. 10015 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10016 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10017 } 10018 else 10019 Cand->Conversions[ConvIdx].setEllipsis(); 10020 } 10021 } 10022 10023 /// PrintOverloadCandidates - When overload resolution fails, prints 10024 /// diagnostic messages containing the candidates in the candidate 10025 /// set. 10026 void OverloadCandidateSet::NoteCandidates(Sema &S, 10027 OverloadCandidateDisplayKind OCD, 10028 ArrayRef<Expr *> Args, 10029 StringRef Opc, 10030 SourceLocation OpLoc) { 10031 // Sort the candidates by viability and position. Sorting directly would 10032 // be prohibitive, so we make a set of pointers and sort those. 10033 SmallVector<OverloadCandidate*, 32> Cands; 10034 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10035 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10036 if (Cand->Viable) 10037 Cands.push_back(Cand); 10038 else if (OCD == OCD_AllCandidates) { 10039 CompleteNonViableCandidate(S, Cand, Args); 10040 if (Cand->Function || Cand->IsSurrogate) 10041 Cands.push_back(Cand); 10042 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10043 // want to list every possible builtin candidate. 10044 } 10045 } 10046 10047 std::sort(Cands.begin(), Cands.end(), 10048 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10049 10050 bool ReportedAmbiguousConversions = false; 10051 10052 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10053 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10054 unsigned CandsShown = 0; 10055 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10056 OverloadCandidate *Cand = *I; 10057 10058 // Set an arbitrary limit on the number of candidate functions we'll spam 10059 // the user with. FIXME: This limit should depend on details of the 10060 // candidate list. 10061 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10062 break; 10063 } 10064 ++CandsShown; 10065 10066 if (Cand->Function) 10067 NoteFunctionCandidate(S, Cand, Args.size(), 10068 /*TakingCandidateAddress=*/false); 10069 else if (Cand->IsSurrogate) 10070 NoteSurrogateCandidate(S, Cand); 10071 else { 10072 assert(Cand->Viable && 10073 "Non-viable built-in candidates are not added to Cands."); 10074 // Generally we only see ambiguities including viable builtin 10075 // operators if overload resolution got screwed up by an 10076 // ambiguous user-defined conversion. 10077 // 10078 // FIXME: It's quite possible for different conversions to see 10079 // different ambiguities, though. 10080 if (!ReportedAmbiguousConversions) { 10081 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10082 ReportedAmbiguousConversions = true; 10083 } 10084 10085 // If this is a viable builtin, print it. 10086 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10087 } 10088 } 10089 10090 if (I != E) 10091 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10092 } 10093 10094 static SourceLocation 10095 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10096 return Cand->Specialization ? Cand->Specialization->getLocation() 10097 : SourceLocation(); 10098 } 10099 10100 namespace { 10101 struct CompareTemplateSpecCandidatesForDisplay { 10102 Sema &S; 10103 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10104 10105 bool operator()(const TemplateSpecCandidate *L, 10106 const TemplateSpecCandidate *R) { 10107 // Fast-path this check. 10108 if (L == R) 10109 return false; 10110 10111 // Assuming that both candidates are not matches... 10112 10113 // Sort by the ranking of deduction failures. 10114 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10115 return RankDeductionFailure(L->DeductionFailure) < 10116 RankDeductionFailure(R->DeductionFailure); 10117 10118 // Sort everything else by location. 10119 SourceLocation LLoc = GetLocationForCandidate(L); 10120 SourceLocation RLoc = GetLocationForCandidate(R); 10121 10122 // Put candidates without locations (e.g. builtins) at the end. 10123 if (LLoc.isInvalid()) 10124 return false; 10125 if (RLoc.isInvalid()) 10126 return true; 10127 10128 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10129 } 10130 }; 10131 } 10132 10133 /// Diagnose a template argument deduction failure. 10134 /// We are treating these failures as overload failures due to bad 10135 /// deductions. 10136 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10137 bool ForTakingAddress) { 10138 DiagnoseBadDeduction(S, Specialization, // pattern 10139 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10140 } 10141 10142 void TemplateSpecCandidateSet::destroyCandidates() { 10143 for (iterator i = begin(), e = end(); i != e; ++i) { 10144 i->DeductionFailure.Destroy(); 10145 } 10146 } 10147 10148 void TemplateSpecCandidateSet::clear() { 10149 destroyCandidates(); 10150 Candidates.clear(); 10151 } 10152 10153 /// NoteCandidates - When no template specialization match is found, prints 10154 /// diagnostic messages containing the non-matching specializations that form 10155 /// the candidate set. 10156 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10157 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10158 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10159 // Sort the candidates by position (assuming no candidate is a match). 10160 // Sorting directly would be prohibitive, so we make a set of pointers 10161 // and sort those. 10162 SmallVector<TemplateSpecCandidate *, 32> Cands; 10163 Cands.reserve(size()); 10164 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10165 if (Cand->Specialization) 10166 Cands.push_back(Cand); 10167 // Otherwise, this is a non-matching builtin candidate. We do not, 10168 // in general, want to list every possible builtin candidate. 10169 } 10170 10171 std::sort(Cands.begin(), Cands.end(), 10172 CompareTemplateSpecCandidatesForDisplay(S)); 10173 10174 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10175 // for generalization purposes (?). 10176 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10177 10178 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10179 unsigned CandsShown = 0; 10180 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10181 TemplateSpecCandidate *Cand = *I; 10182 10183 // Set an arbitrary limit on the number of candidates we'll spam 10184 // the user with. FIXME: This limit should depend on details of the 10185 // candidate list. 10186 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10187 break; 10188 ++CandsShown; 10189 10190 assert(Cand->Specialization && 10191 "Non-matching built-in candidates are not added to Cands."); 10192 Cand->NoteDeductionFailure(S, ForTakingAddress); 10193 } 10194 10195 if (I != E) 10196 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10197 } 10198 10199 // [PossiblyAFunctionType] --> [Return] 10200 // NonFunctionType --> NonFunctionType 10201 // R (A) --> R(A) 10202 // R (*)(A) --> R (A) 10203 // R (&)(A) --> R (A) 10204 // R (S::*)(A) --> R (A) 10205 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10206 QualType Ret = PossiblyAFunctionType; 10207 if (const PointerType *ToTypePtr = 10208 PossiblyAFunctionType->getAs<PointerType>()) 10209 Ret = ToTypePtr->getPointeeType(); 10210 else if (const ReferenceType *ToTypeRef = 10211 PossiblyAFunctionType->getAs<ReferenceType>()) 10212 Ret = ToTypeRef->getPointeeType(); 10213 else if (const MemberPointerType *MemTypePtr = 10214 PossiblyAFunctionType->getAs<MemberPointerType>()) 10215 Ret = MemTypePtr->getPointeeType(); 10216 Ret = 10217 Context.getCanonicalType(Ret).getUnqualifiedType(); 10218 return Ret; 10219 } 10220 10221 namespace { 10222 // A helper class to help with address of function resolution 10223 // - allows us to avoid passing around all those ugly parameters 10224 class AddressOfFunctionResolver { 10225 Sema& S; 10226 Expr* SourceExpr; 10227 const QualType& TargetType; 10228 QualType TargetFunctionType; // Extracted function type from target type 10229 10230 bool Complain; 10231 //DeclAccessPair& ResultFunctionAccessPair; 10232 ASTContext& Context; 10233 10234 bool TargetTypeIsNonStaticMemberFunction; 10235 bool FoundNonTemplateFunction; 10236 bool StaticMemberFunctionFromBoundPointer; 10237 bool HasComplained; 10238 10239 OverloadExpr::FindResult OvlExprInfo; 10240 OverloadExpr *OvlExpr; 10241 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10242 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10243 TemplateSpecCandidateSet FailedCandidates; 10244 10245 public: 10246 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10247 const QualType &TargetType, bool Complain) 10248 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10249 Complain(Complain), Context(S.getASTContext()), 10250 TargetTypeIsNonStaticMemberFunction( 10251 !!TargetType->getAs<MemberPointerType>()), 10252 FoundNonTemplateFunction(false), 10253 StaticMemberFunctionFromBoundPointer(false), 10254 HasComplained(false), 10255 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10256 OvlExpr(OvlExprInfo.Expression), 10257 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10258 ExtractUnqualifiedFunctionTypeFromTargetType(); 10259 10260 if (TargetFunctionType->isFunctionType()) { 10261 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10262 if (!UME->isImplicitAccess() && 10263 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10264 StaticMemberFunctionFromBoundPointer = true; 10265 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10266 DeclAccessPair dap; 10267 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10268 OvlExpr, false, &dap)) { 10269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10270 if (!Method->isStatic()) { 10271 // If the target type is a non-function type and the function found 10272 // is a non-static member function, pretend as if that was the 10273 // target, it's the only possible type to end up with. 10274 TargetTypeIsNonStaticMemberFunction = true; 10275 10276 // And skip adding the function if its not in the proper form. 10277 // We'll diagnose this due to an empty set of functions. 10278 if (!OvlExprInfo.HasFormOfMemberPointer) 10279 return; 10280 } 10281 10282 Matches.push_back(std::make_pair(dap, Fn)); 10283 } 10284 return; 10285 } 10286 10287 if (OvlExpr->hasExplicitTemplateArgs()) 10288 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10289 10290 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10291 // C++ [over.over]p4: 10292 // If more than one function is selected, [...] 10293 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10294 if (FoundNonTemplateFunction) 10295 EliminateAllTemplateMatches(); 10296 else 10297 EliminateAllExceptMostSpecializedTemplate(); 10298 } 10299 } 10300 10301 if (S.getLangOpts().CUDA && Matches.size() > 1) 10302 EliminateSuboptimalCudaMatches(); 10303 } 10304 10305 bool hasComplained() const { return HasComplained; } 10306 10307 private: 10308 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10309 QualType Discard; 10310 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10311 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard); 10312 } 10313 10314 /// \return true if A is considered a better overload candidate for the 10315 /// desired type than B. 10316 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10317 // If A doesn't have exactly the correct type, we don't want to classify it 10318 // as "better" than anything else. This way, the user is required to 10319 // disambiguate for us if there are multiple candidates and no exact match. 10320 return candidateHasExactlyCorrectType(A) && 10321 (!candidateHasExactlyCorrectType(B) || 10322 hasBetterEnableIfAttrs(S, A, B)); 10323 } 10324 10325 /// \return true if we were able to eliminate all but one overload candidate, 10326 /// false otherwise. 10327 bool eliminiateSuboptimalOverloadCandidates() { 10328 // Same algorithm as overload resolution -- one pass to pick the "best", 10329 // another pass to be sure that nothing is better than the best. 10330 auto Best = Matches.begin(); 10331 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10332 if (isBetterCandidate(I->second, Best->second)) 10333 Best = I; 10334 10335 const FunctionDecl *BestFn = Best->second; 10336 auto IsBestOrInferiorToBest = [this, BestFn]( 10337 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10338 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10339 }; 10340 10341 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10342 // option, so we can potentially give the user a better error 10343 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10344 return false; 10345 Matches[0] = *Best; 10346 Matches.resize(1); 10347 return true; 10348 } 10349 10350 bool isTargetTypeAFunction() const { 10351 return TargetFunctionType->isFunctionType(); 10352 } 10353 10354 // [ToType] [Return] 10355 10356 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10357 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10358 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10359 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10360 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10361 } 10362 10363 // return true if any matching specializations were found 10364 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10365 const DeclAccessPair& CurAccessFunPair) { 10366 if (CXXMethodDecl *Method 10367 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10368 // Skip non-static function templates when converting to pointer, and 10369 // static when converting to member pointer. 10370 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10371 return false; 10372 } 10373 else if (TargetTypeIsNonStaticMemberFunction) 10374 return false; 10375 10376 // C++ [over.over]p2: 10377 // If the name is a function template, template argument deduction is 10378 // done (14.8.2.2), and if the argument deduction succeeds, the 10379 // resulting template argument list is used to generate a single 10380 // function template specialization, which is added to the set of 10381 // overloaded functions considered. 10382 FunctionDecl *Specialization = nullptr; 10383 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10384 if (Sema::TemplateDeductionResult Result 10385 = S.DeduceTemplateArguments(FunctionTemplate, 10386 &OvlExplicitTemplateArgs, 10387 TargetFunctionType, Specialization, 10388 Info, /*InOverloadResolution=*/true)) { 10389 // Make a note of the failed deduction for diagnostics. 10390 FailedCandidates.addCandidate() 10391 .set(FunctionTemplate->getTemplatedDecl(), 10392 MakeDeductionFailureInfo(Context, Result, Info)); 10393 return false; 10394 } 10395 10396 // Template argument deduction ensures that we have an exact match or 10397 // compatible pointer-to-function arguments that would be adjusted by ICS. 10398 // This function template specicalization works. 10399 assert(S.isSameOrCompatibleFunctionType( 10400 Context.getCanonicalType(Specialization->getType()), 10401 Context.getCanonicalType(TargetFunctionType))); 10402 10403 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10404 return false; 10405 10406 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10407 return true; 10408 } 10409 10410 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10411 const DeclAccessPair& CurAccessFunPair) { 10412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10413 // Skip non-static functions when converting to pointer, and static 10414 // when converting to member pointer. 10415 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10416 return false; 10417 } 10418 else if (TargetTypeIsNonStaticMemberFunction) 10419 return false; 10420 10421 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10422 if (S.getLangOpts().CUDA) 10423 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10424 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10425 return false; 10426 10427 // If any candidate has a placeholder return type, trigger its deduction 10428 // now. 10429 if (S.getLangOpts().CPlusPlus14 && 10430 FunDecl->getReturnType()->isUndeducedType() && 10431 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10432 HasComplained |= Complain; 10433 return false; 10434 } 10435 10436 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10437 return false; 10438 10439 // If we're in C, we need to support types that aren't exactly identical. 10440 if (!S.getLangOpts().CPlusPlus || 10441 candidateHasExactlyCorrectType(FunDecl)) { 10442 Matches.push_back(std::make_pair( 10443 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10444 FoundNonTemplateFunction = true; 10445 return true; 10446 } 10447 } 10448 10449 return false; 10450 } 10451 10452 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10453 bool Ret = false; 10454 10455 // If the overload expression doesn't have the form of a pointer to 10456 // member, don't try to convert it to a pointer-to-member type. 10457 if (IsInvalidFormOfPointerToMemberFunction()) 10458 return false; 10459 10460 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10461 E = OvlExpr->decls_end(); 10462 I != E; ++I) { 10463 // Look through any using declarations to find the underlying function. 10464 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10465 10466 // C++ [over.over]p3: 10467 // Non-member functions and static member functions match 10468 // targets of type "pointer-to-function" or "reference-to-function." 10469 // Nonstatic member functions match targets of 10470 // type "pointer-to-member-function." 10471 // Note that according to DR 247, the containing class does not matter. 10472 if (FunctionTemplateDecl *FunctionTemplate 10473 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10474 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10475 Ret = true; 10476 } 10477 // If we have explicit template arguments supplied, skip non-templates. 10478 else if (!OvlExpr->hasExplicitTemplateArgs() && 10479 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10480 Ret = true; 10481 } 10482 assert(Ret || Matches.empty()); 10483 return Ret; 10484 } 10485 10486 void EliminateAllExceptMostSpecializedTemplate() { 10487 // [...] and any given function template specialization F1 is 10488 // eliminated if the set contains a second function template 10489 // specialization whose function template is more specialized 10490 // than the function template of F1 according to the partial 10491 // ordering rules of 14.5.5.2. 10492 10493 // The algorithm specified above is quadratic. We instead use a 10494 // two-pass algorithm (similar to the one used to identify the 10495 // best viable function in an overload set) that identifies the 10496 // best function template (if it exists). 10497 10498 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10499 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10500 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10501 10502 // TODO: It looks like FailedCandidates does not serve much purpose 10503 // here, since the no_viable diagnostic has index 0. 10504 UnresolvedSetIterator Result = S.getMostSpecialized( 10505 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10506 SourceExpr->getLocStart(), S.PDiag(), 10507 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10508 .second->getDeclName(), 10509 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10510 Complain, TargetFunctionType); 10511 10512 if (Result != MatchesCopy.end()) { 10513 // Make it the first and only element 10514 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10515 Matches[0].second = cast<FunctionDecl>(*Result); 10516 Matches.resize(1); 10517 } else 10518 HasComplained |= Complain; 10519 } 10520 10521 void EliminateAllTemplateMatches() { 10522 // [...] any function template specializations in the set are 10523 // eliminated if the set also contains a non-template function, [...] 10524 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10525 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10526 ++I; 10527 else { 10528 Matches[I] = Matches[--N]; 10529 Matches.resize(N); 10530 } 10531 } 10532 } 10533 10534 void EliminateSuboptimalCudaMatches() { 10535 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10536 } 10537 10538 public: 10539 void ComplainNoMatchesFound() const { 10540 assert(Matches.empty()); 10541 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10542 << OvlExpr->getName() << TargetFunctionType 10543 << OvlExpr->getSourceRange(); 10544 if (FailedCandidates.empty()) 10545 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10546 /*TakingAddress=*/true); 10547 else { 10548 // We have some deduction failure messages. Use them to diagnose 10549 // the function templates, and diagnose the non-template candidates 10550 // normally. 10551 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10552 IEnd = OvlExpr->decls_end(); 10553 I != IEnd; ++I) 10554 if (FunctionDecl *Fun = 10555 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10556 if (!functionHasPassObjectSizeParams(Fun)) 10557 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10558 /*TakingAddress=*/true); 10559 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10560 } 10561 } 10562 10563 bool IsInvalidFormOfPointerToMemberFunction() const { 10564 return TargetTypeIsNonStaticMemberFunction && 10565 !OvlExprInfo.HasFormOfMemberPointer; 10566 } 10567 10568 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10569 // TODO: Should we condition this on whether any functions might 10570 // have matched, or is it more appropriate to do that in callers? 10571 // TODO: a fixit wouldn't hurt. 10572 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10573 << TargetType << OvlExpr->getSourceRange(); 10574 } 10575 10576 bool IsStaticMemberFunctionFromBoundPointer() const { 10577 return StaticMemberFunctionFromBoundPointer; 10578 } 10579 10580 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10581 S.Diag(OvlExpr->getLocStart(), 10582 diag::err_invalid_form_pointer_member_function) 10583 << OvlExpr->getSourceRange(); 10584 } 10585 10586 void ComplainOfInvalidConversion() const { 10587 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10588 << OvlExpr->getName() << TargetType; 10589 } 10590 10591 void ComplainMultipleMatchesFound() const { 10592 assert(Matches.size() > 1); 10593 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10594 << OvlExpr->getName() 10595 << OvlExpr->getSourceRange(); 10596 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10597 /*TakingAddress=*/true); 10598 } 10599 10600 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10601 10602 int getNumMatches() const { return Matches.size(); } 10603 10604 FunctionDecl* getMatchingFunctionDecl() const { 10605 if (Matches.size() != 1) return nullptr; 10606 return Matches[0].second; 10607 } 10608 10609 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10610 if (Matches.size() != 1) return nullptr; 10611 return &Matches[0].first; 10612 } 10613 }; 10614 } 10615 10616 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10617 /// an overloaded function (C++ [over.over]), where @p From is an 10618 /// expression with overloaded function type and @p ToType is the type 10619 /// we're trying to resolve to. For example: 10620 /// 10621 /// @code 10622 /// int f(double); 10623 /// int f(int); 10624 /// 10625 /// int (*pfd)(double) = f; // selects f(double) 10626 /// @endcode 10627 /// 10628 /// This routine returns the resulting FunctionDecl if it could be 10629 /// resolved, and NULL otherwise. When @p Complain is true, this 10630 /// routine will emit diagnostics if there is an error. 10631 FunctionDecl * 10632 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10633 QualType TargetType, 10634 bool Complain, 10635 DeclAccessPair &FoundResult, 10636 bool *pHadMultipleCandidates) { 10637 assert(AddressOfExpr->getType() == Context.OverloadTy); 10638 10639 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10640 Complain); 10641 int NumMatches = Resolver.getNumMatches(); 10642 FunctionDecl *Fn = nullptr; 10643 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10644 if (NumMatches == 0 && ShouldComplain) { 10645 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10646 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10647 else 10648 Resolver.ComplainNoMatchesFound(); 10649 } 10650 else if (NumMatches > 1 && ShouldComplain) 10651 Resolver.ComplainMultipleMatchesFound(); 10652 else if (NumMatches == 1) { 10653 Fn = Resolver.getMatchingFunctionDecl(); 10654 assert(Fn); 10655 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10656 if (Complain) { 10657 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10658 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10659 else 10660 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10661 } 10662 } 10663 10664 if (pHadMultipleCandidates) 10665 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10666 return Fn; 10667 } 10668 10669 /// \brief Given an expression that refers to an overloaded function, try to 10670 /// resolve that function to a single function that can have its address taken. 10671 /// This will modify `Pair` iff it returns non-null. 10672 /// 10673 /// This routine can only realistically succeed if all but one candidates in the 10674 /// overload set for SrcExpr cannot have their addresses taken. 10675 FunctionDecl * 10676 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10677 DeclAccessPair &Pair) { 10678 OverloadExpr::FindResult R = OverloadExpr::find(E); 10679 OverloadExpr *Ovl = R.Expression; 10680 FunctionDecl *Result = nullptr; 10681 DeclAccessPair DAP; 10682 // Don't use the AddressOfResolver because we're specifically looking for 10683 // cases where we have one overload candidate that lacks 10684 // enable_if/pass_object_size/... 10685 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10686 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10687 if (!FD) 10688 return nullptr; 10689 10690 if (!checkAddressOfFunctionIsAvailable(FD)) 10691 continue; 10692 10693 // We have more than one result; quit. 10694 if (Result) 10695 return nullptr; 10696 DAP = I.getPair(); 10697 Result = FD; 10698 } 10699 10700 if (Result) 10701 Pair = DAP; 10702 return Result; 10703 } 10704 10705 /// \brief Given an expression that refers to an overloaded function, try to 10706 /// resolve that overloaded function expression down to a single function. 10707 /// 10708 /// This routine can only resolve template-ids that refer to a single function 10709 /// template, where that template-id refers to a single template whose template 10710 /// arguments are either provided by the template-id or have defaults, 10711 /// as described in C++0x [temp.arg.explicit]p3. 10712 /// 10713 /// If no template-ids are found, no diagnostics are emitted and NULL is 10714 /// returned. 10715 FunctionDecl * 10716 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10717 bool Complain, 10718 DeclAccessPair *FoundResult) { 10719 // C++ [over.over]p1: 10720 // [...] [Note: any redundant set of parentheses surrounding the 10721 // overloaded function name is ignored (5.1). ] 10722 // C++ [over.over]p1: 10723 // [...] The overloaded function name can be preceded by the & 10724 // operator. 10725 10726 // If we didn't actually find any template-ids, we're done. 10727 if (!ovl->hasExplicitTemplateArgs()) 10728 return nullptr; 10729 10730 TemplateArgumentListInfo ExplicitTemplateArgs; 10731 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10732 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10733 10734 // Look through all of the overloaded functions, searching for one 10735 // whose type matches exactly. 10736 FunctionDecl *Matched = nullptr; 10737 for (UnresolvedSetIterator I = ovl->decls_begin(), 10738 E = ovl->decls_end(); I != E; ++I) { 10739 // C++0x [temp.arg.explicit]p3: 10740 // [...] In contexts where deduction is done and fails, or in contexts 10741 // where deduction is not done, if a template argument list is 10742 // specified and it, along with any default template arguments, 10743 // identifies a single function template specialization, then the 10744 // template-id is an lvalue for the function template specialization. 10745 FunctionTemplateDecl *FunctionTemplate 10746 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10747 10748 // C++ [over.over]p2: 10749 // If the name is a function template, template argument deduction is 10750 // done (14.8.2.2), and if the argument deduction succeeds, the 10751 // resulting template argument list is used to generate a single 10752 // function template specialization, which is added to the set of 10753 // overloaded functions considered. 10754 FunctionDecl *Specialization = nullptr; 10755 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10756 if (TemplateDeductionResult Result 10757 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10758 Specialization, Info, 10759 /*InOverloadResolution=*/true)) { 10760 // Make a note of the failed deduction for diagnostics. 10761 // TODO: Actually use the failed-deduction info? 10762 FailedCandidates.addCandidate() 10763 .set(FunctionTemplate->getTemplatedDecl(), 10764 MakeDeductionFailureInfo(Context, Result, Info)); 10765 continue; 10766 } 10767 10768 assert(Specialization && "no specialization and no error?"); 10769 10770 // Multiple matches; we can't resolve to a single declaration. 10771 if (Matched) { 10772 if (Complain) { 10773 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10774 << ovl->getName(); 10775 NoteAllOverloadCandidates(ovl); 10776 } 10777 return nullptr; 10778 } 10779 10780 Matched = Specialization; 10781 if (FoundResult) *FoundResult = I.getPair(); 10782 } 10783 10784 if (Matched && getLangOpts().CPlusPlus14 && 10785 Matched->getReturnType()->isUndeducedType() && 10786 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10787 return nullptr; 10788 10789 return Matched; 10790 } 10791 10792 10793 10794 10795 // Resolve and fix an overloaded expression that can be resolved 10796 // because it identifies a single function template specialization. 10797 // 10798 // Last three arguments should only be supplied if Complain = true 10799 // 10800 // Return true if it was logically possible to so resolve the 10801 // expression, regardless of whether or not it succeeded. Always 10802 // returns true if 'complain' is set. 10803 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10804 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10805 bool complain, SourceRange OpRangeForComplaining, 10806 QualType DestTypeForComplaining, 10807 unsigned DiagIDForComplaining) { 10808 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10809 10810 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10811 10812 DeclAccessPair found; 10813 ExprResult SingleFunctionExpression; 10814 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10815 ovl.Expression, /*complain*/ false, &found)) { 10816 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10817 SrcExpr = ExprError(); 10818 return true; 10819 } 10820 10821 // It is only correct to resolve to an instance method if we're 10822 // resolving a form that's permitted to be a pointer to member. 10823 // Otherwise we'll end up making a bound member expression, which 10824 // is illegal in all the contexts we resolve like this. 10825 if (!ovl.HasFormOfMemberPointer && 10826 isa<CXXMethodDecl>(fn) && 10827 cast<CXXMethodDecl>(fn)->isInstance()) { 10828 if (!complain) return false; 10829 10830 Diag(ovl.Expression->getExprLoc(), 10831 diag::err_bound_member_function) 10832 << 0 << ovl.Expression->getSourceRange(); 10833 10834 // TODO: I believe we only end up here if there's a mix of 10835 // static and non-static candidates (otherwise the expression 10836 // would have 'bound member' type, not 'overload' type). 10837 // Ideally we would note which candidate was chosen and why 10838 // the static candidates were rejected. 10839 SrcExpr = ExprError(); 10840 return true; 10841 } 10842 10843 // Fix the expression to refer to 'fn'. 10844 SingleFunctionExpression = 10845 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10846 10847 // If desired, do function-to-pointer decay. 10848 if (doFunctionPointerConverion) { 10849 SingleFunctionExpression = 10850 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10851 if (SingleFunctionExpression.isInvalid()) { 10852 SrcExpr = ExprError(); 10853 return true; 10854 } 10855 } 10856 } 10857 10858 if (!SingleFunctionExpression.isUsable()) { 10859 if (complain) { 10860 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10861 << ovl.Expression->getName() 10862 << DestTypeForComplaining 10863 << OpRangeForComplaining 10864 << ovl.Expression->getQualifierLoc().getSourceRange(); 10865 NoteAllOverloadCandidates(SrcExpr.get()); 10866 10867 SrcExpr = ExprError(); 10868 return true; 10869 } 10870 10871 return false; 10872 } 10873 10874 SrcExpr = SingleFunctionExpression; 10875 return true; 10876 } 10877 10878 /// \brief Add a single candidate to the overload set. 10879 static void AddOverloadedCallCandidate(Sema &S, 10880 DeclAccessPair FoundDecl, 10881 TemplateArgumentListInfo *ExplicitTemplateArgs, 10882 ArrayRef<Expr *> Args, 10883 OverloadCandidateSet &CandidateSet, 10884 bool PartialOverloading, 10885 bool KnownValid) { 10886 NamedDecl *Callee = FoundDecl.getDecl(); 10887 if (isa<UsingShadowDecl>(Callee)) 10888 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10889 10890 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10891 if (ExplicitTemplateArgs) { 10892 assert(!KnownValid && "Explicit template arguments?"); 10893 return; 10894 } 10895 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10896 /*SuppressUsedConversions=*/false, 10897 PartialOverloading); 10898 return; 10899 } 10900 10901 if (FunctionTemplateDecl *FuncTemplate 10902 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10903 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10904 ExplicitTemplateArgs, Args, CandidateSet, 10905 /*SuppressUsedConversions=*/false, 10906 PartialOverloading); 10907 return; 10908 } 10909 10910 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10911 } 10912 10913 /// \brief Add the overload candidates named by callee and/or found by argument 10914 /// dependent lookup to the given overload set. 10915 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10916 ArrayRef<Expr *> Args, 10917 OverloadCandidateSet &CandidateSet, 10918 bool PartialOverloading) { 10919 10920 #ifndef NDEBUG 10921 // Verify that ArgumentDependentLookup is consistent with the rules 10922 // in C++0x [basic.lookup.argdep]p3: 10923 // 10924 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10925 // and let Y be the lookup set produced by argument dependent 10926 // lookup (defined as follows). If X contains 10927 // 10928 // -- a declaration of a class member, or 10929 // 10930 // -- a block-scope function declaration that is not a 10931 // using-declaration, or 10932 // 10933 // -- a declaration that is neither a function or a function 10934 // template 10935 // 10936 // then Y is empty. 10937 10938 if (ULE->requiresADL()) { 10939 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10940 E = ULE->decls_end(); I != E; ++I) { 10941 assert(!(*I)->getDeclContext()->isRecord()); 10942 assert(isa<UsingShadowDecl>(*I) || 10943 !(*I)->getDeclContext()->isFunctionOrMethod()); 10944 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10945 } 10946 } 10947 #endif 10948 10949 // It would be nice to avoid this copy. 10950 TemplateArgumentListInfo TABuffer; 10951 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10952 if (ULE->hasExplicitTemplateArgs()) { 10953 ULE->copyTemplateArgumentsInto(TABuffer); 10954 ExplicitTemplateArgs = &TABuffer; 10955 } 10956 10957 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10958 E = ULE->decls_end(); I != E; ++I) 10959 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10960 CandidateSet, PartialOverloading, 10961 /*KnownValid*/ true); 10962 10963 if (ULE->requiresADL()) 10964 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10965 Args, ExplicitTemplateArgs, 10966 CandidateSet, PartialOverloading); 10967 } 10968 10969 /// Determine whether a declaration with the specified name could be moved into 10970 /// a different namespace. 10971 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10972 switch (Name.getCXXOverloadedOperator()) { 10973 case OO_New: case OO_Array_New: 10974 case OO_Delete: case OO_Array_Delete: 10975 return false; 10976 10977 default: 10978 return true; 10979 } 10980 } 10981 10982 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10983 /// template, where the non-dependent name was declared after the template 10984 /// was defined. This is common in code written for a compilers which do not 10985 /// correctly implement two-stage name lookup. 10986 /// 10987 /// Returns true if a viable candidate was found and a diagnostic was issued. 10988 static bool 10989 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10990 const CXXScopeSpec &SS, LookupResult &R, 10991 OverloadCandidateSet::CandidateSetKind CSK, 10992 TemplateArgumentListInfo *ExplicitTemplateArgs, 10993 ArrayRef<Expr *> Args, 10994 bool *DoDiagnoseEmptyLookup = nullptr) { 10995 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10996 return false; 10997 10998 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10999 if (DC->isTransparentContext()) 11000 continue; 11001 11002 SemaRef.LookupQualifiedName(R, DC); 11003 11004 if (!R.empty()) { 11005 R.suppressDiagnostics(); 11006 11007 if (isa<CXXRecordDecl>(DC)) { 11008 // Don't diagnose names we find in classes; we get much better 11009 // diagnostics for these from DiagnoseEmptyLookup. 11010 R.clear(); 11011 if (DoDiagnoseEmptyLookup) 11012 *DoDiagnoseEmptyLookup = true; 11013 return false; 11014 } 11015 11016 OverloadCandidateSet Candidates(FnLoc, CSK); 11017 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11018 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11019 ExplicitTemplateArgs, Args, 11020 Candidates, false, /*KnownValid*/ false); 11021 11022 OverloadCandidateSet::iterator Best; 11023 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11024 // No viable functions. Don't bother the user with notes for functions 11025 // which don't work and shouldn't be found anyway. 11026 R.clear(); 11027 return false; 11028 } 11029 11030 // Find the namespaces where ADL would have looked, and suggest 11031 // declaring the function there instead. 11032 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11033 Sema::AssociatedClassSet AssociatedClasses; 11034 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11035 AssociatedNamespaces, 11036 AssociatedClasses); 11037 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11038 if (canBeDeclaredInNamespace(R.getLookupName())) { 11039 DeclContext *Std = SemaRef.getStdNamespace(); 11040 for (Sema::AssociatedNamespaceSet::iterator 11041 it = AssociatedNamespaces.begin(), 11042 end = AssociatedNamespaces.end(); it != end; ++it) { 11043 // Never suggest declaring a function within namespace 'std'. 11044 if (Std && Std->Encloses(*it)) 11045 continue; 11046 11047 // Never suggest declaring a function within a namespace with a 11048 // reserved name, like __gnu_cxx. 11049 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11050 if (NS && 11051 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11052 continue; 11053 11054 SuggestedNamespaces.insert(*it); 11055 } 11056 } 11057 11058 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11059 << R.getLookupName(); 11060 if (SuggestedNamespaces.empty()) { 11061 SemaRef.Diag(Best->Function->getLocation(), 11062 diag::note_not_found_by_two_phase_lookup) 11063 << R.getLookupName() << 0; 11064 } else if (SuggestedNamespaces.size() == 1) { 11065 SemaRef.Diag(Best->Function->getLocation(), 11066 diag::note_not_found_by_two_phase_lookup) 11067 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11068 } else { 11069 // FIXME: It would be useful to list the associated namespaces here, 11070 // but the diagnostics infrastructure doesn't provide a way to produce 11071 // a localized representation of a list of items. 11072 SemaRef.Diag(Best->Function->getLocation(), 11073 diag::note_not_found_by_two_phase_lookup) 11074 << R.getLookupName() << 2; 11075 } 11076 11077 // Try to recover by calling this function. 11078 return true; 11079 } 11080 11081 R.clear(); 11082 } 11083 11084 return false; 11085 } 11086 11087 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11088 /// template, where the non-dependent operator was declared after the template 11089 /// was defined. 11090 /// 11091 /// Returns true if a viable candidate was found and a diagnostic was issued. 11092 static bool 11093 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11094 SourceLocation OpLoc, 11095 ArrayRef<Expr *> Args) { 11096 DeclarationName OpName = 11097 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11098 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11099 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11100 OverloadCandidateSet::CSK_Operator, 11101 /*ExplicitTemplateArgs=*/nullptr, Args); 11102 } 11103 11104 namespace { 11105 class BuildRecoveryCallExprRAII { 11106 Sema &SemaRef; 11107 public: 11108 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11109 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11110 SemaRef.IsBuildingRecoveryCallExpr = true; 11111 } 11112 11113 ~BuildRecoveryCallExprRAII() { 11114 SemaRef.IsBuildingRecoveryCallExpr = false; 11115 } 11116 }; 11117 11118 } 11119 11120 static std::unique_ptr<CorrectionCandidateCallback> 11121 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11122 bool HasTemplateArgs, bool AllowTypoCorrection) { 11123 if (!AllowTypoCorrection) 11124 return llvm::make_unique<NoTypoCorrectionCCC>(); 11125 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11126 HasTemplateArgs, ME); 11127 } 11128 11129 /// Attempts to recover from a call where no functions were found. 11130 /// 11131 /// Returns true if new candidates were found. 11132 static ExprResult 11133 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11134 UnresolvedLookupExpr *ULE, 11135 SourceLocation LParenLoc, 11136 MutableArrayRef<Expr *> Args, 11137 SourceLocation RParenLoc, 11138 bool EmptyLookup, bool AllowTypoCorrection) { 11139 // Do not try to recover if it is already building a recovery call. 11140 // This stops infinite loops for template instantiations like 11141 // 11142 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11143 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11144 // 11145 if (SemaRef.IsBuildingRecoveryCallExpr) 11146 return ExprError(); 11147 BuildRecoveryCallExprRAII RCE(SemaRef); 11148 11149 CXXScopeSpec SS; 11150 SS.Adopt(ULE->getQualifierLoc()); 11151 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11152 11153 TemplateArgumentListInfo TABuffer; 11154 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11155 if (ULE->hasExplicitTemplateArgs()) { 11156 ULE->copyTemplateArgumentsInto(TABuffer); 11157 ExplicitTemplateArgs = &TABuffer; 11158 } 11159 11160 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11161 Sema::LookupOrdinaryName); 11162 bool DoDiagnoseEmptyLookup = EmptyLookup; 11163 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11164 OverloadCandidateSet::CSK_Normal, 11165 ExplicitTemplateArgs, Args, 11166 &DoDiagnoseEmptyLookup) && 11167 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11168 S, SS, R, 11169 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11170 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11171 ExplicitTemplateArgs, Args))) 11172 return ExprError(); 11173 11174 assert(!R.empty() && "lookup results empty despite recovery"); 11175 11176 // Build an implicit member call if appropriate. Just drop the 11177 // casts and such from the call, we don't really care. 11178 ExprResult NewFn = ExprError(); 11179 if ((*R.begin())->isCXXClassMember()) 11180 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11181 ExplicitTemplateArgs, S); 11182 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11183 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11184 ExplicitTemplateArgs); 11185 else 11186 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11187 11188 if (NewFn.isInvalid()) 11189 return ExprError(); 11190 11191 // This shouldn't cause an infinite loop because we're giving it 11192 // an expression with viable lookup results, which should never 11193 // end up here. 11194 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11195 MultiExprArg(Args.data(), Args.size()), 11196 RParenLoc); 11197 } 11198 11199 /// \brief Constructs and populates an OverloadedCandidateSet from 11200 /// the given function. 11201 /// \returns true when an the ExprResult output parameter has been set. 11202 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11203 UnresolvedLookupExpr *ULE, 11204 MultiExprArg Args, 11205 SourceLocation RParenLoc, 11206 OverloadCandidateSet *CandidateSet, 11207 ExprResult *Result) { 11208 #ifndef NDEBUG 11209 if (ULE->requiresADL()) { 11210 // To do ADL, we must have found an unqualified name. 11211 assert(!ULE->getQualifier() && "qualified name with ADL"); 11212 11213 // We don't perform ADL for implicit declarations of builtins. 11214 // Verify that this was correctly set up. 11215 FunctionDecl *F; 11216 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11217 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11218 F->getBuiltinID() && F->isImplicit()) 11219 llvm_unreachable("performing ADL for builtin"); 11220 11221 // We don't perform ADL in C. 11222 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11223 } 11224 #endif 11225 11226 UnbridgedCastsSet UnbridgedCasts; 11227 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11228 *Result = ExprError(); 11229 return true; 11230 } 11231 11232 // Add the functions denoted by the callee to the set of candidate 11233 // functions, including those from argument-dependent lookup. 11234 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11235 11236 if (getLangOpts().MSVCCompat && 11237 CurContext->isDependentContext() && !isSFINAEContext() && 11238 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11239 11240 OverloadCandidateSet::iterator Best; 11241 if (CandidateSet->empty() || 11242 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11243 OR_No_Viable_Function) { 11244 // In Microsoft mode, if we are inside a template class member function then 11245 // create a type dependent CallExpr. The goal is to postpone name lookup 11246 // to instantiation time to be able to search into type dependent base 11247 // classes. 11248 CallExpr *CE = new (Context) CallExpr( 11249 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11250 CE->setTypeDependent(true); 11251 CE->setValueDependent(true); 11252 CE->setInstantiationDependent(true); 11253 *Result = CE; 11254 return true; 11255 } 11256 } 11257 11258 if (CandidateSet->empty()) 11259 return false; 11260 11261 UnbridgedCasts.restore(); 11262 return false; 11263 } 11264 11265 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11266 /// the completed call expression. If overload resolution fails, emits 11267 /// diagnostics and returns ExprError() 11268 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11269 UnresolvedLookupExpr *ULE, 11270 SourceLocation LParenLoc, 11271 MultiExprArg Args, 11272 SourceLocation RParenLoc, 11273 Expr *ExecConfig, 11274 OverloadCandidateSet *CandidateSet, 11275 OverloadCandidateSet::iterator *Best, 11276 OverloadingResult OverloadResult, 11277 bool AllowTypoCorrection) { 11278 if (CandidateSet->empty()) 11279 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11280 RParenLoc, /*EmptyLookup=*/true, 11281 AllowTypoCorrection); 11282 11283 switch (OverloadResult) { 11284 case OR_Success: { 11285 FunctionDecl *FDecl = (*Best)->Function; 11286 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11287 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11288 return ExprError(); 11289 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11290 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11291 ExecConfig); 11292 } 11293 11294 case OR_No_Viable_Function: { 11295 // Try to recover by looking for viable functions which the user might 11296 // have meant to call. 11297 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11298 Args, RParenLoc, 11299 /*EmptyLookup=*/false, 11300 AllowTypoCorrection); 11301 if (!Recovery.isInvalid()) 11302 return Recovery; 11303 11304 // If the user passes in a function that we can't take the address of, we 11305 // generally end up emitting really bad error messages. Here, we attempt to 11306 // emit better ones. 11307 for (const Expr *Arg : Args) { 11308 if (!Arg->getType()->isFunctionType()) 11309 continue; 11310 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11311 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11312 if (FD && 11313 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11314 Arg->getExprLoc())) 11315 return ExprError(); 11316 } 11317 } 11318 11319 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11320 << ULE->getName() << Fn->getSourceRange(); 11321 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11322 break; 11323 } 11324 11325 case OR_Ambiguous: 11326 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11327 << ULE->getName() << Fn->getSourceRange(); 11328 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11329 break; 11330 11331 case OR_Deleted: { 11332 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11333 << (*Best)->Function->isDeleted() 11334 << ULE->getName() 11335 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11336 << Fn->getSourceRange(); 11337 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11338 11339 // We emitted an error for the unvailable/deleted function call but keep 11340 // the call in the AST. 11341 FunctionDecl *FDecl = (*Best)->Function; 11342 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11343 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11344 ExecConfig); 11345 } 11346 } 11347 11348 // Overload resolution failed. 11349 return ExprError(); 11350 } 11351 11352 static void markUnaddressableCandidatesUnviable(Sema &S, 11353 OverloadCandidateSet &CS) { 11354 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11355 if (I->Viable && 11356 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11357 I->Viable = false; 11358 I->FailureKind = ovl_fail_addr_not_available; 11359 } 11360 } 11361 } 11362 11363 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11364 /// (which eventually refers to the declaration Func) and the call 11365 /// arguments Args/NumArgs, attempt to resolve the function call down 11366 /// to a specific function. If overload resolution succeeds, returns 11367 /// the call expression produced by overload resolution. 11368 /// Otherwise, emits diagnostics and returns ExprError. 11369 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11370 UnresolvedLookupExpr *ULE, 11371 SourceLocation LParenLoc, 11372 MultiExprArg Args, 11373 SourceLocation RParenLoc, 11374 Expr *ExecConfig, 11375 bool AllowTypoCorrection, 11376 bool CalleesAddressIsTaken) { 11377 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11378 OverloadCandidateSet::CSK_Normal); 11379 ExprResult result; 11380 11381 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11382 &result)) 11383 return result; 11384 11385 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11386 // functions that aren't addressible are considered unviable. 11387 if (CalleesAddressIsTaken) 11388 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11389 11390 OverloadCandidateSet::iterator Best; 11391 OverloadingResult OverloadResult = 11392 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11393 11394 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11395 RParenLoc, ExecConfig, &CandidateSet, 11396 &Best, OverloadResult, 11397 AllowTypoCorrection); 11398 } 11399 11400 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11401 return Functions.size() > 1 || 11402 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11403 } 11404 11405 /// \brief Create a unary operation that may resolve to an overloaded 11406 /// operator. 11407 /// 11408 /// \param OpLoc The location of the operator itself (e.g., '*'). 11409 /// 11410 /// \param Opc The UnaryOperatorKind that describes this operator. 11411 /// 11412 /// \param Fns The set of non-member functions that will be 11413 /// considered by overload resolution. The caller needs to build this 11414 /// set based on the context using, e.g., 11415 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11416 /// set should not contain any member functions; those will be added 11417 /// by CreateOverloadedUnaryOp(). 11418 /// 11419 /// \param Input The input argument. 11420 ExprResult 11421 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11422 const UnresolvedSetImpl &Fns, 11423 Expr *Input) { 11424 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11425 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11426 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11427 // TODO: provide better source location info. 11428 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11429 11430 if (checkPlaceholderForOverload(*this, Input)) 11431 return ExprError(); 11432 11433 Expr *Args[2] = { Input, nullptr }; 11434 unsigned NumArgs = 1; 11435 11436 // For post-increment and post-decrement, add the implicit '0' as 11437 // the second argument, so that we know this is a post-increment or 11438 // post-decrement. 11439 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11440 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11441 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11442 SourceLocation()); 11443 NumArgs = 2; 11444 } 11445 11446 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11447 11448 if (Input->isTypeDependent()) { 11449 if (Fns.empty()) 11450 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11451 VK_RValue, OK_Ordinary, OpLoc); 11452 11453 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11454 UnresolvedLookupExpr *Fn 11455 = UnresolvedLookupExpr::Create(Context, NamingClass, 11456 NestedNameSpecifierLoc(), OpNameInfo, 11457 /*ADL*/ true, IsOverloaded(Fns), 11458 Fns.begin(), Fns.end()); 11459 return new (Context) 11460 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11461 VK_RValue, OpLoc, false); 11462 } 11463 11464 // Build an empty overload set. 11465 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11466 11467 // Add the candidates from the given function set. 11468 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11469 11470 // Add operator candidates that are member functions. 11471 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11472 11473 // Add candidates from ADL. 11474 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11475 /*ExplicitTemplateArgs*/nullptr, 11476 CandidateSet); 11477 11478 // Add builtin operator candidates. 11479 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11480 11481 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11482 11483 // Perform overload resolution. 11484 OverloadCandidateSet::iterator Best; 11485 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11486 case OR_Success: { 11487 // We found a built-in operator or an overloaded operator. 11488 FunctionDecl *FnDecl = Best->Function; 11489 11490 if (FnDecl) { 11491 // We matched an overloaded operator. Build a call to that 11492 // operator. 11493 11494 // Convert the arguments. 11495 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11496 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11497 11498 ExprResult InputRes = 11499 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11500 Best->FoundDecl, Method); 11501 if (InputRes.isInvalid()) 11502 return ExprError(); 11503 Input = InputRes.get(); 11504 } else { 11505 // Convert the arguments. 11506 ExprResult InputInit 11507 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11508 Context, 11509 FnDecl->getParamDecl(0)), 11510 SourceLocation(), 11511 Input); 11512 if (InputInit.isInvalid()) 11513 return ExprError(); 11514 Input = InputInit.get(); 11515 } 11516 11517 // Build the actual expression node. 11518 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11519 HadMultipleCandidates, OpLoc); 11520 if (FnExpr.isInvalid()) 11521 return ExprError(); 11522 11523 // Determine the result type. 11524 QualType ResultTy = FnDecl->getReturnType(); 11525 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11526 ResultTy = ResultTy.getNonLValueExprType(Context); 11527 11528 Args[0] = Input; 11529 CallExpr *TheCall = 11530 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11531 ResultTy, VK, OpLoc, false); 11532 11533 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11534 return ExprError(); 11535 11536 return MaybeBindToTemporary(TheCall); 11537 } else { 11538 // We matched a built-in operator. Convert the arguments, then 11539 // break out so that we will build the appropriate built-in 11540 // operator node. 11541 ExprResult InputRes = 11542 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11543 Best->Conversions[0], AA_Passing); 11544 if (InputRes.isInvalid()) 11545 return ExprError(); 11546 Input = InputRes.get(); 11547 break; 11548 } 11549 } 11550 11551 case OR_No_Viable_Function: 11552 // This is an erroneous use of an operator which can be overloaded by 11553 // a non-member function. Check for non-member operators which were 11554 // defined too late to be candidates. 11555 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11556 // FIXME: Recover by calling the found function. 11557 return ExprError(); 11558 11559 // No viable function; fall through to handling this as a 11560 // built-in operator, which will produce an error message for us. 11561 break; 11562 11563 case OR_Ambiguous: 11564 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11565 << UnaryOperator::getOpcodeStr(Opc) 11566 << Input->getType() 11567 << Input->getSourceRange(); 11568 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11569 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11570 return ExprError(); 11571 11572 case OR_Deleted: 11573 Diag(OpLoc, diag::err_ovl_deleted_oper) 11574 << Best->Function->isDeleted() 11575 << UnaryOperator::getOpcodeStr(Opc) 11576 << getDeletedOrUnavailableSuffix(Best->Function) 11577 << Input->getSourceRange(); 11578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11579 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11580 return ExprError(); 11581 } 11582 11583 // Either we found no viable overloaded operator or we matched a 11584 // built-in operator. In either case, fall through to trying to 11585 // build a built-in operation. 11586 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11587 } 11588 11589 /// \brief Create a binary operation that may resolve to an overloaded 11590 /// operator. 11591 /// 11592 /// \param OpLoc The location of the operator itself (e.g., '+'). 11593 /// 11594 /// \param Opc The BinaryOperatorKind that describes this operator. 11595 /// 11596 /// \param Fns The set of non-member functions that will be 11597 /// considered by overload resolution. The caller needs to build this 11598 /// set based on the context using, e.g., 11599 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11600 /// set should not contain any member functions; those will be added 11601 /// by CreateOverloadedBinOp(). 11602 /// 11603 /// \param LHS Left-hand argument. 11604 /// \param RHS Right-hand argument. 11605 ExprResult 11606 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11607 BinaryOperatorKind Opc, 11608 const UnresolvedSetImpl &Fns, 11609 Expr *LHS, Expr *RHS) { 11610 Expr *Args[2] = { LHS, RHS }; 11611 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11612 11613 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11614 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11615 11616 // If either side is type-dependent, create an appropriate dependent 11617 // expression. 11618 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11619 if (Fns.empty()) { 11620 // If there are no functions to store, just build a dependent 11621 // BinaryOperator or CompoundAssignment. 11622 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11623 return new (Context) BinaryOperator( 11624 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11625 OpLoc, FPFeatures.fp_contract); 11626 11627 return new (Context) CompoundAssignOperator( 11628 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11629 Context.DependentTy, Context.DependentTy, OpLoc, 11630 FPFeatures.fp_contract); 11631 } 11632 11633 // FIXME: save results of ADL from here? 11634 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11635 // TODO: provide better source location info in DNLoc component. 11636 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11637 UnresolvedLookupExpr *Fn 11638 = UnresolvedLookupExpr::Create(Context, NamingClass, 11639 NestedNameSpecifierLoc(), OpNameInfo, 11640 /*ADL*/ true, IsOverloaded(Fns), 11641 Fns.begin(), Fns.end()); 11642 return new (Context) 11643 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11644 VK_RValue, OpLoc, FPFeatures.fp_contract); 11645 } 11646 11647 // Always do placeholder-like conversions on the RHS. 11648 if (checkPlaceholderForOverload(*this, Args[1])) 11649 return ExprError(); 11650 11651 // Do placeholder-like conversion on the LHS; note that we should 11652 // not get here with a PseudoObject LHS. 11653 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11654 if (checkPlaceholderForOverload(*this, Args[0])) 11655 return ExprError(); 11656 11657 // If this is the assignment operator, we only perform overload resolution 11658 // if the left-hand side is a class or enumeration type. This is actually 11659 // a hack. The standard requires that we do overload resolution between the 11660 // various built-in candidates, but as DR507 points out, this can lead to 11661 // problems. So we do it this way, which pretty much follows what GCC does. 11662 // Note that we go the traditional code path for compound assignment forms. 11663 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11664 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11665 11666 // If this is the .* operator, which is not overloadable, just 11667 // create a built-in binary operator. 11668 if (Opc == BO_PtrMemD) 11669 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11670 11671 // Build an empty overload set. 11672 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11673 11674 // Add the candidates from the given function set. 11675 AddFunctionCandidates(Fns, Args, CandidateSet); 11676 11677 // Add operator candidates that are member functions. 11678 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11679 11680 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11681 // performed for an assignment operator (nor for operator[] nor operator->, 11682 // which don't get here). 11683 if (Opc != BO_Assign) 11684 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11685 /*ExplicitTemplateArgs*/ nullptr, 11686 CandidateSet); 11687 11688 // Add builtin operator candidates. 11689 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11690 11691 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11692 11693 // Perform overload resolution. 11694 OverloadCandidateSet::iterator Best; 11695 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11696 case OR_Success: { 11697 // We found a built-in operator or an overloaded operator. 11698 FunctionDecl *FnDecl = Best->Function; 11699 11700 if (FnDecl) { 11701 // We matched an overloaded operator. Build a call to that 11702 // operator. 11703 11704 // Convert the arguments. 11705 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11706 // Best->Access is only meaningful for class members. 11707 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11708 11709 ExprResult Arg1 = 11710 PerformCopyInitialization( 11711 InitializedEntity::InitializeParameter(Context, 11712 FnDecl->getParamDecl(0)), 11713 SourceLocation(), Args[1]); 11714 if (Arg1.isInvalid()) 11715 return ExprError(); 11716 11717 ExprResult Arg0 = 11718 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11719 Best->FoundDecl, Method); 11720 if (Arg0.isInvalid()) 11721 return ExprError(); 11722 Args[0] = Arg0.getAs<Expr>(); 11723 Args[1] = RHS = Arg1.getAs<Expr>(); 11724 } else { 11725 // Convert the arguments. 11726 ExprResult Arg0 = PerformCopyInitialization( 11727 InitializedEntity::InitializeParameter(Context, 11728 FnDecl->getParamDecl(0)), 11729 SourceLocation(), Args[0]); 11730 if (Arg0.isInvalid()) 11731 return ExprError(); 11732 11733 ExprResult Arg1 = 11734 PerformCopyInitialization( 11735 InitializedEntity::InitializeParameter(Context, 11736 FnDecl->getParamDecl(1)), 11737 SourceLocation(), Args[1]); 11738 if (Arg1.isInvalid()) 11739 return ExprError(); 11740 Args[0] = LHS = Arg0.getAs<Expr>(); 11741 Args[1] = RHS = Arg1.getAs<Expr>(); 11742 } 11743 11744 // Build the actual expression node. 11745 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11746 Best->FoundDecl, 11747 HadMultipleCandidates, OpLoc); 11748 if (FnExpr.isInvalid()) 11749 return ExprError(); 11750 11751 // Determine the result type. 11752 QualType ResultTy = FnDecl->getReturnType(); 11753 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11754 ResultTy = ResultTy.getNonLValueExprType(Context); 11755 11756 CXXOperatorCallExpr *TheCall = 11757 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11758 Args, ResultTy, VK, OpLoc, 11759 FPFeatures.fp_contract); 11760 11761 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11762 FnDecl)) 11763 return ExprError(); 11764 11765 ArrayRef<const Expr *> ArgsArray(Args, 2); 11766 // Cut off the implicit 'this'. 11767 if (isa<CXXMethodDecl>(FnDecl)) 11768 ArgsArray = ArgsArray.slice(1); 11769 11770 // Check for a self move. 11771 if (Op == OO_Equal) 11772 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11773 11774 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11775 TheCall->getSourceRange(), VariadicDoesNotApply); 11776 11777 return MaybeBindToTemporary(TheCall); 11778 } else { 11779 // We matched a built-in operator. Convert the arguments, then 11780 // break out so that we will build the appropriate built-in 11781 // operator node. 11782 ExprResult ArgsRes0 = 11783 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11784 Best->Conversions[0], AA_Passing); 11785 if (ArgsRes0.isInvalid()) 11786 return ExprError(); 11787 Args[0] = ArgsRes0.get(); 11788 11789 ExprResult ArgsRes1 = 11790 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11791 Best->Conversions[1], AA_Passing); 11792 if (ArgsRes1.isInvalid()) 11793 return ExprError(); 11794 Args[1] = ArgsRes1.get(); 11795 break; 11796 } 11797 } 11798 11799 case OR_No_Viable_Function: { 11800 // C++ [over.match.oper]p9: 11801 // If the operator is the operator , [...] and there are no 11802 // viable functions, then the operator is assumed to be the 11803 // built-in operator and interpreted according to clause 5. 11804 if (Opc == BO_Comma) 11805 break; 11806 11807 // For class as left operand for assignment or compound assigment 11808 // operator do not fall through to handling in built-in, but report that 11809 // no overloaded assignment operator found 11810 ExprResult Result = ExprError(); 11811 if (Args[0]->getType()->isRecordType() && 11812 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11813 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11814 << BinaryOperator::getOpcodeStr(Opc) 11815 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11816 if (Args[0]->getType()->isIncompleteType()) { 11817 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11818 << Args[0]->getType() 11819 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11820 } 11821 } else { 11822 // This is an erroneous use of an operator which can be overloaded by 11823 // a non-member function. Check for non-member operators which were 11824 // defined too late to be candidates. 11825 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11826 // FIXME: Recover by calling the found function. 11827 return ExprError(); 11828 11829 // No viable function; try to create a built-in operation, which will 11830 // produce an error. Then, show the non-viable candidates. 11831 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11832 } 11833 assert(Result.isInvalid() && 11834 "C++ binary operator overloading is missing candidates!"); 11835 if (Result.isInvalid()) 11836 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11837 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11838 return Result; 11839 } 11840 11841 case OR_Ambiguous: 11842 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11843 << BinaryOperator::getOpcodeStr(Opc) 11844 << Args[0]->getType() << Args[1]->getType() 11845 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11846 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11847 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11848 return ExprError(); 11849 11850 case OR_Deleted: 11851 if (isImplicitlyDeleted(Best->Function)) { 11852 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11853 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11854 << Context.getRecordType(Method->getParent()) 11855 << getSpecialMember(Method); 11856 11857 // The user probably meant to call this special member. Just 11858 // explain why it's deleted. 11859 NoteDeletedFunction(Method); 11860 return ExprError(); 11861 } else { 11862 Diag(OpLoc, diag::err_ovl_deleted_oper) 11863 << Best->Function->isDeleted() 11864 << BinaryOperator::getOpcodeStr(Opc) 11865 << getDeletedOrUnavailableSuffix(Best->Function) 11866 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11867 } 11868 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11869 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11870 return ExprError(); 11871 } 11872 11873 // We matched a built-in operator; build it. 11874 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11875 } 11876 11877 ExprResult 11878 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11879 SourceLocation RLoc, 11880 Expr *Base, Expr *Idx) { 11881 Expr *Args[2] = { Base, Idx }; 11882 DeclarationName OpName = 11883 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11884 11885 // If either side is type-dependent, create an appropriate dependent 11886 // expression. 11887 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11888 11889 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11890 // CHECKME: no 'operator' keyword? 11891 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11892 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11893 UnresolvedLookupExpr *Fn 11894 = UnresolvedLookupExpr::Create(Context, NamingClass, 11895 NestedNameSpecifierLoc(), OpNameInfo, 11896 /*ADL*/ true, /*Overloaded*/ false, 11897 UnresolvedSetIterator(), 11898 UnresolvedSetIterator()); 11899 // Can't add any actual overloads yet 11900 11901 return new (Context) 11902 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11903 Context.DependentTy, VK_RValue, RLoc, false); 11904 } 11905 11906 // Handle placeholders on both operands. 11907 if (checkPlaceholderForOverload(*this, Args[0])) 11908 return ExprError(); 11909 if (checkPlaceholderForOverload(*this, Args[1])) 11910 return ExprError(); 11911 11912 // Build an empty overload set. 11913 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11914 11915 // Subscript can only be overloaded as a member function. 11916 11917 // Add operator candidates that are member functions. 11918 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11919 11920 // Add builtin operator candidates. 11921 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11922 11923 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11924 11925 // Perform overload resolution. 11926 OverloadCandidateSet::iterator Best; 11927 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11928 case OR_Success: { 11929 // We found a built-in operator or an overloaded operator. 11930 FunctionDecl *FnDecl = Best->Function; 11931 11932 if (FnDecl) { 11933 // We matched an overloaded operator. Build a call to that 11934 // operator. 11935 11936 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11937 11938 // Convert the arguments. 11939 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11940 ExprResult Arg0 = 11941 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11942 Best->FoundDecl, Method); 11943 if (Arg0.isInvalid()) 11944 return ExprError(); 11945 Args[0] = Arg0.get(); 11946 11947 // Convert the arguments. 11948 ExprResult InputInit 11949 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11950 Context, 11951 FnDecl->getParamDecl(0)), 11952 SourceLocation(), 11953 Args[1]); 11954 if (InputInit.isInvalid()) 11955 return ExprError(); 11956 11957 Args[1] = InputInit.getAs<Expr>(); 11958 11959 // Build the actual expression node. 11960 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11961 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11962 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11963 Best->FoundDecl, 11964 HadMultipleCandidates, 11965 OpLocInfo.getLoc(), 11966 OpLocInfo.getInfo()); 11967 if (FnExpr.isInvalid()) 11968 return ExprError(); 11969 11970 // Determine the result type 11971 QualType ResultTy = FnDecl->getReturnType(); 11972 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11973 ResultTy = ResultTy.getNonLValueExprType(Context); 11974 11975 CXXOperatorCallExpr *TheCall = 11976 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11977 FnExpr.get(), Args, 11978 ResultTy, VK, RLoc, 11979 false); 11980 11981 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11982 return ExprError(); 11983 11984 return MaybeBindToTemporary(TheCall); 11985 } else { 11986 // We matched a built-in operator. Convert the arguments, then 11987 // break out so that we will build the appropriate built-in 11988 // operator node. 11989 ExprResult ArgsRes0 = 11990 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11991 Best->Conversions[0], AA_Passing); 11992 if (ArgsRes0.isInvalid()) 11993 return ExprError(); 11994 Args[0] = ArgsRes0.get(); 11995 11996 ExprResult ArgsRes1 = 11997 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11998 Best->Conversions[1], AA_Passing); 11999 if (ArgsRes1.isInvalid()) 12000 return ExprError(); 12001 Args[1] = ArgsRes1.get(); 12002 12003 break; 12004 } 12005 } 12006 12007 case OR_No_Viable_Function: { 12008 if (CandidateSet.empty()) 12009 Diag(LLoc, diag::err_ovl_no_oper) 12010 << Args[0]->getType() << /*subscript*/ 0 12011 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12012 else 12013 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12014 << Args[0]->getType() 12015 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12016 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12017 "[]", LLoc); 12018 return ExprError(); 12019 } 12020 12021 case OR_Ambiguous: 12022 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12023 << "[]" 12024 << Args[0]->getType() << Args[1]->getType() 12025 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12026 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12027 "[]", LLoc); 12028 return ExprError(); 12029 12030 case OR_Deleted: 12031 Diag(LLoc, diag::err_ovl_deleted_oper) 12032 << Best->Function->isDeleted() << "[]" 12033 << getDeletedOrUnavailableSuffix(Best->Function) 12034 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12035 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12036 "[]", LLoc); 12037 return ExprError(); 12038 } 12039 12040 // We matched a built-in operator; build it. 12041 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12042 } 12043 12044 /// BuildCallToMemberFunction - Build a call to a member 12045 /// function. MemExpr is the expression that refers to the member 12046 /// function (and includes the object parameter), Args/NumArgs are the 12047 /// arguments to the function call (not including the object 12048 /// parameter). The caller needs to validate that the member 12049 /// expression refers to a non-static member function or an overloaded 12050 /// member function. 12051 ExprResult 12052 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12053 SourceLocation LParenLoc, 12054 MultiExprArg Args, 12055 SourceLocation RParenLoc) { 12056 assert(MemExprE->getType() == Context.BoundMemberTy || 12057 MemExprE->getType() == Context.OverloadTy); 12058 12059 // Dig out the member expression. This holds both the object 12060 // argument and the member function we're referring to. 12061 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12062 12063 // Determine whether this is a call to a pointer-to-member function. 12064 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12065 assert(op->getType() == Context.BoundMemberTy); 12066 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12067 12068 QualType fnType = 12069 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12070 12071 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12072 QualType resultType = proto->getCallResultType(Context); 12073 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12074 12075 // Check that the object type isn't more qualified than the 12076 // member function we're calling. 12077 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12078 12079 QualType objectType = op->getLHS()->getType(); 12080 if (op->getOpcode() == BO_PtrMemI) 12081 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12082 Qualifiers objectQuals = objectType.getQualifiers(); 12083 12084 Qualifiers difference = objectQuals - funcQuals; 12085 difference.removeObjCGCAttr(); 12086 difference.removeAddressSpace(); 12087 if (difference) { 12088 std::string qualsString = difference.getAsString(); 12089 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12090 << fnType.getUnqualifiedType() 12091 << qualsString 12092 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12093 } 12094 12095 CXXMemberCallExpr *call 12096 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12097 resultType, valueKind, RParenLoc); 12098 12099 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12100 call, nullptr)) 12101 return ExprError(); 12102 12103 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12104 return ExprError(); 12105 12106 if (CheckOtherCall(call, proto)) 12107 return ExprError(); 12108 12109 return MaybeBindToTemporary(call); 12110 } 12111 12112 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12113 return new (Context) 12114 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12115 12116 UnbridgedCastsSet UnbridgedCasts; 12117 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12118 return ExprError(); 12119 12120 MemberExpr *MemExpr; 12121 CXXMethodDecl *Method = nullptr; 12122 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12123 NestedNameSpecifier *Qualifier = nullptr; 12124 if (isa<MemberExpr>(NakedMemExpr)) { 12125 MemExpr = cast<MemberExpr>(NakedMemExpr); 12126 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12127 FoundDecl = MemExpr->getFoundDecl(); 12128 Qualifier = MemExpr->getQualifier(); 12129 UnbridgedCasts.restore(); 12130 } else { 12131 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12132 Qualifier = UnresExpr->getQualifier(); 12133 12134 QualType ObjectType = UnresExpr->getBaseType(); 12135 Expr::Classification ObjectClassification 12136 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12137 : UnresExpr->getBase()->Classify(Context); 12138 12139 // Add overload candidates 12140 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12141 OverloadCandidateSet::CSK_Normal); 12142 12143 // FIXME: avoid copy. 12144 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12145 if (UnresExpr->hasExplicitTemplateArgs()) { 12146 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12147 TemplateArgs = &TemplateArgsBuffer; 12148 } 12149 12150 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12151 E = UnresExpr->decls_end(); I != E; ++I) { 12152 12153 NamedDecl *Func = *I; 12154 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12155 if (isa<UsingShadowDecl>(Func)) 12156 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12157 12158 12159 // Microsoft supports direct constructor calls. 12160 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12161 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12162 Args, CandidateSet); 12163 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12164 // If explicit template arguments were provided, we can't call a 12165 // non-template member function. 12166 if (TemplateArgs) 12167 continue; 12168 12169 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12170 ObjectClassification, Args, CandidateSet, 12171 /*SuppressUserConversions=*/false); 12172 } else { 12173 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12174 I.getPair(), ActingDC, TemplateArgs, 12175 ObjectType, ObjectClassification, 12176 Args, CandidateSet, 12177 /*SuppressUsedConversions=*/false); 12178 } 12179 } 12180 12181 DeclarationName DeclName = UnresExpr->getMemberName(); 12182 12183 UnbridgedCasts.restore(); 12184 12185 OverloadCandidateSet::iterator Best; 12186 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12187 Best)) { 12188 case OR_Success: 12189 Method = cast<CXXMethodDecl>(Best->Function); 12190 FoundDecl = Best->FoundDecl; 12191 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12192 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12193 return ExprError(); 12194 // If FoundDecl is different from Method (such as if one is a template 12195 // and the other a specialization), make sure DiagnoseUseOfDecl is 12196 // called on both. 12197 // FIXME: This would be more comprehensively addressed by modifying 12198 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12199 // being used. 12200 if (Method != FoundDecl.getDecl() && 12201 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12202 return ExprError(); 12203 break; 12204 12205 case OR_No_Viable_Function: 12206 Diag(UnresExpr->getMemberLoc(), 12207 diag::err_ovl_no_viable_member_function_in_call) 12208 << DeclName << MemExprE->getSourceRange(); 12209 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12210 // FIXME: Leaking incoming expressions! 12211 return ExprError(); 12212 12213 case OR_Ambiguous: 12214 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12215 << DeclName << MemExprE->getSourceRange(); 12216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12217 // FIXME: Leaking incoming expressions! 12218 return ExprError(); 12219 12220 case OR_Deleted: 12221 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12222 << Best->Function->isDeleted() 12223 << DeclName 12224 << getDeletedOrUnavailableSuffix(Best->Function) 12225 << MemExprE->getSourceRange(); 12226 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12227 // FIXME: Leaking incoming expressions! 12228 return ExprError(); 12229 } 12230 12231 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12232 12233 // If overload resolution picked a static member, build a 12234 // non-member call based on that function. 12235 if (Method->isStatic()) { 12236 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12237 RParenLoc); 12238 } 12239 12240 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12241 } 12242 12243 QualType ResultType = Method->getReturnType(); 12244 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12245 ResultType = ResultType.getNonLValueExprType(Context); 12246 12247 assert(Method && "Member call to something that isn't a method?"); 12248 CXXMemberCallExpr *TheCall = 12249 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12250 ResultType, VK, RParenLoc); 12251 12252 // (CUDA B.1): Check for invalid calls between targets. 12253 if (getLangOpts().CUDA) { 12254 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12255 if (CheckCUDATarget(Caller, Method)) { 12256 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12257 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12258 << IdentifyCUDATarget(Caller); 12259 return ExprError(); 12260 } 12261 } 12262 } 12263 12264 // Check for a valid return type. 12265 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12266 TheCall, Method)) 12267 return ExprError(); 12268 12269 // Convert the object argument (for a non-static member function call). 12270 // We only need to do this if there was actually an overload; otherwise 12271 // it was done at lookup. 12272 if (!Method->isStatic()) { 12273 ExprResult ObjectArg = 12274 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12275 FoundDecl, Method); 12276 if (ObjectArg.isInvalid()) 12277 return ExprError(); 12278 MemExpr->setBase(ObjectArg.get()); 12279 } 12280 12281 // Convert the rest of the arguments 12282 const FunctionProtoType *Proto = 12283 Method->getType()->getAs<FunctionProtoType>(); 12284 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12285 RParenLoc)) 12286 return ExprError(); 12287 12288 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12289 12290 if (CheckFunctionCall(Method, TheCall, Proto)) 12291 return ExprError(); 12292 12293 // In the case the method to call was not selected by the overloading 12294 // resolution process, we still need to handle the enable_if attribute. Do 12295 // that here, so it will not hide previous -- and more relevant -- errors 12296 if (isa<MemberExpr>(NakedMemExpr)) { 12297 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12298 Diag(MemExprE->getLocStart(), 12299 diag::err_ovl_no_viable_member_function_in_call) 12300 << Method << Method->getSourceRange(); 12301 Diag(Method->getLocation(), 12302 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12303 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12304 return ExprError(); 12305 } 12306 } 12307 12308 if ((isa<CXXConstructorDecl>(CurContext) || 12309 isa<CXXDestructorDecl>(CurContext)) && 12310 TheCall->getMethodDecl()->isPure()) { 12311 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12312 12313 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12314 MemExpr->performsVirtualDispatch(getLangOpts())) { 12315 Diag(MemExpr->getLocStart(), 12316 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12317 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12318 << MD->getParent()->getDeclName(); 12319 12320 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12321 if (getLangOpts().AppleKext) 12322 Diag(MemExpr->getLocStart(), 12323 diag::note_pure_qualified_call_kext) 12324 << MD->getParent()->getDeclName() 12325 << MD->getDeclName(); 12326 } 12327 } 12328 12329 if (CXXDestructorDecl *DD = 12330 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12331 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12332 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() || 12333 getLangOpts().AppleKext; 12334 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12335 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12336 MemExpr->getMemberLoc()); 12337 } 12338 12339 return MaybeBindToTemporary(TheCall); 12340 } 12341 12342 /// BuildCallToObjectOfClassType - Build a call to an object of class 12343 /// type (C++ [over.call.object]), which can end up invoking an 12344 /// overloaded function call operator (@c operator()) or performing a 12345 /// user-defined conversion on the object argument. 12346 ExprResult 12347 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12348 SourceLocation LParenLoc, 12349 MultiExprArg Args, 12350 SourceLocation RParenLoc) { 12351 if (checkPlaceholderForOverload(*this, Obj)) 12352 return ExprError(); 12353 ExprResult Object = Obj; 12354 12355 UnbridgedCastsSet UnbridgedCasts; 12356 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12357 return ExprError(); 12358 12359 assert(Object.get()->getType()->isRecordType() && 12360 "Requires object type argument"); 12361 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12362 12363 // C++ [over.call.object]p1: 12364 // If the primary-expression E in the function call syntax 12365 // evaluates to a class object of type "cv T", then the set of 12366 // candidate functions includes at least the function call 12367 // operators of T. The function call operators of T are obtained by 12368 // ordinary lookup of the name operator() in the context of 12369 // (E).operator(). 12370 OverloadCandidateSet CandidateSet(LParenLoc, 12371 OverloadCandidateSet::CSK_Operator); 12372 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12373 12374 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12375 diag::err_incomplete_object_call, Object.get())) 12376 return true; 12377 12378 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12379 LookupQualifiedName(R, Record->getDecl()); 12380 R.suppressDiagnostics(); 12381 12382 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12383 Oper != OperEnd; ++Oper) { 12384 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12385 Object.get()->Classify(Context), 12386 Args, CandidateSet, 12387 /*SuppressUserConversions=*/ false); 12388 } 12389 12390 // C++ [over.call.object]p2: 12391 // In addition, for each (non-explicit in C++0x) conversion function 12392 // declared in T of the form 12393 // 12394 // operator conversion-type-id () cv-qualifier; 12395 // 12396 // where cv-qualifier is the same cv-qualification as, or a 12397 // greater cv-qualification than, cv, and where conversion-type-id 12398 // denotes the type "pointer to function of (P1,...,Pn) returning 12399 // R", or the type "reference to pointer to function of 12400 // (P1,...,Pn) returning R", or the type "reference to function 12401 // of (P1,...,Pn) returning R", a surrogate call function [...] 12402 // is also considered as a candidate function. Similarly, 12403 // surrogate call functions are added to the set of candidate 12404 // functions for each conversion function declared in an 12405 // accessible base class provided the function is not hidden 12406 // within T by another intervening declaration. 12407 const auto &Conversions = 12408 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12409 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12410 NamedDecl *D = *I; 12411 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12412 if (isa<UsingShadowDecl>(D)) 12413 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12414 12415 // Skip over templated conversion functions; they aren't 12416 // surrogates. 12417 if (isa<FunctionTemplateDecl>(D)) 12418 continue; 12419 12420 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12421 if (!Conv->isExplicit()) { 12422 // Strip the reference type (if any) and then the pointer type (if 12423 // any) to get down to what might be a function type. 12424 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12425 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12426 ConvType = ConvPtrType->getPointeeType(); 12427 12428 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12429 { 12430 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12431 Object.get(), Args, CandidateSet); 12432 } 12433 } 12434 } 12435 12436 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12437 12438 // Perform overload resolution. 12439 OverloadCandidateSet::iterator Best; 12440 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12441 Best)) { 12442 case OR_Success: 12443 // Overload resolution succeeded; we'll build the appropriate call 12444 // below. 12445 break; 12446 12447 case OR_No_Viable_Function: 12448 if (CandidateSet.empty()) 12449 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12450 << Object.get()->getType() << /*call*/ 1 12451 << Object.get()->getSourceRange(); 12452 else 12453 Diag(Object.get()->getLocStart(), 12454 diag::err_ovl_no_viable_object_call) 12455 << Object.get()->getType() << Object.get()->getSourceRange(); 12456 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12457 break; 12458 12459 case OR_Ambiguous: 12460 Diag(Object.get()->getLocStart(), 12461 diag::err_ovl_ambiguous_object_call) 12462 << Object.get()->getType() << Object.get()->getSourceRange(); 12463 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12464 break; 12465 12466 case OR_Deleted: 12467 Diag(Object.get()->getLocStart(), 12468 diag::err_ovl_deleted_object_call) 12469 << Best->Function->isDeleted() 12470 << Object.get()->getType() 12471 << getDeletedOrUnavailableSuffix(Best->Function) 12472 << Object.get()->getSourceRange(); 12473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12474 break; 12475 } 12476 12477 if (Best == CandidateSet.end()) 12478 return true; 12479 12480 UnbridgedCasts.restore(); 12481 12482 if (Best->Function == nullptr) { 12483 // Since there is no function declaration, this is one of the 12484 // surrogate candidates. Dig out the conversion function. 12485 CXXConversionDecl *Conv 12486 = cast<CXXConversionDecl>( 12487 Best->Conversions[0].UserDefined.ConversionFunction); 12488 12489 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12490 Best->FoundDecl); 12491 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12492 return ExprError(); 12493 assert(Conv == Best->FoundDecl.getDecl() && 12494 "Found Decl & conversion-to-functionptr should be same, right?!"); 12495 // We selected one of the surrogate functions that converts the 12496 // object parameter to a function pointer. Perform the conversion 12497 // on the object argument, then let ActOnCallExpr finish the job. 12498 12499 // Create an implicit member expr to refer to the conversion operator. 12500 // and then call it. 12501 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12502 Conv, HadMultipleCandidates); 12503 if (Call.isInvalid()) 12504 return ExprError(); 12505 // Record usage of conversion in an implicit cast. 12506 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12507 CK_UserDefinedConversion, Call.get(), 12508 nullptr, VK_RValue); 12509 12510 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12511 } 12512 12513 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12514 12515 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12516 // that calls this method, using Object for the implicit object 12517 // parameter and passing along the remaining arguments. 12518 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12519 12520 // An error diagnostic has already been printed when parsing the declaration. 12521 if (Method->isInvalidDecl()) 12522 return ExprError(); 12523 12524 const FunctionProtoType *Proto = 12525 Method->getType()->getAs<FunctionProtoType>(); 12526 12527 unsigned NumParams = Proto->getNumParams(); 12528 12529 DeclarationNameInfo OpLocInfo( 12530 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12531 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12532 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12533 HadMultipleCandidates, 12534 OpLocInfo.getLoc(), 12535 OpLocInfo.getInfo()); 12536 if (NewFn.isInvalid()) 12537 return true; 12538 12539 // Build the full argument list for the method call (the implicit object 12540 // parameter is placed at the beginning of the list). 12541 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12542 MethodArgs[0] = Object.get(); 12543 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12544 12545 // Once we've built TheCall, all of the expressions are properly 12546 // owned. 12547 QualType ResultTy = Method->getReturnType(); 12548 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12549 ResultTy = ResultTy.getNonLValueExprType(Context); 12550 12551 CXXOperatorCallExpr *TheCall = new (Context) 12552 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12553 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12554 ResultTy, VK, RParenLoc, false); 12555 MethodArgs.reset(); 12556 12557 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12558 return true; 12559 12560 // We may have default arguments. If so, we need to allocate more 12561 // slots in the call for them. 12562 if (Args.size() < NumParams) 12563 TheCall->setNumArgs(Context, NumParams + 1); 12564 12565 bool IsError = false; 12566 12567 // Initialize the implicit object parameter. 12568 ExprResult ObjRes = 12569 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12570 Best->FoundDecl, Method); 12571 if (ObjRes.isInvalid()) 12572 IsError = true; 12573 else 12574 Object = ObjRes; 12575 TheCall->setArg(0, Object.get()); 12576 12577 // Check the argument types. 12578 for (unsigned i = 0; i != NumParams; i++) { 12579 Expr *Arg; 12580 if (i < Args.size()) { 12581 Arg = Args[i]; 12582 12583 // Pass the argument. 12584 12585 ExprResult InputInit 12586 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12587 Context, 12588 Method->getParamDecl(i)), 12589 SourceLocation(), Arg); 12590 12591 IsError |= InputInit.isInvalid(); 12592 Arg = InputInit.getAs<Expr>(); 12593 } else { 12594 ExprResult DefArg 12595 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12596 if (DefArg.isInvalid()) { 12597 IsError = true; 12598 break; 12599 } 12600 12601 Arg = DefArg.getAs<Expr>(); 12602 } 12603 12604 TheCall->setArg(i + 1, Arg); 12605 } 12606 12607 // If this is a variadic call, handle args passed through "...". 12608 if (Proto->isVariadic()) { 12609 // Promote the arguments (C99 6.5.2.2p7). 12610 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12611 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12612 nullptr); 12613 IsError |= Arg.isInvalid(); 12614 TheCall->setArg(i + 1, Arg.get()); 12615 } 12616 } 12617 12618 if (IsError) return true; 12619 12620 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12621 12622 if (CheckFunctionCall(Method, TheCall, Proto)) 12623 return true; 12624 12625 return MaybeBindToTemporary(TheCall); 12626 } 12627 12628 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12629 /// (if one exists), where @c Base is an expression of class type and 12630 /// @c Member is the name of the member we're trying to find. 12631 ExprResult 12632 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12633 bool *NoArrowOperatorFound) { 12634 assert(Base->getType()->isRecordType() && 12635 "left-hand side must have class type"); 12636 12637 if (checkPlaceholderForOverload(*this, Base)) 12638 return ExprError(); 12639 12640 SourceLocation Loc = Base->getExprLoc(); 12641 12642 // C++ [over.ref]p1: 12643 // 12644 // [...] An expression x->m is interpreted as (x.operator->())->m 12645 // for a class object x of type T if T::operator->() exists and if 12646 // the operator is selected as the best match function by the 12647 // overload resolution mechanism (13.3). 12648 DeclarationName OpName = 12649 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12650 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12651 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12652 12653 if (RequireCompleteType(Loc, Base->getType(), 12654 diag::err_typecheck_incomplete_tag, Base)) 12655 return ExprError(); 12656 12657 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12658 LookupQualifiedName(R, BaseRecord->getDecl()); 12659 R.suppressDiagnostics(); 12660 12661 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12662 Oper != OperEnd; ++Oper) { 12663 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12664 None, CandidateSet, /*SuppressUserConversions=*/false); 12665 } 12666 12667 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12668 12669 // Perform overload resolution. 12670 OverloadCandidateSet::iterator Best; 12671 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12672 case OR_Success: 12673 // Overload resolution succeeded; we'll build the call below. 12674 break; 12675 12676 case OR_No_Viable_Function: 12677 if (CandidateSet.empty()) { 12678 QualType BaseType = Base->getType(); 12679 if (NoArrowOperatorFound) { 12680 // Report this specific error to the caller instead of emitting a 12681 // diagnostic, as requested. 12682 *NoArrowOperatorFound = true; 12683 return ExprError(); 12684 } 12685 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12686 << BaseType << Base->getSourceRange(); 12687 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12688 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12689 << FixItHint::CreateReplacement(OpLoc, "."); 12690 } 12691 } else 12692 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12693 << "operator->" << Base->getSourceRange(); 12694 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12695 return ExprError(); 12696 12697 case OR_Ambiguous: 12698 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12699 << "->" << Base->getType() << Base->getSourceRange(); 12700 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12701 return ExprError(); 12702 12703 case OR_Deleted: 12704 Diag(OpLoc, diag::err_ovl_deleted_oper) 12705 << Best->Function->isDeleted() 12706 << "->" 12707 << getDeletedOrUnavailableSuffix(Best->Function) 12708 << Base->getSourceRange(); 12709 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12710 return ExprError(); 12711 } 12712 12713 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12714 12715 // Convert the object parameter. 12716 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12717 ExprResult BaseResult = 12718 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12719 Best->FoundDecl, Method); 12720 if (BaseResult.isInvalid()) 12721 return ExprError(); 12722 Base = BaseResult.get(); 12723 12724 // Build the operator call. 12725 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12726 HadMultipleCandidates, OpLoc); 12727 if (FnExpr.isInvalid()) 12728 return ExprError(); 12729 12730 QualType ResultTy = Method->getReturnType(); 12731 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12732 ResultTy = ResultTy.getNonLValueExprType(Context); 12733 CXXOperatorCallExpr *TheCall = 12734 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12735 Base, ResultTy, VK, OpLoc, false); 12736 12737 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12738 return ExprError(); 12739 12740 return MaybeBindToTemporary(TheCall); 12741 } 12742 12743 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12744 /// a literal operator described by the provided lookup results. 12745 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12746 DeclarationNameInfo &SuffixInfo, 12747 ArrayRef<Expr*> Args, 12748 SourceLocation LitEndLoc, 12749 TemplateArgumentListInfo *TemplateArgs) { 12750 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12751 12752 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12753 OverloadCandidateSet::CSK_Normal); 12754 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12755 /*SuppressUserConversions=*/true); 12756 12757 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12758 12759 // Perform overload resolution. This will usually be trivial, but might need 12760 // to perform substitutions for a literal operator template. 12761 OverloadCandidateSet::iterator Best; 12762 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12763 case OR_Success: 12764 case OR_Deleted: 12765 break; 12766 12767 case OR_No_Viable_Function: 12768 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12769 << R.getLookupName(); 12770 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12771 return ExprError(); 12772 12773 case OR_Ambiguous: 12774 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12775 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12776 return ExprError(); 12777 } 12778 12779 FunctionDecl *FD = Best->Function; 12780 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12781 HadMultipleCandidates, 12782 SuffixInfo.getLoc(), 12783 SuffixInfo.getInfo()); 12784 if (Fn.isInvalid()) 12785 return true; 12786 12787 // Check the argument types. This should almost always be a no-op, except 12788 // that array-to-pointer decay is applied to string literals. 12789 Expr *ConvArgs[2]; 12790 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12791 ExprResult InputInit = PerformCopyInitialization( 12792 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12793 SourceLocation(), Args[ArgIdx]); 12794 if (InputInit.isInvalid()) 12795 return true; 12796 ConvArgs[ArgIdx] = InputInit.get(); 12797 } 12798 12799 QualType ResultTy = FD->getReturnType(); 12800 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12801 ResultTy = ResultTy.getNonLValueExprType(Context); 12802 12803 UserDefinedLiteral *UDL = 12804 new (Context) UserDefinedLiteral(Context, Fn.get(), 12805 llvm::makeArrayRef(ConvArgs, Args.size()), 12806 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12807 12808 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12809 return ExprError(); 12810 12811 if (CheckFunctionCall(FD, UDL, nullptr)) 12812 return ExprError(); 12813 12814 return MaybeBindToTemporary(UDL); 12815 } 12816 12817 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12818 /// given LookupResult is non-empty, it is assumed to describe a member which 12819 /// will be invoked. Otherwise, the function will be found via argument 12820 /// dependent lookup. 12821 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12822 /// otherwise CallExpr is set to ExprError() and some non-success value 12823 /// is returned. 12824 Sema::ForRangeStatus 12825 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12826 SourceLocation RangeLoc, 12827 const DeclarationNameInfo &NameInfo, 12828 LookupResult &MemberLookup, 12829 OverloadCandidateSet *CandidateSet, 12830 Expr *Range, ExprResult *CallExpr) { 12831 Scope *S = nullptr; 12832 12833 CandidateSet->clear(); 12834 if (!MemberLookup.empty()) { 12835 ExprResult MemberRef = 12836 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12837 /*IsPtr=*/false, CXXScopeSpec(), 12838 /*TemplateKWLoc=*/SourceLocation(), 12839 /*FirstQualifierInScope=*/nullptr, 12840 MemberLookup, 12841 /*TemplateArgs=*/nullptr, S); 12842 if (MemberRef.isInvalid()) { 12843 *CallExpr = ExprError(); 12844 return FRS_DiagnosticIssued; 12845 } 12846 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12847 if (CallExpr->isInvalid()) { 12848 *CallExpr = ExprError(); 12849 return FRS_DiagnosticIssued; 12850 } 12851 } else { 12852 UnresolvedSet<0> FoundNames; 12853 UnresolvedLookupExpr *Fn = 12854 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12855 NestedNameSpecifierLoc(), NameInfo, 12856 /*NeedsADL=*/true, /*Overloaded=*/false, 12857 FoundNames.begin(), FoundNames.end()); 12858 12859 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12860 CandidateSet, CallExpr); 12861 if (CandidateSet->empty() || CandidateSetError) { 12862 *CallExpr = ExprError(); 12863 return FRS_NoViableFunction; 12864 } 12865 OverloadCandidateSet::iterator Best; 12866 OverloadingResult OverloadResult = 12867 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12868 12869 if (OverloadResult == OR_No_Viable_Function) { 12870 *CallExpr = ExprError(); 12871 return FRS_NoViableFunction; 12872 } 12873 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12874 Loc, nullptr, CandidateSet, &Best, 12875 OverloadResult, 12876 /*AllowTypoCorrection=*/false); 12877 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12878 *CallExpr = ExprError(); 12879 return FRS_DiagnosticIssued; 12880 } 12881 } 12882 return FRS_Success; 12883 } 12884 12885 12886 /// FixOverloadedFunctionReference - E is an expression that refers to 12887 /// a C++ overloaded function (possibly with some parentheses and 12888 /// perhaps a '&' around it). We have resolved the overloaded function 12889 /// to the function declaration Fn, so patch up the expression E to 12890 /// refer (possibly indirectly) to Fn. Returns the new expr. 12891 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12892 FunctionDecl *Fn) { 12893 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12894 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12895 Found, Fn); 12896 if (SubExpr == PE->getSubExpr()) 12897 return PE; 12898 12899 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12900 } 12901 12902 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12903 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12904 Found, Fn); 12905 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12906 SubExpr->getType()) && 12907 "Implicit cast type cannot be determined from overload"); 12908 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12909 if (SubExpr == ICE->getSubExpr()) 12910 return ICE; 12911 12912 return ImplicitCastExpr::Create(Context, ICE->getType(), 12913 ICE->getCastKind(), 12914 SubExpr, nullptr, 12915 ICE->getValueKind()); 12916 } 12917 12918 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12919 assert(UnOp->getOpcode() == UO_AddrOf && 12920 "Can only take the address of an overloaded function"); 12921 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12922 if (Method->isStatic()) { 12923 // Do nothing: static member functions aren't any different 12924 // from non-member functions. 12925 } else { 12926 // Fix the subexpression, which really has to be an 12927 // UnresolvedLookupExpr holding an overloaded member function 12928 // or template. 12929 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12930 Found, Fn); 12931 if (SubExpr == UnOp->getSubExpr()) 12932 return UnOp; 12933 12934 assert(isa<DeclRefExpr>(SubExpr) 12935 && "fixed to something other than a decl ref"); 12936 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12937 && "fixed to a member ref with no nested name qualifier"); 12938 12939 // We have taken the address of a pointer to member 12940 // function. Perform the computation here so that we get the 12941 // appropriate pointer to member type. 12942 QualType ClassType 12943 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12944 QualType MemPtrType 12945 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12946 12947 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12948 VK_RValue, OK_Ordinary, 12949 UnOp->getOperatorLoc()); 12950 } 12951 } 12952 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12953 Found, Fn); 12954 if (SubExpr == UnOp->getSubExpr()) 12955 return UnOp; 12956 12957 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12958 Context.getPointerType(SubExpr->getType()), 12959 VK_RValue, OK_Ordinary, 12960 UnOp->getOperatorLoc()); 12961 } 12962 12963 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12964 // FIXME: avoid copy. 12965 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12966 if (ULE->hasExplicitTemplateArgs()) { 12967 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12968 TemplateArgs = &TemplateArgsBuffer; 12969 } 12970 12971 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12972 ULE->getQualifierLoc(), 12973 ULE->getTemplateKeywordLoc(), 12974 Fn, 12975 /*enclosing*/ false, // FIXME? 12976 ULE->getNameLoc(), 12977 Fn->getType(), 12978 VK_LValue, 12979 Found.getDecl(), 12980 TemplateArgs); 12981 MarkDeclRefReferenced(DRE); 12982 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12983 return DRE; 12984 } 12985 12986 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12987 // FIXME: avoid copy. 12988 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12989 if (MemExpr->hasExplicitTemplateArgs()) { 12990 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12991 TemplateArgs = &TemplateArgsBuffer; 12992 } 12993 12994 Expr *Base; 12995 12996 // If we're filling in a static method where we used to have an 12997 // implicit member access, rewrite to a simple decl ref. 12998 if (MemExpr->isImplicitAccess()) { 12999 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13000 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13001 MemExpr->getQualifierLoc(), 13002 MemExpr->getTemplateKeywordLoc(), 13003 Fn, 13004 /*enclosing*/ false, 13005 MemExpr->getMemberLoc(), 13006 Fn->getType(), 13007 VK_LValue, 13008 Found.getDecl(), 13009 TemplateArgs); 13010 MarkDeclRefReferenced(DRE); 13011 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13012 return DRE; 13013 } else { 13014 SourceLocation Loc = MemExpr->getMemberLoc(); 13015 if (MemExpr->getQualifier()) 13016 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13017 CheckCXXThisCapture(Loc); 13018 Base = new (Context) CXXThisExpr(Loc, 13019 MemExpr->getBaseType(), 13020 /*isImplicit=*/true); 13021 } 13022 } else 13023 Base = MemExpr->getBase(); 13024 13025 ExprValueKind valueKind; 13026 QualType type; 13027 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13028 valueKind = VK_LValue; 13029 type = Fn->getType(); 13030 } else { 13031 valueKind = VK_RValue; 13032 type = Context.BoundMemberTy; 13033 } 13034 13035 MemberExpr *ME = MemberExpr::Create( 13036 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13037 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13038 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13039 OK_Ordinary); 13040 ME->setHadMultipleCandidates(true); 13041 MarkMemberReferenced(ME); 13042 return ME; 13043 } 13044 13045 llvm_unreachable("Invalid reference to overloaded function"); 13046 } 13047 13048 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13049 DeclAccessPair Found, 13050 FunctionDecl *Fn) { 13051 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13052 } 13053