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 && getLangOpts().CUDATargetOverloads) { 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 && S.getLangOpts().CUDATargetOverloads && 8643 Cand1.Function && Cand2.Function) { 8644 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8645 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8646 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8647 } 8648 8649 bool HasPS1 = Cand1.Function != nullptr && 8650 functionHasPassObjectSizeParams(Cand1.Function); 8651 bool HasPS2 = Cand2.Function != nullptr && 8652 functionHasPassObjectSizeParams(Cand2.Function); 8653 return HasPS1 != HasPS2 && HasPS1; 8654 } 8655 8656 /// Determine whether two declarations are "equivalent" for the purposes of 8657 /// name lookup and overload resolution. This applies when the same internal/no 8658 /// linkage entity is defined by two modules (probably by textually including 8659 /// the same header). In such a case, we don't consider the declarations to 8660 /// declare the same entity, but we also don't want lookups with both 8661 /// declarations visible to be ambiguous in some cases (this happens when using 8662 /// a modularized libstdc++). 8663 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8664 const NamedDecl *B) { 8665 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8666 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8667 if (!VA || !VB) 8668 return false; 8669 8670 // The declarations must be declaring the same name as an internal linkage 8671 // entity in different modules. 8672 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8673 VB->getDeclContext()->getRedeclContext()) || 8674 getOwningModule(const_cast<ValueDecl *>(VA)) == 8675 getOwningModule(const_cast<ValueDecl *>(VB)) || 8676 VA->isExternallyVisible() || VB->isExternallyVisible()) 8677 return false; 8678 8679 // Check that the declarations appear to be equivalent. 8680 // 8681 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8682 // For constants and functions, we should check the initializer or body is 8683 // the same. For non-constant variables, we shouldn't allow it at all. 8684 if (Context.hasSameType(VA->getType(), VB->getType())) 8685 return true; 8686 8687 // Enum constants within unnamed enumerations will have different types, but 8688 // may still be similar enough to be interchangeable for our purposes. 8689 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8690 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8691 // Only handle anonymous enums. If the enumerations were named and 8692 // equivalent, they would have been merged to the same type. 8693 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8694 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8695 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8696 !Context.hasSameType(EnumA->getIntegerType(), 8697 EnumB->getIntegerType())) 8698 return false; 8699 // Allow this only if the value is the same for both enumerators. 8700 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8701 } 8702 } 8703 8704 // Nothing else is sufficiently similar. 8705 return false; 8706 } 8707 8708 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8709 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8710 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8711 8712 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8713 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8714 << !M << (M ? M->getFullModuleName() : ""); 8715 8716 for (auto *E : Equiv) { 8717 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8718 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8719 << !M << (M ? M->getFullModuleName() : ""); 8720 } 8721 } 8722 8723 /// \brief Computes the best viable function (C++ 13.3.3) 8724 /// within an overload candidate set. 8725 /// 8726 /// \param Loc The location of the function name (or operator symbol) for 8727 /// which overload resolution occurs. 8728 /// 8729 /// \param Best If overload resolution was successful or found a deleted 8730 /// function, \p Best points to the candidate function found. 8731 /// 8732 /// \returns The result of overload resolution. 8733 OverloadingResult 8734 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8735 iterator &Best, 8736 bool UserDefinedConversion) { 8737 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8738 std::transform(begin(), end(), std::back_inserter(Candidates), 8739 [](OverloadCandidate &Cand) { return &Cand; }); 8740 8741 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA 8742 // but accepted by both clang and NVCC. However during a particular 8743 // compilation mode only one call variant is viable. We need to 8744 // exclude non-viable overload candidates from consideration based 8745 // only on their host/device attributes. Specifically, if one 8746 // candidate call is WrongSide and the other is SameSide, we ignore 8747 // the WrongSide candidate. 8748 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads) { 8749 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8750 bool ContainsSameSideCandidate = 8751 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8752 return Cand->Function && 8753 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8754 Sema::CFP_SameSide; 8755 }); 8756 if (ContainsSameSideCandidate) { 8757 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8758 return Cand->Function && 8759 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8760 Sema::CFP_WrongSide; 8761 }; 8762 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8763 IsWrongSideCandidate), 8764 Candidates.end()); 8765 } 8766 } 8767 8768 // Find the best viable function. 8769 Best = end(); 8770 for (auto *Cand : Candidates) 8771 if (Cand->Viable) 8772 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8773 UserDefinedConversion)) 8774 Best = Cand; 8775 8776 // If we didn't find any viable functions, abort. 8777 if (Best == end()) 8778 return OR_No_Viable_Function; 8779 8780 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8781 8782 // Make sure that this function is better than every other viable 8783 // function. If not, we have an ambiguity. 8784 for (auto *Cand : Candidates) { 8785 if (Cand->Viable && 8786 Cand != Best && 8787 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8788 UserDefinedConversion)) { 8789 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8790 Cand->Function)) { 8791 EquivalentCands.push_back(Cand->Function); 8792 continue; 8793 } 8794 8795 Best = end(); 8796 return OR_Ambiguous; 8797 } 8798 } 8799 8800 // Best is the best viable function. 8801 if (Best->Function && 8802 (Best->Function->isDeleted() || 8803 S.isFunctionConsideredUnavailable(Best->Function))) 8804 return OR_Deleted; 8805 8806 if (!EquivalentCands.empty()) 8807 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8808 EquivalentCands); 8809 8810 return OR_Success; 8811 } 8812 8813 namespace { 8814 8815 enum OverloadCandidateKind { 8816 oc_function, 8817 oc_method, 8818 oc_constructor, 8819 oc_function_template, 8820 oc_method_template, 8821 oc_constructor_template, 8822 oc_implicit_default_constructor, 8823 oc_implicit_copy_constructor, 8824 oc_implicit_move_constructor, 8825 oc_implicit_copy_assignment, 8826 oc_implicit_move_assignment, 8827 oc_implicit_inherited_constructor 8828 }; 8829 8830 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8831 FunctionDecl *Fn, 8832 std::string &Description) { 8833 bool isTemplate = false; 8834 8835 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8836 isTemplate = true; 8837 Description = S.getTemplateArgumentBindingsText( 8838 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8839 } 8840 8841 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8842 if (!Ctor->isImplicit()) 8843 return isTemplate ? oc_constructor_template : oc_constructor; 8844 8845 if (Ctor->getInheritedConstructor()) 8846 return oc_implicit_inherited_constructor; 8847 8848 if (Ctor->isDefaultConstructor()) 8849 return oc_implicit_default_constructor; 8850 8851 if (Ctor->isMoveConstructor()) 8852 return oc_implicit_move_constructor; 8853 8854 assert(Ctor->isCopyConstructor() && 8855 "unexpected sort of implicit constructor"); 8856 return oc_implicit_copy_constructor; 8857 } 8858 8859 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8860 // This actually gets spelled 'candidate function' for now, but 8861 // it doesn't hurt to split it out. 8862 if (!Meth->isImplicit()) 8863 return isTemplate ? oc_method_template : oc_method; 8864 8865 if (Meth->isMoveAssignmentOperator()) 8866 return oc_implicit_move_assignment; 8867 8868 if (Meth->isCopyAssignmentOperator()) 8869 return oc_implicit_copy_assignment; 8870 8871 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8872 return oc_method; 8873 } 8874 8875 return isTemplate ? oc_function_template : oc_function; 8876 } 8877 8878 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8879 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8880 if (!Ctor) return; 8881 8882 Ctor = Ctor->getInheritedConstructor(); 8883 if (!Ctor) return; 8884 8885 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8886 } 8887 8888 } // end anonymous namespace 8889 8890 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8891 const FunctionDecl *FD) { 8892 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8893 bool AlwaysTrue; 8894 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8895 return false; 8896 if (!AlwaysTrue) 8897 return false; 8898 } 8899 return true; 8900 } 8901 8902 /// \brief Returns true if we can take the address of the function. 8903 /// 8904 /// \param Complain - If true, we'll emit a diagnostic 8905 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8906 /// we in overload resolution? 8907 /// \param Loc - The location of the statement we're complaining about. Ignored 8908 /// if we're not complaining, or if we're in overload resolution. 8909 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8910 bool Complain, 8911 bool InOverloadResolution, 8912 SourceLocation Loc) { 8913 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8914 if (Complain) { 8915 if (InOverloadResolution) 8916 S.Diag(FD->getLocStart(), 8917 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8918 else 8919 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8920 } 8921 return false; 8922 } 8923 8924 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8925 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8926 if (I == FD->param_end()) 8927 return true; 8928 8929 if (Complain) { 8930 // Add one to ParamNo because it's user-facing 8931 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8932 if (InOverloadResolution) 8933 S.Diag(FD->getLocation(), 8934 diag::note_ovl_candidate_has_pass_object_size_params) 8935 << ParamNo; 8936 else 8937 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8938 << FD << ParamNo; 8939 } 8940 return false; 8941 } 8942 8943 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8944 const FunctionDecl *FD) { 8945 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8946 /*InOverloadResolution=*/true, 8947 /*Loc=*/SourceLocation()); 8948 } 8949 8950 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8951 bool Complain, 8952 SourceLocation Loc) { 8953 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8954 /*InOverloadResolution=*/false, 8955 Loc); 8956 } 8957 8958 // Notes the location of an overload candidate. 8959 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8960 bool TakingAddress) { 8961 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8962 return; 8963 8964 std::string FnDesc; 8965 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8966 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8967 << (unsigned) K << FnDesc; 8968 8969 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8970 Diag(Fn->getLocation(), PD); 8971 MaybeEmitInheritedConstructorNote(*this, Fn); 8972 } 8973 8974 // Notes the location of all overload candidates designated through 8975 // OverloadedExpr 8976 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8977 bool TakingAddress) { 8978 assert(OverloadedExpr->getType() == Context.OverloadTy); 8979 8980 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8981 OverloadExpr *OvlExpr = Ovl.Expression; 8982 8983 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8984 IEnd = OvlExpr->decls_end(); 8985 I != IEnd; ++I) { 8986 if (FunctionTemplateDecl *FunTmpl = 8987 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8988 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8989 TakingAddress); 8990 } else if (FunctionDecl *Fun 8991 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8992 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8993 } 8994 } 8995 } 8996 8997 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8998 /// "lead" diagnostic; it will be given two arguments, the source and 8999 /// target types of the conversion. 9000 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9001 Sema &S, 9002 SourceLocation CaretLoc, 9003 const PartialDiagnostic &PDiag) const { 9004 S.Diag(CaretLoc, PDiag) 9005 << Ambiguous.getFromType() << Ambiguous.getToType(); 9006 // FIXME: The note limiting machinery is borrowed from 9007 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9008 // refactoring here. 9009 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9010 unsigned CandsShown = 0; 9011 AmbiguousConversionSequence::const_iterator I, E; 9012 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9013 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9014 break; 9015 ++CandsShown; 9016 S.NoteOverloadCandidate(*I); 9017 } 9018 if (I != E) 9019 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9020 } 9021 9022 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9023 unsigned I, bool TakingCandidateAddress) { 9024 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9025 assert(Conv.isBad()); 9026 assert(Cand->Function && "for now, candidate must be a function"); 9027 FunctionDecl *Fn = Cand->Function; 9028 9029 // There's a conversion slot for the object argument if this is a 9030 // non-constructor method. Note that 'I' corresponds the 9031 // conversion-slot index. 9032 bool isObjectArgument = false; 9033 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9034 if (I == 0) 9035 isObjectArgument = true; 9036 else 9037 I--; 9038 } 9039 9040 std::string FnDesc; 9041 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9042 9043 Expr *FromExpr = Conv.Bad.FromExpr; 9044 QualType FromTy = Conv.Bad.getFromType(); 9045 QualType ToTy = Conv.Bad.getToType(); 9046 9047 if (FromTy == S.Context.OverloadTy) { 9048 assert(FromExpr && "overload set argument came from implicit argument?"); 9049 Expr *E = FromExpr->IgnoreParens(); 9050 if (isa<UnaryOperator>(E)) 9051 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9052 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9053 9054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9055 << (unsigned) FnKind << FnDesc 9056 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9057 << ToTy << Name << I+1; 9058 MaybeEmitInheritedConstructorNote(S, Fn); 9059 return; 9060 } 9061 9062 // Do some hand-waving analysis to see if the non-viability is due 9063 // to a qualifier mismatch. 9064 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9065 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9066 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9067 CToTy = RT->getPointeeType(); 9068 else { 9069 // TODO: detect and diagnose the full richness of const mismatches. 9070 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9071 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9072 CFromTy = FromPT->getPointeeType(); 9073 CToTy = ToPT->getPointeeType(); 9074 } 9075 } 9076 9077 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9078 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9079 Qualifiers FromQs = CFromTy.getQualifiers(); 9080 Qualifiers ToQs = CToTy.getQualifiers(); 9081 9082 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9083 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9084 << (unsigned) FnKind << FnDesc 9085 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9086 << FromTy 9087 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9088 << (unsigned) isObjectArgument << I+1; 9089 MaybeEmitInheritedConstructorNote(S, Fn); 9090 return; 9091 } 9092 9093 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9095 << (unsigned) FnKind << FnDesc 9096 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9097 << FromTy 9098 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9099 << (unsigned) isObjectArgument << I+1; 9100 MaybeEmitInheritedConstructorNote(S, Fn); 9101 return; 9102 } 9103 9104 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9106 << (unsigned) FnKind << FnDesc 9107 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9108 << FromTy 9109 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9110 << (unsigned) isObjectArgument << I+1; 9111 MaybeEmitInheritedConstructorNote(S, Fn); 9112 return; 9113 } 9114 9115 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9116 assert(CVR && "unexpected qualifiers mismatch"); 9117 9118 if (isObjectArgument) { 9119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9120 << (unsigned) FnKind << FnDesc 9121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9122 << FromTy << (CVR - 1); 9123 } else { 9124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9125 << (unsigned) FnKind << FnDesc 9126 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9127 << FromTy << (CVR - 1) << I+1; 9128 } 9129 MaybeEmitInheritedConstructorNote(S, Fn); 9130 return; 9131 } 9132 9133 // Special diagnostic for failure to convert an initializer list, since 9134 // telling the user that it has type void is not useful. 9135 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9136 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9137 << (unsigned) FnKind << FnDesc 9138 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9139 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9140 MaybeEmitInheritedConstructorNote(S, Fn); 9141 return; 9142 } 9143 9144 // Diagnose references or pointers to incomplete types differently, 9145 // since it's far from impossible that the incompleteness triggered 9146 // the failure. 9147 QualType TempFromTy = FromTy.getNonReferenceType(); 9148 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9149 TempFromTy = PTy->getPointeeType(); 9150 if (TempFromTy->isIncompleteType()) { 9151 // Emit the generic diagnostic and, optionally, add the hints to it. 9152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9153 << (unsigned) FnKind << FnDesc 9154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9155 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9156 << (unsigned) (Cand->Fix.Kind); 9157 9158 MaybeEmitInheritedConstructorNote(S, Fn); 9159 return; 9160 } 9161 9162 // Diagnose base -> derived pointer conversions. 9163 unsigned BaseToDerivedConversion = 0; 9164 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9165 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9166 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9167 FromPtrTy->getPointeeType()) && 9168 !FromPtrTy->getPointeeType()->isIncompleteType() && 9169 !ToPtrTy->getPointeeType()->isIncompleteType() && 9170 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9171 FromPtrTy->getPointeeType())) 9172 BaseToDerivedConversion = 1; 9173 } 9174 } else if (const ObjCObjectPointerType *FromPtrTy 9175 = FromTy->getAs<ObjCObjectPointerType>()) { 9176 if (const ObjCObjectPointerType *ToPtrTy 9177 = ToTy->getAs<ObjCObjectPointerType>()) 9178 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9179 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9180 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9181 FromPtrTy->getPointeeType()) && 9182 FromIface->isSuperClassOf(ToIface)) 9183 BaseToDerivedConversion = 2; 9184 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9185 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9186 !FromTy->isIncompleteType() && 9187 !ToRefTy->getPointeeType()->isIncompleteType() && 9188 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9189 BaseToDerivedConversion = 3; 9190 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9191 ToTy.getNonReferenceType().getCanonicalType() == 9192 FromTy.getNonReferenceType().getCanonicalType()) { 9193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9194 << (unsigned) FnKind << FnDesc 9195 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9196 << (unsigned) isObjectArgument << I + 1; 9197 MaybeEmitInheritedConstructorNote(S, Fn); 9198 return; 9199 } 9200 } 9201 9202 if (BaseToDerivedConversion) { 9203 S.Diag(Fn->getLocation(), 9204 diag::note_ovl_candidate_bad_base_to_derived_conv) 9205 << (unsigned) FnKind << FnDesc 9206 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9207 << (BaseToDerivedConversion - 1) 9208 << FromTy << ToTy << I+1; 9209 MaybeEmitInheritedConstructorNote(S, Fn); 9210 return; 9211 } 9212 9213 if (isa<ObjCObjectPointerType>(CFromTy) && 9214 isa<PointerType>(CToTy)) { 9215 Qualifiers FromQs = CFromTy.getQualifiers(); 9216 Qualifiers ToQs = CToTy.getQualifiers(); 9217 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9219 << (unsigned) FnKind << FnDesc 9220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9221 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9222 MaybeEmitInheritedConstructorNote(S, Fn); 9223 return; 9224 } 9225 } 9226 9227 if (TakingCandidateAddress && 9228 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9229 return; 9230 9231 // Emit the generic diagnostic and, optionally, add the hints to it. 9232 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9233 FDiag << (unsigned) FnKind << FnDesc 9234 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9235 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9236 << (unsigned) (Cand->Fix.Kind); 9237 9238 // If we can fix the conversion, suggest the FixIts. 9239 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9240 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9241 FDiag << *HI; 9242 S.Diag(Fn->getLocation(), FDiag); 9243 9244 MaybeEmitInheritedConstructorNote(S, Fn); 9245 } 9246 9247 /// Additional arity mismatch diagnosis specific to a function overload 9248 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9249 /// over a candidate in any candidate set. 9250 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9251 unsigned NumArgs) { 9252 FunctionDecl *Fn = Cand->Function; 9253 unsigned MinParams = Fn->getMinRequiredArguments(); 9254 9255 // With invalid overloaded operators, it's possible that we think we 9256 // have an arity mismatch when in fact it looks like we have the 9257 // right number of arguments, because only overloaded operators have 9258 // the weird behavior of overloading member and non-member functions. 9259 // Just don't report anything. 9260 if (Fn->isInvalidDecl() && 9261 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9262 return true; 9263 9264 if (NumArgs < MinParams) { 9265 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9266 (Cand->FailureKind == ovl_fail_bad_deduction && 9267 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9268 } else { 9269 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9270 (Cand->FailureKind == ovl_fail_bad_deduction && 9271 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9272 } 9273 9274 return false; 9275 } 9276 9277 /// General arity mismatch diagnosis over a candidate in a candidate set. 9278 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9279 assert(isa<FunctionDecl>(D) && 9280 "The templated declaration should at least be a function" 9281 " when diagnosing bad template argument deduction due to too many" 9282 " or too few arguments"); 9283 9284 FunctionDecl *Fn = cast<FunctionDecl>(D); 9285 9286 // TODO: treat calls to a missing default constructor as a special case 9287 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9288 unsigned MinParams = Fn->getMinRequiredArguments(); 9289 9290 // at least / at most / exactly 9291 unsigned mode, modeCount; 9292 if (NumFormalArgs < MinParams) { 9293 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9294 FnTy->isTemplateVariadic()) 9295 mode = 0; // "at least" 9296 else 9297 mode = 2; // "exactly" 9298 modeCount = MinParams; 9299 } else { 9300 if (MinParams != FnTy->getNumParams()) 9301 mode = 1; // "at most" 9302 else 9303 mode = 2; // "exactly" 9304 modeCount = FnTy->getNumParams(); 9305 } 9306 9307 std::string Description; 9308 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9309 9310 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9312 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9313 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9314 else 9315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9316 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9317 << mode << modeCount << NumFormalArgs; 9318 MaybeEmitInheritedConstructorNote(S, Fn); 9319 } 9320 9321 /// Arity mismatch diagnosis specific to a function overload candidate. 9322 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9323 unsigned NumFormalArgs) { 9324 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9325 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9326 } 9327 9328 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9329 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9330 return FD->getDescribedFunctionTemplate(); 9331 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9332 return RD->getDescribedClassTemplate(); 9333 9334 llvm_unreachable("Unsupported: Getting the described template declaration" 9335 " for bad deduction diagnosis"); 9336 } 9337 9338 /// Diagnose a failed template-argument deduction. 9339 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9340 DeductionFailureInfo &DeductionFailure, 9341 unsigned NumArgs, 9342 bool TakingCandidateAddress) { 9343 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9344 NamedDecl *ParamD; 9345 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9346 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9347 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9348 switch (DeductionFailure.Result) { 9349 case Sema::TDK_Success: 9350 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9351 9352 case Sema::TDK_Incomplete: { 9353 assert(ParamD && "no parameter found for incomplete deduction result"); 9354 S.Diag(Templated->getLocation(), 9355 diag::note_ovl_candidate_incomplete_deduction) 9356 << ParamD->getDeclName(); 9357 MaybeEmitInheritedConstructorNote(S, Templated); 9358 return; 9359 } 9360 9361 case Sema::TDK_Underqualified: { 9362 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9363 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9364 9365 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9366 9367 // Param will have been canonicalized, but it should just be a 9368 // qualified version of ParamD, so move the qualifiers to that. 9369 QualifierCollector Qs; 9370 Qs.strip(Param); 9371 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9372 assert(S.Context.hasSameType(Param, NonCanonParam)); 9373 9374 // Arg has also been canonicalized, but there's nothing we can do 9375 // about that. It also doesn't matter as much, because it won't 9376 // have any template parameters in it (because deduction isn't 9377 // done on dependent types). 9378 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9379 9380 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9381 << ParamD->getDeclName() << Arg << NonCanonParam; 9382 MaybeEmitInheritedConstructorNote(S, Templated); 9383 return; 9384 } 9385 9386 case Sema::TDK_Inconsistent: { 9387 assert(ParamD && "no parameter found for inconsistent deduction result"); 9388 int which = 0; 9389 if (isa<TemplateTypeParmDecl>(ParamD)) 9390 which = 0; 9391 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9392 which = 1; 9393 else { 9394 which = 2; 9395 } 9396 9397 S.Diag(Templated->getLocation(), 9398 diag::note_ovl_candidate_inconsistent_deduction) 9399 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9400 << *DeductionFailure.getSecondArg(); 9401 MaybeEmitInheritedConstructorNote(S, Templated); 9402 return; 9403 } 9404 9405 case Sema::TDK_InvalidExplicitArguments: 9406 assert(ParamD && "no parameter found for invalid explicit arguments"); 9407 if (ParamD->getDeclName()) 9408 S.Diag(Templated->getLocation(), 9409 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9410 << ParamD->getDeclName(); 9411 else { 9412 int index = 0; 9413 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9414 index = TTP->getIndex(); 9415 else if (NonTypeTemplateParmDecl *NTTP 9416 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9417 index = NTTP->getIndex(); 9418 else 9419 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9420 S.Diag(Templated->getLocation(), 9421 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9422 << (index + 1); 9423 } 9424 MaybeEmitInheritedConstructorNote(S, Templated); 9425 return; 9426 9427 case Sema::TDK_TooManyArguments: 9428 case Sema::TDK_TooFewArguments: 9429 DiagnoseArityMismatch(S, Templated, NumArgs); 9430 return; 9431 9432 case Sema::TDK_InstantiationDepth: 9433 S.Diag(Templated->getLocation(), 9434 diag::note_ovl_candidate_instantiation_depth); 9435 MaybeEmitInheritedConstructorNote(S, Templated); 9436 return; 9437 9438 case Sema::TDK_SubstitutionFailure: { 9439 // Format the template argument list into the argument string. 9440 SmallString<128> TemplateArgString; 9441 if (TemplateArgumentList *Args = 9442 DeductionFailure.getTemplateArgumentList()) { 9443 TemplateArgString = " "; 9444 TemplateArgString += S.getTemplateArgumentBindingsText( 9445 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9446 } 9447 9448 // If this candidate was disabled by enable_if, say so. 9449 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9450 if (PDiag && PDiag->second.getDiagID() == 9451 diag::err_typename_nested_not_found_enable_if) { 9452 // FIXME: Use the source range of the condition, and the fully-qualified 9453 // name of the enable_if template. These are both present in PDiag. 9454 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9455 << "'enable_if'" << TemplateArgString; 9456 return; 9457 } 9458 9459 // Format the SFINAE diagnostic into the argument string. 9460 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9461 // formatted message in another diagnostic. 9462 SmallString<128> SFINAEArgString; 9463 SourceRange R; 9464 if (PDiag) { 9465 SFINAEArgString = ": "; 9466 R = SourceRange(PDiag->first, PDiag->first); 9467 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9468 } 9469 9470 S.Diag(Templated->getLocation(), 9471 diag::note_ovl_candidate_substitution_failure) 9472 << TemplateArgString << SFINAEArgString << R; 9473 MaybeEmitInheritedConstructorNote(S, Templated); 9474 return; 9475 } 9476 9477 case Sema::TDK_FailedOverloadResolution: { 9478 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9479 S.Diag(Templated->getLocation(), 9480 diag::note_ovl_candidate_failed_overload_resolution) 9481 << R.Expression->getName(); 9482 return; 9483 } 9484 9485 case Sema::TDK_DeducedMismatch: { 9486 // Format the template argument list into the argument string. 9487 SmallString<128> TemplateArgString; 9488 if (TemplateArgumentList *Args = 9489 DeductionFailure.getTemplateArgumentList()) { 9490 TemplateArgString = " "; 9491 TemplateArgString += S.getTemplateArgumentBindingsText( 9492 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9493 } 9494 9495 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9496 << (*DeductionFailure.getCallArgIndex() + 1) 9497 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9498 << TemplateArgString; 9499 break; 9500 } 9501 9502 case Sema::TDK_NonDeducedMismatch: { 9503 // FIXME: Provide a source location to indicate what we couldn't match. 9504 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9505 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9506 if (FirstTA.getKind() == TemplateArgument::Template && 9507 SecondTA.getKind() == TemplateArgument::Template) { 9508 TemplateName FirstTN = FirstTA.getAsTemplate(); 9509 TemplateName SecondTN = SecondTA.getAsTemplate(); 9510 if (FirstTN.getKind() == TemplateName::Template && 9511 SecondTN.getKind() == TemplateName::Template) { 9512 if (FirstTN.getAsTemplateDecl()->getName() == 9513 SecondTN.getAsTemplateDecl()->getName()) { 9514 // FIXME: This fixes a bad diagnostic where both templates are named 9515 // the same. This particular case is a bit difficult since: 9516 // 1) It is passed as a string to the diagnostic printer. 9517 // 2) The diagnostic printer only attempts to find a better 9518 // name for types, not decls. 9519 // Ideally, this should folded into the diagnostic printer. 9520 S.Diag(Templated->getLocation(), 9521 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9522 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9523 return; 9524 } 9525 } 9526 } 9527 9528 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9529 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9530 return; 9531 9532 // FIXME: For generic lambda parameters, check if the function is a lambda 9533 // call operator, and if so, emit a prettier and more informative 9534 // diagnostic that mentions 'auto' and lambda in addition to 9535 // (or instead of?) the canonical template type parameters. 9536 S.Diag(Templated->getLocation(), 9537 diag::note_ovl_candidate_non_deduced_mismatch) 9538 << FirstTA << SecondTA; 9539 return; 9540 } 9541 // TODO: diagnose these individually, then kill off 9542 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9543 case Sema::TDK_MiscellaneousDeductionFailure: 9544 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9545 MaybeEmitInheritedConstructorNote(S, Templated); 9546 return; 9547 } 9548 } 9549 9550 /// Diagnose a failed template-argument deduction, for function calls. 9551 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9552 unsigned NumArgs, 9553 bool TakingCandidateAddress) { 9554 unsigned TDK = Cand->DeductionFailure.Result; 9555 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9556 if (CheckArityMismatch(S, Cand, NumArgs)) 9557 return; 9558 } 9559 DiagnoseBadDeduction(S, Cand->Function, // pattern 9560 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9561 } 9562 9563 /// CUDA: diagnose an invalid call across targets. 9564 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9565 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9566 FunctionDecl *Callee = Cand->Function; 9567 9568 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9569 CalleeTarget = S.IdentifyCUDATarget(Callee); 9570 9571 std::string FnDesc; 9572 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9573 9574 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9575 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9576 9577 // This could be an implicit constructor for which we could not infer the 9578 // target due to a collsion. Diagnose that case. 9579 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9580 if (Meth != nullptr && Meth->isImplicit()) { 9581 CXXRecordDecl *ParentClass = Meth->getParent(); 9582 Sema::CXXSpecialMember CSM; 9583 9584 switch (FnKind) { 9585 default: 9586 return; 9587 case oc_implicit_default_constructor: 9588 CSM = Sema::CXXDefaultConstructor; 9589 break; 9590 case oc_implicit_copy_constructor: 9591 CSM = Sema::CXXCopyConstructor; 9592 break; 9593 case oc_implicit_move_constructor: 9594 CSM = Sema::CXXMoveConstructor; 9595 break; 9596 case oc_implicit_copy_assignment: 9597 CSM = Sema::CXXCopyAssignment; 9598 break; 9599 case oc_implicit_move_assignment: 9600 CSM = Sema::CXXMoveAssignment; 9601 break; 9602 }; 9603 9604 bool ConstRHS = false; 9605 if (Meth->getNumParams()) { 9606 if (const ReferenceType *RT = 9607 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9608 ConstRHS = RT->getPointeeType().isConstQualified(); 9609 } 9610 } 9611 9612 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9613 /* ConstRHS */ ConstRHS, 9614 /* Diagnose */ true); 9615 } 9616 } 9617 9618 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9619 FunctionDecl *Callee = Cand->Function; 9620 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9621 9622 S.Diag(Callee->getLocation(), 9623 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9624 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9625 } 9626 9627 /// Generates a 'note' diagnostic for an overload candidate. We've 9628 /// already generated a primary error at the call site. 9629 /// 9630 /// It really does need to be a single diagnostic with its caret 9631 /// pointed at the candidate declaration. Yes, this creates some 9632 /// major challenges of technical writing. Yes, this makes pointing 9633 /// out problems with specific arguments quite awkward. It's still 9634 /// better than generating twenty screens of text for every failed 9635 /// overload. 9636 /// 9637 /// It would be great to be able to express per-candidate problems 9638 /// more richly for those diagnostic clients that cared, but we'd 9639 /// still have to be just as careful with the default diagnostics. 9640 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9641 unsigned NumArgs, 9642 bool TakingCandidateAddress) { 9643 FunctionDecl *Fn = Cand->Function; 9644 9645 // Note deleted candidates, but only if they're viable. 9646 if (Cand->Viable && (Fn->isDeleted() || 9647 S.isFunctionConsideredUnavailable(Fn))) { 9648 std::string FnDesc; 9649 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9650 9651 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9652 << FnKind << FnDesc 9653 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9654 MaybeEmitInheritedConstructorNote(S, Fn); 9655 return; 9656 } 9657 9658 // We don't really have anything else to say about viable candidates. 9659 if (Cand->Viable) { 9660 S.NoteOverloadCandidate(Fn); 9661 return; 9662 } 9663 9664 switch (Cand->FailureKind) { 9665 case ovl_fail_too_many_arguments: 9666 case ovl_fail_too_few_arguments: 9667 return DiagnoseArityMismatch(S, Cand, NumArgs); 9668 9669 case ovl_fail_bad_deduction: 9670 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9671 9672 case ovl_fail_illegal_constructor: { 9673 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9674 << (Fn->getPrimaryTemplate() ? 1 : 0); 9675 MaybeEmitInheritedConstructorNote(S, Fn); 9676 return; 9677 } 9678 9679 case ovl_fail_trivial_conversion: 9680 case ovl_fail_bad_final_conversion: 9681 case ovl_fail_final_conversion_not_exact: 9682 return S.NoteOverloadCandidate(Fn); 9683 9684 case ovl_fail_bad_conversion: { 9685 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9686 for (unsigned N = Cand->NumConversions; I != N; ++I) 9687 if (Cand->Conversions[I].isBad()) 9688 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9689 9690 // FIXME: this currently happens when we're called from SemaInit 9691 // when user-conversion overload fails. Figure out how to handle 9692 // those conditions and diagnose them well. 9693 return S.NoteOverloadCandidate(Fn); 9694 } 9695 9696 case ovl_fail_bad_target: 9697 return DiagnoseBadTarget(S, Cand); 9698 9699 case ovl_fail_enable_if: 9700 return DiagnoseFailedEnableIfAttr(S, Cand); 9701 9702 case ovl_fail_addr_not_available: { 9703 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9704 (void)Available; 9705 assert(!Available); 9706 break; 9707 } 9708 } 9709 } 9710 9711 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9712 // Desugar the type of the surrogate down to a function type, 9713 // retaining as many typedefs as possible while still showing 9714 // the function type (and, therefore, its parameter types). 9715 QualType FnType = Cand->Surrogate->getConversionType(); 9716 bool isLValueReference = false; 9717 bool isRValueReference = false; 9718 bool isPointer = false; 9719 if (const LValueReferenceType *FnTypeRef = 9720 FnType->getAs<LValueReferenceType>()) { 9721 FnType = FnTypeRef->getPointeeType(); 9722 isLValueReference = true; 9723 } else if (const RValueReferenceType *FnTypeRef = 9724 FnType->getAs<RValueReferenceType>()) { 9725 FnType = FnTypeRef->getPointeeType(); 9726 isRValueReference = true; 9727 } 9728 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9729 FnType = FnTypePtr->getPointeeType(); 9730 isPointer = true; 9731 } 9732 // Desugar down to a function type. 9733 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9734 // Reconstruct the pointer/reference as appropriate. 9735 if (isPointer) FnType = S.Context.getPointerType(FnType); 9736 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9737 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9738 9739 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9740 << FnType; 9741 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9742 } 9743 9744 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9745 SourceLocation OpLoc, 9746 OverloadCandidate *Cand) { 9747 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9748 std::string TypeStr("operator"); 9749 TypeStr += Opc; 9750 TypeStr += "("; 9751 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9752 if (Cand->NumConversions == 1) { 9753 TypeStr += ")"; 9754 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9755 } else { 9756 TypeStr += ", "; 9757 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9758 TypeStr += ")"; 9759 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9760 } 9761 } 9762 9763 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9764 OverloadCandidate *Cand) { 9765 unsigned NoOperands = Cand->NumConversions; 9766 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9767 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9768 if (ICS.isBad()) break; // all meaningless after first invalid 9769 if (!ICS.isAmbiguous()) continue; 9770 9771 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9772 S.PDiag(diag::note_ambiguous_type_conversion)); 9773 } 9774 } 9775 9776 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9777 if (Cand->Function) 9778 return Cand->Function->getLocation(); 9779 if (Cand->IsSurrogate) 9780 return Cand->Surrogate->getLocation(); 9781 return SourceLocation(); 9782 } 9783 9784 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9785 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9786 case Sema::TDK_Success: 9787 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9788 9789 case Sema::TDK_Invalid: 9790 case Sema::TDK_Incomplete: 9791 return 1; 9792 9793 case Sema::TDK_Underqualified: 9794 case Sema::TDK_Inconsistent: 9795 return 2; 9796 9797 case Sema::TDK_SubstitutionFailure: 9798 case Sema::TDK_DeducedMismatch: 9799 case Sema::TDK_NonDeducedMismatch: 9800 case Sema::TDK_MiscellaneousDeductionFailure: 9801 return 3; 9802 9803 case Sema::TDK_InstantiationDepth: 9804 case Sema::TDK_FailedOverloadResolution: 9805 return 4; 9806 9807 case Sema::TDK_InvalidExplicitArguments: 9808 return 5; 9809 9810 case Sema::TDK_TooManyArguments: 9811 case Sema::TDK_TooFewArguments: 9812 return 6; 9813 } 9814 llvm_unreachable("Unhandled deduction result"); 9815 } 9816 9817 namespace { 9818 struct CompareOverloadCandidatesForDisplay { 9819 Sema &S; 9820 SourceLocation Loc; 9821 size_t NumArgs; 9822 9823 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9824 : S(S), NumArgs(nArgs) {} 9825 9826 bool operator()(const OverloadCandidate *L, 9827 const OverloadCandidate *R) { 9828 // Fast-path this check. 9829 if (L == R) return false; 9830 9831 // Order first by viability. 9832 if (L->Viable) { 9833 if (!R->Viable) return true; 9834 9835 // TODO: introduce a tri-valued comparison for overload 9836 // candidates. Would be more worthwhile if we had a sort 9837 // that could exploit it. 9838 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9839 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9840 } else if (R->Viable) 9841 return false; 9842 9843 assert(L->Viable == R->Viable); 9844 9845 // Criteria by which we can sort non-viable candidates: 9846 if (!L->Viable) { 9847 // 1. Arity mismatches come after other candidates. 9848 if (L->FailureKind == ovl_fail_too_many_arguments || 9849 L->FailureKind == ovl_fail_too_few_arguments) { 9850 if (R->FailureKind == ovl_fail_too_many_arguments || 9851 R->FailureKind == ovl_fail_too_few_arguments) { 9852 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9853 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9854 if (LDist == RDist) { 9855 if (L->FailureKind == R->FailureKind) 9856 // Sort non-surrogates before surrogates. 9857 return !L->IsSurrogate && R->IsSurrogate; 9858 // Sort candidates requiring fewer parameters than there were 9859 // arguments given after candidates requiring more parameters 9860 // than there were arguments given. 9861 return L->FailureKind == ovl_fail_too_many_arguments; 9862 } 9863 return LDist < RDist; 9864 } 9865 return false; 9866 } 9867 if (R->FailureKind == ovl_fail_too_many_arguments || 9868 R->FailureKind == ovl_fail_too_few_arguments) 9869 return true; 9870 9871 // 2. Bad conversions come first and are ordered by the number 9872 // of bad conversions and quality of good conversions. 9873 if (L->FailureKind == ovl_fail_bad_conversion) { 9874 if (R->FailureKind != ovl_fail_bad_conversion) 9875 return true; 9876 9877 // The conversion that can be fixed with a smaller number of changes, 9878 // comes first. 9879 unsigned numLFixes = L->Fix.NumConversionsFixed; 9880 unsigned numRFixes = R->Fix.NumConversionsFixed; 9881 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9882 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9883 if (numLFixes != numRFixes) { 9884 return numLFixes < numRFixes; 9885 } 9886 9887 // If there's any ordering between the defined conversions... 9888 // FIXME: this might not be transitive. 9889 assert(L->NumConversions == R->NumConversions); 9890 9891 int leftBetter = 0; 9892 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9893 for (unsigned E = L->NumConversions; I != E; ++I) { 9894 switch (CompareImplicitConversionSequences(S, Loc, 9895 L->Conversions[I], 9896 R->Conversions[I])) { 9897 case ImplicitConversionSequence::Better: 9898 leftBetter++; 9899 break; 9900 9901 case ImplicitConversionSequence::Worse: 9902 leftBetter--; 9903 break; 9904 9905 case ImplicitConversionSequence::Indistinguishable: 9906 break; 9907 } 9908 } 9909 if (leftBetter > 0) return true; 9910 if (leftBetter < 0) return false; 9911 9912 } else if (R->FailureKind == ovl_fail_bad_conversion) 9913 return false; 9914 9915 if (L->FailureKind == ovl_fail_bad_deduction) { 9916 if (R->FailureKind != ovl_fail_bad_deduction) 9917 return true; 9918 9919 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9920 return RankDeductionFailure(L->DeductionFailure) 9921 < RankDeductionFailure(R->DeductionFailure); 9922 } else if (R->FailureKind == ovl_fail_bad_deduction) 9923 return false; 9924 9925 // TODO: others? 9926 } 9927 9928 // Sort everything else by location. 9929 SourceLocation LLoc = GetLocationForCandidate(L); 9930 SourceLocation RLoc = GetLocationForCandidate(R); 9931 9932 // Put candidates without locations (e.g. builtins) at the end. 9933 if (LLoc.isInvalid()) return false; 9934 if (RLoc.isInvalid()) return true; 9935 9936 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9937 } 9938 }; 9939 } 9940 9941 /// CompleteNonViableCandidate - Normally, overload resolution only 9942 /// computes up to the first. Produces the FixIt set if possible. 9943 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9944 ArrayRef<Expr *> Args) { 9945 assert(!Cand->Viable); 9946 9947 // Don't do anything on failures other than bad conversion. 9948 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9949 9950 // We only want the FixIts if all the arguments can be corrected. 9951 bool Unfixable = false; 9952 // Use a implicit copy initialization to check conversion fixes. 9953 Cand->Fix.setConversionChecker(TryCopyInitialization); 9954 9955 // Skip forward to the first bad conversion. 9956 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9957 unsigned ConvCount = Cand->NumConversions; 9958 while (true) { 9959 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9960 ConvIdx++; 9961 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9962 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9963 break; 9964 } 9965 } 9966 9967 if (ConvIdx == ConvCount) 9968 return; 9969 9970 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9971 "remaining conversion is initialized?"); 9972 9973 // FIXME: this should probably be preserved from the overload 9974 // operation somehow. 9975 bool SuppressUserConversions = false; 9976 9977 const FunctionProtoType* Proto; 9978 unsigned ArgIdx = ConvIdx; 9979 9980 if (Cand->IsSurrogate) { 9981 QualType ConvType 9982 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9983 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9984 ConvType = ConvPtrType->getPointeeType(); 9985 Proto = ConvType->getAs<FunctionProtoType>(); 9986 ArgIdx--; 9987 } else if (Cand->Function) { 9988 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9989 if (isa<CXXMethodDecl>(Cand->Function) && 9990 !isa<CXXConstructorDecl>(Cand->Function)) 9991 ArgIdx--; 9992 } else { 9993 // Builtin binary operator with a bad first conversion. 9994 assert(ConvCount <= 3); 9995 for (; ConvIdx != ConvCount; ++ConvIdx) 9996 Cand->Conversions[ConvIdx] 9997 = TryCopyInitialization(S, Args[ConvIdx], 9998 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9999 SuppressUserConversions, 10000 /*InOverloadResolution*/ true, 10001 /*AllowObjCWritebackConversion=*/ 10002 S.getLangOpts().ObjCAutoRefCount); 10003 return; 10004 } 10005 10006 // Fill in the rest of the conversions. 10007 unsigned NumParams = Proto->getNumParams(); 10008 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10009 if (ArgIdx < NumParams) { 10010 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10011 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10012 /*InOverloadResolution=*/true, 10013 /*AllowObjCWritebackConversion=*/ 10014 S.getLangOpts().ObjCAutoRefCount); 10015 // Store the FixIt in the candidate if it exists. 10016 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10017 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10018 } 10019 else 10020 Cand->Conversions[ConvIdx].setEllipsis(); 10021 } 10022 } 10023 10024 /// PrintOverloadCandidates - When overload resolution fails, prints 10025 /// diagnostic messages containing the candidates in the candidate 10026 /// set. 10027 void OverloadCandidateSet::NoteCandidates(Sema &S, 10028 OverloadCandidateDisplayKind OCD, 10029 ArrayRef<Expr *> Args, 10030 StringRef Opc, 10031 SourceLocation OpLoc) { 10032 // Sort the candidates by viability and position. Sorting directly would 10033 // be prohibitive, so we make a set of pointers and sort those. 10034 SmallVector<OverloadCandidate*, 32> Cands; 10035 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10036 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10037 if (Cand->Viable) 10038 Cands.push_back(Cand); 10039 else if (OCD == OCD_AllCandidates) { 10040 CompleteNonViableCandidate(S, Cand, Args); 10041 if (Cand->Function || Cand->IsSurrogate) 10042 Cands.push_back(Cand); 10043 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10044 // want to list every possible builtin candidate. 10045 } 10046 } 10047 10048 std::sort(Cands.begin(), Cands.end(), 10049 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10050 10051 bool ReportedAmbiguousConversions = false; 10052 10053 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10054 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10055 unsigned CandsShown = 0; 10056 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10057 OverloadCandidate *Cand = *I; 10058 10059 // Set an arbitrary limit on the number of candidate functions we'll spam 10060 // the user with. FIXME: This limit should depend on details of the 10061 // candidate list. 10062 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10063 break; 10064 } 10065 ++CandsShown; 10066 10067 if (Cand->Function) 10068 NoteFunctionCandidate(S, Cand, Args.size(), 10069 /*TakingCandidateAddress=*/false); 10070 else if (Cand->IsSurrogate) 10071 NoteSurrogateCandidate(S, Cand); 10072 else { 10073 assert(Cand->Viable && 10074 "Non-viable built-in candidates are not added to Cands."); 10075 // Generally we only see ambiguities including viable builtin 10076 // operators if overload resolution got screwed up by an 10077 // ambiguous user-defined conversion. 10078 // 10079 // FIXME: It's quite possible for different conversions to see 10080 // different ambiguities, though. 10081 if (!ReportedAmbiguousConversions) { 10082 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10083 ReportedAmbiguousConversions = true; 10084 } 10085 10086 // If this is a viable builtin, print it. 10087 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10088 } 10089 } 10090 10091 if (I != E) 10092 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10093 } 10094 10095 static SourceLocation 10096 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10097 return Cand->Specialization ? Cand->Specialization->getLocation() 10098 : SourceLocation(); 10099 } 10100 10101 namespace { 10102 struct CompareTemplateSpecCandidatesForDisplay { 10103 Sema &S; 10104 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10105 10106 bool operator()(const TemplateSpecCandidate *L, 10107 const TemplateSpecCandidate *R) { 10108 // Fast-path this check. 10109 if (L == R) 10110 return false; 10111 10112 // Assuming that both candidates are not matches... 10113 10114 // Sort by the ranking of deduction failures. 10115 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10116 return RankDeductionFailure(L->DeductionFailure) < 10117 RankDeductionFailure(R->DeductionFailure); 10118 10119 // Sort everything else by location. 10120 SourceLocation LLoc = GetLocationForCandidate(L); 10121 SourceLocation RLoc = GetLocationForCandidate(R); 10122 10123 // Put candidates without locations (e.g. builtins) at the end. 10124 if (LLoc.isInvalid()) 10125 return false; 10126 if (RLoc.isInvalid()) 10127 return true; 10128 10129 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10130 } 10131 }; 10132 } 10133 10134 /// Diagnose a template argument deduction failure. 10135 /// We are treating these failures as overload failures due to bad 10136 /// deductions. 10137 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10138 bool ForTakingAddress) { 10139 DiagnoseBadDeduction(S, Specialization, // pattern 10140 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10141 } 10142 10143 void TemplateSpecCandidateSet::destroyCandidates() { 10144 for (iterator i = begin(), e = end(); i != e; ++i) { 10145 i->DeductionFailure.Destroy(); 10146 } 10147 } 10148 10149 void TemplateSpecCandidateSet::clear() { 10150 destroyCandidates(); 10151 Candidates.clear(); 10152 } 10153 10154 /// NoteCandidates - When no template specialization match is found, prints 10155 /// diagnostic messages containing the non-matching specializations that form 10156 /// the candidate set. 10157 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10158 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10159 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10160 // Sort the candidates by position (assuming no candidate is a match). 10161 // Sorting directly would be prohibitive, so we make a set of pointers 10162 // and sort those. 10163 SmallVector<TemplateSpecCandidate *, 32> Cands; 10164 Cands.reserve(size()); 10165 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10166 if (Cand->Specialization) 10167 Cands.push_back(Cand); 10168 // Otherwise, this is a non-matching builtin candidate. We do not, 10169 // in general, want to list every possible builtin candidate. 10170 } 10171 10172 std::sort(Cands.begin(), Cands.end(), 10173 CompareTemplateSpecCandidatesForDisplay(S)); 10174 10175 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10176 // for generalization purposes (?). 10177 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10178 10179 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10180 unsigned CandsShown = 0; 10181 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10182 TemplateSpecCandidate *Cand = *I; 10183 10184 // Set an arbitrary limit on the number of candidates we'll spam 10185 // the user with. FIXME: This limit should depend on details of the 10186 // candidate list. 10187 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10188 break; 10189 ++CandsShown; 10190 10191 assert(Cand->Specialization && 10192 "Non-matching built-in candidates are not added to Cands."); 10193 Cand->NoteDeductionFailure(S, ForTakingAddress); 10194 } 10195 10196 if (I != E) 10197 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10198 } 10199 10200 // [PossiblyAFunctionType] --> [Return] 10201 // NonFunctionType --> NonFunctionType 10202 // R (A) --> R(A) 10203 // R (*)(A) --> R (A) 10204 // R (&)(A) --> R (A) 10205 // R (S::*)(A) --> R (A) 10206 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10207 QualType Ret = PossiblyAFunctionType; 10208 if (const PointerType *ToTypePtr = 10209 PossiblyAFunctionType->getAs<PointerType>()) 10210 Ret = ToTypePtr->getPointeeType(); 10211 else if (const ReferenceType *ToTypeRef = 10212 PossiblyAFunctionType->getAs<ReferenceType>()) 10213 Ret = ToTypeRef->getPointeeType(); 10214 else if (const MemberPointerType *MemTypePtr = 10215 PossiblyAFunctionType->getAs<MemberPointerType>()) 10216 Ret = MemTypePtr->getPointeeType(); 10217 Ret = 10218 Context.getCanonicalType(Ret).getUnqualifiedType(); 10219 return Ret; 10220 } 10221 10222 namespace { 10223 // A helper class to help with address of function resolution 10224 // - allows us to avoid passing around all those ugly parameters 10225 class AddressOfFunctionResolver { 10226 Sema& S; 10227 Expr* SourceExpr; 10228 const QualType& TargetType; 10229 QualType TargetFunctionType; // Extracted function type from target type 10230 10231 bool Complain; 10232 //DeclAccessPair& ResultFunctionAccessPair; 10233 ASTContext& Context; 10234 10235 bool TargetTypeIsNonStaticMemberFunction; 10236 bool FoundNonTemplateFunction; 10237 bool StaticMemberFunctionFromBoundPointer; 10238 bool HasComplained; 10239 10240 OverloadExpr::FindResult OvlExprInfo; 10241 OverloadExpr *OvlExpr; 10242 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10243 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10244 TemplateSpecCandidateSet FailedCandidates; 10245 10246 public: 10247 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10248 const QualType &TargetType, bool Complain) 10249 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10250 Complain(Complain), Context(S.getASTContext()), 10251 TargetTypeIsNonStaticMemberFunction( 10252 !!TargetType->getAs<MemberPointerType>()), 10253 FoundNonTemplateFunction(false), 10254 StaticMemberFunctionFromBoundPointer(false), 10255 HasComplained(false), 10256 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10257 OvlExpr(OvlExprInfo.Expression), 10258 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10259 ExtractUnqualifiedFunctionTypeFromTargetType(); 10260 10261 if (TargetFunctionType->isFunctionType()) { 10262 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10263 if (!UME->isImplicitAccess() && 10264 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10265 StaticMemberFunctionFromBoundPointer = true; 10266 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10267 DeclAccessPair dap; 10268 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10269 OvlExpr, false, &dap)) { 10270 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10271 if (!Method->isStatic()) { 10272 // If the target type is a non-function type and the function found 10273 // is a non-static member function, pretend as if that was the 10274 // target, it's the only possible type to end up with. 10275 TargetTypeIsNonStaticMemberFunction = true; 10276 10277 // And skip adding the function if its not in the proper form. 10278 // We'll diagnose this due to an empty set of functions. 10279 if (!OvlExprInfo.HasFormOfMemberPointer) 10280 return; 10281 } 10282 10283 Matches.push_back(std::make_pair(dap, Fn)); 10284 } 10285 return; 10286 } 10287 10288 if (OvlExpr->hasExplicitTemplateArgs()) 10289 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10290 10291 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10292 // C++ [over.over]p4: 10293 // If more than one function is selected, [...] 10294 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10295 if (FoundNonTemplateFunction) 10296 EliminateAllTemplateMatches(); 10297 else 10298 EliminateAllExceptMostSpecializedTemplate(); 10299 } 10300 } 10301 10302 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10303 Matches.size() > 1) 10304 EliminateSuboptimalCudaMatches(); 10305 } 10306 10307 bool hasComplained() const { return HasComplained; } 10308 10309 private: 10310 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10311 QualType Discard; 10312 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10313 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard); 10314 } 10315 10316 /// \return true if A is considered a better overload candidate for the 10317 /// desired type than B. 10318 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10319 // If A doesn't have exactly the correct type, we don't want to classify it 10320 // as "better" than anything else. This way, the user is required to 10321 // disambiguate for us if there are multiple candidates and no exact match. 10322 return candidateHasExactlyCorrectType(A) && 10323 (!candidateHasExactlyCorrectType(B) || 10324 hasBetterEnableIfAttrs(S, A, B)); 10325 } 10326 10327 /// \return true if we were able to eliminate all but one overload candidate, 10328 /// false otherwise. 10329 bool eliminiateSuboptimalOverloadCandidates() { 10330 // Same algorithm as overload resolution -- one pass to pick the "best", 10331 // another pass to be sure that nothing is better than the best. 10332 auto Best = Matches.begin(); 10333 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10334 if (isBetterCandidate(I->second, Best->second)) 10335 Best = I; 10336 10337 const FunctionDecl *BestFn = Best->second; 10338 auto IsBestOrInferiorToBest = [this, BestFn]( 10339 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10340 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10341 }; 10342 10343 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10344 // option, so we can potentially give the user a better error 10345 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10346 return false; 10347 Matches[0] = *Best; 10348 Matches.resize(1); 10349 return true; 10350 } 10351 10352 bool isTargetTypeAFunction() const { 10353 return TargetFunctionType->isFunctionType(); 10354 } 10355 10356 // [ToType] [Return] 10357 10358 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10359 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10360 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10361 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10362 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10363 } 10364 10365 // return true if any matching specializations were found 10366 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10367 const DeclAccessPair& CurAccessFunPair) { 10368 if (CXXMethodDecl *Method 10369 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10370 // Skip non-static function templates when converting to pointer, and 10371 // static when converting to member pointer. 10372 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10373 return false; 10374 } 10375 else if (TargetTypeIsNonStaticMemberFunction) 10376 return false; 10377 10378 // C++ [over.over]p2: 10379 // If the name is a function template, template argument deduction is 10380 // done (14.8.2.2), and if the argument deduction succeeds, the 10381 // resulting template argument list is used to generate a single 10382 // function template specialization, which is added to the set of 10383 // overloaded functions considered. 10384 FunctionDecl *Specialization = nullptr; 10385 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10386 if (Sema::TemplateDeductionResult Result 10387 = S.DeduceTemplateArguments(FunctionTemplate, 10388 &OvlExplicitTemplateArgs, 10389 TargetFunctionType, Specialization, 10390 Info, /*InOverloadResolution=*/true)) { 10391 // Make a note of the failed deduction for diagnostics. 10392 FailedCandidates.addCandidate() 10393 .set(FunctionTemplate->getTemplatedDecl(), 10394 MakeDeductionFailureInfo(Context, Result, Info)); 10395 return false; 10396 } 10397 10398 // Template argument deduction ensures that we have an exact match or 10399 // compatible pointer-to-function arguments that would be adjusted by ICS. 10400 // This function template specicalization works. 10401 assert(S.isSameOrCompatibleFunctionType( 10402 Context.getCanonicalType(Specialization->getType()), 10403 Context.getCanonicalType(TargetFunctionType))); 10404 10405 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10406 return false; 10407 10408 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10409 return true; 10410 } 10411 10412 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10413 const DeclAccessPair& CurAccessFunPair) { 10414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10415 // Skip non-static functions when converting to pointer, and static 10416 // when converting to member pointer. 10417 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10418 return false; 10419 } 10420 else if (TargetTypeIsNonStaticMemberFunction) 10421 return false; 10422 10423 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10424 if (S.getLangOpts().CUDA) 10425 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10426 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10427 return false; 10428 10429 // If any candidate has a placeholder return type, trigger its deduction 10430 // now. 10431 if (S.getLangOpts().CPlusPlus14 && 10432 FunDecl->getReturnType()->isUndeducedType() && 10433 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10434 HasComplained |= Complain; 10435 return false; 10436 } 10437 10438 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10439 return false; 10440 10441 // If we're in C, we need to support types that aren't exactly identical. 10442 if (!S.getLangOpts().CPlusPlus || 10443 candidateHasExactlyCorrectType(FunDecl)) { 10444 Matches.push_back(std::make_pair( 10445 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10446 FoundNonTemplateFunction = true; 10447 return true; 10448 } 10449 } 10450 10451 return false; 10452 } 10453 10454 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10455 bool Ret = false; 10456 10457 // If the overload expression doesn't have the form of a pointer to 10458 // member, don't try to convert it to a pointer-to-member type. 10459 if (IsInvalidFormOfPointerToMemberFunction()) 10460 return false; 10461 10462 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10463 E = OvlExpr->decls_end(); 10464 I != E; ++I) { 10465 // Look through any using declarations to find the underlying function. 10466 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10467 10468 // C++ [over.over]p3: 10469 // Non-member functions and static member functions match 10470 // targets of type "pointer-to-function" or "reference-to-function." 10471 // Nonstatic member functions match targets of 10472 // type "pointer-to-member-function." 10473 // Note that according to DR 247, the containing class does not matter. 10474 if (FunctionTemplateDecl *FunctionTemplate 10475 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10476 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10477 Ret = true; 10478 } 10479 // If we have explicit template arguments supplied, skip non-templates. 10480 else if (!OvlExpr->hasExplicitTemplateArgs() && 10481 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10482 Ret = true; 10483 } 10484 assert(Ret || Matches.empty()); 10485 return Ret; 10486 } 10487 10488 void EliminateAllExceptMostSpecializedTemplate() { 10489 // [...] and any given function template specialization F1 is 10490 // eliminated if the set contains a second function template 10491 // specialization whose function template is more specialized 10492 // than the function template of F1 according to the partial 10493 // ordering rules of 14.5.5.2. 10494 10495 // The algorithm specified above is quadratic. We instead use a 10496 // two-pass algorithm (similar to the one used to identify the 10497 // best viable function in an overload set) that identifies the 10498 // best function template (if it exists). 10499 10500 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10501 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10502 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10503 10504 // TODO: It looks like FailedCandidates does not serve much purpose 10505 // here, since the no_viable diagnostic has index 0. 10506 UnresolvedSetIterator Result = S.getMostSpecialized( 10507 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10508 SourceExpr->getLocStart(), S.PDiag(), 10509 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10510 .second->getDeclName(), 10511 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10512 Complain, TargetFunctionType); 10513 10514 if (Result != MatchesCopy.end()) { 10515 // Make it the first and only element 10516 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10517 Matches[0].second = cast<FunctionDecl>(*Result); 10518 Matches.resize(1); 10519 } else 10520 HasComplained |= Complain; 10521 } 10522 10523 void EliminateAllTemplateMatches() { 10524 // [...] any function template specializations in the set are 10525 // eliminated if the set also contains a non-template function, [...] 10526 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10527 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10528 ++I; 10529 else { 10530 Matches[I] = Matches[--N]; 10531 Matches.resize(N); 10532 } 10533 } 10534 } 10535 10536 void EliminateSuboptimalCudaMatches() { 10537 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10538 } 10539 10540 public: 10541 void ComplainNoMatchesFound() const { 10542 assert(Matches.empty()); 10543 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10544 << OvlExpr->getName() << TargetFunctionType 10545 << OvlExpr->getSourceRange(); 10546 if (FailedCandidates.empty()) 10547 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10548 /*TakingAddress=*/true); 10549 else { 10550 // We have some deduction failure messages. Use them to diagnose 10551 // the function templates, and diagnose the non-template candidates 10552 // normally. 10553 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10554 IEnd = OvlExpr->decls_end(); 10555 I != IEnd; ++I) 10556 if (FunctionDecl *Fun = 10557 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10558 if (!functionHasPassObjectSizeParams(Fun)) 10559 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10560 /*TakingAddress=*/true); 10561 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10562 } 10563 } 10564 10565 bool IsInvalidFormOfPointerToMemberFunction() const { 10566 return TargetTypeIsNonStaticMemberFunction && 10567 !OvlExprInfo.HasFormOfMemberPointer; 10568 } 10569 10570 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10571 // TODO: Should we condition this on whether any functions might 10572 // have matched, or is it more appropriate to do that in callers? 10573 // TODO: a fixit wouldn't hurt. 10574 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10575 << TargetType << OvlExpr->getSourceRange(); 10576 } 10577 10578 bool IsStaticMemberFunctionFromBoundPointer() const { 10579 return StaticMemberFunctionFromBoundPointer; 10580 } 10581 10582 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10583 S.Diag(OvlExpr->getLocStart(), 10584 diag::err_invalid_form_pointer_member_function) 10585 << OvlExpr->getSourceRange(); 10586 } 10587 10588 void ComplainOfInvalidConversion() const { 10589 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10590 << OvlExpr->getName() << TargetType; 10591 } 10592 10593 void ComplainMultipleMatchesFound() const { 10594 assert(Matches.size() > 1); 10595 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10596 << OvlExpr->getName() 10597 << OvlExpr->getSourceRange(); 10598 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10599 /*TakingAddress=*/true); 10600 } 10601 10602 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10603 10604 int getNumMatches() const { return Matches.size(); } 10605 10606 FunctionDecl* getMatchingFunctionDecl() const { 10607 if (Matches.size() != 1) return nullptr; 10608 return Matches[0].second; 10609 } 10610 10611 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10612 if (Matches.size() != 1) return nullptr; 10613 return &Matches[0].first; 10614 } 10615 }; 10616 } 10617 10618 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10619 /// an overloaded function (C++ [over.over]), where @p From is an 10620 /// expression with overloaded function type and @p ToType is the type 10621 /// we're trying to resolve to. For example: 10622 /// 10623 /// @code 10624 /// int f(double); 10625 /// int f(int); 10626 /// 10627 /// int (*pfd)(double) = f; // selects f(double) 10628 /// @endcode 10629 /// 10630 /// This routine returns the resulting FunctionDecl if it could be 10631 /// resolved, and NULL otherwise. When @p Complain is true, this 10632 /// routine will emit diagnostics if there is an error. 10633 FunctionDecl * 10634 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10635 QualType TargetType, 10636 bool Complain, 10637 DeclAccessPair &FoundResult, 10638 bool *pHadMultipleCandidates) { 10639 assert(AddressOfExpr->getType() == Context.OverloadTy); 10640 10641 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10642 Complain); 10643 int NumMatches = Resolver.getNumMatches(); 10644 FunctionDecl *Fn = nullptr; 10645 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10646 if (NumMatches == 0 && ShouldComplain) { 10647 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10648 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10649 else 10650 Resolver.ComplainNoMatchesFound(); 10651 } 10652 else if (NumMatches > 1 && ShouldComplain) 10653 Resolver.ComplainMultipleMatchesFound(); 10654 else if (NumMatches == 1) { 10655 Fn = Resolver.getMatchingFunctionDecl(); 10656 assert(Fn); 10657 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10658 if (Complain) { 10659 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10660 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10661 else 10662 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10663 } 10664 } 10665 10666 if (pHadMultipleCandidates) 10667 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10668 return Fn; 10669 } 10670 10671 /// \brief Given an expression that refers to an overloaded function, try to 10672 /// resolve that function to a single function that can have its address taken. 10673 /// This will modify `Pair` iff it returns non-null. 10674 /// 10675 /// This routine can only realistically succeed if all but one candidates in the 10676 /// overload set for SrcExpr cannot have their addresses taken. 10677 FunctionDecl * 10678 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10679 DeclAccessPair &Pair) { 10680 OverloadExpr::FindResult R = OverloadExpr::find(E); 10681 OverloadExpr *Ovl = R.Expression; 10682 FunctionDecl *Result = nullptr; 10683 DeclAccessPair DAP; 10684 // Don't use the AddressOfResolver because we're specifically looking for 10685 // cases where we have one overload candidate that lacks 10686 // enable_if/pass_object_size/... 10687 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10688 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10689 if (!FD) 10690 return nullptr; 10691 10692 if (!checkAddressOfFunctionIsAvailable(FD)) 10693 continue; 10694 10695 // We have more than one result; quit. 10696 if (Result) 10697 return nullptr; 10698 DAP = I.getPair(); 10699 Result = FD; 10700 } 10701 10702 if (Result) 10703 Pair = DAP; 10704 return Result; 10705 } 10706 10707 /// \brief Given an expression that refers to an overloaded function, try to 10708 /// resolve that overloaded function expression down to a single function. 10709 /// 10710 /// This routine can only resolve template-ids that refer to a single function 10711 /// template, where that template-id refers to a single template whose template 10712 /// arguments are either provided by the template-id or have defaults, 10713 /// as described in C++0x [temp.arg.explicit]p3. 10714 /// 10715 /// If no template-ids are found, no diagnostics are emitted and NULL is 10716 /// returned. 10717 FunctionDecl * 10718 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10719 bool Complain, 10720 DeclAccessPair *FoundResult) { 10721 // C++ [over.over]p1: 10722 // [...] [Note: any redundant set of parentheses surrounding the 10723 // overloaded function name is ignored (5.1). ] 10724 // C++ [over.over]p1: 10725 // [...] The overloaded function name can be preceded by the & 10726 // operator. 10727 10728 // If we didn't actually find any template-ids, we're done. 10729 if (!ovl->hasExplicitTemplateArgs()) 10730 return nullptr; 10731 10732 TemplateArgumentListInfo ExplicitTemplateArgs; 10733 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10734 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10735 10736 // Look through all of the overloaded functions, searching for one 10737 // whose type matches exactly. 10738 FunctionDecl *Matched = nullptr; 10739 for (UnresolvedSetIterator I = ovl->decls_begin(), 10740 E = ovl->decls_end(); I != E; ++I) { 10741 // C++0x [temp.arg.explicit]p3: 10742 // [...] In contexts where deduction is done and fails, or in contexts 10743 // where deduction is not done, if a template argument list is 10744 // specified and it, along with any default template arguments, 10745 // identifies a single function template specialization, then the 10746 // template-id is an lvalue for the function template specialization. 10747 FunctionTemplateDecl *FunctionTemplate 10748 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10749 10750 // C++ [over.over]p2: 10751 // If the name is a function template, template argument deduction is 10752 // done (14.8.2.2), and if the argument deduction succeeds, the 10753 // resulting template argument list is used to generate a single 10754 // function template specialization, which is added to the set of 10755 // overloaded functions considered. 10756 FunctionDecl *Specialization = nullptr; 10757 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10758 if (TemplateDeductionResult Result 10759 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10760 Specialization, Info, 10761 /*InOverloadResolution=*/true)) { 10762 // Make a note of the failed deduction for diagnostics. 10763 // TODO: Actually use the failed-deduction info? 10764 FailedCandidates.addCandidate() 10765 .set(FunctionTemplate->getTemplatedDecl(), 10766 MakeDeductionFailureInfo(Context, Result, Info)); 10767 continue; 10768 } 10769 10770 assert(Specialization && "no specialization and no error?"); 10771 10772 // Multiple matches; we can't resolve to a single declaration. 10773 if (Matched) { 10774 if (Complain) { 10775 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10776 << ovl->getName(); 10777 NoteAllOverloadCandidates(ovl); 10778 } 10779 return nullptr; 10780 } 10781 10782 Matched = Specialization; 10783 if (FoundResult) *FoundResult = I.getPair(); 10784 } 10785 10786 if (Matched && getLangOpts().CPlusPlus14 && 10787 Matched->getReturnType()->isUndeducedType() && 10788 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10789 return nullptr; 10790 10791 return Matched; 10792 } 10793 10794 10795 10796 10797 // Resolve and fix an overloaded expression that can be resolved 10798 // because it identifies a single function template specialization. 10799 // 10800 // Last three arguments should only be supplied if Complain = true 10801 // 10802 // Return true if it was logically possible to so resolve the 10803 // expression, regardless of whether or not it succeeded. Always 10804 // returns true if 'complain' is set. 10805 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10806 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10807 bool complain, SourceRange OpRangeForComplaining, 10808 QualType DestTypeForComplaining, 10809 unsigned DiagIDForComplaining) { 10810 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10811 10812 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10813 10814 DeclAccessPair found; 10815 ExprResult SingleFunctionExpression; 10816 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10817 ovl.Expression, /*complain*/ false, &found)) { 10818 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10819 SrcExpr = ExprError(); 10820 return true; 10821 } 10822 10823 // It is only correct to resolve to an instance method if we're 10824 // resolving a form that's permitted to be a pointer to member. 10825 // Otherwise we'll end up making a bound member expression, which 10826 // is illegal in all the contexts we resolve like this. 10827 if (!ovl.HasFormOfMemberPointer && 10828 isa<CXXMethodDecl>(fn) && 10829 cast<CXXMethodDecl>(fn)->isInstance()) { 10830 if (!complain) return false; 10831 10832 Diag(ovl.Expression->getExprLoc(), 10833 diag::err_bound_member_function) 10834 << 0 << ovl.Expression->getSourceRange(); 10835 10836 // TODO: I believe we only end up here if there's a mix of 10837 // static and non-static candidates (otherwise the expression 10838 // would have 'bound member' type, not 'overload' type). 10839 // Ideally we would note which candidate was chosen and why 10840 // the static candidates were rejected. 10841 SrcExpr = ExprError(); 10842 return true; 10843 } 10844 10845 // Fix the expression to refer to 'fn'. 10846 SingleFunctionExpression = 10847 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10848 10849 // If desired, do function-to-pointer decay. 10850 if (doFunctionPointerConverion) { 10851 SingleFunctionExpression = 10852 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10853 if (SingleFunctionExpression.isInvalid()) { 10854 SrcExpr = ExprError(); 10855 return true; 10856 } 10857 } 10858 } 10859 10860 if (!SingleFunctionExpression.isUsable()) { 10861 if (complain) { 10862 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10863 << ovl.Expression->getName() 10864 << DestTypeForComplaining 10865 << OpRangeForComplaining 10866 << ovl.Expression->getQualifierLoc().getSourceRange(); 10867 NoteAllOverloadCandidates(SrcExpr.get()); 10868 10869 SrcExpr = ExprError(); 10870 return true; 10871 } 10872 10873 return false; 10874 } 10875 10876 SrcExpr = SingleFunctionExpression; 10877 return true; 10878 } 10879 10880 /// \brief Add a single candidate to the overload set. 10881 static void AddOverloadedCallCandidate(Sema &S, 10882 DeclAccessPair FoundDecl, 10883 TemplateArgumentListInfo *ExplicitTemplateArgs, 10884 ArrayRef<Expr *> Args, 10885 OverloadCandidateSet &CandidateSet, 10886 bool PartialOverloading, 10887 bool KnownValid) { 10888 NamedDecl *Callee = FoundDecl.getDecl(); 10889 if (isa<UsingShadowDecl>(Callee)) 10890 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10891 10892 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10893 if (ExplicitTemplateArgs) { 10894 assert(!KnownValid && "Explicit template arguments?"); 10895 return; 10896 } 10897 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10898 /*SuppressUsedConversions=*/false, 10899 PartialOverloading); 10900 return; 10901 } 10902 10903 if (FunctionTemplateDecl *FuncTemplate 10904 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10905 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10906 ExplicitTemplateArgs, Args, CandidateSet, 10907 /*SuppressUsedConversions=*/false, 10908 PartialOverloading); 10909 return; 10910 } 10911 10912 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10913 } 10914 10915 /// \brief Add the overload candidates named by callee and/or found by argument 10916 /// dependent lookup to the given overload set. 10917 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10918 ArrayRef<Expr *> Args, 10919 OverloadCandidateSet &CandidateSet, 10920 bool PartialOverloading) { 10921 10922 #ifndef NDEBUG 10923 // Verify that ArgumentDependentLookup is consistent with the rules 10924 // in C++0x [basic.lookup.argdep]p3: 10925 // 10926 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10927 // and let Y be the lookup set produced by argument dependent 10928 // lookup (defined as follows). If X contains 10929 // 10930 // -- a declaration of a class member, or 10931 // 10932 // -- a block-scope function declaration that is not a 10933 // using-declaration, or 10934 // 10935 // -- a declaration that is neither a function or a function 10936 // template 10937 // 10938 // then Y is empty. 10939 10940 if (ULE->requiresADL()) { 10941 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10942 E = ULE->decls_end(); I != E; ++I) { 10943 assert(!(*I)->getDeclContext()->isRecord()); 10944 assert(isa<UsingShadowDecl>(*I) || 10945 !(*I)->getDeclContext()->isFunctionOrMethod()); 10946 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10947 } 10948 } 10949 #endif 10950 10951 // It would be nice to avoid this copy. 10952 TemplateArgumentListInfo TABuffer; 10953 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10954 if (ULE->hasExplicitTemplateArgs()) { 10955 ULE->copyTemplateArgumentsInto(TABuffer); 10956 ExplicitTemplateArgs = &TABuffer; 10957 } 10958 10959 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10960 E = ULE->decls_end(); I != E; ++I) 10961 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10962 CandidateSet, PartialOverloading, 10963 /*KnownValid*/ true); 10964 10965 if (ULE->requiresADL()) 10966 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10967 Args, ExplicitTemplateArgs, 10968 CandidateSet, PartialOverloading); 10969 } 10970 10971 /// Determine whether a declaration with the specified name could be moved into 10972 /// a different namespace. 10973 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10974 switch (Name.getCXXOverloadedOperator()) { 10975 case OO_New: case OO_Array_New: 10976 case OO_Delete: case OO_Array_Delete: 10977 return false; 10978 10979 default: 10980 return true; 10981 } 10982 } 10983 10984 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10985 /// template, where the non-dependent name was declared after the template 10986 /// was defined. This is common in code written for a compilers which do not 10987 /// correctly implement two-stage name lookup. 10988 /// 10989 /// Returns true if a viable candidate was found and a diagnostic was issued. 10990 static bool 10991 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10992 const CXXScopeSpec &SS, LookupResult &R, 10993 OverloadCandidateSet::CandidateSetKind CSK, 10994 TemplateArgumentListInfo *ExplicitTemplateArgs, 10995 ArrayRef<Expr *> Args, 10996 bool *DoDiagnoseEmptyLookup = nullptr) { 10997 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10998 return false; 10999 11000 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11001 if (DC->isTransparentContext()) 11002 continue; 11003 11004 SemaRef.LookupQualifiedName(R, DC); 11005 11006 if (!R.empty()) { 11007 R.suppressDiagnostics(); 11008 11009 if (isa<CXXRecordDecl>(DC)) { 11010 // Don't diagnose names we find in classes; we get much better 11011 // diagnostics for these from DiagnoseEmptyLookup. 11012 R.clear(); 11013 if (DoDiagnoseEmptyLookup) 11014 *DoDiagnoseEmptyLookup = true; 11015 return false; 11016 } 11017 11018 OverloadCandidateSet Candidates(FnLoc, CSK); 11019 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11020 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11021 ExplicitTemplateArgs, Args, 11022 Candidates, false, /*KnownValid*/ false); 11023 11024 OverloadCandidateSet::iterator Best; 11025 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11026 // No viable functions. Don't bother the user with notes for functions 11027 // which don't work and shouldn't be found anyway. 11028 R.clear(); 11029 return false; 11030 } 11031 11032 // Find the namespaces where ADL would have looked, and suggest 11033 // declaring the function there instead. 11034 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11035 Sema::AssociatedClassSet AssociatedClasses; 11036 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11037 AssociatedNamespaces, 11038 AssociatedClasses); 11039 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11040 if (canBeDeclaredInNamespace(R.getLookupName())) { 11041 DeclContext *Std = SemaRef.getStdNamespace(); 11042 for (Sema::AssociatedNamespaceSet::iterator 11043 it = AssociatedNamespaces.begin(), 11044 end = AssociatedNamespaces.end(); it != end; ++it) { 11045 // Never suggest declaring a function within namespace 'std'. 11046 if (Std && Std->Encloses(*it)) 11047 continue; 11048 11049 // Never suggest declaring a function within a namespace with a 11050 // reserved name, like __gnu_cxx. 11051 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11052 if (NS && 11053 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11054 continue; 11055 11056 SuggestedNamespaces.insert(*it); 11057 } 11058 } 11059 11060 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11061 << R.getLookupName(); 11062 if (SuggestedNamespaces.empty()) { 11063 SemaRef.Diag(Best->Function->getLocation(), 11064 diag::note_not_found_by_two_phase_lookup) 11065 << R.getLookupName() << 0; 11066 } else if (SuggestedNamespaces.size() == 1) { 11067 SemaRef.Diag(Best->Function->getLocation(), 11068 diag::note_not_found_by_two_phase_lookup) 11069 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11070 } else { 11071 // FIXME: It would be useful to list the associated namespaces here, 11072 // but the diagnostics infrastructure doesn't provide a way to produce 11073 // a localized representation of a list of items. 11074 SemaRef.Diag(Best->Function->getLocation(), 11075 diag::note_not_found_by_two_phase_lookup) 11076 << R.getLookupName() << 2; 11077 } 11078 11079 // Try to recover by calling this function. 11080 return true; 11081 } 11082 11083 R.clear(); 11084 } 11085 11086 return false; 11087 } 11088 11089 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11090 /// template, where the non-dependent operator was declared after the template 11091 /// was defined. 11092 /// 11093 /// Returns true if a viable candidate was found and a diagnostic was issued. 11094 static bool 11095 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11096 SourceLocation OpLoc, 11097 ArrayRef<Expr *> Args) { 11098 DeclarationName OpName = 11099 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11100 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11101 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11102 OverloadCandidateSet::CSK_Operator, 11103 /*ExplicitTemplateArgs=*/nullptr, Args); 11104 } 11105 11106 namespace { 11107 class BuildRecoveryCallExprRAII { 11108 Sema &SemaRef; 11109 public: 11110 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11111 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11112 SemaRef.IsBuildingRecoveryCallExpr = true; 11113 } 11114 11115 ~BuildRecoveryCallExprRAII() { 11116 SemaRef.IsBuildingRecoveryCallExpr = false; 11117 } 11118 }; 11119 11120 } 11121 11122 static std::unique_ptr<CorrectionCandidateCallback> 11123 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11124 bool HasTemplateArgs, bool AllowTypoCorrection) { 11125 if (!AllowTypoCorrection) 11126 return llvm::make_unique<NoTypoCorrectionCCC>(); 11127 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11128 HasTemplateArgs, ME); 11129 } 11130 11131 /// Attempts to recover from a call where no functions were found. 11132 /// 11133 /// Returns true if new candidates were found. 11134 static ExprResult 11135 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11136 UnresolvedLookupExpr *ULE, 11137 SourceLocation LParenLoc, 11138 MutableArrayRef<Expr *> Args, 11139 SourceLocation RParenLoc, 11140 bool EmptyLookup, bool AllowTypoCorrection) { 11141 // Do not try to recover if it is already building a recovery call. 11142 // This stops infinite loops for template instantiations like 11143 // 11144 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11145 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11146 // 11147 if (SemaRef.IsBuildingRecoveryCallExpr) 11148 return ExprError(); 11149 BuildRecoveryCallExprRAII RCE(SemaRef); 11150 11151 CXXScopeSpec SS; 11152 SS.Adopt(ULE->getQualifierLoc()); 11153 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11154 11155 TemplateArgumentListInfo TABuffer; 11156 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11157 if (ULE->hasExplicitTemplateArgs()) { 11158 ULE->copyTemplateArgumentsInto(TABuffer); 11159 ExplicitTemplateArgs = &TABuffer; 11160 } 11161 11162 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11163 Sema::LookupOrdinaryName); 11164 bool DoDiagnoseEmptyLookup = EmptyLookup; 11165 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11166 OverloadCandidateSet::CSK_Normal, 11167 ExplicitTemplateArgs, Args, 11168 &DoDiagnoseEmptyLookup) && 11169 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11170 S, SS, R, 11171 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11172 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11173 ExplicitTemplateArgs, Args))) 11174 return ExprError(); 11175 11176 assert(!R.empty() && "lookup results empty despite recovery"); 11177 11178 // Build an implicit member call if appropriate. Just drop the 11179 // casts and such from the call, we don't really care. 11180 ExprResult NewFn = ExprError(); 11181 if ((*R.begin())->isCXXClassMember()) 11182 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11183 ExplicitTemplateArgs, S); 11184 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11185 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11186 ExplicitTemplateArgs); 11187 else 11188 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11189 11190 if (NewFn.isInvalid()) 11191 return ExprError(); 11192 11193 // This shouldn't cause an infinite loop because we're giving it 11194 // an expression with viable lookup results, which should never 11195 // end up here. 11196 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11197 MultiExprArg(Args.data(), Args.size()), 11198 RParenLoc); 11199 } 11200 11201 /// \brief Constructs and populates an OverloadedCandidateSet from 11202 /// the given function. 11203 /// \returns true when an the ExprResult output parameter has been set. 11204 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11205 UnresolvedLookupExpr *ULE, 11206 MultiExprArg Args, 11207 SourceLocation RParenLoc, 11208 OverloadCandidateSet *CandidateSet, 11209 ExprResult *Result) { 11210 #ifndef NDEBUG 11211 if (ULE->requiresADL()) { 11212 // To do ADL, we must have found an unqualified name. 11213 assert(!ULE->getQualifier() && "qualified name with ADL"); 11214 11215 // We don't perform ADL for implicit declarations of builtins. 11216 // Verify that this was correctly set up. 11217 FunctionDecl *F; 11218 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11219 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11220 F->getBuiltinID() && F->isImplicit()) 11221 llvm_unreachable("performing ADL for builtin"); 11222 11223 // We don't perform ADL in C. 11224 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11225 } 11226 #endif 11227 11228 UnbridgedCastsSet UnbridgedCasts; 11229 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11230 *Result = ExprError(); 11231 return true; 11232 } 11233 11234 // Add the functions denoted by the callee to the set of candidate 11235 // functions, including those from argument-dependent lookup. 11236 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11237 11238 if (getLangOpts().MSVCCompat && 11239 CurContext->isDependentContext() && !isSFINAEContext() && 11240 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11241 11242 OverloadCandidateSet::iterator Best; 11243 if (CandidateSet->empty() || 11244 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11245 OR_No_Viable_Function) { 11246 // In Microsoft mode, if we are inside a template class member function then 11247 // create a type dependent CallExpr. The goal is to postpone name lookup 11248 // to instantiation time to be able to search into type dependent base 11249 // classes. 11250 CallExpr *CE = new (Context) CallExpr( 11251 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11252 CE->setTypeDependent(true); 11253 CE->setValueDependent(true); 11254 CE->setInstantiationDependent(true); 11255 *Result = CE; 11256 return true; 11257 } 11258 } 11259 11260 if (CandidateSet->empty()) 11261 return false; 11262 11263 UnbridgedCasts.restore(); 11264 return false; 11265 } 11266 11267 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11268 /// the completed call expression. If overload resolution fails, emits 11269 /// diagnostics and returns ExprError() 11270 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11271 UnresolvedLookupExpr *ULE, 11272 SourceLocation LParenLoc, 11273 MultiExprArg Args, 11274 SourceLocation RParenLoc, 11275 Expr *ExecConfig, 11276 OverloadCandidateSet *CandidateSet, 11277 OverloadCandidateSet::iterator *Best, 11278 OverloadingResult OverloadResult, 11279 bool AllowTypoCorrection) { 11280 if (CandidateSet->empty()) 11281 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11282 RParenLoc, /*EmptyLookup=*/true, 11283 AllowTypoCorrection); 11284 11285 switch (OverloadResult) { 11286 case OR_Success: { 11287 FunctionDecl *FDecl = (*Best)->Function; 11288 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11289 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11290 return ExprError(); 11291 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11292 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11293 ExecConfig); 11294 } 11295 11296 case OR_No_Viable_Function: { 11297 // Try to recover by looking for viable functions which the user might 11298 // have meant to call. 11299 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11300 Args, RParenLoc, 11301 /*EmptyLookup=*/false, 11302 AllowTypoCorrection); 11303 if (!Recovery.isInvalid()) 11304 return Recovery; 11305 11306 // If the user passes in a function that we can't take the address of, we 11307 // generally end up emitting really bad error messages. Here, we attempt to 11308 // emit better ones. 11309 for (const Expr *Arg : Args) { 11310 if (!Arg->getType()->isFunctionType()) 11311 continue; 11312 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11313 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11314 if (FD && 11315 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11316 Arg->getExprLoc())) 11317 return ExprError(); 11318 } 11319 } 11320 11321 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11322 << ULE->getName() << Fn->getSourceRange(); 11323 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11324 break; 11325 } 11326 11327 case OR_Ambiguous: 11328 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11329 << ULE->getName() << Fn->getSourceRange(); 11330 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11331 break; 11332 11333 case OR_Deleted: { 11334 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11335 << (*Best)->Function->isDeleted() 11336 << ULE->getName() 11337 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11338 << Fn->getSourceRange(); 11339 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11340 11341 // We emitted an error for the unvailable/deleted function call but keep 11342 // the call in the AST. 11343 FunctionDecl *FDecl = (*Best)->Function; 11344 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11345 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11346 ExecConfig); 11347 } 11348 } 11349 11350 // Overload resolution failed. 11351 return ExprError(); 11352 } 11353 11354 static void markUnaddressableCandidatesUnviable(Sema &S, 11355 OverloadCandidateSet &CS) { 11356 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11357 if (I->Viable && 11358 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11359 I->Viable = false; 11360 I->FailureKind = ovl_fail_addr_not_available; 11361 } 11362 } 11363 } 11364 11365 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11366 /// (which eventually refers to the declaration Func) and the call 11367 /// arguments Args/NumArgs, attempt to resolve the function call down 11368 /// to a specific function. If overload resolution succeeds, returns 11369 /// the call expression produced by overload resolution. 11370 /// Otherwise, emits diagnostics and returns ExprError. 11371 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11372 UnresolvedLookupExpr *ULE, 11373 SourceLocation LParenLoc, 11374 MultiExprArg Args, 11375 SourceLocation RParenLoc, 11376 Expr *ExecConfig, 11377 bool AllowTypoCorrection, 11378 bool CalleesAddressIsTaken) { 11379 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11380 OverloadCandidateSet::CSK_Normal); 11381 ExprResult result; 11382 11383 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11384 &result)) 11385 return result; 11386 11387 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11388 // functions that aren't addressible are considered unviable. 11389 if (CalleesAddressIsTaken) 11390 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11391 11392 OverloadCandidateSet::iterator Best; 11393 OverloadingResult OverloadResult = 11394 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11395 11396 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11397 RParenLoc, ExecConfig, &CandidateSet, 11398 &Best, OverloadResult, 11399 AllowTypoCorrection); 11400 } 11401 11402 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11403 return Functions.size() > 1 || 11404 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11405 } 11406 11407 /// \brief Create a unary operation that may resolve to an overloaded 11408 /// operator. 11409 /// 11410 /// \param OpLoc The location of the operator itself (e.g., '*'). 11411 /// 11412 /// \param Opc The UnaryOperatorKind that describes this operator. 11413 /// 11414 /// \param Fns The set of non-member functions that will be 11415 /// considered by overload resolution. The caller needs to build this 11416 /// set based on the context using, e.g., 11417 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11418 /// set should not contain any member functions; those will be added 11419 /// by CreateOverloadedUnaryOp(). 11420 /// 11421 /// \param Input The input argument. 11422 ExprResult 11423 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11424 const UnresolvedSetImpl &Fns, 11425 Expr *Input) { 11426 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11427 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11428 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11429 // TODO: provide better source location info. 11430 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11431 11432 if (checkPlaceholderForOverload(*this, Input)) 11433 return ExprError(); 11434 11435 Expr *Args[2] = { Input, nullptr }; 11436 unsigned NumArgs = 1; 11437 11438 // For post-increment and post-decrement, add the implicit '0' as 11439 // the second argument, so that we know this is a post-increment or 11440 // post-decrement. 11441 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11442 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11443 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11444 SourceLocation()); 11445 NumArgs = 2; 11446 } 11447 11448 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11449 11450 if (Input->isTypeDependent()) { 11451 if (Fns.empty()) 11452 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11453 VK_RValue, OK_Ordinary, OpLoc); 11454 11455 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11456 UnresolvedLookupExpr *Fn 11457 = UnresolvedLookupExpr::Create(Context, NamingClass, 11458 NestedNameSpecifierLoc(), OpNameInfo, 11459 /*ADL*/ true, IsOverloaded(Fns), 11460 Fns.begin(), Fns.end()); 11461 return new (Context) 11462 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11463 VK_RValue, OpLoc, false); 11464 } 11465 11466 // Build an empty overload set. 11467 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11468 11469 // Add the candidates from the given function set. 11470 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11471 11472 // Add operator candidates that are member functions. 11473 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11474 11475 // Add candidates from ADL. 11476 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11477 /*ExplicitTemplateArgs*/nullptr, 11478 CandidateSet); 11479 11480 // Add builtin operator candidates. 11481 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11482 11483 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11484 11485 // Perform overload resolution. 11486 OverloadCandidateSet::iterator Best; 11487 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11488 case OR_Success: { 11489 // We found a built-in operator or an overloaded operator. 11490 FunctionDecl *FnDecl = Best->Function; 11491 11492 if (FnDecl) { 11493 // We matched an overloaded operator. Build a call to that 11494 // operator. 11495 11496 // Convert the arguments. 11497 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11498 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11499 11500 ExprResult InputRes = 11501 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11502 Best->FoundDecl, Method); 11503 if (InputRes.isInvalid()) 11504 return ExprError(); 11505 Input = InputRes.get(); 11506 } else { 11507 // Convert the arguments. 11508 ExprResult InputInit 11509 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11510 Context, 11511 FnDecl->getParamDecl(0)), 11512 SourceLocation(), 11513 Input); 11514 if (InputInit.isInvalid()) 11515 return ExprError(); 11516 Input = InputInit.get(); 11517 } 11518 11519 // Build the actual expression node. 11520 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11521 HadMultipleCandidates, OpLoc); 11522 if (FnExpr.isInvalid()) 11523 return ExprError(); 11524 11525 // Determine the result type. 11526 QualType ResultTy = FnDecl->getReturnType(); 11527 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11528 ResultTy = ResultTy.getNonLValueExprType(Context); 11529 11530 Args[0] = Input; 11531 CallExpr *TheCall = 11532 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11533 ResultTy, VK, OpLoc, false); 11534 11535 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11536 return ExprError(); 11537 11538 return MaybeBindToTemporary(TheCall); 11539 } else { 11540 // We matched a built-in operator. Convert the arguments, then 11541 // break out so that we will build the appropriate built-in 11542 // operator node. 11543 ExprResult InputRes = 11544 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11545 Best->Conversions[0], AA_Passing); 11546 if (InputRes.isInvalid()) 11547 return ExprError(); 11548 Input = InputRes.get(); 11549 break; 11550 } 11551 } 11552 11553 case OR_No_Viable_Function: 11554 // This is an erroneous use of an operator which can be overloaded by 11555 // a non-member function. Check for non-member operators which were 11556 // defined too late to be candidates. 11557 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11558 // FIXME: Recover by calling the found function. 11559 return ExprError(); 11560 11561 // No viable function; fall through to handling this as a 11562 // built-in operator, which will produce an error message for us. 11563 break; 11564 11565 case OR_Ambiguous: 11566 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11567 << UnaryOperator::getOpcodeStr(Opc) 11568 << Input->getType() 11569 << Input->getSourceRange(); 11570 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11571 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11572 return ExprError(); 11573 11574 case OR_Deleted: 11575 Diag(OpLoc, diag::err_ovl_deleted_oper) 11576 << Best->Function->isDeleted() 11577 << UnaryOperator::getOpcodeStr(Opc) 11578 << getDeletedOrUnavailableSuffix(Best->Function) 11579 << Input->getSourceRange(); 11580 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11581 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11582 return ExprError(); 11583 } 11584 11585 // Either we found no viable overloaded operator or we matched a 11586 // built-in operator. In either case, fall through to trying to 11587 // build a built-in operation. 11588 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11589 } 11590 11591 /// \brief Create a binary operation that may resolve to an overloaded 11592 /// operator. 11593 /// 11594 /// \param OpLoc The location of the operator itself (e.g., '+'). 11595 /// 11596 /// \param Opc The BinaryOperatorKind that describes this operator. 11597 /// 11598 /// \param Fns The set of non-member functions that will be 11599 /// considered by overload resolution. The caller needs to build this 11600 /// set based on the context using, e.g., 11601 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11602 /// set should not contain any member functions; those will be added 11603 /// by CreateOverloadedBinOp(). 11604 /// 11605 /// \param LHS Left-hand argument. 11606 /// \param RHS Right-hand argument. 11607 ExprResult 11608 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11609 BinaryOperatorKind Opc, 11610 const UnresolvedSetImpl &Fns, 11611 Expr *LHS, Expr *RHS) { 11612 Expr *Args[2] = { LHS, RHS }; 11613 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11614 11615 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11616 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11617 11618 // If either side is type-dependent, create an appropriate dependent 11619 // expression. 11620 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11621 if (Fns.empty()) { 11622 // If there are no functions to store, just build a dependent 11623 // BinaryOperator or CompoundAssignment. 11624 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11625 return new (Context) BinaryOperator( 11626 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11627 OpLoc, FPFeatures.fp_contract); 11628 11629 return new (Context) CompoundAssignOperator( 11630 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11631 Context.DependentTy, Context.DependentTy, OpLoc, 11632 FPFeatures.fp_contract); 11633 } 11634 11635 // FIXME: save results of ADL from here? 11636 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11637 // TODO: provide better source location info in DNLoc component. 11638 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11639 UnresolvedLookupExpr *Fn 11640 = UnresolvedLookupExpr::Create(Context, NamingClass, 11641 NestedNameSpecifierLoc(), OpNameInfo, 11642 /*ADL*/ true, IsOverloaded(Fns), 11643 Fns.begin(), Fns.end()); 11644 return new (Context) 11645 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11646 VK_RValue, OpLoc, FPFeatures.fp_contract); 11647 } 11648 11649 // Always do placeholder-like conversions on the RHS. 11650 if (checkPlaceholderForOverload(*this, Args[1])) 11651 return ExprError(); 11652 11653 // Do placeholder-like conversion on the LHS; note that we should 11654 // not get here with a PseudoObject LHS. 11655 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11656 if (checkPlaceholderForOverload(*this, Args[0])) 11657 return ExprError(); 11658 11659 // If this is the assignment operator, we only perform overload resolution 11660 // if the left-hand side is a class or enumeration type. This is actually 11661 // a hack. The standard requires that we do overload resolution between the 11662 // various built-in candidates, but as DR507 points out, this can lead to 11663 // problems. So we do it this way, which pretty much follows what GCC does. 11664 // Note that we go the traditional code path for compound assignment forms. 11665 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11666 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11667 11668 // If this is the .* operator, which is not overloadable, just 11669 // create a built-in binary operator. 11670 if (Opc == BO_PtrMemD) 11671 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11672 11673 // Build an empty overload set. 11674 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11675 11676 // Add the candidates from the given function set. 11677 AddFunctionCandidates(Fns, Args, CandidateSet); 11678 11679 // Add operator candidates that are member functions. 11680 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11681 11682 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11683 // performed for an assignment operator (nor for operator[] nor operator->, 11684 // which don't get here). 11685 if (Opc != BO_Assign) 11686 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11687 /*ExplicitTemplateArgs*/ nullptr, 11688 CandidateSet); 11689 11690 // Add builtin operator candidates. 11691 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11692 11693 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11694 11695 // Perform overload resolution. 11696 OverloadCandidateSet::iterator Best; 11697 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11698 case OR_Success: { 11699 // We found a built-in operator or an overloaded operator. 11700 FunctionDecl *FnDecl = Best->Function; 11701 11702 if (FnDecl) { 11703 // We matched an overloaded operator. Build a call to that 11704 // operator. 11705 11706 // Convert the arguments. 11707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11708 // Best->Access is only meaningful for class members. 11709 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11710 11711 ExprResult Arg1 = 11712 PerformCopyInitialization( 11713 InitializedEntity::InitializeParameter(Context, 11714 FnDecl->getParamDecl(0)), 11715 SourceLocation(), Args[1]); 11716 if (Arg1.isInvalid()) 11717 return ExprError(); 11718 11719 ExprResult Arg0 = 11720 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11721 Best->FoundDecl, Method); 11722 if (Arg0.isInvalid()) 11723 return ExprError(); 11724 Args[0] = Arg0.getAs<Expr>(); 11725 Args[1] = RHS = Arg1.getAs<Expr>(); 11726 } else { 11727 // Convert the arguments. 11728 ExprResult Arg0 = PerformCopyInitialization( 11729 InitializedEntity::InitializeParameter(Context, 11730 FnDecl->getParamDecl(0)), 11731 SourceLocation(), Args[0]); 11732 if (Arg0.isInvalid()) 11733 return ExprError(); 11734 11735 ExprResult Arg1 = 11736 PerformCopyInitialization( 11737 InitializedEntity::InitializeParameter(Context, 11738 FnDecl->getParamDecl(1)), 11739 SourceLocation(), Args[1]); 11740 if (Arg1.isInvalid()) 11741 return ExprError(); 11742 Args[0] = LHS = Arg0.getAs<Expr>(); 11743 Args[1] = RHS = Arg1.getAs<Expr>(); 11744 } 11745 11746 // Build the actual expression node. 11747 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11748 Best->FoundDecl, 11749 HadMultipleCandidates, OpLoc); 11750 if (FnExpr.isInvalid()) 11751 return ExprError(); 11752 11753 // Determine the result type. 11754 QualType ResultTy = FnDecl->getReturnType(); 11755 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11756 ResultTy = ResultTy.getNonLValueExprType(Context); 11757 11758 CXXOperatorCallExpr *TheCall = 11759 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11760 Args, ResultTy, VK, OpLoc, 11761 FPFeatures.fp_contract); 11762 11763 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11764 FnDecl)) 11765 return ExprError(); 11766 11767 ArrayRef<const Expr *> ArgsArray(Args, 2); 11768 // Cut off the implicit 'this'. 11769 if (isa<CXXMethodDecl>(FnDecl)) 11770 ArgsArray = ArgsArray.slice(1); 11771 11772 // Check for a self move. 11773 if (Op == OO_Equal) 11774 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11775 11776 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11777 TheCall->getSourceRange(), VariadicDoesNotApply); 11778 11779 return MaybeBindToTemporary(TheCall); 11780 } else { 11781 // We matched a built-in operator. Convert the arguments, then 11782 // break out so that we will build the appropriate built-in 11783 // operator node. 11784 ExprResult ArgsRes0 = 11785 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11786 Best->Conversions[0], AA_Passing); 11787 if (ArgsRes0.isInvalid()) 11788 return ExprError(); 11789 Args[0] = ArgsRes0.get(); 11790 11791 ExprResult ArgsRes1 = 11792 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11793 Best->Conversions[1], AA_Passing); 11794 if (ArgsRes1.isInvalid()) 11795 return ExprError(); 11796 Args[1] = ArgsRes1.get(); 11797 break; 11798 } 11799 } 11800 11801 case OR_No_Viable_Function: { 11802 // C++ [over.match.oper]p9: 11803 // If the operator is the operator , [...] and there are no 11804 // viable functions, then the operator is assumed to be the 11805 // built-in operator and interpreted according to clause 5. 11806 if (Opc == BO_Comma) 11807 break; 11808 11809 // For class as left operand for assignment or compound assigment 11810 // operator do not fall through to handling in built-in, but report that 11811 // no overloaded assignment operator found 11812 ExprResult Result = ExprError(); 11813 if (Args[0]->getType()->isRecordType() && 11814 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11815 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11816 << BinaryOperator::getOpcodeStr(Opc) 11817 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11818 if (Args[0]->getType()->isIncompleteType()) { 11819 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11820 << Args[0]->getType() 11821 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11822 } 11823 } else { 11824 // This is an erroneous use of an operator which can be overloaded by 11825 // a non-member function. Check for non-member operators which were 11826 // defined too late to be candidates. 11827 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11828 // FIXME: Recover by calling the found function. 11829 return ExprError(); 11830 11831 // No viable function; try to create a built-in operation, which will 11832 // produce an error. Then, show the non-viable candidates. 11833 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11834 } 11835 assert(Result.isInvalid() && 11836 "C++ binary operator overloading is missing candidates!"); 11837 if (Result.isInvalid()) 11838 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11839 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11840 return Result; 11841 } 11842 11843 case OR_Ambiguous: 11844 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11845 << BinaryOperator::getOpcodeStr(Opc) 11846 << Args[0]->getType() << Args[1]->getType() 11847 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11848 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11849 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11850 return ExprError(); 11851 11852 case OR_Deleted: 11853 if (isImplicitlyDeleted(Best->Function)) { 11854 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11855 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11856 << Context.getRecordType(Method->getParent()) 11857 << getSpecialMember(Method); 11858 11859 // The user probably meant to call this special member. Just 11860 // explain why it's deleted. 11861 NoteDeletedFunction(Method); 11862 return ExprError(); 11863 } else { 11864 Diag(OpLoc, diag::err_ovl_deleted_oper) 11865 << Best->Function->isDeleted() 11866 << BinaryOperator::getOpcodeStr(Opc) 11867 << getDeletedOrUnavailableSuffix(Best->Function) 11868 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11869 } 11870 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11871 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11872 return ExprError(); 11873 } 11874 11875 // We matched a built-in operator; build it. 11876 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11877 } 11878 11879 ExprResult 11880 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11881 SourceLocation RLoc, 11882 Expr *Base, Expr *Idx) { 11883 Expr *Args[2] = { Base, Idx }; 11884 DeclarationName OpName = 11885 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11886 11887 // If either side is type-dependent, create an appropriate dependent 11888 // expression. 11889 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11890 11891 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11892 // CHECKME: no 'operator' keyword? 11893 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11894 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11895 UnresolvedLookupExpr *Fn 11896 = UnresolvedLookupExpr::Create(Context, NamingClass, 11897 NestedNameSpecifierLoc(), OpNameInfo, 11898 /*ADL*/ true, /*Overloaded*/ false, 11899 UnresolvedSetIterator(), 11900 UnresolvedSetIterator()); 11901 // Can't add any actual overloads yet 11902 11903 return new (Context) 11904 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11905 Context.DependentTy, VK_RValue, RLoc, false); 11906 } 11907 11908 // Handle placeholders on both operands. 11909 if (checkPlaceholderForOverload(*this, Args[0])) 11910 return ExprError(); 11911 if (checkPlaceholderForOverload(*this, Args[1])) 11912 return ExprError(); 11913 11914 // Build an empty overload set. 11915 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11916 11917 // Subscript can only be overloaded as a member function. 11918 11919 // Add operator candidates that are member functions. 11920 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11921 11922 // Add builtin operator candidates. 11923 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11924 11925 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11926 11927 // Perform overload resolution. 11928 OverloadCandidateSet::iterator Best; 11929 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11930 case OR_Success: { 11931 // We found a built-in operator or an overloaded operator. 11932 FunctionDecl *FnDecl = Best->Function; 11933 11934 if (FnDecl) { 11935 // We matched an overloaded operator. Build a call to that 11936 // operator. 11937 11938 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11939 11940 // Convert the arguments. 11941 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11942 ExprResult Arg0 = 11943 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11944 Best->FoundDecl, Method); 11945 if (Arg0.isInvalid()) 11946 return ExprError(); 11947 Args[0] = Arg0.get(); 11948 11949 // Convert the arguments. 11950 ExprResult InputInit 11951 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11952 Context, 11953 FnDecl->getParamDecl(0)), 11954 SourceLocation(), 11955 Args[1]); 11956 if (InputInit.isInvalid()) 11957 return ExprError(); 11958 11959 Args[1] = InputInit.getAs<Expr>(); 11960 11961 // Build the actual expression node. 11962 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11963 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11964 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11965 Best->FoundDecl, 11966 HadMultipleCandidates, 11967 OpLocInfo.getLoc(), 11968 OpLocInfo.getInfo()); 11969 if (FnExpr.isInvalid()) 11970 return ExprError(); 11971 11972 // Determine the result type 11973 QualType ResultTy = FnDecl->getReturnType(); 11974 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11975 ResultTy = ResultTy.getNonLValueExprType(Context); 11976 11977 CXXOperatorCallExpr *TheCall = 11978 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11979 FnExpr.get(), Args, 11980 ResultTy, VK, RLoc, 11981 false); 11982 11983 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11984 return ExprError(); 11985 11986 return MaybeBindToTemporary(TheCall); 11987 } else { 11988 // We matched a built-in operator. Convert the arguments, then 11989 // break out so that we will build the appropriate built-in 11990 // operator node. 11991 ExprResult ArgsRes0 = 11992 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11993 Best->Conversions[0], AA_Passing); 11994 if (ArgsRes0.isInvalid()) 11995 return ExprError(); 11996 Args[0] = ArgsRes0.get(); 11997 11998 ExprResult ArgsRes1 = 11999 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12000 Best->Conversions[1], AA_Passing); 12001 if (ArgsRes1.isInvalid()) 12002 return ExprError(); 12003 Args[1] = ArgsRes1.get(); 12004 12005 break; 12006 } 12007 } 12008 12009 case OR_No_Viable_Function: { 12010 if (CandidateSet.empty()) 12011 Diag(LLoc, diag::err_ovl_no_oper) 12012 << Args[0]->getType() << /*subscript*/ 0 12013 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12014 else 12015 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12016 << Args[0]->getType() 12017 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12018 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12019 "[]", LLoc); 12020 return ExprError(); 12021 } 12022 12023 case OR_Ambiguous: 12024 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12025 << "[]" 12026 << Args[0]->getType() << Args[1]->getType() 12027 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12028 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12029 "[]", LLoc); 12030 return ExprError(); 12031 12032 case OR_Deleted: 12033 Diag(LLoc, diag::err_ovl_deleted_oper) 12034 << Best->Function->isDeleted() << "[]" 12035 << getDeletedOrUnavailableSuffix(Best->Function) 12036 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12037 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12038 "[]", LLoc); 12039 return ExprError(); 12040 } 12041 12042 // We matched a built-in operator; build it. 12043 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12044 } 12045 12046 /// BuildCallToMemberFunction - Build a call to a member 12047 /// function. MemExpr is the expression that refers to the member 12048 /// function (and includes the object parameter), Args/NumArgs are the 12049 /// arguments to the function call (not including the object 12050 /// parameter). The caller needs to validate that the member 12051 /// expression refers to a non-static member function or an overloaded 12052 /// member function. 12053 ExprResult 12054 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12055 SourceLocation LParenLoc, 12056 MultiExprArg Args, 12057 SourceLocation RParenLoc) { 12058 assert(MemExprE->getType() == Context.BoundMemberTy || 12059 MemExprE->getType() == Context.OverloadTy); 12060 12061 // Dig out the member expression. This holds both the object 12062 // argument and the member function we're referring to. 12063 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12064 12065 // Determine whether this is a call to a pointer-to-member function. 12066 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12067 assert(op->getType() == Context.BoundMemberTy); 12068 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12069 12070 QualType fnType = 12071 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12072 12073 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12074 QualType resultType = proto->getCallResultType(Context); 12075 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12076 12077 // Check that the object type isn't more qualified than the 12078 // member function we're calling. 12079 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12080 12081 QualType objectType = op->getLHS()->getType(); 12082 if (op->getOpcode() == BO_PtrMemI) 12083 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12084 Qualifiers objectQuals = objectType.getQualifiers(); 12085 12086 Qualifiers difference = objectQuals - funcQuals; 12087 difference.removeObjCGCAttr(); 12088 difference.removeAddressSpace(); 12089 if (difference) { 12090 std::string qualsString = difference.getAsString(); 12091 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12092 << fnType.getUnqualifiedType() 12093 << qualsString 12094 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12095 } 12096 12097 CXXMemberCallExpr *call 12098 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12099 resultType, valueKind, RParenLoc); 12100 12101 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12102 call, nullptr)) 12103 return ExprError(); 12104 12105 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12106 return ExprError(); 12107 12108 if (CheckOtherCall(call, proto)) 12109 return ExprError(); 12110 12111 return MaybeBindToTemporary(call); 12112 } 12113 12114 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12115 return new (Context) 12116 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12117 12118 UnbridgedCastsSet UnbridgedCasts; 12119 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12120 return ExprError(); 12121 12122 MemberExpr *MemExpr; 12123 CXXMethodDecl *Method = nullptr; 12124 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12125 NestedNameSpecifier *Qualifier = nullptr; 12126 if (isa<MemberExpr>(NakedMemExpr)) { 12127 MemExpr = cast<MemberExpr>(NakedMemExpr); 12128 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12129 FoundDecl = MemExpr->getFoundDecl(); 12130 Qualifier = MemExpr->getQualifier(); 12131 UnbridgedCasts.restore(); 12132 } else { 12133 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12134 Qualifier = UnresExpr->getQualifier(); 12135 12136 QualType ObjectType = UnresExpr->getBaseType(); 12137 Expr::Classification ObjectClassification 12138 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12139 : UnresExpr->getBase()->Classify(Context); 12140 12141 // Add overload candidates 12142 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12143 OverloadCandidateSet::CSK_Normal); 12144 12145 // FIXME: avoid copy. 12146 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12147 if (UnresExpr->hasExplicitTemplateArgs()) { 12148 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12149 TemplateArgs = &TemplateArgsBuffer; 12150 } 12151 12152 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12153 E = UnresExpr->decls_end(); I != E; ++I) { 12154 12155 NamedDecl *Func = *I; 12156 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12157 if (isa<UsingShadowDecl>(Func)) 12158 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12159 12160 12161 // Microsoft supports direct constructor calls. 12162 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12163 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12164 Args, CandidateSet); 12165 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12166 // If explicit template arguments were provided, we can't call a 12167 // non-template member function. 12168 if (TemplateArgs) 12169 continue; 12170 12171 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12172 ObjectClassification, Args, CandidateSet, 12173 /*SuppressUserConversions=*/false); 12174 } else { 12175 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12176 I.getPair(), ActingDC, TemplateArgs, 12177 ObjectType, ObjectClassification, 12178 Args, CandidateSet, 12179 /*SuppressUsedConversions=*/false); 12180 } 12181 } 12182 12183 DeclarationName DeclName = UnresExpr->getMemberName(); 12184 12185 UnbridgedCasts.restore(); 12186 12187 OverloadCandidateSet::iterator Best; 12188 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12189 Best)) { 12190 case OR_Success: 12191 Method = cast<CXXMethodDecl>(Best->Function); 12192 FoundDecl = Best->FoundDecl; 12193 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12194 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12195 return ExprError(); 12196 // If FoundDecl is different from Method (such as if one is a template 12197 // and the other a specialization), make sure DiagnoseUseOfDecl is 12198 // called on both. 12199 // FIXME: This would be more comprehensively addressed by modifying 12200 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12201 // being used. 12202 if (Method != FoundDecl.getDecl() && 12203 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12204 return ExprError(); 12205 break; 12206 12207 case OR_No_Viable_Function: 12208 Diag(UnresExpr->getMemberLoc(), 12209 diag::err_ovl_no_viable_member_function_in_call) 12210 << DeclName << MemExprE->getSourceRange(); 12211 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12212 // FIXME: Leaking incoming expressions! 12213 return ExprError(); 12214 12215 case OR_Ambiguous: 12216 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12217 << DeclName << MemExprE->getSourceRange(); 12218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12219 // FIXME: Leaking incoming expressions! 12220 return ExprError(); 12221 12222 case OR_Deleted: 12223 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12224 << Best->Function->isDeleted() 12225 << DeclName 12226 << getDeletedOrUnavailableSuffix(Best->Function) 12227 << MemExprE->getSourceRange(); 12228 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12229 // FIXME: Leaking incoming expressions! 12230 return ExprError(); 12231 } 12232 12233 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12234 12235 // If overload resolution picked a static member, build a 12236 // non-member call based on that function. 12237 if (Method->isStatic()) { 12238 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12239 RParenLoc); 12240 } 12241 12242 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12243 } 12244 12245 QualType ResultType = Method->getReturnType(); 12246 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12247 ResultType = ResultType.getNonLValueExprType(Context); 12248 12249 assert(Method && "Member call to something that isn't a method?"); 12250 CXXMemberCallExpr *TheCall = 12251 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12252 ResultType, VK, RParenLoc); 12253 12254 // (CUDA B.1): Check for invalid calls between targets. 12255 if (getLangOpts().CUDA) { 12256 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12257 if (CheckCUDATarget(Caller, Method)) { 12258 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12259 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12260 << IdentifyCUDATarget(Caller); 12261 return ExprError(); 12262 } 12263 } 12264 } 12265 12266 // Check for a valid return type. 12267 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12268 TheCall, Method)) 12269 return ExprError(); 12270 12271 // Convert the object argument (for a non-static member function call). 12272 // We only need to do this if there was actually an overload; otherwise 12273 // it was done at lookup. 12274 if (!Method->isStatic()) { 12275 ExprResult ObjectArg = 12276 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12277 FoundDecl, Method); 12278 if (ObjectArg.isInvalid()) 12279 return ExprError(); 12280 MemExpr->setBase(ObjectArg.get()); 12281 } 12282 12283 // Convert the rest of the arguments 12284 const FunctionProtoType *Proto = 12285 Method->getType()->getAs<FunctionProtoType>(); 12286 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12287 RParenLoc)) 12288 return ExprError(); 12289 12290 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12291 12292 if (CheckFunctionCall(Method, TheCall, Proto)) 12293 return ExprError(); 12294 12295 // In the case the method to call was not selected by the overloading 12296 // resolution process, we still need to handle the enable_if attribute. Do 12297 // that here, so it will not hide previous -- and more relevant -- errors 12298 if (isa<MemberExpr>(NakedMemExpr)) { 12299 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12300 Diag(MemExprE->getLocStart(), 12301 diag::err_ovl_no_viable_member_function_in_call) 12302 << Method << Method->getSourceRange(); 12303 Diag(Method->getLocation(), 12304 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12305 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12306 return ExprError(); 12307 } 12308 } 12309 12310 if ((isa<CXXConstructorDecl>(CurContext) || 12311 isa<CXXDestructorDecl>(CurContext)) && 12312 TheCall->getMethodDecl()->isPure()) { 12313 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12314 12315 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12316 MemExpr->performsVirtualDispatch(getLangOpts())) { 12317 Diag(MemExpr->getLocStart(), 12318 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12319 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12320 << MD->getParent()->getDeclName(); 12321 12322 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12323 if (getLangOpts().AppleKext) 12324 Diag(MemExpr->getLocStart(), 12325 diag::note_pure_qualified_call_kext) 12326 << MD->getParent()->getDeclName() 12327 << MD->getDeclName(); 12328 } 12329 } 12330 12331 if (CXXDestructorDecl *DD = 12332 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12333 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12334 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() || 12335 getLangOpts().AppleKext; 12336 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12337 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12338 MemExpr->getMemberLoc()); 12339 } 12340 12341 return MaybeBindToTemporary(TheCall); 12342 } 12343 12344 /// BuildCallToObjectOfClassType - Build a call to an object of class 12345 /// type (C++ [over.call.object]), which can end up invoking an 12346 /// overloaded function call operator (@c operator()) or performing a 12347 /// user-defined conversion on the object argument. 12348 ExprResult 12349 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12350 SourceLocation LParenLoc, 12351 MultiExprArg Args, 12352 SourceLocation RParenLoc) { 12353 if (checkPlaceholderForOverload(*this, Obj)) 12354 return ExprError(); 12355 ExprResult Object = Obj; 12356 12357 UnbridgedCastsSet UnbridgedCasts; 12358 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12359 return ExprError(); 12360 12361 assert(Object.get()->getType()->isRecordType() && 12362 "Requires object type argument"); 12363 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12364 12365 // C++ [over.call.object]p1: 12366 // If the primary-expression E in the function call syntax 12367 // evaluates to a class object of type "cv T", then the set of 12368 // candidate functions includes at least the function call 12369 // operators of T. The function call operators of T are obtained by 12370 // ordinary lookup of the name operator() in the context of 12371 // (E).operator(). 12372 OverloadCandidateSet CandidateSet(LParenLoc, 12373 OverloadCandidateSet::CSK_Operator); 12374 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12375 12376 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12377 diag::err_incomplete_object_call, Object.get())) 12378 return true; 12379 12380 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12381 LookupQualifiedName(R, Record->getDecl()); 12382 R.suppressDiagnostics(); 12383 12384 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12385 Oper != OperEnd; ++Oper) { 12386 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12387 Object.get()->Classify(Context), 12388 Args, CandidateSet, 12389 /*SuppressUserConversions=*/ false); 12390 } 12391 12392 // C++ [over.call.object]p2: 12393 // In addition, for each (non-explicit in C++0x) conversion function 12394 // declared in T of the form 12395 // 12396 // operator conversion-type-id () cv-qualifier; 12397 // 12398 // where cv-qualifier is the same cv-qualification as, or a 12399 // greater cv-qualification than, cv, and where conversion-type-id 12400 // denotes the type "pointer to function of (P1,...,Pn) returning 12401 // R", or the type "reference to pointer to function of 12402 // (P1,...,Pn) returning R", or the type "reference to function 12403 // of (P1,...,Pn) returning R", a surrogate call function [...] 12404 // is also considered as a candidate function. Similarly, 12405 // surrogate call functions are added to the set of candidate 12406 // functions for each conversion function declared in an 12407 // accessible base class provided the function is not hidden 12408 // within T by another intervening declaration. 12409 const auto &Conversions = 12410 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12411 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12412 NamedDecl *D = *I; 12413 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12414 if (isa<UsingShadowDecl>(D)) 12415 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12416 12417 // Skip over templated conversion functions; they aren't 12418 // surrogates. 12419 if (isa<FunctionTemplateDecl>(D)) 12420 continue; 12421 12422 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12423 if (!Conv->isExplicit()) { 12424 // Strip the reference type (if any) and then the pointer type (if 12425 // any) to get down to what might be a function type. 12426 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12427 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12428 ConvType = ConvPtrType->getPointeeType(); 12429 12430 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12431 { 12432 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12433 Object.get(), Args, CandidateSet); 12434 } 12435 } 12436 } 12437 12438 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12439 12440 // Perform overload resolution. 12441 OverloadCandidateSet::iterator Best; 12442 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12443 Best)) { 12444 case OR_Success: 12445 // Overload resolution succeeded; we'll build the appropriate call 12446 // below. 12447 break; 12448 12449 case OR_No_Viable_Function: 12450 if (CandidateSet.empty()) 12451 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12452 << Object.get()->getType() << /*call*/ 1 12453 << Object.get()->getSourceRange(); 12454 else 12455 Diag(Object.get()->getLocStart(), 12456 diag::err_ovl_no_viable_object_call) 12457 << Object.get()->getType() << Object.get()->getSourceRange(); 12458 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12459 break; 12460 12461 case OR_Ambiguous: 12462 Diag(Object.get()->getLocStart(), 12463 diag::err_ovl_ambiguous_object_call) 12464 << Object.get()->getType() << Object.get()->getSourceRange(); 12465 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12466 break; 12467 12468 case OR_Deleted: 12469 Diag(Object.get()->getLocStart(), 12470 diag::err_ovl_deleted_object_call) 12471 << Best->Function->isDeleted() 12472 << Object.get()->getType() 12473 << getDeletedOrUnavailableSuffix(Best->Function) 12474 << Object.get()->getSourceRange(); 12475 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12476 break; 12477 } 12478 12479 if (Best == CandidateSet.end()) 12480 return true; 12481 12482 UnbridgedCasts.restore(); 12483 12484 if (Best->Function == nullptr) { 12485 // Since there is no function declaration, this is one of the 12486 // surrogate candidates. Dig out the conversion function. 12487 CXXConversionDecl *Conv 12488 = cast<CXXConversionDecl>( 12489 Best->Conversions[0].UserDefined.ConversionFunction); 12490 12491 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12492 Best->FoundDecl); 12493 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12494 return ExprError(); 12495 assert(Conv == Best->FoundDecl.getDecl() && 12496 "Found Decl & conversion-to-functionptr should be same, right?!"); 12497 // We selected one of the surrogate functions that converts the 12498 // object parameter to a function pointer. Perform the conversion 12499 // on the object argument, then let ActOnCallExpr finish the job. 12500 12501 // Create an implicit member expr to refer to the conversion operator. 12502 // and then call it. 12503 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12504 Conv, HadMultipleCandidates); 12505 if (Call.isInvalid()) 12506 return ExprError(); 12507 // Record usage of conversion in an implicit cast. 12508 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12509 CK_UserDefinedConversion, Call.get(), 12510 nullptr, VK_RValue); 12511 12512 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12513 } 12514 12515 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12516 12517 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12518 // that calls this method, using Object for the implicit object 12519 // parameter and passing along the remaining arguments. 12520 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12521 12522 // An error diagnostic has already been printed when parsing the declaration. 12523 if (Method->isInvalidDecl()) 12524 return ExprError(); 12525 12526 const FunctionProtoType *Proto = 12527 Method->getType()->getAs<FunctionProtoType>(); 12528 12529 unsigned NumParams = Proto->getNumParams(); 12530 12531 DeclarationNameInfo OpLocInfo( 12532 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12533 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12534 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12535 HadMultipleCandidates, 12536 OpLocInfo.getLoc(), 12537 OpLocInfo.getInfo()); 12538 if (NewFn.isInvalid()) 12539 return true; 12540 12541 // Build the full argument list for the method call (the implicit object 12542 // parameter is placed at the beginning of the list). 12543 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12544 MethodArgs[0] = Object.get(); 12545 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12546 12547 // Once we've built TheCall, all of the expressions are properly 12548 // owned. 12549 QualType ResultTy = Method->getReturnType(); 12550 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12551 ResultTy = ResultTy.getNonLValueExprType(Context); 12552 12553 CXXOperatorCallExpr *TheCall = new (Context) 12554 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12555 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12556 ResultTy, VK, RParenLoc, false); 12557 MethodArgs.reset(); 12558 12559 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12560 return true; 12561 12562 // We may have default arguments. If so, we need to allocate more 12563 // slots in the call for them. 12564 if (Args.size() < NumParams) 12565 TheCall->setNumArgs(Context, NumParams + 1); 12566 12567 bool IsError = false; 12568 12569 // Initialize the implicit object parameter. 12570 ExprResult ObjRes = 12571 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12572 Best->FoundDecl, Method); 12573 if (ObjRes.isInvalid()) 12574 IsError = true; 12575 else 12576 Object = ObjRes; 12577 TheCall->setArg(0, Object.get()); 12578 12579 // Check the argument types. 12580 for (unsigned i = 0; i != NumParams; i++) { 12581 Expr *Arg; 12582 if (i < Args.size()) { 12583 Arg = Args[i]; 12584 12585 // Pass the argument. 12586 12587 ExprResult InputInit 12588 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12589 Context, 12590 Method->getParamDecl(i)), 12591 SourceLocation(), Arg); 12592 12593 IsError |= InputInit.isInvalid(); 12594 Arg = InputInit.getAs<Expr>(); 12595 } else { 12596 ExprResult DefArg 12597 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12598 if (DefArg.isInvalid()) { 12599 IsError = true; 12600 break; 12601 } 12602 12603 Arg = DefArg.getAs<Expr>(); 12604 } 12605 12606 TheCall->setArg(i + 1, Arg); 12607 } 12608 12609 // If this is a variadic call, handle args passed through "...". 12610 if (Proto->isVariadic()) { 12611 // Promote the arguments (C99 6.5.2.2p7). 12612 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12613 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12614 nullptr); 12615 IsError |= Arg.isInvalid(); 12616 TheCall->setArg(i + 1, Arg.get()); 12617 } 12618 } 12619 12620 if (IsError) return true; 12621 12622 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12623 12624 if (CheckFunctionCall(Method, TheCall, Proto)) 12625 return true; 12626 12627 return MaybeBindToTemporary(TheCall); 12628 } 12629 12630 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12631 /// (if one exists), where @c Base is an expression of class type and 12632 /// @c Member is the name of the member we're trying to find. 12633 ExprResult 12634 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12635 bool *NoArrowOperatorFound) { 12636 assert(Base->getType()->isRecordType() && 12637 "left-hand side must have class type"); 12638 12639 if (checkPlaceholderForOverload(*this, Base)) 12640 return ExprError(); 12641 12642 SourceLocation Loc = Base->getExprLoc(); 12643 12644 // C++ [over.ref]p1: 12645 // 12646 // [...] An expression x->m is interpreted as (x.operator->())->m 12647 // for a class object x of type T if T::operator->() exists and if 12648 // the operator is selected as the best match function by the 12649 // overload resolution mechanism (13.3). 12650 DeclarationName OpName = 12651 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12652 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12653 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12654 12655 if (RequireCompleteType(Loc, Base->getType(), 12656 diag::err_typecheck_incomplete_tag, Base)) 12657 return ExprError(); 12658 12659 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12660 LookupQualifiedName(R, BaseRecord->getDecl()); 12661 R.suppressDiagnostics(); 12662 12663 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12664 Oper != OperEnd; ++Oper) { 12665 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12666 None, CandidateSet, /*SuppressUserConversions=*/false); 12667 } 12668 12669 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12670 12671 // Perform overload resolution. 12672 OverloadCandidateSet::iterator Best; 12673 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12674 case OR_Success: 12675 // Overload resolution succeeded; we'll build the call below. 12676 break; 12677 12678 case OR_No_Viable_Function: 12679 if (CandidateSet.empty()) { 12680 QualType BaseType = Base->getType(); 12681 if (NoArrowOperatorFound) { 12682 // Report this specific error to the caller instead of emitting a 12683 // diagnostic, as requested. 12684 *NoArrowOperatorFound = true; 12685 return ExprError(); 12686 } 12687 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12688 << BaseType << Base->getSourceRange(); 12689 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12690 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12691 << FixItHint::CreateReplacement(OpLoc, "."); 12692 } 12693 } else 12694 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12695 << "operator->" << Base->getSourceRange(); 12696 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12697 return ExprError(); 12698 12699 case OR_Ambiguous: 12700 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12701 << "->" << Base->getType() << Base->getSourceRange(); 12702 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12703 return ExprError(); 12704 12705 case OR_Deleted: 12706 Diag(OpLoc, diag::err_ovl_deleted_oper) 12707 << Best->Function->isDeleted() 12708 << "->" 12709 << getDeletedOrUnavailableSuffix(Best->Function) 12710 << Base->getSourceRange(); 12711 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12712 return ExprError(); 12713 } 12714 12715 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12716 12717 // Convert the object parameter. 12718 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12719 ExprResult BaseResult = 12720 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12721 Best->FoundDecl, Method); 12722 if (BaseResult.isInvalid()) 12723 return ExprError(); 12724 Base = BaseResult.get(); 12725 12726 // Build the operator call. 12727 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12728 HadMultipleCandidates, OpLoc); 12729 if (FnExpr.isInvalid()) 12730 return ExprError(); 12731 12732 QualType ResultTy = Method->getReturnType(); 12733 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12734 ResultTy = ResultTy.getNonLValueExprType(Context); 12735 CXXOperatorCallExpr *TheCall = 12736 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12737 Base, ResultTy, VK, OpLoc, false); 12738 12739 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12740 return ExprError(); 12741 12742 return MaybeBindToTemporary(TheCall); 12743 } 12744 12745 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12746 /// a literal operator described by the provided lookup results. 12747 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12748 DeclarationNameInfo &SuffixInfo, 12749 ArrayRef<Expr*> Args, 12750 SourceLocation LitEndLoc, 12751 TemplateArgumentListInfo *TemplateArgs) { 12752 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12753 12754 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12755 OverloadCandidateSet::CSK_Normal); 12756 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12757 /*SuppressUserConversions=*/true); 12758 12759 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12760 12761 // Perform overload resolution. This will usually be trivial, but might need 12762 // to perform substitutions for a literal operator template. 12763 OverloadCandidateSet::iterator Best; 12764 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12765 case OR_Success: 12766 case OR_Deleted: 12767 break; 12768 12769 case OR_No_Viable_Function: 12770 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12771 << R.getLookupName(); 12772 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12773 return ExprError(); 12774 12775 case OR_Ambiguous: 12776 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12777 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12778 return ExprError(); 12779 } 12780 12781 FunctionDecl *FD = Best->Function; 12782 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12783 HadMultipleCandidates, 12784 SuffixInfo.getLoc(), 12785 SuffixInfo.getInfo()); 12786 if (Fn.isInvalid()) 12787 return true; 12788 12789 // Check the argument types. This should almost always be a no-op, except 12790 // that array-to-pointer decay is applied to string literals. 12791 Expr *ConvArgs[2]; 12792 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12793 ExprResult InputInit = PerformCopyInitialization( 12794 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12795 SourceLocation(), Args[ArgIdx]); 12796 if (InputInit.isInvalid()) 12797 return true; 12798 ConvArgs[ArgIdx] = InputInit.get(); 12799 } 12800 12801 QualType ResultTy = FD->getReturnType(); 12802 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12803 ResultTy = ResultTy.getNonLValueExprType(Context); 12804 12805 UserDefinedLiteral *UDL = 12806 new (Context) UserDefinedLiteral(Context, Fn.get(), 12807 llvm::makeArrayRef(ConvArgs, Args.size()), 12808 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12809 12810 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12811 return ExprError(); 12812 12813 if (CheckFunctionCall(FD, UDL, nullptr)) 12814 return ExprError(); 12815 12816 return MaybeBindToTemporary(UDL); 12817 } 12818 12819 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12820 /// given LookupResult is non-empty, it is assumed to describe a member which 12821 /// will be invoked. Otherwise, the function will be found via argument 12822 /// dependent lookup. 12823 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12824 /// otherwise CallExpr is set to ExprError() and some non-success value 12825 /// is returned. 12826 Sema::ForRangeStatus 12827 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12828 SourceLocation RangeLoc, 12829 const DeclarationNameInfo &NameInfo, 12830 LookupResult &MemberLookup, 12831 OverloadCandidateSet *CandidateSet, 12832 Expr *Range, ExprResult *CallExpr) { 12833 Scope *S = nullptr; 12834 12835 CandidateSet->clear(); 12836 if (!MemberLookup.empty()) { 12837 ExprResult MemberRef = 12838 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12839 /*IsPtr=*/false, CXXScopeSpec(), 12840 /*TemplateKWLoc=*/SourceLocation(), 12841 /*FirstQualifierInScope=*/nullptr, 12842 MemberLookup, 12843 /*TemplateArgs=*/nullptr, S); 12844 if (MemberRef.isInvalid()) { 12845 *CallExpr = ExprError(); 12846 return FRS_DiagnosticIssued; 12847 } 12848 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12849 if (CallExpr->isInvalid()) { 12850 *CallExpr = ExprError(); 12851 return FRS_DiagnosticIssued; 12852 } 12853 } else { 12854 UnresolvedSet<0> FoundNames; 12855 UnresolvedLookupExpr *Fn = 12856 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12857 NestedNameSpecifierLoc(), NameInfo, 12858 /*NeedsADL=*/true, /*Overloaded=*/false, 12859 FoundNames.begin(), FoundNames.end()); 12860 12861 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12862 CandidateSet, CallExpr); 12863 if (CandidateSet->empty() || CandidateSetError) { 12864 *CallExpr = ExprError(); 12865 return FRS_NoViableFunction; 12866 } 12867 OverloadCandidateSet::iterator Best; 12868 OverloadingResult OverloadResult = 12869 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12870 12871 if (OverloadResult == OR_No_Viable_Function) { 12872 *CallExpr = ExprError(); 12873 return FRS_NoViableFunction; 12874 } 12875 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12876 Loc, nullptr, CandidateSet, &Best, 12877 OverloadResult, 12878 /*AllowTypoCorrection=*/false); 12879 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12880 *CallExpr = ExprError(); 12881 return FRS_DiagnosticIssued; 12882 } 12883 } 12884 return FRS_Success; 12885 } 12886 12887 12888 /// FixOverloadedFunctionReference - E is an expression that refers to 12889 /// a C++ overloaded function (possibly with some parentheses and 12890 /// perhaps a '&' around it). We have resolved the overloaded function 12891 /// to the function declaration Fn, so patch up the expression E to 12892 /// refer (possibly indirectly) to Fn. Returns the new expr. 12893 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12894 FunctionDecl *Fn) { 12895 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12896 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12897 Found, Fn); 12898 if (SubExpr == PE->getSubExpr()) 12899 return PE; 12900 12901 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12902 } 12903 12904 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12905 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12906 Found, Fn); 12907 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12908 SubExpr->getType()) && 12909 "Implicit cast type cannot be determined from overload"); 12910 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12911 if (SubExpr == ICE->getSubExpr()) 12912 return ICE; 12913 12914 return ImplicitCastExpr::Create(Context, ICE->getType(), 12915 ICE->getCastKind(), 12916 SubExpr, nullptr, 12917 ICE->getValueKind()); 12918 } 12919 12920 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12921 assert(UnOp->getOpcode() == UO_AddrOf && 12922 "Can only take the address of an overloaded function"); 12923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12924 if (Method->isStatic()) { 12925 // Do nothing: static member functions aren't any different 12926 // from non-member functions. 12927 } else { 12928 // Fix the subexpression, which really has to be an 12929 // UnresolvedLookupExpr holding an overloaded member function 12930 // or template. 12931 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12932 Found, Fn); 12933 if (SubExpr == UnOp->getSubExpr()) 12934 return UnOp; 12935 12936 assert(isa<DeclRefExpr>(SubExpr) 12937 && "fixed to something other than a decl ref"); 12938 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12939 && "fixed to a member ref with no nested name qualifier"); 12940 12941 // We have taken the address of a pointer to member 12942 // function. Perform the computation here so that we get the 12943 // appropriate pointer to member type. 12944 QualType ClassType 12945 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12946 QualType MemPtrType 12947 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12948 12949 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12950 VK_RValue, OK_Ordinary, 12951 UnOp->getOperatorLoc()); 12952 } 12953 } 12954 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12955 Found, Fn); 12956 if (SubExpr == UnOp->getSubExpr()) 12957 return UnOp; 12958 12959 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12960 Context.getPointerType(SubExpr->getType()), 12961 VK_RValue, OK_Ordinary, 12962 UnOp->getOperatorLoc()); 12963 } 12964 12965 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12966 // FIXME: avoid copy. 12967 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12968 if (ULE->hasExplicitTemplateArgs()) { 12969 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12970 TemplateArgs = &TemplateArgsBuffer; 12971 } 12972 12973 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12974 ULE->getQualifierLoc(), 12975 ULE->getTemplateKeywordLoc(), 12976 Fn, 12977 /*enclosing*/ false, // FIXME? 12978 ULE->getNameLoc(), 12979 Fn->getType(), 12980 VK_LValue, 12981 Found.getDecl(), 12982 TemplateArgs); 12983 MarkDeclRefReferenced(DRE); 12984 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12985 return DRE; 12986 } 12987 12988 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12989 // FIXME: avoid copy. 12990 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12991 if (MemExpr->hasExplicitTemplateArgs()) { 12992 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12993 TemplateArgs = &TemplateArgsBuffer; 12994 } 12995 12996 Expr *Base; 12997 12998 // If we're filling in a static method where we used to have an 12999 // implicit member access, rewrite to a simple decl ref. 13000 if (MemExpr->isImplicitAccess()) { 13001 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13002 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13003 MemExpr->getQualifierLoc(), 13004 MemExpr->getTemplateKeywordLoc(), 13005 Fn, 13006 /*enclosing*/ false, 13007 MemExpr->getMemberLoc(), 13008 Fn->getType(), 13009 VK_LValue, 13010 Found.getDecl(), 13011 TemplateArgs); 13012 MarkDeclRefReferenced(DRE); 13013 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13014 return DRE; 13015 } else { 13016 SourceLocation Loc = MemExpr->getMemberLoc(); 13017 if (MemExpr->getQualifier()) 13018 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13019 CheckCXXThisCapture(Loc); 13020 Base = new (Context) CXXThisExpr(Loc, 13021 MemExpr->getBaseType(), 13022 /*isImplicit=*/true); 13023 } 13024 } else 13025 Base = MemExpr->getBase(); 13026 13027 ExprValueKind valueKind; 13028 QualType type; 13029 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13030 valueKind = VK_LValue; 13031 type = Fn->getType(); 13032 } else { 13033 valueKind = VK_RValue; 13034 type = Context.BoundMemberTy; 13035 } 13036 13037 MemberExpr *ME = MemberExpr::Create( 13038 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13039 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13040 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13041 OK_Ordinary); 13042 ME->setHadMultipleCandidates(true); 13043 MarkMemberReferenced(ME); 13044 return ME; 13045 } 13046 13047 llvm_unreachable("Invalid reference to overloaded function"); 13048 } 13049 13050 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13051 DeclAccessPair Found, 13052 FunctionDecl *Fn) { 13053 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13054 } 13055