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/PartialDiagnostic.h" 24 #include "clang/Lex/Preprocessor.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallString.h" 34 #include <algorithm> 35 36 namespace clang { 37 using namespace sema; 38 39 /// A convenience routine for creating a decayed reference to a function. 40 static ExprResult 41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42 bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 46 return ExprError(); 47 // If FoundDecl is different from Fn (such as if one is a template 48 // and the other a specialization), make sure DiagnoseUseOfDecl is 49 // called on both. 50 // FIXME: This would be more comprehensively addressed by modifying 51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 52 // being used. 53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 54 return ExprError(); 55 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 56 VK_LValue, Loc, LocInfo); 57 if (HadMultipleCandidates) 58 DRE->setHadMultipleCandidates(true); 59 60 S.MarkDeclRefReferenced(DRE); 61 62 ExprResult E = S.Owned(DRE); 63 E = S.DefaultFunctionArrayConversion(E.take()); 64 if (E.isInvalid()) 65 return ExprError(); 66 return E; 67 } 68 69 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 70 bool InOverloadResolution, 71 StandardConversionSequence &SCS, 72 bool CStyle, 73 bool AllowObjCWritebackConversion); 74 75 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 76 QualType &ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle); 80 static OverloadingResult 81 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 82 UserDefinedConversionSequence& User, 83 OverloadCandidateSet& Conversions, 84 bool AllowExplicit); 85 86 87 static ImplicitConversionSequence::CompareKind 88 CompareStandardConversionSequences(Sema &S, 89 const StandardConversionSequence& SCS1, 90 const StandardConversionSequence& SCS2); 91 92 static ImplicitConversionSequence::CompareKind 93 CompareQualificationConversions(Sema &S, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97 static ImplicitConversionSequence::CompareKind 98 CompareDerivedToBaseConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 103 104 /// GetConversionCategory - Retrieve the implicit conversion 105 /// category corresponding to the given implicit conversion kind. 106 ImplicitConversionCategory 107 GetConversionCategory(ImplicitConversionKind Kind) { 108 static const ImplicitConversionCategory 109 Category[(int)ICK_Num_Conversion_Kinds] = { 110 ICC_Identity, 111 ICC_Lvalue_Transformation, 112 ICC_Lvalue_Transformation, 113 ICC_Lvalue_Transformation, 114 ICC_Identity, 115 ICC_Qualification_Adjustment, 116 ICC_Promotion, 117 ICC_Promotion, 118 ICC_Promotion, 119 ICC_Conversion, 120 ICC_Conversion, 121 ICC_Conversion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion 132 }; 133 return Category[(int)Kind]; 134 } 135 136 /// GetConversionRank - Retrieve the implicit conversion rank 137 /// corresponding to the given implicit conversion kind. 138 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 139 static const ImplicitConversionRank 140 Rank[(int)ICK_Num_Conversion_Kinds] = { 141 ICR_Exact_Match, 142 ICR_Exact_Match, 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Promotion, 148 ICR_Promotion, 149 ICR_Promotion, 150 ICR_Conversion, 151 ICR_Conversion, 152 ICR_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Complex_Real_Conversion, 162 ICR_Conversion, 163 ICR_Conversion, 164 ICR_Writeback_Conversion 165 }; 166 return Rank[(int)Kind]; 167 } 168 169 /// GetImplicitConversionName - Return the name of this kind of 170 /// implicit conversion. 171 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 173 "No conversion", 174 "Lvalue-to-rvalue", 175 "Array-to-pointer", 176 "Function-to-pointer", 177 "Noreturn adjustment", 178 "Qualification", 179 "Integral promotion", 180 "Floating point promotion", 181 "Complex promotion", 182 "Integral conversion", 183 "Floating conversion", 184 "Complex conversion", 185 "Floating-integral conversion", 186 "Pointer conversion", 187 "Pointer-to-member conversion", 188 "Boolean conversion", 189 "Compatible-types conversion", 190 "Derived-to-base conversion", 191 "Vector conversion", 192 "Vector splat", 193 "Complex-real conversion", 194 "Block Pointer conversion", 195 "Transparent Union Conversion" 196 "Writeback conversion" 197 }; 198 return Name[Kind]; 199 } 200 201 /// StandardConversionSequence - Set the standard conversion 202 /// sequence to the identity conversion. 203 void StandardConversionSequence::setAsIdentityConversion() { 204 First = ICK_Identity; 205 Second = ICK_Identity; 206 Third = ICK_Identity; 207 DeprecatedStringLiteralToCharPtr = false; 208 QualificationIncludesObjCLifetime = false; 209 ReferenceBinding = false; 210 DirectBinding = false; 211 IsLvalueReference = true; 212 BindsToFunctionLvalue = false; 213 BindsToRvalue = false; 214 BindsImplicitObjectArgumentWithoutRefQualifier = false; 215 ObjCLifetimeConversionBinding = false; 216 CopyConstructor = 0; 217 } 218 219 /// getRank - Retrieve the rank of this standard conversion sequence 220 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 221 /// implicit conversions. 222 ImplicitConversionRank StandardConversionSequence::getRank() const { 223 ImplicitConversionRank Rank = ICR_Exact_Match; 224 if (GetConversionRank(First) > Rank) 225 Rank = GetConversionRank(First); 226 if (GetConversionRank(Second) > Rank) 227 Rank = GetConversionRank(Second); 228 if (GetConversionRank(Third) > Rank) 229 Rank = GetConversionRank(Third); 230 return Rank; 231 } 232 233 /// isPointerConversionToBool - Determines whether this conversion is 234 /// a conversion of a pointer or pointer-to-member to bool. This is 235 /// used as part of the ranking of standard conversion sequences 236 /// (C++ 13.3.3.2p4). 237 bool StandardConversionSequence::isPointerConversionToBool() const { 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer or function-to-pointer implicit conversions, so 240 // check for their presence as well as checking whether FromType is 241 // a pointer. 242 if (getToType(1)->isBooleanType() && 243 (getFromType()->isPointerType() || 244 getFromType()->isObjCObjectPointerType() || 245 getFromType()->isBlockPointerType() || 246 getFromType()->isNullPtrType() || 247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 248 return true; 249 250 return false; 251 } 252 253 /// isPointerConversionToVoidPointer - Determines whether this 254 /// conversion is a conversion of a pointer to a void pointer. This is 255 /// used as part of the ranking of standard conversion sequences (C++ 256 /// 13.3.3.2p4). 257 bool 258 StandardConversionSequence:: 259 isPointerConversionToVoidPointer(ASTContext& Context) const { 260 QualType FromType = getFromType(); 261 QualType ToType = getToType(1); 262 263 // Note that FromType has not necessarily been transformed by the 264 // array-to-pointer implicit conversion, so check for its presence 265 // and redo the conversion to get a pointer. 266 if (First == ICK_Array_To_Pointer) 267 FromType = Context.getArrayDecayedType(FromType); 268 269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 271 return ToPtrType->getPointeeType()->isVoidType(); 272 273 return false; 274 } 275 276 /// Skip any implicit casts which could be either part of a narrowing conversion 277 /// or after one in an implicit conversion. 278 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297 } 298 299 /// Check if this standard conversion sequence represents a narrowing 300 /// conversion, according to C++11 [dcl.init.list]p7. 301 /// 302 /// \param Ctx The AST context. 303 /// \param Converted The result of applying this standard conversion sequence. 304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305 /// value of the expression prior to the narrowing conversion. 306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307 /// type of the expression prior to the narrowing conversion. 308 NarrowingKind 309 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 310 const Expr *Converted, 311 APValue &ConstantValue, 312 QualType &ConstantType) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 switch (Second) { 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 if (Initializer && 333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 334 // Convert the integer to the floating type. 335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 337 llvm::APFloat::rmNearestTiesToEven); 338 // And back. 339 llvm::APSInt ConvertedValue = IntConstantValue; 340 bool ignored; 341 Result.convertToInteger(ConvertedValue, 342 llvm::APFloat::rmTowardZero, &ignored); 343 // If the resulting value is different, this was a narrowing conversion. 344 if (IntConstantValue != ConvertedValue) { 345 ConstantValue = APValue(IntConstantValue); 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 // Variables are always narrowings. 351 return NK_Variable_Narrowing; 352 } 353 } 354 return NK_Not_Narrowing; 355 356 // -- from long double to double or float, or from double to float, except 357 // where the source is a constant expression and the actual value after 358 // conversion is within the range of values that can be represented (even 359 // if it cannot be represented exactly), or 360 case ICK_Floating_Conversion: 361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 363 // FromType is larger than ToType. 364 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 366 // Constant! 367 assert(ConstantValue.isFloat()); 368 llvm::APFloat FloatVal = ConstantValue.getFloat(); 369 // Convert the source value into the target type. 370 bool ignored; 371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 372 Ctx.getFloatTypeSemantics(ToType), 373 llvm::APFloat::rmNearestTiesToEven, &ignored); 374 // If there was no overflow, the source value is within the range of 375 // values that can be represented. 376 if (ConvertStatus & llvm::APFloat::opOverflow) { 377 ConstantType = Initializer->getType(); 378 return NK_Constant_Narrowing; 379 } 380 } else { 381 return NK_Variable_Narrowing; 382 } 383 } 384 return NK_Not_Narrowing; 385 386 // -- from an integer type or unscoped enumeration type to an integer type 387 // that cannot represent all the values of the original type, except where 388 // the source is a constant expression and the actual value after 389 // conversion will fit into the target type and will produce the original 390 // value when converted back to the original type. 391 case ICK_Boolean_Conversion: // Bools are integers too. 392 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 393 // Boolean conversions can be from pointers and pointers to members 394 // [conv.bool], and those aren't considered narrowing conversions. 395 return NK_Not_Narrowing; 396 } // Otherwise, fall through to the integral case. 397 case ICK_Integral_Conversion: { 398 assert(FromType->isIntegralOrUnscopedEnumerationType()); 399 assert(ToType->isIntegralOrUnscopedEnumerationType()); 400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 401 const unsigned FromWidth = Ctx.getIntWidth(FromType); 402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 403 const unsigned ToWidth = Ctx.getIntWidth(ToType); 404 405 if (FromWidth > ToWidth || 406 (FromWidth == ToWidth && FromSigned != ToSigned) || 407 (FromSigned && !ToSigned)) { 408 // Not all values of FromType can be represented in ToType. 409 llvm::APSInt InitializerValue; 410 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 412 // Such conversions on variables are always narrowing. 413 return NK_Variable_Narrowing; 414 } 415 bool Narrowing = false; 416 if (FromWidth < ToWidth) { 417 // Negative -> unsigned is narrowing. Otherwise, more bits is never 418 // narrowing. 419 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 420 Narrowing = true; 421 } else { 422 // Add a bit to the InitializerValue so we don't have to worry about 423 // signed vs. unsigned comparisons. 424 InitializerValue = InitializerValue.extend( 425 InitializerValue.getBitWidth() + 1); 426 // Convert the initializer to and from the target width and signed-ness. 427 llvm::APSInt ConvertedValue = InitializerValue; 428 ConvertedValue = ConvertedValue.trunc(ToWidth); 429 ConvertedValue.setIsSigned(ToSigned); 430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 431 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 432 // If the result is different, this was a narrowing conversion. 433 if (ConvertedValue != InitializerValue) 434 Narrowing = true; 435 } 436 if (Narrowing) { 437 ConstantType = Initializer->getType(); 438 ConstantValue = APValue(InitializerValue); 439 return NK_Constant_Narrowing; 440 } 441 } 442 return NK_Not_Narrowing; 443 } 444 445 default: 446 // Other kinds of conversions are not narrowings. 447 return NK_Not_Narrowing; 448 } 449 } 450 451 /// DebugPrint - Print this standard conversion sequence to standard 452 /// error. Useful for debugging overloading issues. 453 void StandardConversionSequence::DebugPrint() const { 454 raw_ostream &OS = llvm::errs(); 455 bool PrintedSomething = false; 456 if (First != ICK_Identity) { 457 OS << GetImplicitConversionName(First); 458 PrintedSomething = true; 459 } 460 461 if (Second != ICK_Identity) { 462 if (PrintedSomething) { 463 OS << " -> "; 464 } 465 OS << GetImplicitConversionName(Second); 466 467 if (CopyConstructor) { 468 OS << " (by copy constructor)"; 469 } else if (DirectBinding) { 470 OS << " (direct reference binding)"; 471 } else if (ReferenceBinding) { 472 OS << " (reference binding)"; 473 } 474 PrintedSomething = true; 475 } 476 477 if (Third != ICK_Identity) { 478 if (PrintedSomething) { 479 OS << " -> "; 480 } 481 OS << GetImplicitConversionName(Third); 482 PrintedSomething = true; 483 } 484 485 if (!PrintedSomething) { 486 OS << "No conversions required"; 487 } 488 } 489 490 /// DebugPrint - Print this user-defined conversion sequence to standard 491 /// error. Useful for debugging overloading issues. 492 void UserDefinedConversionSequence::DebugPrint() const { 493 raw_ostream &OS = llvm::errs(); 494 if (Before.First || Before.Second || Before.Third) { 495 Before.DebugPrint(); 496 OS << " -> "; 497 } 498 if (ConversionFunction) 499 OS << '\'' << *ConversionFunction << '\''; 500 else 501 OS << "aggregate initialization"; 502 if (After.First || After.Second || After.Third) { 503 OS << " -> "; 504 After.DebugPrint(); 505 } 506 } 507 508 /// DebugPrint - Print this implicit conversion sequence to standard 509 /// error. Useful for debugging overloading issues. 510 void ImplicitConversionSequence::DebugPrint() const { 511 raw_ostream &OS = llvm::errs(); 512 switch (ConversionKind) { 513 case StandardConversion: 514 OS << "Standard conversion: "; 515 Standard.DebugPrint(); 516 break; 517 case UserDefinedConversion: 518 OS << "User-defined conversion: "; 519 UserDefined.DebugPrint(); 520 break; 521 case EllipsisConversion: 522 OS << "Ellipsis conversion"; 523 break; 524 case AmbiguousConversion: 525 OS << "Ambiguous conversion"; 526 break; 527 case BadConversion: 528 OS << "Bad conversion"; 529 break; 530 } 531 532 OS << "\n"; 533 } 534 535 void AmbiguousConversionSequence::construct() { 536 new (&conversions()) ConversionSet(); 537 } 538 539 void AmbiguousConversionSequence::destruct() { 540 conversions().~ConversionSet(); 541 } 542 543 void 544 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 545 FromTypePtr = O.FromTypePtr; 546 ToTypePtr = O.ToTypePtr; 547 new (&conversions()) ConversionSet(O.conversions()); 548 } 549 550 namespace { 551 // Structure used by OverloadCandidate::DeductionFailureInfo to store 552 // template argument information. 553 struct DFIArguments { 554 TemplateArgument FirstArg; 555 TemplateArgument SecondArg; 556 }; 557 // Structure used by OverloadCandidate::DeductionFailureInfo to store 558 // template parameter and template argument information. 559 struct DFIParamWithArguments : DFIArguments { 560 TemplateParameter Param; 561 }; 562 } 563 564 /// \brief Convert from Sema's representation of template deduction information 565 /// to the form used in overload-candidate information. 566 OverloadCandidate::DeductionFailureInfo 567 static MakeDeductionFailureInfo(ASTContext &Context, 568 Sema::TemplateDeductionResult TDK, 569 TemplateDeductionInfo &Info) { 570 OverloadCandidate::DeductionFailureInfo Result; 571 Result.Result = static_cast<unsigned>(TDK); 572 Result.HasDiagnostic = false; 573 Result.Data = 0; 574 switch (TDK) { 575 case Sema::TDK_Success: 576 case Sema::TDK_Invalid: 577 case Sema::TDK_InstantiationDepth: 578 case Sema::TDK_TooManyArguments: 579 case Sema::TDK_TooFewArguments: 580 break; 581 582 case Sema::TDK_Incomplete: 583 case Sema::TDK_InvalidExplicitArguments: 584 Result.Data = Info.Param.getOpaqueValue(); 585 break; 586 587 case Sema::TDK_NonDeducedMismatch: { 588 // FIXME: Should allocate from normal heap so that we can free this later. 589 DFIArguments *Saved = new (Context) DFIArguments; 590 Saved->FirstArg = Info.FirstArg; 591 Saved->SecondArg = Info.SecondArg; 592 Result.Data = Saved; 593 break; 594 } 595 596 case Sema::TDK_Inconsistent: 597 case Sema::TDK_Underqualified: { 598 // FIXME: Should allocate from normal heap so that we can free this later. 599 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 600 Saved->Param = Info.Param; 601 Saved->FirstArg = Info.FirstArg; 602 Saved->SecondArg = Info.SecondArg; 603 Result.Data = Saved; 604 break; 605 } 606 607 case Sema::TDK_SubstitutionFailure: 608 Result.Data = Info.take(); 609 if (Info.hasSFINAEDiagnostic()) { 610 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 611 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 612 Info.takeSFINAEDiagnostic(*Diag); 613 Result.HasDiagnostic = true; 614 } 615 break; 616 617 case Sema::TDK_FailedOverloadResolution: 618 Result.Data = Info.Expression; 619 break; 620 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 break; 623 } 624 625 return Result; 626 } 627 628 void OverloadCandidate::DeductionFailureInfo::Destroy() { 629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 630 case Sema::TDK_Success: 631 case Sema::TDK_Invalid: 632 case Sema::TDK_InstantiationDepth: 633 case Sema::TDK_Incomplete: 634 case Sema::TDK_TooManyArguments: 635 case Sema::TDK_TooFewArguments: 636 case Sema::TDK_InvalidExplicitArguments: 637 case Sema::TDK_FailedOverloadResolution: 638 break; 639 640 case Sema::TDK_Inconsistent: 641 case Sema::TDK_Underqualified: 642 case Sema::TDK_NonDeducedMismatch: 643 // FIXME: Destroy the data? 644 Data = 0; 645 break; 646 647 case Sema::TDK_SubstitutionFailure: 648 // FIXME: Destroy the template argument list? 649 Data = 0; 650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 651 Diag->~PartialDiagnosticAt(); 652 HasDiagnostic = false; 653 } 654 break; 655 656 // Unhandled 657 case Sema::TDK_MiscellaneousDeductionFailure: 658 break; 659 } 660 } 661 662 PartialDiagnosticAt * 663 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 664 if (HasDiagnostic) 665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 666 return 0; 667 } 668 669 TemplateParameter 670 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 672 case Sema::TDK_Success: 673 case Sema::TDK_Invalid: 674 case Sema::TDK_InstantiationDepth: 675 case Sema::TDK_TooManyArguments: 676 case Sema::TDK_TooFewArguments: 677 case Sema::TDK_SubstitutionFailure: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return TemplateParameter(); 681 682 case Sema::TDK_Incomplete: 683 case Sema::TDK_InvalidExplicitArguments: 684 return TemplateParameter::getFromOpaqueValue(Data); 685 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 return static_cast<DFIParamWithArguments*>(Data)->Param; 689 690 // Unhandled 691 case Sema::TDK_MiscellaneousDeductionFailure: 692 break; 693 } 694 695 return TemplateParameter(); 696 } 697 698 TemplateArgumentList * 699 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_TooManyArguments: 705 case Sema::TDK_TooFewArguments: 706 case Sema::TDK_Incomplete: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 return 0; 713 714 case Sema::TDK_SubstitutionFailure: 715 return static_cast<TemplateArgumentList*>(Data); 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return 0; 723 } 724 725 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return 0; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->FirstArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return 0; 749 } 750 751 const TemplateArgument * 752 OverloadCandidate::DeductionFailureInfo::getSecondArg() { 753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 754 case Sema::TDK_Success: 755 case Sema::TDK_Invalid: 756 case Sema::TDK_InstantiationDepth: 757 case Sema::TDK_Incomplete: 758 case Sema::TDK_TooManyArguments: 759 case Sema::TDK_TooFewArguments: 760 case Sema::TDK_InvalidExplicitArguments: 761 case Sema::TDK_SubstitutionFailure: 762 case Sema::TDK_FailedOverloadResolution: 763 return 0; 764 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 case Sema::TDK_NonDeducedMismatch: 768 return &static_cast<DFIArguments*>(Data)->SecondArg; 769 770 // Unhandled 771 case Sema::TDK_MiscellaneousDeductionFailure: 772 break; 773 } 774 775 return 0; 776 } 777 778 Expr * 779 OverloadCandidate::DeductionFailureInfo::getExpr() { 780 if (static_cast<Sema::TemplateDeductionResult>(Result) == 781 Sema::TDK_FailedOverloadResolution) 782 return static_cast<Expr*>(Data); 783 784 return 0; 785 } 786 787 void OverloadCandidateSet::destroyCandidates() { 788 for (iterator i = begin(), e = end(); i != e; ++i) { 789 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 790 i->Conversions[ii].~ImplicitConversionSequence(); 791 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 792 i->DeductionFailure.Destroy(); 793 } 794 } 795 796 void OverloadCandidateSet::clear() { 797 destroyCandidates(); 798 NumInlineSequences = 0; 799 Candidates.clear(); 800 Functions.clear(); 801 } 802 803 namespace { 804 class UnbridgedCastsSet { 805 struct Entry { 806 Expr **Addr; 807 Expr *Saved; 808 }; 809 SmallVector<Entry, 2> Entries; 810 811 public: 812 void save(Sema &S, Expr *&E) { 813 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 814 Entry entry = { &E, E }; 815 Entries.push_back(entry); 816 E = S.stripARCUnbridgedCast(E); 817 } 818 819 void restore() { 820 for (SmallVectorImpl<Entry>::iterator 821 i = Entries.begin(), e = Entries.end(); i != e; ++i) 822 *i->Addr = i->Saved; 823 } 824 }; 825 } 826 827 /// checkPlaceholderForOverload - Do any interesting placeholder-like 828 /// preprocessing on the given expression. 829 /// 830 /// \param unbridgedCasts a collection to which to add unbridged casts; 831 /// without this, they will be immediately diagnosed as errors 832 /// 833 /// Return true on unrecoverable error. 834 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 835 UnbridgedCastsSet *unbridgedCasts = 0) { 836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 837 // We can't handle overloaded expressions here because overload 838 // resolution might reasonably tweak them. 839 if (placeholder->getKind() == BuiltinType::Overload) return false; 840 841 // If the context potentially accepts unbridged ARC casts, strip 842 // the unbridged cast and add it to the collection for later restoration. 843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 844 unbridgedCasts) { 845 unbridgedCasts->save(S, E); 846 return false; 847 } 848 849 // Go ahead and check everything else. 850 ExprResult result = S.CheckPlaceholderExpr(E); 851 if (result.isInvalid()) 852 return true; 853 854 E = result.take(); 855 return false; 856 } 857 858 // Nothing to do. 859 return false; 860 } 861 862 /// checkArgPlaceholdersForOverload - Check a set of call operands for 863 /// placeholders. 864 static bool checkArgPlaceholdersForOverload(Sema &S, 865 MultiExprArg Args, 866 UnbridgedCastsSet &unbridged) { 867 for (unsigned i = 0, e = Args.size(); i != e; ++i) 868 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 869 return true; 870 871 return false; 872 } 873 874 // IsOverload - Determine whether the given New declaration is an 875 // overload of the declarations in Old. This routine returns false if 876 // New and Old cannot be overloaded, e.g., if New has the same 877 // signature as some function in Old (C++ 1.3.10) or if the Old 878 // declarations aren't functions (or function templates) at all. When 879 // it does return false, MatchedDecl will point to the decl that New 880 // cannot be overloaded with. This decl may be a UsingShadowDecl on 881 // top of the underlying declaration. 882 // 883 // Example: Given the following input: 884 // 885 // void f(int, float); // #1 886 // void f(int, int); // #2 887 // int f(int, int); // #3 888 // 889 // When we process #1, there is no previous declaration of "f", 890 // so IsOverload will not be used. 891 // 892 // When we process #2, Old contains only the FunctionDecl for #1. By 893 // comparing the parameter types, we see that #1 and #2 are overloaded 894 // (since they have different signatures), so this routine returns 895 // false; MatchedDecl is unchanged. 896 // 897 // When we process #3, Old is an overload set containing #1 and #2. We 898 // compare the signatures of #3 to #1 (they're overloaded, so we do 899 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 900 // identical (return types of functions are not part of the 901 // signature), IsOverload returns false and MatchedDecl will be set to 902 // point to the FunctionDecl for #2. 903 // 904 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 905 // into a class by a using declaration. The rules for whether to hide 906 // shadow declarations ignore some properties which otherwise figure 907 // into a function template's signature. 908 Sema::OverloadKind 909 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 910 NamedDecl *&Match, bool NewIsUsingDecl) { 911 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 912 I != E; ++I) { 913 NamedDecl *OldD = *I; 914 915 bool OldIsUsingDecl = false; 916 if (isa<UsingShadowDecl>(OldD)) { 917 OldIsUsingDecl = true; 918 919 // We can always introduce two using declarations into the same 920 // context, even if they have identical signatures. 921 if (NewIsUsingDecl) continue; 922 923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 924 } 925 926 // If either declaration was introduced by a using declaration, 927 // we'll need to use slightly different rules for matching. 928 // Essentially, these rules are the normal rules, except that 929 // function templates hide function templates with different 930 // return types or template parameter lists. 931 bool UseMemberUsingDeclRules = 932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 933 !New->getFriendObjectKind(); 934 935 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 936 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 937 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 939 continue; 940 } 941 942 Match = *I; 943 return Ovl_Match; 944 } 945 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 946 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 947 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 948 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 949 continue; 950 } 951 952 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 953 continue; 954 955 Match = *I; 956 return Ovl_Match; 957 } 958 } else if (isa<UsingDecl>(OldD)) { 959 // We can overload with these, which can show up when doing 960 // redeclaration checks for UsingDecls. 961 assert(Old.getLookupKind() == LookupUsingDeclName); 962 } else if (isa<TagDecl>(OldD)) { 963 // We can always overload with tags by hiding them. 964 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 965 // Optimistically assume that an unresolved using decl will 966 // overload; if it doesn't, we'll have to diagnose during 967 // template instantiation. 968 } else { 969 // (C++ 13p1): 970 // Only function declarations can be overloaded; object and type 971 // declarations cannot be overloaded. 972 Match = *I; 973 return Ovl_NonFunction; 974 } 975 } 976 977 return Ovl_Overload; 978 } 979 980 static bool canBeOverloaded(const FunctionDecl &D) { 981 if (D.getAttr<OverloadableAttr>()) 982 return true; 983 if (D.isExternC()) 984 return false; 985 986 // Main cannot be overloaded (basic.start.main). 987 if (D.isMain()) 988 return false; 989 990 return true; 991 } 992 993 static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old, 994 bool UseUsingDeclRules) { 995 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 996 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 997 998 // C++ [temp.fct]p2: 999 // A function template can be overloaded with other function templates 1000 // and with normal (non-template) functions. 1001 if ((OldTemplate == 0) != (NewTemplate == 0)) 1002 return true; 1003 1004 // Is the function New an overload of the function Old? 1005 QualType OldQType = S.Context.getCanonicalType(Old->getType()); 1006 QualType NewQType = S.Context.getCanonicalType(New->getType()); 1007 1008 // Compare the signatures (C++ 1.3.10) of the two functions to 1009 // determine whether they are overloads. If we find any mismatch 1010 // in the signature, they are overloads. 1011 1012 // If either of these functions is a K&R-style function (no 1013 // prototype), then we consider them to have matching signatures. 1014 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1015 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1016 return false; 1017 1018 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1019 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1020 1021 // The signature of a function includes the types of its 1022 // parameters (C++ 1.3.10), which includes the presence or absence 1023 // of the ellipsis; see C++ DR 357). 1024 if (OldQType != NewQType && 1025 (OldType->getNumArgs() != NewType->getNumArgs() || 1026 OldType->isVariadic() != NewType->isVariadic() || 1027 !S.FunctionArgTypesAreEqual(OldType, NewType))) 1028 return true; 1029 1030 // C++ [temp.over.link]p4: 1031 // The signature of a function template consists of its function 1032 // signature, its return type and its template parameter list. The names 1033 // of the template parameters are significant only for establishing the 1034 // relationship between the template parameters and the rest of the 1035 // signature. 1036 // 1037 // We check the return type and template parameter lists for function 1038 // templates first; the remaining checks follow. 1039 // 1040 // However, we don't consider either of these when deciding whether 1041 // a member introduced by a shadow declaration is hidden. 1042 if (!UseUsingDeclRules && NewTemplate && 1043 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1044 OldTemplate->getTemplateParameters(), 1045 false, S.TPL_TemplateMatch) || 1046 OldType->getResultType() != NewType->getResultType())) 1047 return true; 1048 1049 // If the function is a class member, its signature includes the 1050 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1051 // 1052 // As part of this, also check whether one of the member functions 1053 // is static, in which case they are not overloads (C++ 1054 // 13.1p2). While not part of the definition of the signature, 1055 // this check is important to determine whether these functions 1056 // can be overloaded. 1057 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1058 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1059 if (OldMethod && NewMethod && 1060 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1061 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1062 if (!UseUsingDeclRules && 1063 (OldMethod->getRefQualifier() == RQ_None || 1064 NewMethod->getRefQualifier() == RQ_None)) { 1065 // C++0x [over.load]p2: 1066 // - Member function declarations with the same name and the same 1067 // parameter-type-list as well as member function template 1068 // declarations with the same name, the same parameter-type-list, and 1069 // the same template parameter lists cannot be overloaded if any of 1070 // them, but not all, have a ref-qualifier (8.3.5). 1071 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1072 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1073 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1074 } 1075 return true; 1076 } 1077 1078 // We may not have applied the implicit const for a constexpr member 1079 // function yet (because we haven't yet resolved whether this is a static 1080 // or non-static member function). Add it now, on the assumption that this 1081 // is a redeclaration of OldMethod. 1082 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1083 if (!S.getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1084 !isa<CXXConstructorDecl>(NewMethod)) 1085 NewQuals |= Qualifiers::Const; 1086 if (OldMethod->getTypeQualifiers() != NewQuals) 1087 return true; 1088 } 1089 1090 // The signatures match; this is not an overload. 1091 return false; 1092 } 1093 1094 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1095 bool UseUsingDeclRules) { 1096 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules)) 1097 return false; 1098 1099 // If both of the functions are extern "C", then they are not 1100 // overloads. 1101 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 1102 return false; 1103 1104 return true; 1105 } 1106 1107 /// \brief Checks availability of the function depending on the current 1108 /// function context. Inside an unavailable function, unavailability is ignored. 1109 /// 1110 /// \returns true if \arg FD is unavailable and current context is inside 1111 /// an available function, false otherwise. 1112 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1113 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1114 } 1115 1116 /// \brief Tries a user-defined conversion from From to ToType. 1117 /// 1118 /// Produces an implicit conversion sequence for when a standard conversion 1119 /// is not an option. See TryImplicitConversion for more information. 1120 static ImplicitConversionSequence 1121 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1122 bool SuppressUserConversions, 1123 bool AllowExplicit, 1124 bool InOverloadResolution, 1125 bool CStyle, 1126 bool AllowObjCWritebackConversion) { 1127 ImplicitConversionSequence ICS; 1128 1129 if (SuppressUserConversions) { 1130 // We're not in the case above, so there is no conversion that 1131 // we can perform. 1132 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1133 return ICS; 1134 } 1135 1136 // Attempt user-defined conversion. 1137 OverloadCandidateSet Conversions(From->getExprLoc()); 1138 OverloadingResult UserDefResult 1139 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1140 AllowExplicit); 1141 1142 if (UserDefResult == OR_Success) { 1143 ICS.setUserDefined(); 1144 // C++ [over.ics.user]p4: 1145 // A conversion of an expression of class type to the same class 1146 // type is given Exact Match rank, and a conversion of an 1147 // expression of class type to a base class of that type is 1148 // given Conversion rank, in spite of the fact that a copy 1149 // constructor (i.e., a user-defined conversion function) is 1150 // called for those cases. 1151 if (CXXConstructorDecl *Constructor 1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1153 QualType FromCanon 1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1155 QualType ToCanon 1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1157 if (Constructor->isCopyConstructor() && 1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1159 // Turn this into a "standard" conversion sequence, so that it 1160 // gets ranked with standard conversion sequences. 1161 ICS.setStandard(); 1162 ICS.Standard.setAsIdentityConversion(); 1163 ICS.Standard.setFromType(From->getType()); 1164 ICS.Standard.setAllToTypes(ToType); 1165 ICS.Standard.CopyConstructor = Constructor; 1166 if (ToCanon != FromCanon) 1167 ICS.Standard.Second = ICK_Derived_To_Base; 1168 } 1169 } 1170 1171 // C++ [over.best.ics]p4: 1172 // However, when considering the argument of a user-defined 1173 // conversion function that is a candidate by 13.3.1.3 when 1174 // invoked for the copying of the temporary in the second step 1175 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1176 // 13.3.1.6 in all cases, only standard conversion sequences and 1177 // ellipsis conversion sequences are allowed. 1178 if (SuppressUserConversions && ICS.isUserDefined()) { 1179 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1180 } 1181 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1182 ICS.setAmbiguous(); 1183 ICS.Ambiguous.setFromType(From->getType()); 1184 ICS.Ambiguous.setToType(ToType); 1185 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1186 Cand != Conversions.end(); ++Cand) 1187 if (Cand->Viable) 1188 ICS.Ambiguous.addConversion(Cand->Function); 1189 } else { 1190 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1191 } 1192 1193 return ICS; 1194 } 1195 1196 /// TryImplicitConversion - Attempt to perform an implicit conversion 1197 /// from the given expression (Expr) to the given type (ToType). This 1198 /// function returns an implicit conversion sequence that can be used 1199 /// to perform the initialization. Given 1200 /// 1201 /// void f(float f); 1202 /// void g(int i) { f(i); } 1203 /// 1204 /// this routine would produce an implicit conversion sequence to 1205 /// describe the initialization of f from i, which will be a standard 1206 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1207 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1208 // 1209 /// Note that this routine only determines how the conversion can be 1210 /// performed; it does not actually perform the conversion. As such, 1211 /// it will not produce any diagnostics if no conversion is available, 1212 /// but will instead return an implicit conversion sequence of kind 1213 /// "BadConversion". 1214 /// 1215 /// If @p SuppressUserConversions, then user-defined conversions are 1216 /// not permitted. 1217 /// If @p AllowExplicit, then explicit user-defined conversions are 1218 /// permitted. 1219 /// 1220 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1221 /// writeback conversion, which allows __autoreleasing id* parameters to 1222 /// be initialized with __strong id* or __weak id* arguments. 1223 static ImplicitConversionSequence 1224 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1225 bool SuppressUserConversions, 1226 bool AllowExplicit, 1227 bool InOverloadResolution, 1228 bool CStyle, 1229 bool AllowObjCWritebackConversion) { 1230 ImplicitConversionSequence ICS; 1231 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1232 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1233 ICS.setStandard(); 1234 return ICS; 1235 } 1236 1237 if (!S.getLangOpts().CPlusPlus) { 1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1239 return ICS; 1240 } 1241 1242 // C++ [over.ics.user]p4: 1243 // A conversion of an expression of class type to the same class 1244 // type is given Exact Match rank, and a conversion of an 1245 // expression of class type to a base class of that type is 1246 // given Conversion rank, in spite of the fact that a copy/move 1247 // constructor (i.e., a user-defined conversion function) is 1248 // called for those cases. 1249 QualType FromType = From->getType(); 1250 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1251 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1252 S.IsDerivedFrom(FromType, ToType))) { 1253 ICS.setStandard(); 1254 ICS.Standard.setAsIdentityConversion(); 1255 ICS.Standard.setFromType(FromType); 1256 ICS.Standard.setAllToTypes(ToType); 1257 1258 // We don't actually check at this point whether there is a valid 1259 // copy/move constructor, since overloading just assumes that it 1260 // exists. When we actually perform initialization, we'll find the 1261 // appropriate constructor to copy the returned object, if needed. 1262 ICS.Standard.CopyConstructor = 0; 1263 1264 // Determine whether this is considered a derived-to-base conversion. 1265 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1266 ICS.Standard.Second = ICK_Derived_To_Base; 1267 1268 return ICS; 1269 } 1270 1271 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1272 AllowExplicit, InOverloadResolution, CStyle, 1273 AllowObjCWritebackConversion); 1274 } 1275 1276 ImplicitConversionSequence 1277 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1278 bool SuppressUserConversions, 1279 bool AllowExplicit, 1280 bool InOverloadResolution, 1281 bool CStyle, 1282 bool AllowObjCWritebackConversion) { 1283 return clang::TryImplicitConversion(*this, From, ToType, 1284 SuppressUserConversions, AllowExplicit, 1285 InOverloadResolution, CStyle, 1286 AllowObjCWritebackConversion); 1287 } 1288 1289 /// PerformImplicitConversion - Perform an implicit conversion of the 1290 /// expression From to the type ToType. Returns the 1291 /// converted expression. Flavor is the kind of conversion we're 1292 /// performing, used in the error message. If @p AllowExplicit, 1293 /// explicit user-defined conversions are permitted. 1294 ExprResult 1295 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1296 AssignmentAction Action, bool AllowExplicit) { 1297 ImplicitConversionSequence ICS; 1298 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1299 } 1300 1301 ExprResult 1302 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1303 AssignmentAction Action, bool AllowExplicit, 1304 ImplicitConversionSequence& ICS) { 1305 if (checkPlaceholderForOverload(*this, From)) 1306 return ExprError(); 1307 1308 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1309 bool AllowObjCWritebackConversion 1310 = getLangOpts().ObjCAutoRefCount && 1311 (Action == AA_Passing || Action == AA_Sending); 1312 1313 ICS = clang::TryImplicitConversion(*this, From, ToType, 1314 /*SuppressUserConversions=*/false, 1315 AllowExplicit, 1316 /*InOverloadResolution=*/false, 1317 /*CStyle=*/false, 1318 AllowObjCWritebackConversion); 1319 return PerformImplicitConversion(From, ToType, ICS, Action); 1320 } 1321 1322 /// \brief Determine whether the conversion from FromType to ToType is a valid 1323 /// conversion that strips "noreturn" off the nested function type. 1324 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1325 QualType &ResultTy) { 1326 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1327 return false; 1328 1329 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1330 // where F adds one of the following at most once: 1331 // - a pointer 1332 // - a member pointer 1333 // - a block pointer 1334 CanQualType CanTo = Context.getCanonicalType(ToType); 1335 CanQualType CanFrom = Context.getCanonicalType(FromType); 1336 Type::TypeClass TyClass = CanTo->getTypeClass(); 1337 if (TyClass != CanFrom->getTypeClass()) return false; 1338 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1339 if (TyClass == Type::Pointer) { 1340 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1341 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1342 } else if (TyClass == Type::BlockPointer) { 1343 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1344 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1345 } else if (TyClass == Type::MemberPointer) { 1346 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1347 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1348 } else { 1349 return false; 1350 } 1351 1352 TyClass = CanTo->getTypeClass(); 1353 if (TyClass != CanFrom->getTypeClass()) return false; 1354 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1355 return false; 1356 } 1357 1358 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1359 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1360 if (!EInfo.getNoReturn()) return false; 1361 1362 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1363 assert(QualType(FromFn, 0).isCanonical()); 1364 if (QualType(FromFn, 0) != CanTo) return false; 1365 1366 ResultTy = ToType; 1367 return true; 1368 } 1369 1370 /// \brief Determine whether the conversion from FromType to ToType is a valid 1371 /// vector conversion. 1372 /// 1373 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1374 /// conversion. 1375 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1376 QualType ToType, ImplicitConversionKind &ICK) { 1377 // We need at least one of these types to be a vector type to have a vector 1378 // conversion. 1379 if (!ToType->isVectorType() && !FromType->isVectorType()) 1380 return false; 1381 1382 // Identical types require no conversions. 1383 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1384 return false; 1385 1386 // There are no conversions between extended vector types, only identity. 1387 if (ToType->isExtVectorType()) { 1388 // There are no conversions between extended vector types other than the 1389 // identity conversion. 1390 if (FromType->isExtVectorType()) 1391 return false; 1392 1393 // Vector splat from any arithmetic type to a vector. 1394 if (FromType->isArithmeticType()) { 1395 ICK = ICK_Vector_Splat; 1396 return true; 1397 } 1398 } 1399 1400 // We can perform the conversion between vector types in the following cases: 1401 // 1)vector types are equivalent AltiVec and GCC vector types 1402 // 2)lax vector conversions are permitted and the vector types are of the 1403 // same size 1404 if (ToType->isVectorType() && FromType->isVectorType()) { 1405 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1406 (Context.getLangOpts().LaxVectorConversions && 1407 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414 } 1415 1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421 /// IsStandardConversion - Determines whether there is a standard 1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423 /// expression From to the type ToType. Standard conversion sequences 1424 /// only consider non-class types; for conversions that involve class 1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1426 /// contain the standard conversion sequence required to perform this 1427 /// conversion and this routine will return true. Otherwise, this 1428 /// routine will return false and the value of SCS is unspecified. 1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.DeprecatedStringLiteralToCharPtr = false; 1439 SCS.IncompatibleObjC = false; 1440 SCS.setFromType(FromType); 1441 SCS.CopyConstructor = 0; 1442 1443 // There are no standard conversions for class types in C++, so 1444 // abort early. When overloading in C, however, we do permit 1445 if (FromType->isRecordType() || ToType->isRecordType()) { 1446 if (S.getLangOpts().CPlusPlus) 1447 return false; 1448 1449 // When we're overloading in C, we allow, as standard conversions, 1450 } 1451 1452 // The first conversion can be an lvalue-to-rvalue conversion, 1453 // array-to-pointer conversion, or function-to-pointer conversion 1454 // (C++ 4p1). 1455 1456 if (FromType == S.Context.OverloadTy) { 1457 DeclAccessPair AccessPair; 1458 if (FunctionDecl *Fn 1459 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1460 AccessPair)) { 1461 // We were able to resolve the address of the overloaded function, 1462 // so we can convert to the type of that function. 1463 FromType = Fn->getType(); 1464 1465 // we can sometimes resolve &foo<int> regardless of ToType, so check 1466 // if the type matches (identity) or we are converting to bool 1467 if (!S.Context.hasSameUnqualifiedType( 1468 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1469 QualType resultTy; 1470 // if the function type matches except for [[noreturn]], it's ok 1471 if (!S.IsNoReturnConversion(FromType, 1472 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1473 // otherwise, only a boolean conversion is standard 1474 if (!ToType->isBooleanType()) 1475 return false; 1476 } 1477 1478 // Check if the "from" expression is taking the address of an overloaded 1479 // function and recompute the FromType accordingly. Take advantage of the 1480 // fact that non-static member functions *must* have such an address-of 1481 // expression. 1482 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1483 if (Method && !Method->isStatic()) { 1484 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1485 "Non-unary operator on non-static member address"); 1486 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1487 == UO_AddrOf && 1488 "Non-address-of operator on non-static member address"); 1489 const Type *ClassType 1490 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1491 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1492 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1494 UO_AddrOf && 1495 "Non-address-of operator for overloaded function expression"); 1496 FromType = S.Context.getPointerType(FromType); 1497 } 1498 1499 // Check that we've computed the proper type after overload resolution. 1500 assert(S.Context.hasSameType( 1501 FromType, 1502 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1503 } else { 1504 return false; 1505 } 1506 } 1507 // Lvalue-to-rvalue conversion (C++11 4.1): 1508 // A glvalue (3.10) of a non-function, non-array type T can 1509 // be converted to a prvalue. 1510 bool argIsLValue = From->isGLValue(); 1511 if (argIsLValue && 1512 !FromType->isFunctionType() && !FromType->isArrayType() && 1513 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1514 SCS.First = ICK_Lvalue_To_Rvalue; 1515 1516 // C11 6.3.2.1p2: 1517 // ... if the lvalue has atomic type, the value has the non-atomic version 1518 // of the type of the lvalue ... 1519 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1520 FromType = Atomic->getValueType(); 1521 1522 // If T is a non-class type, the type of the rvalue is the 1523 // cv-unqualified version of T. Otherwise, the type of the rvalue 1524 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1525 // just strip the qualifiers because they don't matter. 1526 FromType = FromType.getUnqualifiedType(); 1527 } else if (FromType->isArrayType()) { 1528 // Array-to-pointer conversion (C++ 4.2) 1529 SCS.First = ICK_Array_To_Pointer; 1530 1531 // An lvalue or rvalue of type "array of N T" or "array of unknown 1532 // bound of T" can be converted to an rvalue of type "pointer to 1533 // T" (C++ 4.2p1). 1534 FromType = S.Context.getArrayDecayedType(FromType); 1535 1536 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1537 // This conversion is deprecated. (C++ D.4). 1538 SCS.DeprecatedStringLiteralToCharPtr = true; 1539 1540 // For the purpose of ranking in overload resolution 1541 // (13.3.3.1.1), this conversion is considered an 1542 // array-to-pointer conversion followed by a qualification 1543 // conversion (4.4). (C++ 4.2p2) 1544 SCS.Second = ICK_Identity; 1545 SCS.Third = ICK_Qualification; 1546 SCS.QualificationIncludesObjCLifetime = false; 1547 SCS.setAllToTypes(FromType); 1548 return true; 1549 } 1550 } else if (FromType->isFunctionType() && argIsLValue) { 1551 // Function-to-pointer conversion (C++ 4.3). 1552 SCS.First = ICK_Function_To_Pointer; 1553 1554 // An lvalue of function type T can be converted to an rvalue of 1555 // type "pointer to T." The result is a pointer to the 1556 // function. (C++ 4.3p1). 1557 FromType = S.Context.getPointerType(FromType); 1558 } else { 1559 // We don't require any conversions for the first step. 1560 SCS.First = ICK_Identity; 1561 } 1562 SCS.setToType(0, FromType); 1563 1564 // The second conversion can be an integral promotion, floating 1565 // point promotion, integral conversion, floating point conversion, 1566 // floating-integral conversion, pointer conversion, 1567 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1568 // For overloading in C, this can also be a "compatible-type" 1569 // conversion. 1570 bool IncompatibleObjC = false; 1571 ImplicitConversionKind SecondICK = ICK_Identity; 1572 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1573 // The unqualified versions of the types are the same: there's no 1574 // conversion to do. 1575 SCS.Second = ICK_Identity; 1576 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1577 // Integral promotion (C++ 4.5). 1578 SCS.Second = ICK_Integral_Promotion; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1581 // Floating point promotion (C++ 4.6). 1582 SCS.Second = ICK_Floating_Promotion; 1583 FromType = ToType.getUnqualifiedType(); 1584 } else if (S.IsComplexPromotion(FromType, ToType)) { 1585 // Complex promotion (Clang extension) 1586 SCS.Second = ICK_Complex_Promotion; 1587 FromType = ToType.getUnqualifiedType(); 1588 } else if (ToType->isBooleanType() && 1589 (FromType->isArithmeticType() || 1590 FromType->isAnyPointerType() || 1591 FromType->isBlockPointerType() || 1592 FromType->isMemberPointerType() || 1593 FromType->isNullPtrType())) { 1594 // Boolean conversions (C++ 4.12). 1595 SCS.Second = ICK_Boolean_Conversion; 1596 FromType = S.Context.BoolTy; 1597 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1598 ToType->isIntegralType(S.Context)) { 1599 // Integral conversions (C++ 4.7). 1600 SCS.Second = ICK_Integral_Conversion; 1601 FromType = ToType.getUnqualifiedType(); 1602 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1603 // Complex conversions (C99 6.3.1.6) 1604 SCS.Second = ICK_Complex_Conversion; 1605 FromType = ToType.getUnqualifiedType(); 1606 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1607 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1608 // Complex-real conversions (C99 6.3.1.7) 1609 SCS.Second = ICK_Complex_Real; 1610 FromType = ToType.getUnqualifiedType(); 1611 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1612 // Floating point conversions (C++ 4.8). 1613 SCS.Second = ICK_Floating_Conversion; 1614 FromType = ToType.getUnqualifiedType(); 1615 } else if ((FromType->isRealFloatingType() && 1616 ToType->isIntegralType(S.Context)) || 1617 (FromType->isIntegralOrUnscopedEnumerationType() && 1618 ToType->isRealFloatingType())) { 1619 // Floating-integral conversions (C++ 4.9). 1620 SCS.Second = ICK_Floating_Integral; 1621 FromType = ToType.getUnqualifiedType(); 1622 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1623 SCS.Second = ICK_Block_Pointer_Conversion; 1624 } else if (AllowObjCWritebackConversion && 1625 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1626 SCS.Second = ICK_Writeback_Conversion; 1627 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1628 FromType, IncompatibleObjC)) { 1629 // Pointer conversions (C++ 4.10). 1630 SCS.Second = ICK_Pointer_Conversion; 1631 SCS.IncompatibleObjC = IncompatibleObjC; 1632 FromType = FromType.getUnqualifiedType(); 1633 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1634 InOverloadResolution, FromType)) { 1635 // Pointer to member conversions (4.11). 1636 SCS.Second = ICK_Pointer_Member; 1637 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1638 SCS.Second = SecondICK; 1639 FromType = ToType.getUnqualifiedType(); 1640 } else if (!S.getLangOpts().CPlusPlus && 1641 S.Context.typesAreCompatible(ToType, FromType)) { 1642 // Compatible conversions (Clang extension for C function overloading) 1643 SCS.Second = ICK_Compatible_Conversion; 1644 FromType = ToType.getUnqualifiedType(); 1645 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1646 // Treat a conversion that strips "noreturn" as an identity conversion. 1647 SCS.Second = ICK_NoReturn_Adjustment; 1648 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1649 InOverloadResolution, 1650 SCS, CStyle)) { 1651 SCS.Second = ICK_TransparentUnionConversion; 1652 FromType = ToType; 1653 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1654 CStyle)) { 1655 // tryAtomicConversion has updated the standard conversion sequence 1656 // appropriately. 1657 return true; 1658 } else if (ToType->isEventT() && 1659 From->isIntegerConstantExpr(S.getASTContext()) && 1660 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1661 SCS.Second = ICK_Zero_Event_Conversion; 1662 FromType = ToType; 1663 } else { 1664 // No second conversion required. 1665 SCS.Second = ICK_Identity; 1666 } 1667 SCS.setToType(1, FromType); 1668 1669 QualType CanonFrom; 1670 QualType CanonTo; 1671 // The third conversion can be a qualification conversion (C++ 4p1). 1672 bool ObjCLifetimeConversion; 1673 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1674 ObjCLifetimeConversion)) { 1675 SCS.Third = ICK_Qualification; 1676 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1677 FromType = ToType; 1678 CanonFrom = S.Context.getCanonicalType(FromType); 1679 CanonTo = S.Context.getCanonicalType(ToType); 1680 } else { 1681 // No conversion required 1682 SCS.Third = ICK_Identity; 1683 1684 // C++ [over.best.ics]p6: 1685 // [...] Any difference in top-level cv-qualification is 1686 // subsumed by the initialization itself and does not constitute 1687 // a conversion. [...] 1688 CanonFrom = S.Context.getCanonicalType(FromType); 1689 CanonTo = S.Context.getCanonicalType(ToType); 1690 if (CanonFrom.getLocalUnqualifiedType() 1691 == CanonTo.getLocalUnqualifiedType() && 1692 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1693 FromType = ToType; 1694 CanonFrom = CanonTo; 1695 } 1696 } 1697 SCS.setToType(2, FromType); 1698 1699 // If we have not converted the argument type to the parameter type, 1700 // this is a bad conversion sequence. 1701 if (CanonFrom != CanonTo) 1702 return false; 1703 1704 return true; 1705 } 1706 1707 static bool 1708 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1709 QualType &ToType, 1710 bool InOverloadResolution, 1711 StandardConversionSequence &SCS, 1712 bool CStyle) { 1713 1714 const RecordType *UT = ToType->getAsUnionType(); 1715 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1716 return false; 1717 // The field to initialize within the transparent union. 1718 RecordDecl *UD = UT->getDecl(); 1719 // It's compatible if the expression matches any of the fields. 1720 for (RecordDecl::field_iterator it = UD->field_begin(), 1721 itend = UD->field_end(); 1722 it != itend; ++it) { 1723 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1724 CStyle, /*ObjCWritebackConversion=*/false)) { 1725 ToType = it->getType(); 1726 return true; 1727 } 1728 } 1729 return false; 1730 } 1731 1732 /// IsIntegralPromotion - Determines whether the conversion from the 1733 /// expression From (whose potentially-adjusted type is FromType) to 1734 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1735 /// sets PromotedType to the promoted type. 1736 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1737 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1738 // All integers are built-in. 1739 if (!To) { 1740 return false; 1741 } 1742 1743 // An rvalue of type char, signed char, unsigned char, short int, or 1744 // unsigned short int can be converted to an rvalue of type int if 1745 // int can represent all the values of the source type; otherwise, 1746 // the source rvalue can be converted to an rvalue of type unsigned 1747 // int (C++ 4.5p1). 1748 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1749 !FromType->isEnumeralType()) { 1750 if (// We can promote any signed, promotable integer type to an int 1751 (FromType->isSignedIntegerType() || 1752 // We can promote any unsigned integer type whose size is 1753 // less than int to an int. 1754 (!FromType->isSignedIntegerType() && 1755 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1756 return To->getKind() == BuiltinType::Int; 1757 } 1758 1759 return To->getKind() == BuiltinType::UInt; 1760 } 1761 1762 // C++11 [conv.prom]p3: 1763 // A prvalue of an unscoped enumeration type whose underlying type is not 1764 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1765 // following types that can represent all the values of the enumeration 1766 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1767 // unsigned int, long int, unsigned long int, long long int, or unsigned 1768 // long long int. If none of the types in that list can represent all the 1769 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1770 // type can be converted to an rvalue a prvalue of the extended integer type 1771 // with lowest integer conversion rank (4.13) greater than the rank of long 1772 // long in which all the values of the enumeration can be represented. If 1773 // there are two such extended types, the signed one is chosen. 1774 // C++11 [conv.prom]p4: 1775 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1776 // can be converted to a prvalue of its underlying type. Moreover, if 1777 // integral promotion can be applied to its underlying type, a prvalue of an 1778 // unscoped enumeration type whose underlying type is fixed can also be 1779 // converted to a prvalue of the promoted underlying type. 1780 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1781 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1782 // provided for a scoped enumeration. 1783 if (FromEnumType->getDecl()->isScoped()) 1784 return false; 1785 1786 // We can perform an integral promotion to the underlying type of the enum, 1787 // even if that's not the promoted type. 1788 if (FromEnumType->getDecl()->isFixed()) { 1789 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1790 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1791 IsIntegralPromotion(From, Underlying, ToType); 1792 } 1793 1794 // We have already pre-calculated the promotion type, so this is trivial. 1795 if (ToType->isIntegerType() && 1796 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1797 return Context.hasSameUnqualifiedType(ToType, 1798 FromEnumType->getDecl()->getPromotionType()); 1799 } 1800 1801 // C++0x [conv.prom]p2: 1802 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1803 // to an rvalue a prvalue of the first of the following types that can 1804 // represent all the values of its underlying type: int, unsigned int, 1805 // long int, unsigned long int, long long int, or unsigned long long int. 1806 // If none of the types in that list can represent all the values of its 1807 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1808 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1809 // type. 1810 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1811 ToType->isIntegerType()) { 1812 // Determine whether the type we're converting from is signed or 1813 // unsigned. 1814 bool FromIsSigned = FromType->isSignedIntegerType(); 1815 uint64_t FromSize = Context.getTypeSize(FromType); 1816 1817 // The types we'll try to promote to, in the appropriate 1818 // order. Try each of these types. 1819 QualType PromoteTypes[6] = { 1820 Context.IntTy, Context.UnsignedIntTy, 1821 Context.LongTy, Context.UnsignedLongTy , 1822 Context.LongLongTy, Context.UnsignedLongLongTy 1823 }; 1824 for (int Idx = 0; Idx < 6; ++Idx) { 1825 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1826 if (FromSize < ToSize || 1827 (FromSize == ToSize && 1828 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1829 // We found the type that we can promote to. If this is the 1830 // type we wanted, we have a promotion. Otherwise, no 1831 // promotion. 1832 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1833 } 1834 } 1835 } 1836 1837 // An rvalue for an integral bit-field (9.6) can be converted to an 1838 // rvalue of type int if int can represent all the values of the 1839 // bit-field; otherwise, it can be converted to unsigned int if 1840 // unsigned int can represent all the values of the bit-field. If 1841 // the bit-field is larger yet, no integral promotion applies to 1842 // it. If the bit-field has an enumerated type, it is treated as any 1843 // other value of that type for promotion purposes (C++ 4.5p3). 1844 // FIXME: We should delay checking of bit-fields until we actually perform the 1845 // conversion. 1846 using llvm::APSInt; 1847 if (From) 1848 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1849 APSInt BitWidth; 1850 if (FromType->isIntegralType(Context) && 1851 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1852 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1853 ToSize = Context.getTypeSize(ToType); 1854 1855 // Are we promoting to an int from a bitfield that fits in an int? 1856 if (BitWidth < ToSize || 1857 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1858 return To->getKind() == BuiltinType::Int; 1859 } 1860 1861 // Are we promoting to an unsigned int from an unsigned bitfield 1862 // that fits into an unsigned int? 1863 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1864 return To->getKind() == BuiltinType::UInt; 1865 } 1866 1867 return false; 1868 } 1869 } 1870 1871 // An rvalue of type bool can be converted to an rvalue of type int, 1872 // with false becoming zero and true becoming one (C++ 4.5p4). 1873 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1874 return true; 1875 } 1876 1877 return false; 1878 } 1879 1880 /// IsFloatingPointPromotion - Determines whether the conversion from 1881 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1882 /// returns true and sets PromotedType to the promoted type. 1883 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1884 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1885 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1886 /// An rvalue of type float can be converted to an rvalue of type 1887 /// double. (C++ 4.6p1). 1888 if (FromBuiltin->getKind() == BuiltinType::Float && 1889 ToBuiltin->getKind() == BuiltinType::Double) 1890 return true; 1891 1892 // C99 6.3.1.5p1: 1893 // When a float is promoted to double or long double, or a 1894 // double is promoted to long double [...]. 1895 if (!getLangOpts().CPlusPlus && 1896 (FromBuiltin->getKind() == BuiltinType::Float || 1897 FromBuiltin->getKind() == BuiltinType::Double) && 1898 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1899 return true; 1900 1901 // Half can be promoted to float. 1902 if (!getLangOpts().NativeHalfType && 1903 FromBuiltin->getKind() == BuiltinType::Half && 1904 ToBuiltin->getKind() == BuiltinType::Float) 1905 return true; 1906 } 1907 1908 return false; 1909 } 1910 1911 /// \brief Determine if a conversion is a complex promotion. 1912 /// 1913 /// A complex promotion is defined as a complex -> complex conversion 1914 /// where the conversion between the underlying real types is a 1915 /// floating-point or integral promotion. 1916 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1917 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1918 if (!FromComplex) 1919 return false; 1920 1921 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1922 if (!ToComplex) 1923 return false; 1924 1925 return IsFloatingPointPromotion(FromComplex->getElementType(), 1926 ToComplex->getElementType()) || 1927 IsIntegralPromotion(0, FromComplex->getElementType(), 1928 ToComplex->getElementType()); 1929 } 1930 1931 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1932 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1933 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1934 /// if non-empty, will be a pointer to ToType that may or may not have 1935 /// the right set of qualifiers on its pointee. 1936 /// 1937 static QualType 1938 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1939 QualType ToPointee, QualType ToType, 1940 ASTContext &Context, 1941 bool StripObjCLifetime = false) { 1942 assert((FromPtr->getTypeClass() == Type::Pointer || 1943 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1944 "Invalid similarly-qualified pointer type"); 1945 1946 /// Conversions to 'id' subsume cv-qualifier conversions. 1947 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1948 return ToType.getUnqualifiedType(); 1949 1950 QualType CanonFromPointee 1951 = Context.getCanonicalType(FromPtr->getPointeeType()); 1952 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1953 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1954 1955 if (StripObjCLifetime) 1956 Quals.removeObjCLifetime(); 1957 1958 // Exact qualifier match -> return the pointer type we're converting to. 1959 if (CanonToPointee.getLocalQualifiers() == Quals) { 1960 // ToType is exactly what we need. Return it. 1961 if (!ToType.isNull()) 1962 return ToType.getUnqualifiedType(); 1963 1964 // Build a pointer to ToPointee. It has the right qualifiers 1965 // already. 1966 if (isa<ObjCObjectPointerType>(ToType)) 1967 return Context.getObjCObjectPointerType(ToPointee); 1968 return Context.getPointerType(ToPointee); 1969 } 1970 1971 // Just build a canonical type that has the right qualifiers. 1972 QualType QualifiedCanonToPointee 1973 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1974 1975 if (isa<ObjCObjectPointerType>(ToType)) 1976 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1977 return Context.getPointerType(QualifiedCanonToPointee); 1978 } 1979 1980 static bool isNullPointerConstantForConversion(Expr *Expr, 1981 bool InOverloadResolution, 1982 ASTContext &Context) { 1983 // Handle value-dependent integral null pointer constants correctly. 1984 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1985 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1986 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1987 return !InOverloadResolution; 1988 1989 return Expr->isNullPointerConstant(Context, 1990 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1991 : Expr::NPC_ValueDependentIsNull); 1992 } 1993 1994 /// IsPointerConversion - Determines whether the conversion of the 1995 /// expression From, which has the (possibly adjusted) type FromType, 1996 /// can be converted to the type ToType via a pointer conversion (C++ 1997 /// 4.10). If so, returns true and places the converted type (that 1998 /// might differ from ToType in its cv-qualifiers at some level) into 1999 /// ConvertedType. 2000 /// 2001 /// This routine also supports conversions to and from block pointers 2002 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2003 /// pointers to interfaces. FIXME: Once we've determined the 2004 /// appropriate overloading rules for Objective-C, we may want to 2005 /// split the Objective-C checks into a different routine; however, 2006 /// GCC seems to consider all of these conversions to be pointer 2007 /// conversions, so for now they live here. IncompatibleObjC will be 2008 /// set if the conversion is an allowed Objective-C conversion that 2009 /// should result in a warning. 2010 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2011 bool InOverloadResolution, 2012 QualType& ConvertedType, 2013 bool &IncompatibleObjC) { 2014 IncompatibleObjC = false; 2015 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2016 IncompatibleObjC)) 2017 return true; 2018 2019 // Conversion from a null pointer constant to any Objective-C pointer type. 2020 if (ToType->isObjCObjectPointerType() && 2021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2022 ConvertedType = ToType; 2023 return true; 2024 } 2025 2026 // Blocks: Block pointers can be converted to void*. 2027 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2028 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2029 ConvertedType = ToType; 2030 return true; 2031 } 2032 // Blocks: A null pointer constant can be converted to a block 2033 // pointer type. 2034 if (ToType->isBlockPointerType() && 2035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2036 ConvertedType = ToType; 2037 return true; 2038 } 2039 2040 // If the left-hand-side is nullptr_t, the right side can be a null 2041 // pointer constant. 2042 if (ToType->isNullPtrType() && 2043 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2044 ConvertedType = ToType; 2045 return true; 2046 } 2047 2048 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2049 if (!ToTypePtr) 2050 return false; 2051 2052 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2053 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2054 ConvertedType = ToType; 2055 return true; 2056 } 2057 2058 // Beyond this point, both types need to be pointers 2059 // , including objective-c pointers. 2060 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2061 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2062 !getLangOpts().ObjCAutoRefCount) { 2063 ConvertedType = BuildSimilarlyQualifiedPointerType( 2064 FromType->getAs<ObjCObjectPointerType>(), 2065 ToPointeeType, 2066 ToType, Context); 2067 return true; 2068 } 2069 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2070 if (!FromTypePtr) 2071 return false; 2072 2073 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2074 2075 // If the unqualified pointee types are the same, this can't be a 2076 // pointer conversion, so don't do all of the work below. 2077 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2078 return false; 2079 2080 // An rvalue of type "pointer to cv T," where T is an object type, 2081 // can be converted to an rvalue of type "pointer to cv void" (C++ 2082 // 4.10p2). 2083 if (FromPointeeType->isIncompleteOrObjectType() && 2084 ToPointeeType->isVoidType()) { 2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2086 ToPointeeType, 2087 ToType, Context, 2088 /*StripObjCLifetime=*/true); 2089 return true; 2090 } 2091 2092 // MSVC allows implicit function to void* type conversion. 2093 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2094 ToPointeeType->isVoidType()) { 2095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2096 ToPointeeType, 2097 ToType, Context); 2098 return true; 2099 } 2100 2101 // When we're overloading in C, we allow a special kind of pointer 2102 // conversion for compatible-but-not-identical pointee types. 2103 if (!getLangOpts().CPlusPlus && 2104 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2105 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2106 ToPointeeType, 2107 ToType, Context); 2108 return true; 2109 } 2110 2111 // C++ [conv.ptr]p3: 2112 // 2113 // An rvalue of type "pointer to cv D," where D is a class type, 2114 // can be converted to an rvalue of type "pointer to cv B," where 2115 // B is a base class (clause 10) of D. If B is an inaccessible 2116 // (clause 11) or ambiguous (10.2) base class of D, a program that 2117 // necessitates this conversion is ill-formed. The result of the 2118 // conversion is a pointer to the base class sub-object of the 2119 // derived class object. The null pointer value is converted to 2120 // the null pointer value of the destination type. 2121 // 2122 // Note that we do not check for ambiguity or inaccessibility 2123 // here. That is handled by CheckPointerConversion. 2124 if (getLangOpts().CPlusPlus && 2125 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2126 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2127 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2128 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2129 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2130 ToPointeeType, 2131 ToType, Context); 2132 return true; 2133 } 2134 2135 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2136 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2138 ToPointeeType, 2139 ToType, Context); 2140 return true; 2141 } 2142 2143 return false; 2144 } 2145 2146 /// \brief Adopt the given qualifiers for the given type. 2147 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2148 Qualifiers TQs = T.getQualifiers(); 2149 2150 // Check whether qualifiers already match. 2151 if (TQs == Qs) 2152 return T; 2153 2154 if (Qs.compatiblyIncludes(TQs)) 2155 return Context.getQualifiedType(T, Qs); 2156 2157 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2158 } 2159 2160 /// isObjCPointerConversion - Determines whether this is an 2161 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2162 /// with the same arguments and return values. 2163 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2164 QualType& ConvertedType, 2165 bool &IncompatibleObjC) { 2166 if (!getLangOpts().ObjC1) 2167 return false; 2168 2169 // The set of qualifiers on the type we're converting from. 2170 Qualifiers FromQualifiers = FromType.getQualifiers(); 2171 2172 // First, we handle all conversions on ObjC object pointer types. 2173 const ObjCObjectPointerType* ToObjCPtr = 2174 ToType->getAs<ObjCObjectPointerType>(); 2175 const ObjCObjectPointerType *FromObjCPtr = 2176 FromType->getAs<ObjCObjectPointerType>(); 2177 2178 if (ToObjCPtr && FromObjCPtr) { 2179 // If the pointee types are the same (ignoring qualifications), 2180 // then this is not a pointer conversion. 2181 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2182 FromObjCPtr->getPointeeType())) 2183 return false; 2184 2185 // Check for compatible 2186 // Objective C++: We're able to convert between "id" or "Class" and a 2187 // pointer to any interface (in both directions). 2188 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2189 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2190 return true; 2191 } 2192 // Conversions with Objective-C's id<...>. 2193 if ((FromObjCPtr->isObjCQualifiedIdType() || 2194 ToObjCPtr->isObjCQualifiedIdType()) && 2195 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2196 /*compare=*/false)) { 2197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2198 return true; 2199 } 2200 // Objective C++: We're able to convert from a pointer to an 2201 // interface to a pointer to a different interface. 2202 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2203 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2204 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2205 if (getLangOpts().CPlusPlus && LHS && RHS && 2206 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2207 FromObjCPtr->getPointeeType())) 2208 return false; 2209 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2210 ToObjCPtr->getPointeeType(), 2211 ToType, Context); 2212 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2213 return true; 2214 } 2215 2216 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2217 // Okay: this is some kind of implicit downcast of Objective-C 2218 // interfaces, which is permitted. However, we're going to 2219 // complain about it. 2220 IncompatibleObjC = true; 2221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2222 ToObjCPtr->getPointeeType(), 2223 ToType, Context); 2224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2225 return true; 2226 } 2227 } 2228 // Beyond this point, both types need to be C pointers or block pointers. 2229 QualType ToPointeeType; 2230 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2231 ToPointeeType = ToCPtr->getPointeeType(); 2232 else if (const BlockPointerType *ToBlockPtr = 2233 ToType->getAs<BlockPointerType>()) { 2234 // Objective C++: We're able to convert from a pointer to any object 2235 // to a block pointer type. 2236 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2237 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2238 return true; 2239 } 2240 ToPointeeType = ToBlockPtr->getPointeeType(); 2241 } 2242 else if (FromType->getAs<BlockPointerType>() && 2243 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2244 // Objective C++: We're able to convert from a block pointer type to a 2245 // pointer to any object. 2246 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2247 return true; 2248 } 2249 else 2250 return false; 2251 2252 QualType FromPointeeType; 2253 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2254 FromPointeeType = FromCPtr->getPointeeType(); 2255 else if (const BlockPointerType *FromBlockPtr = 2256 FromType->getAs<BlockPointerType>()) 2257 FromPointeeType = FromBlockPtr->getPointeeType(); 2258 else 2259 return false; 2260 2261 // If we have pointers to pointers, recursively check whether this 2262 // is an Objective-C conversion. 2263 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2264 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2265 IncompatibleObjC)) { 2266 // We always complain about this conversion. 2267 IncompatibleObjC = true; 2268 ConvertedType = Context.getPointerType(ConvertedType); 2269 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2270 return true; 2271 } 2272 // Allow conversion of pointee being objective-c pointer to another one; 2273 // as in I* to id. 2274 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2275 ToPointeeType->getAs<ObjCObjectPointerType>() && 2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2277 IncompatibleObjC)) { 2278 2279 ConvertedType = Context.getPointerType(ConvertedType); 2280 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2281 return true; 2282 } 2283 2284 // If we have pointers to functions or blocks, check whether the only 2285 // differences in the argument and result types are in Objective-C 2286 // pointer conversions. If so, we permit the conversion (but 2287 // complain about it). 2288 const FunctionProtoType *FromFunctionType 2289 = FromPointeeType->getAs<FunctionProtoType>(); 2290 const FunctionProtoType *ToFunctionType 2291 = ToPointeeType->getAs<FunctionProtoType>(); 2292 if (FromFunctionType && ToFunctionType) { 2293 // If the function types are exactly the same, this isn't an 2294 // Objective-C pointer conversion. 2295 if (Context.getCanonicalType(FromPointeeType) 2296 == Context.getCanonicalType(ToPointeeType)) 2297 return false; 2298 2299 // Perform the quick checks that will tell us whether these 2300 // function types are obviously different. 2301 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2302 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2303 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2304 return false; 2305 2306 bool HasObjCConversion = false; 2307 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2308 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2309 // Okay, the types match exactly. Nothing to do. 2310 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2311 ToFunctionType->getResultType(), 2312 ConvertedType, IncompatibleObjC)) { 2313 // Okay, we have an Objective-C pointer conversion. 2314 HasObjCConversion = true; 2315 } else { 2316 // Function types are too different. Abort. 2317 return false; 2318 } 2319 2320 // Check argument types. 2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2322 ArgIdx != NumArgs; ++ArgIdx) { 2323 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2324 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2325 if (Context.getCanonicalType(FromArgType) 2326 == Context.getCanonicalType(ToArgType)) { 2327 // Okay, the types match exactly. Nothing to do. 2328 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2329 ConvertedType, IncompatibleObjC)) { 2330 // Okay, we have an Objective-C pointer conversion. 2331 HasObjCConversion = true; 2332 } else { 2333 // Argument types are too different. Abort. 2334 return false; 2335 } 2336 } 2337 2338 if (HasObjCConversion) { 2339 // We had an Objective-C conversion. Allow this pointer 2340 // conversion, but complain about it. 2341 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2342 IncompatibleObjC = true; 2343 return true; 2344 } 2345 } 2346 2347 return false; 2348 } 2349 2350 /// \brief Determine whether this is an Objective-C writeback conversion, 2351 /// used for parameter passing when performing automatic reference counting. 2352 /// 2353 /// \param FromType The type we're converting form. 2354 /// 2355 /// \param ToType The type we're converting to. 2356 /// 2357 /// \param ConvertedType The type that will be produced after applying 2358 /// this conversion. 2359 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2360 QualType &ConvertedType) { 2361 if (!getLangOpts().ObjCAutoRefCount || 2362 Context.hasSameUnqualifiedType(FromType, ToType)) 2363 return false; 2364 2365 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2366 QualType ToPointee; 2367 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2368 ToPointee = ToPointer->getPointeeType(); 2369 else 2370 return false; 2371 2372 Qualifiers ToQuals = ToPointee.getQualifiers(); 2373 if (!ToPointee->isObjCLifetimeType() || 2374 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2375 !ToQuals.withoutObjCLifetime().empty()) 2376 return false; 2377 2378 // Argument must be a pointer to __strong to __weak. 2379 QualType FromPointee; 2380 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2381 FromPointee = FromPointer->getPointeeType(); 2382 else 2383 return false; 2384 2385 Qualifiers FromQuals = FromPointee.getQualifiers(); 2386 if (!FromPointee->isObjCLifetimeType() || 2387 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2388 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2389 return false; 2390 2391 // Make sure that we have compatible qualifiers. 2392 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2393 if (!ToQuals.compatiblyIncludes(FromQuals)) 2394 return false; 2395 2396 // Remove qualifiers from the pointee type we're converting from; they 2397 // aren't used in the compatibility check belong, and we'll be adding back 2398 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2399 FromPointee = FromPointee.getUnqualifiedType(); 2400 2401 // The unqualified form of the pointee types must be compatible. 2402 ToPointee = ToPointee.getUnqualifiedType(); 2403 bool IncompatibleObjC; 2404 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2405 FromPointee = ToPointee; 2406 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2407 IncompatibleObjC)) 2408 return false; 2409 2410 /// \brief Construct the type we're converting to, which is a pointer to 2411 /// __autoreleasing pointee. 2412 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2413 ConvertedType = Context.getPointerType(FromPointee); 2414 return true; 2415 } 2416 2417 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2418 QualType& ConvertedType) { 2419 QualType ToPointeeType; 2420 if (const BlockPointerType *ToBlockPtr = 2421 ToType->getAs<BlockPointerType>()) 2422 ToPointeeType = ToBlockPtr->getPointeeType(); 2423 else 2424 return false; 2425 2426 QualType FromPointeeType; 2427 if (const BlockPointerType *FromBlockPtr = 2428 FromType->getAs<BlockPointerType>()) 2429 FromPointeeType = FromBlockPtr->getPointeeType(); 2430 else 2431 return false; 2432 // We have pointer to blocks, check whether the only 2433 // differences in the argument and result types are in Objective-C 2434 // pointer conversions. If so, we permit the conversion. 2435 2436 const FunctionProtoType *FromFunctionType 2437 = FromPointeeType->getAs<FunctionProtoType>(); 2438 const FunctionProtoType *ToFunctionType 2439 = ToPointeeType->getAs<FunctionProtoType>(); 2440 2441 if (!FromFunctionType || !ToFunctionType) 2442 return false; 2443 2444 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2445 return true; 2446 2447 // Perform the quick checks that will tell us whether these 2448 // function types are obviously different. 2449 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2450 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2451 return false; 2452 2453 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2454 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2455 if (FromEInfo != ToEInfo) 2456 return false; 2457 2458 bool IncompatibleObjC = false; 2459 if (Context.hasSameType(FromFunctionType->getResultType(), 2460 ToFunctionType->getResultType())) { 2461 // Okay, the types match exactly. Nothing to do. 2462 } else { 2463 QualType RHS = FromFunctionType->getResultType(); 2464 QualType LHS = ToFunctionType->getResultType(); 2465 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2466 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2467 LHS = LHS.getUnqualifiedType(); 2468 2469 if (Context.hasSameType(RHS,LHS)) { 2470 // OK exact match. 2471 } else if (isObjCPointerConversion(RHS, LHS, 2472 ConvertedType, IncompatibleObjC)) { 2473 if (IncompatibleObjC) 2474 return false; 2475 // Okay, we have an Objective-C pointer conversion. 2476 } 2477 else 2478 return false; 2479 } 2480 2481 // Check argument types. 2482 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2483 ArgIdx != NumArgs; ++ArgIdx) { 2484 IncompatibleObjC = false; 2485 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2486 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2487 if (Context.hasSameType(FromArgType, ToArgType)) { 2488 // Okay, the types match exactly. Nothing to do. 2489 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2490 ConvertedType, IncompatibleObjC)) { 2491 if (IncompatibleObjC) 2492 return false; 2493 // Okay, we have an Objective-C pointer conversion. 2494 } else 2495 // Argument types are too different. Abort. 2496 return false; 2497 } 2498 if (LangOpts.ObjCAutoRefCount && 2499 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2500 ToFunctionType)) 2501 return false; 2502 2503 ConvertedType = ToType; 2504 return true; 2505 } 2506 2507 enum { 2508 ft_default, 2509 ft_different_class, 2510 ft_parameter_arity, 2511 ft_parameter_mismatch, 2512 ft_return_type, 2513 ft_qualifer_mismatch 2514 }; 2515 2516 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2517 /// function types. Catches different number of parameter, mismatch in 2518 /// parameter types, and different return types. 2519 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2520 QualType FromType, QualType ToType) { 2521 // If either type is not valid, include no extra info. 2522 if (FromType.isNull() || ToType.isNull()) { 2523 PDiag << ft_default; 2524 return; 2525 } 2526 2527 // Get the function type from the pointers. 2528 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2529 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2530 *ToMember = ToType->getAs<MemberPointerType>(); 2531 if (FromMember->getClass() != ToMember->getClass()) { 2532 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2533 << QualType(FromMember->getClass(), 0); 2534 return; 2535 } 2536 FromType = FromMember->getPointeeType(); 2537 ToType = ToMember->getPointeeType(); 2538 } 2539 2540 if (FromType->isPointerType()) 2541 FromType = FromType->getPointeeType(); 2542 if (ToType->isPointerType()) 2543 ToType = ToType->getPointeeType(); 2544 2545 // Remove references. 2546 FromType = FromType.getNonReferenceType(); 2547 ToType = ToType.getNonReferenceType(); 2548 2549 // Don't print extra info for non-specialized template functions. 2550 if (FromType->isInstantiationDependentType() && 2551 !FromType->getAs<TemplateSpecializationType>()) { 2552 PDiag << ft_default; 2553 return; 2554 } 2555 2556 // No extra info for same types. 2557 if (Context.hasSameType(FromType, ToType)) { 2558 PDiag << ft_default; 2559 return; 2560 } 2561 2562 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2563 *ToFunction = ToType->getAs<FunctionProtoType>(); 2564 2565 // Both types need to be function types. 2566 if (!FromFunction || !ToFunction) { 2567 PDiag << ft_default; 2568 return; 2569 } 2570 2571 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2572 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2573 << FromFunction->getNumArgs(); 2574 return; 2575 } 2576 2577 // Handle different parameter types. 2578 unsigned ArgPos; 2579 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2580 PDiag << ft_parameter_mismatch << ArgPos + 1 2581 << ToFunction->getArgType(ArgPos) 2582 << FromFunction->getArgType(ArgPos); 2583 return; 2584 } 2585 2586 // Handle different return type. 2587 if (!Context.hasSameType(FromFunction->getResultType(), 2588 ToFunction->getResultType())) { 2589 PDiag << ft_return_type << ToFunction->getResultType() 2590 << FromFunction->getResultType(); 2591 return; 2592 } 2593 2594 unsigned FromQuals = FromFunction->getTypeQuals(), 2595 ToQuals = ToFunction->getTypeQuals(); 2596 if (FromQuals != ToQuals) { 2597 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2598 return; 2599 } 2600 2601 // Unable to find a difference, so add no extra info. 2602 PDiag << ft_default; 2603 } 2604 2605 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2606 /// for equality of their argument types. Caller has already checked that 2607 /// they have same number of arguments. If the parameters are different, 2608 /// ArgPos will have the parameter index of the first different parameter. 2609 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2610 const FunctionProtoType *NewType, 2611 unsigned *ArgPos) { 2612 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2613 N = NewType->arg_type_begin(), 2614 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2615 if (!Context.hasSameType(*O, *N)) { 2616 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2617 return false; 2618 } 2619 } 2620 return true; 2621 } 2622 2623 /// CheckPointerConversion - Check the pointer conversion from the 2624 /// expression From to the type ToType. This routine checks for 2625 /// ambiguous or inaccessible derived-to-base pointer 2626 /// conversions for which IsPointerConversion has already returned 2627 /// true. It returns true and produces a diagnostic if there was an 2628 /// error, or returns false otherwise. 2629 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2630 CastKind &Kind, 2631 CXXCastPath& BasePath, 2632 bool IgnoreBaseAccess) { 2633 QualType FromType = From->getType(); 2634 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2635 2636 Kind = CK_BitCast; 2637 2638 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2639 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2640 Expr::NPCK_ZeroExpression) { 2641 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2642 DiagRuntimeBehavior(From->getExprLoc(), From, 2643 PDiag(diag::warn_impcast_bool_to_null_pointer) 2644 << ToType << From->getSourceRange()); 2645 else if (!isUnevaluatedContext()) 2646 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2647 << ToType << From->getSourceRange(); 2648 } 2649 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2650 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2651 QualType FromPointeeType = FromPtrType->getPointeeType(), 2652 ToPointeeType = ToPtrType->getPointeeType(); 2653 2654 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2656 // We must have a derived-to-base conversion. Check an 2657 // ambiguous or inaccessible conversion. 2658 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2659 From->getExprLoc(), 2660 From->getSourceRange(), &BasePath, 2661 IgnoreBaseAccess)) 2662 return true; 2663 2664 // The conversion was successful. 2665 Kind = CK_DerivedToBase; 2666 } 2667 } 2668 } else if (const ObjCObjectPointerType *ToPtrType = 2669 ToType->getAs<ObjCObjectPointerType>()) { 2670 if (const ObjCObjectPointerType *FromPtrType = 2671 FromType->getAs<ObjCObjectPointerType>()) { 2672 // Objective-C++ conversions are always okay. 2673 // FIXME: We should have a different class of conversions for the 2674 // Objective-C++ implicit conversions. 2675 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2676 return false; 2677 } else if (FromType->isBlockPointerType()) { 2678 Kind = CK_BlockPointerToObjCPointerCast; 2679 } else { 2680 Kind = CK_CPointerToObjCPointerCast; 2681 } 2682 } else if (ToType->isBlockPointerType()) { 2683 if (!FromType->isBlockPointerType()) 2684 Kind = CK_AnyPointerToBlockPointerCast; 2685 } 2686 2687 // We shouldn't fall into this case unless it's valid for other 2688 // reasons. 2689 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2690 Kind = CK_NullToPointer; 2691 2692 return false; 2693 } 2694 2695 /// IsMemberPointerConversion - Determines whether the conversion of the 2696 /// expression From, which has the (possibly adjusted) type FromType, can be 2697 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2698 /// If so, returns true and places the converted type (that might differ from 2699 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2700 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2701 QualType ToType, 2702 bool InOverloadResolution, 2703 QualType &ConvertedType) { 2704 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2705 if (!ToTypePtr) 2706 return false; 2707 2708 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2709 if (From->isNullPointerConstant(Context, 2710 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2711 : Expr::NPC_ValueDependentIsNull)) { 2712 ConvertedType = ToType; 2713 return true; 2714 } 2715 2716 // Otherwise, both types have to be member pointers. 2717 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2718 if (!FromTypePtr) 2719 return false; 2720 2721 // A pointer to member of B can be converted to a pointer to member of D, 2722 // where D is derived from B (C++ 4.11p2). 2723 QualType FromClass(FromTypePtr->getClass(), 0); 2724 QualType ToClass(ToTypePtr->getClass(), 0); 2725 2726 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2727 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2728 IsDerivedFrom(ToClass, FromClass)) { 2729 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2730 ToClass.getTypePtr()); 2731 return true; 2732 } 2733 2734 return false; 2735 } 2736 2737 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2738 /// expression From to the type ToType. This routine checks for ambiguous or 2739 /// virtual or inaccessible base-to-derived member pointer conversions 2740 /// for which IsMemberPointerConversion has already returned true. It returns 2741 /// true and produces a diagnostic if there was an error, or returns false 2742 /// otherwise. 2743 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2744 CastKind &Kind, 2745 CXXCastPath &BasePath, 2746 bool IgnoreBaseAccess) { 2747 QualType FromType = From->getType(); 2748 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2749 if (!FromPtrType) { 2750 // This must be a null pointer to member pointer conversion 2751 assert(From->isNullPointerConstant(Context, 2752 Expr::NPC_ValueDependentIsNull) && 2753 "Expr must be null pointer constant!"); 2754 Kind = CK_NullToMemberPointer; 2755 return false; 2756 } 2757 2758 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2759 assert(ToPtrType && "No member pointer cast has a target type " 2760 "that is not a member pointer."); 2761 2762 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2763 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2764 2765 // FIXME: What about dependent types? 2766 assert(FromClass->isRecordType() && "Pointer into non-class."); 2767 assert(ToClass->isRecordType() && "Pointer into non-class."); 2768 2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2770 /*DetectVirtual=*/true); 2771 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2772 assert(DerivationOkay && 2773 "Should not have been called if derivation isn't OK."); 2774 (void)DerivationOkay; 2775 2776 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2777 getUnqualifiedType())) { 2778 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2779 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2780 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2781 return true; 2782 } 2783 2784 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2785 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2786 << FromClass << ToClass << QualType(VBase, 0) 2787 << From->getSourceRange(); 2788 return true; 2789 } 2790 2791 if (!IgnoreBaseAccess) 2792 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2793 Paths.front(), 2794 diag::err_downcast_from_inaccessible_base); 2795 2796 // Must be a base to derived member conversion. 2797 BuildBasePathArray(Paths, BasePath); 2798 Kind = CK_BaseToDerivedMemberPointer; 2799 return false; 2800 } 2801 2802 /// IsQualificationConversion - Determines whether the conversion from 2803 /// an rvalue of type FromType to ToType is a qualification conversion 2804 /// (C++ 4.4). 2805 /// 2806 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2807 /// when the qualification conversion involves a change in the Objective-C 2808 /// object lifetime. 2809 bool 2810 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2811 bool CStyle, bool &ObjCLifetimeConversion) { 2812 FromType = Context.getCanonicalType(FromType); 2813 ToType = Context.getCanonicalType(ToType); 2814 ObjCLifetimeConversion = false; 2815 2816 // If FromType and ToType are the same type, this is not a 2817 // qualification conversion. 2818 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2819 return false; 2820 2821 // (C++ 4.4p4): 2822 // A conversion can add cv-qualifiers at levels other than the first 2823 // in multi-level pointers, subject to the following rules: [...] 2824 bool PreviousToQualsIncludeConst = true; 2825 bool UnwrappedAnyPointer = false; 2826 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2827 // Within each iteration of the loop, we check the qualifiers to 2828 // determine if this still looks like a qualification 2829 // conversion. Then, if all is well, we unwrap one more level of 2830 // pointers or pointers-to-members and do it all again 2831 // until there are no more pointers or pointers-to-members left to 2832 // unwrap. 2833 UnwrappedAnyPointer = true; 2834 2835 Qualifiers FromQuals = FromType.getQualifiers(); 2836 Qualifiers ToQuals = ToType.getQualifiers(); 2837 2838 // Objective-C ARC: 2839 // Check Objective-C lifetime conversions. 2840 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2841 UnwrappedAnyPointer) { 2842 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2843 ObjCLifetimeConversion = true; 2844 FromQuals.removeObjCLifetime(); 2845 ToQuals.removeObjCLifetime(); 2846 } else { 2847 // Qualification conversions cannot cast between different 2848 // Objective-C lifetime qualifiers. 2849 return false; 2850 } 2851 } 2852 2853 // Allow addition/removal of GC attributes but not changing GC attributes. 2854 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2855 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2856 FromQuals.removeObjCGCAttr(); 2857 ToQuals.removeObjCGCAttr(); 2858 } 2859 2860 // -- for every j > 0, if const is in cv 1,j then const is in cv 2861 // 2,j, and similarly for volatile. 2862 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2863 return false; 2864 2865 // -- if the cv 1,j and cv 2,j are different, then const is in 2866 // every cv for 0 < k < j. 2867 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2868 && !PreviousToQualsIncludeConst) 2869 return false; 2870 2871 // Keep track of whether all prior cv-qualifiers in the "to" type 2872 // include const. 2873 PreviousToQualsIncludeConst 2874 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2875 } 2876 2877 // We are left with FromType and ToType being the pointee types 2878 // after unwrapping the original FromType and ToType the same number 2879 // of types. If we unwrapped any pointers, and if FromType and 2880 // ToType have the same unqualified type (since we checked 2881 // qualifiers above), then this is a qualification conversion. 2882 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2883 } 2884 2885 /// \brief - Determine whether this is a conversion from a scalar type to an 2886 /// atomic type. 2887 /// 2888 /// If successful, updates \c SCS's second and third steps in the conversion 2889 /// sequence to finish the conversion. 2890 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2891 bool InOverloadResolution, 2892 StandardConversionSequence &SCS, 2893 bool CStyle) { 2894 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2895 if (!ToAtomic) 2896 return false; 2897 2898 StandardConversionSequence InnerSCS; 2899 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2900 InOverloadResolution, InnerSCS, 2901 CStyle, /*AllowObjCWritebackConversion=*/false)) 2902 return false; 2903 2904 SCS.Second = InnerSCS.Second; 2905 SCS.setToType(1, InnerSCS.getToType(1)); 2906 SCS.Third = InnerSCS.Third; 2907 SCS.QualificationIncludesObjCLifetime 2908 = InnerSCS.QualificationIncludesObjCLifetime; 2909 SCS.setToType(2, InnerSCS.getToType(2)); 2910 return true; 2911 } 2912 2913 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2914 CXXConstructorDecl *Constructor, 2915 QualType Type) { 2916 const FunctionProtoType *CtorType = 2917 Constructor->getType()->getAs<FunctionProtoType>(); 2918 if (CtorType->getNumArgs() > 0) { 2919 QualType FirstArg = CtorType->getArgType(0); 2920 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2921 return true; 2922 } 2923 return false; 2924 } 2925 2926 static OverloadingResult 2927 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2928 CXXRecordDecl *To, 2929 UserDefinedConversionSequence &User, 2930 OverloadCandidateSet &CandidateSet, 2931 bool AllowExplicit) { 2932 DeclContext::lookup_result R = S.LookupConstructors(To); 2933 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2934 Con != ConEnd; ++Con) { 2935 NamedDecl *D = *Con; 2936 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2937 2938 // Find the constructor (which may be a template). 2939 CXXConstructorDecl *Constructor = 0; 2940 FunctionTemplateDecl *ConstructorTmpl 2941 = dyn_cast<FunctionTemplateDecl>(D); 2942 if (ConstructorTmpl) 2943 Constructor 2944 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2945 else 2946 Constructor = cast<CXXConstructorDecl>(D); 2947 2948 bool Usable = !Constructor->isInvalidDecl() && 2949 S.isInitListConstructor(Constructor) && 2950 (AllowExplicit || !Constructor->isExplicit()); 2951 if (Usable) { 2952 // If the first argument is (a reference to) the target type, 2953 // suppress conversions. 2954 bool SuppressUserConversions = 2955 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2956 if (ConstructorTmpl) 2957 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2958 /*ExplicitArgs*/ 0, 2959 From, CandidateSet, 2960 SuppressUserConversions); 2961 else 2962 S.AddOverloadCandidate(Constructor, FoundDecl, 2963 From, CandidateSet, 2964 SuppressUserConversions); 2965 } 2966 } 2967 2968 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2969 2970 OverloadCandidateSet::iterator Best; 2971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2972 case OR_Success: { 2973 // Record the standard conversion we used and the conversion function. 2974 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2975 QualType ThisType = Constructor->getThisType(S.Context); 2976 // Initializer lists don't have conversions as such. 2977 User.Before.setAsIdentityConversion(); 2978 User.HadMultipleCandidates = HadMultipleCandidates; 2979 User.ConversionFunction = Constructor; 2980 User.FoundConversionFunction = Best->FoundDecl; 2981 User.After.setAsIdentityConversion(); 2982 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2983 User.After.setAllToTypes(ToType); 2984 return OR_Success; 2985 } 2986 2987 case OR_No_Viable_Function: 2988 return OR_No_Viable_Function; 2989 case OR_Deleted: 2990 return OR_Deleted; 2991 case OR_Ambiguous: 2992 return OR_Ambiguous; 2993 } 2994 2995 llvm_unreachable("Invalid OverloadResult!"); 2996 } 2997 2998 /// Determines whether there is a user-defined conversion sequence 2999 /// (C++ [over.ics.user]) that converts expression From to the type 3000 /// ToType. If such a conversion exists, User will contain the 3001 /// user-defined conversion sequence that performs such a conversion 3002 /// and this routine will return true. Otherwise, this routine returns 3003 /// false and User is unspecified. 3004 /// 3005 /// \param AllowExplicit true if the conversion should consider C++0x 3006 /// "explicit" conversion functions as well as non-explicit conversion 3007 /// functions (C++0x [class.conv.fct]p2). 3008 static OverloadingResult 3009 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3010 UserDefinedConversionSequence &User, 3011 OverloadCandidateSet &CandidateSet, 3012 bool AllowExplicit) { 3013 // Whether we will only visit constructors. 3014 bool ConstructorsOnly = false; 3015 3016 // If the type we are conversion to is a class type, enumerate its 3017 // constructors. 3018 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3019 // C++ [over.match.ctor]p1: 3020 // When objects of class type are direct-initialized (8.5), or 3021 // copy-initialized from an expression of the same or a 3022 // derived class type (8.5), overload resolution selects the 3023 // constructor. [...] For copy-initialization, the candidate 3024 // functions are all the converting constructors (12.3.1) of 3025 // that class. The argument list is the expression-list within 3026 // the parentheses of the initializer. 3027 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3028 (From->getType()->getAs<RecordType>() && 3029 S.IsDerivedFrom(From->getType(), ToType))) 3030 ConstructorsOnly = true; 3031 3032 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3033 // RequireCompleteType may have returned true due to some invalid decl 3034 // during template instantiation, but ToType may be complete enough now 3035 // to try to recover. 3036 if (ToType->isIncompleteType()) { 3037 // We're not going to find any constructors. 3038 } else if (CXXRecordDecl *ToRecordDecl 3039 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3040 3041 Expr **Args = &From; 3042 unsigned NumArgs = 1; 3043 bool ListInitializing = false; 3044 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3045 // But first, see if there is an init-list-contructor that will work. 3046 OverloadingResult Result = IsInitializerListConstructorConversion( 3047 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3048 if (Result != OR_No_Viable_Function) 3049 return Result; 3050 // Never mind. 3051 CandidateSet.clear(); 3052 3053 // If we're list-initializing, we pass the individual elements as 3054 // arguments, not the entire list. 3055 Args = InitList->getInits(); 3056 NumArgs = InitList->getNumInits(); 3057 ListInitializing = true; 3058 } 3059 3060 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3061 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3062 Con != ConEnd; ++Con) { 3063 NamedDecl *D = *Con; 3064 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3065 3066 // Find the constructor (which may be a template). 3067 CXXConstructorDecl *Constructor = 0; 3068 FunctionTemplateDecl *ConstructorTmpl 3069 = dyn_cast<FunctionTemplateDecl>(D); 3070 if (ConstructorTmpl) 3071 Constructor 3072 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3073 else 3074 Constructor = cast<CXXConstructorDecl>(D); 3075 3076 bool Usable = !Constructor->isInvalidDecl(); 3077 if (ListInitializing) 3078 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3079 else 3080 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3081 if (Usable) { 3082 bool SuppressUserConversions = !ConstructorsOnly; 3083 if (SuppressUserConversions && ListInitializing) { 3084 SuppressUserConversions = false; 3085 if (NumArgs == 1) { 3086 // If the first argument is (a reference to) the target type, 3087 // suppress conversions. 3088 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3089 S.Context, Constructor, ToType); 3090 } 3091 } 3092 if (ConstructorTmpl) 3093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3094 /*ExplicitArgs*/ 0, 3095 llvm::makeArrayRef(Args, NumArgs), 3096 CandidateSet, SuppressUserConversions); 3097 else 3098 // Allow one user-defined conversion when user specifies a 3099 // From->ToType conversion via an static cast (c-style, etc). 3100 S.AddOverloadCandidate(Constructor, FoundDecl, 3101 llvm::makeArrayRef(Args, NumArgs), 3102 CandidateSet, SuppressUserConversions); 3103 } 3104 } 3105 } 3106 } 3107 3108 // Enumerate conversion functions, if we're allowed to. 3109 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3110 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3111 // No conversion functions from incomplete types. 3112 } else if (const RecordType *FromRecordType 3113 = From->getType()->getAs<RecordType>()) { 3114 if (CXXRecordDecl *FromRecordDecl 3115 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3116 // Add all of the conversion functions as candidates. 3117 std::pair<CXXRecordDecl::conversion_iterator, 3118 CXXRecordDecl::conversion_iterator> 3119 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3120 for (CXXRecordDecl::conversion_iterator 3121 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3122 DeclAccessPair FoundDecl = I.getPair(); 3123 NamedDecl *D = FoundDecl.getDecl(); 3124 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3125 if (isa<UsingShadowDecl>(D)) 3126 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3127 3128 CXXConversionDecl *Conv; 3129 FunctionTemplateDecl *ConvTemplate; 3130 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3131 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3132 else 3133 Conv = cast<CXXConversionDecl>(D); 3134 3135 if (AllowExplicit || !Conv->isExplicit()) { 3136 if (ConvTemplate) 3137 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3138 ActingContext, From, ToType, 3139 CandidateSet); 3140 else 3141 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3142 From, ToType, CandidateSet); 3143 } 3144 } 3145 } 3146 } 3147 3148 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3149 3150 OverloadCandidateSet::iterator Best; 3151 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3152 case OR_Success: 3153 // Record the standard conversion we used and the conversion function. 3154 if (CXXConstructorDecl *Constructor 3155 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3156 // C++ [over.ics.user]p1: 3157 // If the user-defined conversion is specified by a 3158 // constructor (12.3.1), the initial standard conversion 3159 // sequence converts the source type to the type required by 3160 // the argument of the constructor. 3161 // 3162 QualType ThisType = Constructor->getThisType(S.Context); 3163 if (isa<InitListExpr>(From)) { 3164 // Initializer lists don't have conversions as such. 3165 User.Before.setAsIdentityConversion(); 3166 } else { 3167 if (Best->Conversions[0].isEllipsis()) 3168 User.EllipsisConversion = true; 3169 else { 3170 User.Before = Best->Conversions[0].Standard; 3171 User.EllipsisConversion = false; 3172 } 3173 } 3174 User.HadMultipleCandidates = HadMultipleCandidates; 3175 User.ConversionFunction = Constructor; 3176 User.FoundConversionFunction = Best->FoundDecl; 3177 User.After.setAsIdentityConversion(); 3178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3179 User.After.setAllToTypes(ToType); 3180 return OR_Success; 3181 } 3182 if (CXXConversionDecl *Conversion 3183 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3184 // C++ [over.ics.user]p1: 3185 // 3186 // [...] If the user-defined conversion is specified by a 3187 // conversion function (12.3.2), the initial standard 3188 // conversion sequence converts the source type to the 3189 // implicit object parameter of the conversion function. 3190 User.Before = Best->Conversions[0].Standard; 3191 User.HadMultipleCandidates = HadMultipleCandidates; 3192 User.ConversionFunction = Conversion; 3193 User.FoundConversionFunction = Best->FoundDecl; 3194 User.EllipsisConversion = false; 3195 3196 // C++ [over.ics.user]p2: 3197 // The second standard conversion sequence converts the 3198 // result of the user-defined conversion to the target type 3199 // for the sequence. Since an implicit conversion sequence 3200 // is an initialization, the special rules for 3201 // initialization by user-defined conversion apply when 3202 // selecting the best user-defined conversion for a 3203 // user-defined conversion sequence (see 13.3.3 and 3204 // 13.3.3.1). 3205 User.After = Best->FinalConversion; 3206 return OR_Success; 3207 } 3208 llvm_unreachable("Not a constructor or conversion function?"); 3209 3210 case OR_No_Viable_Function: 3211 return OR_No_Viable_Function; 3212 case OR_Deleted: 3213 // No conversion here! We're done. 3214 return OR_Deleted; 3215 3216 case OR_Ambiguous: 3217 return OR_Ambiguous; 3218 } 3219 3220 llvm_unreachable("Invalid OverloadResult!"); 3221 } 3222 3223 bool 3224 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3225 ImplicitConversionSequence ICS; 3226 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3227 OverloadingResult OvResult = 3228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3229 CandidateSet, false); 3230 if (OvResult == OR_Ambiguous) 3231 Diag(From->getLocStart(), 3232 diag::err_typecheck_ambiguous_condition) 3233 << From->getType() << ToType << From->getSourceRange(); 3234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3235 Diag(From->getLocStart(), 3236 diag::err_typecheck_nonviable_condition) 3237 << From->getType() << ToType << From->getSourceRange(); 3238 else 3239 return false; 3240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3241 return true; 3242 } 3243 3244 /// \brief Compare the user-defined conversion functions or constructors 3245 /// of two user-defined conversion sequences to determine whether any ordering 3246 /// is possible. 3247 static ImplicitConversionSequence::CompareKind 3248 compareConversionFunctions(Sema &S, 3249 FunctionDecl *Function1, 3250 FunctionDecl *Function2) { 3251 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3252 return ImplicitConversionSequence::Indistinguishable; 3253 3254 // Objective-C++: 3255 // If both conversion functions are implicitly-declared conversions from 3256 // a lambda closure type to a function pointer and a block pointer, 3257 // respectively, always prefer the conversion to a function pointer, 3258 // because the function pointer is more lightweight and is more likely 3259 // to keep code working. 3260 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3261 if (!Conv1) 3262 return ImplicitConversionSequence::Indistinguishable; 3263 3264 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3265 if (!Conv2) 3266 return ImplicitConversionSequence::Indistinguishable; 3267 3268 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3269 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3270 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3271 if (Block1 != Block2) 3272 return Block1? ImplicitConversionSequence::Worse 3273 : ImplicitConversionSequence::Better; 3274 } 3275 3276 return ImplicitConversionSequence::Indistinguishable; 3277 } 3278 3279 /// CompareImplicitConversionSequences - Compare two implicit 3280 /// conversion sequences to determine whether one is better than the 3281 /// other or if they are indistinguishable (C++ 13.3.3.2). 3282 static ImplicitConversionSequence::CompareKind 3283 CompareImplicitConversionSequences(Sema &S, 3284 const ImplicitConversionSequence& ICS1, 3285 const ImplicitConversionSequence& ICS2) 3286 { 3287 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3288 // conversion sequences (as defined in 13.3.3.1) 3289 // -- a standard conversion sequence (13.3.3.1.1) is a better 3290 // conversion sequence than a user-defined conversion sequence or 3291 // an ellipsis conversion sequence, and 3292 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3293 // conversion sequence than an ellipsis conversion sequence 3294 // (13.3.3.1.3). 3295 // 3296 // C++0x [over.best.ics]p10: 3297 // For the purpose of ranking implicit conversion sequences as 3298 // described in 13.3.3.2, the ambiguous conversion sequence is 3299 // treated as a user-defined sequence that is indistinguishable 3300 // from any other user-defined conversion sequence. 3301 if (ICS1.getKindRank() < ICS2.getKindRank()) 3302 return ImplicitConversionSequence::Better; 3303 if (ICS2.getKindRank() < ICS1.getKindRank()) 3304 return ImplicitConversionSequence::Worse; 3305 3306 // The following checks require both conversion sequences to be of 3307 // the same kind. 3308 if (ICS1.getKind() != ICS2.getKind()) 3309 return ImplicitConversionSequence::Indistinguishable; 3310 3311 ImplicitConversionSequence::CompareKind Result = 3312 ImplicitConversionSequence::Indistinguishable; 3313 3314 // Two implicit conversion sequences of the same form are 3315 // indistinguishable conversion sequences unless one of the 3316 // following rules apply: (C++ 13.3.3.2p3): 3317 if (ICS1.isStandard()) 3318 Result = CompareStandardConversionSequences(S, 3319 ICS1.Standard, ICS2.Standard); 3320 else if (ICS1.isUserDefined()) { 3321 // User-defined conversion sequence U1 is a better conversion 3322 // sequence than another user-defined conversion sequence U2 if 3323 // they contain the same user-defined conversion function or 3324 // constructor and if the second standard conversion sequence of 3325 // U1 is better than the second standard conversion sequence of 3326 // U2 (C++ 13.3.3.2p3). 3327 if (ICS1.UserDefined.ConversionFunction == 3328 ICS2.UserDefined.ConversionFunction) 3329 Result = CompareStandardConversionSequences(S, 3330 ICS1.UserDefined.After, 3331 ICS2.UserDefined.After); 3332 else 3333 Result = compareConversionFunctions(S, 3334 ICS1.UserDefined.ConversionFunction, 3335 ICS2.UserDefined.ConversionFunction); 3336 } 3337 3338 // List-initialization sequence L1 is a better conversion sequence than 3339 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3340 // for some X and L2 does not. 3341 if (Result == ImplicitConversionSequence::Indistinguishable && 3342 !ICS1.isBad() && 3343 ICS1.isListInitializationSequence() && 3344 ICS2.isListInitializationSequence()) { 3345 if (ICS1.isStdInitializerListElement() && 3346 !ICS2.isStdInitializerListElement()) 3347 return ImplicitConversionSequence::Better; 3348 if (!ICS1.isStdInitializerListElement() && 3349 ICS2.isStdInitializerListElement()) 3350 return ImplicitConversionSequence::Worse; 3351 } 3352 3353 return Result; 3354 } 3355 3356 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3357 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3358 Qualifiers Quals; 3359 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3360 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3361 } 3362 3363 return Context.hasSameUnqualifiedType(T1, T2); 3364 } 3365 3366 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3367 // determine if one is a proper subset of the other. 3368 static ImplicitConversionSequence::CompareKind 3369 compareStandardConversionSubsets(ASTContext &Context, 3370 const StandardConversionSequence& SCS1, 3371 const StandardConversionSequence& SCS2) { 3372 ImplicitConversionSequence::CompareKind Result 3373 = ImplicitConversionSequence::Indistinguishable; 3374 3375 // the identity conversion sequence is considered to be a subsequence of 3376 // any non-identity conversion sequence 3377 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3378 return ImplicitConversionSequence::Better; 3379 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3380 return ImplicitConversionSequence::Worse; 3381 3382 if (SCS1.Second != SCS2.Second) { 3383 if (SCS1.Second == ICK_Identity) 3384 Result = ImplicitConversionSequence::Better; 3385 else if (SCS2.Second == ICK_Identity) 3386 Result = ImplicitConversionSequence::Worse; 3387 else 3388 return ImplicitConversionSequence::Indistinguishable; 3389 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3390 return ImplicitConversionSequence::Indistinguishable; 3391 3392 if (SCS1.Third == SCS2.Third) { 3393 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3394 : ImplicitConversionSequence::Indistinguishable; 3395 } 3396 3397 if (SCS1.Third == ICK_Identity) 3398 return Result == ImplicitConversionSequence::Worse 3399 ? ImplicitConversionSequence::Indistinguishable 3400 : ImplicitConversionSequence::Better; 3401 3402 if (SCS2.Third == ICK_Identity) 3403 return Result == ImplicitConversionSequence::Better 3404 ? ImplicitConversionSequence::Indistinguishable 3405 : ImplicitConversionSequence::Worse; 3406 3407 return ImplicitConversionSequence::Indistinguishable; 3408 } 3409 3410 /// \brief Determine whether one of the given reference bindings is better 3411 /// than the other based on what kind of bindings they are. 3412 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3413 const StandardConversionSequence &SCS2) { 3414 // C++0x [over.ics.rank]p3b4: 3415 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3416 // implicit object parameter of a non-static member function declared 3417 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3418 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3419 // lvalue reference to a function lvalue and S2 binds an rvalue 3420 // reference*. 3421 // 3422 // FIXME: Rvalue references. We're going rogue with the above edits, 3423 // because the semantics in the current C++0x working paper (N3225 at the 3424 // time of this writing) break the standard definition of std::forward 3425 // and std::reference_wrapper when dealing with references to functions. 3426 // Proposed wording changes submitted to CWG for consideration. 3427 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3428 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3429 return false; 3430 3431 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3432 SCS2.IsLvalueReference) || 3433 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3434 !SCS2.IsLvalueReference); 3435 } 3436 3437 /// CompareStandardConversionSequences - Compare two standard 3438 /// conversion sequences to determine whether one is better than the 3439 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3440 static ImplicitConversionSequence::CompareKind 3441 CompareStandardConversionSequences(Sema &S, 3442 const StandardConversionSequence& SCS1, 3443 const StandardConversionSequence& SCS2) 3444 { 3445 // Standard conversion sequence S1 is a better conversion sequence 3446 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3447 3448 // -- S1 is a proper subsequence of S2 (comparing the conversion 3449 // sequences in the canonical form defined by 13.3.3.1.1, 3450 // excluding any Lvalue Transformation; the identity conversion 3451 // sequence is considered to be a subsequence of any 3452 // non-identity conversion sequence) or, if not that, 3453 if (ImplicitConversionSequence::CompareKind CK 3454 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3455 return CK; 3456 3457 // -- the rank of S1 is better than the rank of S2 (by the rules 3458 // defined below), or, if not that, 3459 ImplicitConversionRank Rank1 = SCS1.getRank(); 3460 ImplicitConversionRank Rank2 = SCS2.getRank(); 3461 if (Rank1 < Rank2) 3462 return ImplicitConversionSequence::Better; 3463 else if (Rank2 < Rank1) 3464 return ImplicitConversionSequence::Worse; 3465 3466 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3467 // are indistinguishable unless one of the following rules 3468 // applies: 3469 3470 // A conversion that is not a conversion of a pointer, or 3471 // pointer to member, to bool is better than another conversion 3472 // that is such a conversion. 3473 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3474 return SCS2.isPointerConversionToBool() 3475 ? ImplicitConversionSequence::Better 3476 : ImplicitConversionSequence::Worse; 3477 3478 // C++ [over.ics.rank]p4b2: 3479 // 3480 // If class B is derived directly or indirectly from class A, 3481 // conversion of B* to A* is better than conversion of B* to 3482 // void*, and conversion of A* to void* is better than conversion 3483 // of B* to void*. 3484 bool SCS1ConvertsToVoid 3485 = SCS1.isPointerConversionToVoidPointer(S.Context); 3486 bool SCS2ConvertsToVoid 3487 = SCS2.isPointerConversionToVoidPointer(S.Context); 3488 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3489 // Exactly one of the conversion sequences is a conversion to 3490 // a void pointer; it's the worse conversion. 3491 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3492 : ImplicitConversionSequence::Worse; 3493 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3494 // Neither conversion sequence converts to a void pointer; compare 3495 // their derived-to-base conversions. 3496 if (ImplicitConversionSequence::CompareKind DerivedCK 3497 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3498 return DerivedCK; 3499 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3500 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3501 // Both conversion sequences are conversions to void 3502 // pointers. Compare the source types to determine if there's an 3503 // inheritance relationship in their sources. 3504 QualType FromType1 = SCS1.getFromType(); 3505 QualType FromType2 = SCS2.getFromType(); 3506 3507 // Adjust the types we're converting from via the array-to-pointer 3508 // conversion, if we need to. 3509 if (SCS1.First == ICK_Array_To_Pointer) 3510 FromType1 = S.Context.getArrayDecayedType(FromType1); 3511 if (SCS2.First == ICK_Array_To_Pointer) 3512 FromType2 = S.Context.getArrayDecayedType(FromType2); 3513 3514 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3515 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3516 3517 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3518 return ImplicitConversionSequence::Better; 3519 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3520 return ImplicitConversionSequence::Worse; 3521 3522 // Objective-C++: If one interface is more specific than the 3523 // other, it is the better one. 3524 const ObjCObjectPointerType* FromObjCPtr1 3525 = FromType1->getAs<ObjCObjectPointerType>(); 3526 const ObjCObjectPointerType* FromObjCPtr2 3527 = FromType2->getAs<ObjCObjectPointerType>(); 3528 if (FromObjCPtr1 && FromObjCPtr2) { 3529 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3530 FromObjCPtr2); 3531 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3532 FromObjCPtr1); 3533 if (AssignLeft != AssignRight) { 3534 return AssignLeft? ImplicitConversionSequence::Better 3535 : ImplicitConversionSequence::Worse; 3536 } 3537 } 3538 } 3539 3540 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3541 // bullet 3). 3542 if (ImplicitConversionSequence::CompareKind QualCK 3543 = CompareQualificationConversions(S, SCS1, SCS2)) 3544 return QualCK; 3545 3546 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3547 // Check for a better reference binding based on the kind of bindings. 3548 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3549 return ImplicitConversionSequence::Better; 3550 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3551 return ImplicitConversionSequence::Worse; 3552 3553 // C++ [over.ics.rank]p3b4: 3554 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3555 // which the references refer are the same type except for 3556 // top-level cv-qualifiers, and the type to which the reference 3557 // initialized by S2 refers is more cv-qualified than the type 3558 // to which the reference initialized by S1 refers. 3559 QualType T1 = SCS1.getToType(2); 3560 QualType T2 = SCS2.getToType(2); 3561 T1 = S.Context.getCanonicalType(T1); 3562 T2 = S.Context.getCanonicalType(T2); 3563 Qualifiers T1Quals, T2Quals; 3564 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3565 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3566 if (UnqualT1 == UnqualT2) { 3567 // Objective-C++ ARC: If the references refer to objects with different 3568 // lifetimes, prefer bindings that don't change lifetime. 3569 if (SCS1.ObjCLifetimeConversionBinding != 3570 SCS2.ObjCLifetimeConversionBinding) { 3571 return SCS1.ObjCLifetimeConversionBinding 3572 ? ImplicitConversionSequence::Worse 3573 : ImplicitConversionSequence::Better; 3574 } 3575 3576 // If the type is an array type, promote the element qualifiers to the 3577 // type for comparison. 3578 if (isa<ArrayType>(T1) && T1Quals) 3579 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3580 if (isa<ArrayType>(T2) && T2Quals) 3581 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3582 if (T2.isMoreQualifiedThan(T1)) 3583 return ImplicitConversionSequence::Better; 3584 else if (T1.isMoreQualifiedThan(T2)) 3585 return ImplicitConversionSequence::Worse; 3586 } 3587 } 3588 3589 // In Microsoft mode, prefer an integral conversion to a 3590 // floating-to-integral conversion if the integral conversion 3591 // is between types of the same size. 3592 // For example: 3593 // void f(float); 3594 // void f(int); 3595 // int main { 3596 // long a; 3597 // f(a); 3598 // } 3599 // Here, MSVC will call f(int) instead of generating a compile error 3600 // as clang will do in standard mode. 3601 if (S.getLangOpts().MicrosoftMode && 3602 SCS1.Second == ICK_Integral_Conversion && 3603 SCS2.Second == ICK_Floating_Integral && 3604 S.Context.getTypeSize(SCS1.getFromType()) == 3605 S.Context.getTypeSize(SCS1.getToType(2))) 3606 return ImplicitConversionSequence::Better; 3607 3608 return ImplicitConversionSequence::Indistinguishable; 3609 } 3610 3611 /// CompareQualificationConversions - Compares two standard conversion 3612 /// sequences to determine whether they can be ranked based on their 3613 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3614 ImplicitConversionSequence::CompareKind 3615 CompareQualificationConversions(Sema &S, 3616 const StandardConversionSequence& SCS1, 3617 const StandardConversionSequence& SCS2) { 3618 // C++ 13.3.3.2p3: 3619 // -- S1 and S2 differ only in their qualification conversion and 3620 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3621 // cv-qualification signature of type T1 is a proper subset of 3622 // the cv-qualification signature of type T2, and S1 is not the 3623 // deprecated string literal array-to-pointer conversion (4.2). 3624 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3625 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3626 return ImplicitConversionSequence::Indistinguishable; 3627 3628 // FIXME: the example in the standard doesn't use a qualification 3629 // conversion (!) 3630 QualType T1 = SCS1.getToType(2); 3631 QualType T2 = SCS2.getToType(2); 3632 T1 = S.Context.getCanonicalType(T1); 3633 T2 = S.Context.getCanonicalType(T2); 3634 Qualifiers T1Quals, T2Quals; 3635 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3636 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3637 3638 // If the types are the same, we won't learn anything by unwrapped 3639 // them. 3640 if (UnqualT1 == UnqualT2) 3641 return ImplicitConversionSequence::Indistinguishable; 3642 3643 // If the type is an array type, promote the element qualifiers to the type 3644 // for comparison. 3645 if (isa<ArrayType>(T1) && T1Quals) 3646 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3647 if (isa<ArrayType>(T2) && T2Quals) 3648 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3649 3650 ImplicitConversionSequence::CompareKind Result 3651 = ImplicitConversionSequence::Indistinguishable; 3652 3653 // Objective-C++ ARC: 3654 // Prefer qualification conversions not involving a change in lifetime 3655 // to qualification conversions that do not change lifetime. 3656 if (SCS1.QualificationIncludesObjCLifetime != 3657 SCS2.QualificationIncludesObjCLifetime) { 3658 Result = SCS1.QualificationIncludesObjCLifetime 3659 ? ImplicitConversionSequence::Worse 3660 : ImplicitConversionSequence::Better; 3661 } 3662 3663 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3664 // Within each iteration of the loop, we check the qualifiers to 3665 // determine if this still looks like a qualification 3666 // conversion. Then, if all is well, we unwrap one more level of 3667 // pointers or pointers-to-members and do it all again 3668 // until there are no more pointers or pointers-to-members left 3669 // to unwrap. This essentially mimics what 3670 // IsQualificationConversion does, but here we're checking for a 3671 // strict subset of qualifiers. 3672 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3673 // The qualifiers are the same, so this doesn't tell us anything 3674 // about how the sequences rank. 3675 ; 3676 else if (T2.isMoreQualifiedThan(T1)) { 3677 // T1 has fewer qualifiers, so it could be the better sequence. 3678 if (Result == ImplicitConversionSequence::Worse) 3679 // Neither has qualifiers that are a subset of the other's 3680 // qualifiers. 3681 return ImplicitConversionSequence::Indistinguishable; 3682 3683 Result = ImplicitConversionSequence::Better; 3684 } else if (T1.isMoreQualifiedThan(T2)) { 3685 // T2 has fewer qualifiers, so it could be the better sequence. 3686 if (Result == ImplicitConversionSequence::Better) 3687 // Neither has qualifiers that are a subset of the other's 3688 // qualifiers. 3689 return ImplicitConversionSequence::Indistinguishable; 3690 3691 Result = ImplicitConversionSequence::Worse; 3692 } else { 3693 // Qualifiers are disjoint. 3694 return ImplicitConversionSequence::Indistinguishable; 3695 } 3696 3697 // If the types after this point are equivalent, we're done. 3698 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3699 break; 3700 } 3701 3702 // Check that the winning standard conversion sequence isn't using 3703 // the deprecated string literal array to pointer conversion. 3704 switch (Result) { 3705 case ImplicitConversionSequence::Better: 3706 if (SCS1.DeprecatedStringLiteralToCharPtr) 3707 Result = ImplicitConversionSequence::Indistinguishable; 3708 break; 3709 3710 case ImplicitConversionSequence::Indistinguishable: 3711 break; 3712 3713 case ImplicitConversionSequence::Worse: 3714 if (SCS2.DeprecatedStringLiteralToCharPtr) 3715 Result = ImplicitConversionSequence::Indistinguishable; 3716 break; 3717 } 3718 3719 return Result; 3720 } 3721 3722 /// CompareDerivedToBaseConversions - Compares two standard conversion 3723 /// sequences to determine whether they can be ranked based on their 3724 /// various kinds of derived-to-base conversions (C++ 3725 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3726 /// conversions between Objective-C interface types. 3727 ImplicitConversionSequence::CompareKind 3728 CompareDerivedToBaseConversions(Sema &S, 3729 const StandardConversionSequence& SCS1, 3730 const StandardConversionSequence& SCS2) { 3731 QualType FromType1 = SCS1.getFromType(); 3732 QualType ToType1 = SCS1.getToType(1); 3733 QualType FromType2 = SCS2.getFromType(); 3734 QualType ToType2 = SCS2.getToType(1); 3735 3736 // Adjust the types we're converting from via the array-to-pointer 3737 // conversion, if we need to. 3738 if (SCS1.First == ICK_Array_To_Pointer) 3739 FromType1 = S.Context.getArrayDecayedType(FromType1); 3740 if (SCS2.First == ICK_Array_To_Pointer) 3741 FromType2 = S.Context.getArrayDecayedType(FromType2); 3742 3743 // Canonicalize all of the types. 3744 FromType1 = S.Context.getCanonicalType(FromType1); 3745 ToType1 = S.Context.getCanonicalType(ToType1); 3746 FromType2 = S.Context.getCanonicalType(FromType2); 3747 ToType2 = S.Context.getCanonicalType(ToType2); 3748 3749 // C++ [over.ics.rank]p4b3: 3750 // 3751 // If class B is derived directly or indirectly from class A and 3752 // class C is derived directly or indirectly from B, 3753 // 3754 // Compare based on pointer conversions. 3755 if (SCS1.Second == ICK_Pointer_Conversion && 3756 SCS2.Second == ICK_Pointer_Conversion && 3757 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3758 FromType1->isPointerType() && FromType2->isPointerType() && 3759 ToType1->isPointerType() && ToType2->isPointerType()) { 3760 QualType FromPointee1 3761 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3762 QualType ToPointee1 3763 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3764 QualType FromPointee2 3765 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3766 QualType ToPointee2 3767 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3768 3769 // -- conversion of C* to B* is better than conversion of C* to A*, 3770 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3771 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3772 return ImplicitConversionSequence::Better; 3773 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3774 return ImplicitConversionSequence::Worse; 3775 } 3776 3777 // -- conversion of B* to A* is better than conversion of C* to A*, 3778 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3779 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3780 return ImplicitConversionSequence::Better; 3781 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3782 return ImplicitConversionSequence::Worse; 3783 } 3784 } else if (SCS1.Second == ICK_Pointer_Conversion && 3785 SCS2.Second == ICK_Pointer_Conversion) { 3786 const ObjCObjectPointerType *FromPtr1 3787 = FromType1->getAs<ObjCObjectPointerType>(); 3788 const ObjCObjectPointerType *FromPtr2 3789 = FromType2->getAs<ObjCObjectPointerType>(); 3790 const ObjCObjectPointerType *ToPtr1 3791 = ToType1->getAs<ObjCObjectPointerType>(); 3792 const ObjCObjectPointerType *ToPtr2 3793 = ToType2->getAs<ObjCObjectPointerType>(); 3794 3795 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3796 // Apply the same conversion ranking rules for Objective-C pointer types 3797 // that we do for C++ pointers to class types. However, we employ the 3798 // Objective-C pseudo-subtyping relationship used for assignment of 3799 // Objective-C pointer types. 3800 bool FromAssignLeft 3801 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3802 bool FromAssignRight 3803 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3804 bool ToAssignLeft 3805 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3806 bool ToAssignRight 3807 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3808 3809 // A conversion to an a non-id object pointer type or qualified 'id' 3810 // type is better than a conversion to 'id'. 3811 if (ToPtr1->isObjCIdType() && 3812 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3813 return ImplicitConversionSequence::Worse; 3814 if (ToPtr2->isObjCIdType() && 3815 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3816 return ImplicitConversionSequence::Better; 3817 3818 // A conversion to a non-id object pointer type is better than a 3819 // conversion to a qualified 'id' type 3820 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3821 return ImplicitConversionSequence::Worse; 3822 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3823 return ImplicitConversionSequence::Better; 3824 3825 // A conversion to an a non-Class object pointer type or qualified 'Class' 3826 // type is better than a conversion to 'Class'. 3827 if (ToPtr1->isObjCClassType() && 3828 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3829 return ImplicitConversionSequence::Worse; 3830 if (ToPtr2->isObjCClassType() && 3831 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3832 return ImplicitConversionSequence::Better; 3833 3834 // A conversion to a non-Class object pointer type is better than a 3835 // conversion to a qualified 'Class' type. 3836 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3837 return ImplicitConversionSequence::Worse; 3838 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3839 return ImplicitConversionSequence::Better; 3840 3841 // -- "conversion of C* to B* is better than conversion of C* to A*," 3842 if (S.Context.hasSameType(FromType1, FromType2) && 3843 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3844 (ToAssignLeft != ToAssignRight)) 3845 return ToAssignLeft? ImplicitConversionSequence::Worse 3846 : ImplicitConversionSequence::Better; 3847 3848 // -- "conversion of B* to A* is better than conversion of C* to A*," 3849 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3850 (FromAssignLeft != FromAssignRight)) 3851 return FromAssignLeft? ImplicitConversionSequence::Better 3852 : ImplicitConversionSequence::Worse; 3853 } 3854 } 3855 3856 // Ranking of member-pointer types. 3857 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3858 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3859 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3860 const MemberPointerType * FromMemPointer1 = 3861 FromType1->getAs<MemberPointerType>(); 3862 const MemberPointerType * ToMemPointer1 = 3863 ToType1->getAs<MemberPointerType>(); 3864 const MemberPointerType * FromMemPointer2 = 3865 FromType2->getAs<MemberPointerType>(); 3866 const MemberPointerType * ToMemPointer2 = 3867 ToType2->getAs<MemberPointerType>(); 3868 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3869 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3870 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3871 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3872 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3873 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3874 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3875 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3876 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3877 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3878 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3879 return ImplicitConversionSequence::Worse; 3880 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3881 return ImplicitConversionSequence::Better; 3882 } 3883 // conversion of B::* to C::* is better than conversion of A::* to C::* 3884 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3885 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3886 return ImplicitConversionSequence::Better; 3887 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3888 return ImplicitConversionSequence::Worse; 3889 } 3890 } 3891 3892 if (SCS1.Second == ICK_Derived_To_Base) { 3893 // -- conversion of C to B is better than conversion of C to A, 3894 // -- binding of an expression of type C to a reference of type 3895 // B& is better than binding an expression of type C to a 3896 // reference of type A&, 3897 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3898 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3899 if (S.IsDerivedFrom(ToType1, ToType2)) 3900 return ImplicitConversionSequence::Better; 3901 else if (S.IsDerivedFrom(ToType2, ToType1)) 3902 return ImplicitConversionSequence::Worse; 3903 } 3904 3905 // -- conversion of B to A is better than conversion of C to A. 3906 // -- binding of an expression of type B to a reference of type 3907 // A& is better than binding an expression of type C to a 3908 // reference of type A&, 3909 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3910 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3911 if (S.IsDerivedFrom(FromType2, FromType1)) 3912 return ImplicitConversionSequence::Better; 3913 else if (S.IsDerivedFrom(FromType1, FromType2)) 3914 return ImplicitConversionSequence::Worse; 3915 } 3916 } 3917 3918 return ImplicitConversionSequence::Indistinguishable; 3919 } 3920 3921 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3922 /// C++ class. 3923 static bool isTypeValid(QualType T) { 3924 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3925 return !Record->isInvalidDecl(); 3926 3927 return true; 3928 } 3929 3930 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3931 /// determine whether they are reference-related, 3932 /// reference-compatible, reference-compatible with added 3933 /// qualification, or incompatible, for use in C++ initialization by 3934 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3935 /// type, and the first type (T1) is the pointee type of the reference 3936 /// type being initialized. 3937 Sema::ReferenceCompareResult 3938 Sema::CompareReferenceRelationship(SourceLocation Loc, 3939 QualType OrigT1, QualType OrigT2, 3940 bool &DerivedToBase, 3941 bool &ObjCConversion, 3942 bool &ObjCLifetimeConversion) { 3943 assert(!OrigT1->isReferenceType() && 3944 "T1 must be the pointee type of the reference type"); 3945 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3946 3947 QualType T1 = Context.getCanonicalType(OrigT1); 3948 QualType T2 = Context.getCanonicalType(OrigT2); 3949 Qualifiers T1Quals, T2Quals; 3950 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3951 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3952 3953 // C++ [dcl.init.ref]p4: 3954 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3955 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3956 // T1 is a base class of T2. 3957 DerivedToBase = false; 3958 ObjCConversion = false; 3959 ObjCLifetimeConversion = false; 3960 if (UnqualT1 == UnqualT2) { 3961 // Nothing to do. 3962 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3963 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3964 IsDerivedFrom(UnqualT2, UnqualT1)) 3965 DerivedToBase = true; 3966 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3967 UnqualT2->isObjCObjectOrInterfaceType() && 3968 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3969 ObjCConversion = true; 3970 else 3971 return Ref_Incompatible; 3972 3973 // At this point, we know that T1 and T2 are reference-related (at 3974 // least). 3975 3976 // If the type is an array type, promote the element qualifiers to the type 3977 // for comparison. 3978 if (isa<ArrayType>(T1) && T1Quals) 3979 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3980 if (isa<ArrayType>(T2) && T2Quals) 3981 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3982 3983 // C++ [dcl.init.ref]p4: 3984 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3985 // reference-related to T2 and cv1 is the same cv-qualification 3986 // as, or greater cv-qualification than, cv2. For purposes of 3987 // overload resolution, cases for which cv1 is greater 3988 // cv-qualification than cv2 are identified as 3989 // reference-compatible with added qualification (see 13.3.3.2). 3990 // 3991 // Note that we also require equivalence of Objective-C GC and address-space 3992 // qualifiers when performing these computations, so that e.g., an int in 3993 // address space 1 is not reference-compatible with an int in address 3994 // space 2. 3995 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3996 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3997 T1Quals.removeObjCLifetime(); 3998 T2Quals.removeObjCLifetime(); 3999 ObjCLifetimeConversion = true; 4000 } 4001 4002 if (T1Quals == T2Quals) 4003 return Ref_Compatible; 4004 else if (T1Quals.compatiblyIncludes(T2Quals)) 4005 return Ref_Compatible_With_Added_Qualification; 4006 else 4007 return Ref_Related; 4008 } 4009 4010 /// \brief Look for a user-defined conversion to an value reference-compatible 4011 /// with DeclType. Return true if something definite is found. 4012 static bool 4013 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4014 QualType DeclType, SourceLocation DeclLoc, 4015 Expr *Init, QualType T2, bool AllowRvalues, 4016 bool AllowExplicit) { 4017 assert(T2->isRecordType() && "Can only find conversions of record types."); 4018 CXXRecordDecl *T2RecordDecl 4019 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4020 4021 OverloadCandidateSet CandidateSet(DeclLoc); 4022 std::pair<CXXRecordDecl::conversion_iterator, 4023 CXXRecordDecl::conversion_iterator> 4024 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4025 for (CXXRecordDecl::conversion_iterator 4026 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4027 NamedDecl *D = *I; 4028 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4029 if (isa<UsingShadowDecl>(D)) 4030 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4031 4032 FunctionTemplateDecl *ConvTemplate 4033 = dyn_cast<FunctionTemplateDecl>(D); 4034 CXXConversionDecl *Conv; 4035 if (ConvTemplate) 4036 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4037 else 4038 Conv = cast<CXXConversionDecl>(D); 4039 4040 // If this is an explicit conversion, and we're not allowed to consider 4041 // explicit conversions, skip it. 4042 if (!AllowExplicit && Conv->isExplicit()) 4043 continue; 4044 4045 if (AllowRvalues) { 4046 bool DerivedToBase = false; 4047 bool ObjCConversion = false; 4048 bool ObjCLifetimeConversion = false; 4049 4050 // If we are initializing an rvalue reference, don't permit conversion 4051 // functions that return lvalues. 4052 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4053 const ReferenceType *RefType 4054 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4055 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4056 continue; 4057 } 4058 4059 if (!ConvTemplate && 4060 S.CompareReferenceRelationship( 4061 DeclLoc, 4062 Conv->getConversionType().getNonReferenceType() 4063 .getUnqualifiedType(), 4064 DeclType.getNonReferenceType().getUnqualifiedType(), 4065 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4066 Sema::Ref_Incompatible) 4067 continue; 4068 } else { 4069 // If the conversion function doesn't return a reference type, 4070 // it can't be considered for this conversion. An rvalue reference 4071 // is only acceptable if its referencee is a function type. 4072 4073 const ReferenceType *RefType = 4074 Conv->getConversionType()->getAs<ReferenceType>(); 4075 if (!RefType || 4076 (!RefType->isLValueReferenceType() && 4077 !RefType->getPointeeType()->isFunctionType())) 4078 continue; 4079 } 4080 4081 if (ConvTemplate) 4082 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4083 Init, DeclType, CandidateSet); 4084 else 4085 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4086 DeclType, CandidateSet); 4087 } 4088 4089 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4090 4091 OverloadCandidateSet::iterator Best; 4092 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4093 case OR_Success: 4094 // C++ [over.ics.ref]p1: 4095 // 4096 // [...] If the parameter binds directly to the result of 4097 // applying a conversion function to the argument 4098 // expression, the implicit conversion sequence is a 4099 // user-defined conversion sequence (13.3.3.1.2), with the 4100 // second standard conversion sequence either an identity 4101 // conversion or, if the conversion function returns an 4102 // entity of a type that is a derived class of the parameter 4103 // type, a derived-to-base Conversion. 4104 if (!Best->FinalConversion.DirectBinding) 4105 return false; 4106 4107 ICS.setUserDefined(); 4108 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4109 ICS.UserDefined.After = Best->FinalConversion; 4110 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4111 ICS.UserDefined.ConversionFunction = Best->Function; 4112 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4113 ICS.UserDefined.EllipsisConversion = false; 4114 assert(ICS.UserDefined.After.ReferenceBinding && 4115 ICS.UserDefined.After.DirectBinding && 4116 "Expected a direct reference binding!"); 4117 return true; 4118 4119 case OR_Ambiguous: 4120 ICS.setAmbiguous(); 4121 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4122 Cand != CandidateSet.end(); ++Cand) 4123 if (Cand->Viable) 4124 ICS.Ambiguous.addConversion(Cand->Function); 4125 return true; 4126 4127 case OR_No_Viable_Function: 4128 case OR_Deleted: 4129 // There was no suitable conversion, or we found a deleted 4130 // conversion; continue with other checks. 4131 return false; 4132 } 4133 4134 llvm_unreachable("Invalid OverloadResult!"); 4135 } 4136 4137 /// \brief Compute an implicit conversion sequence for reference 4138 /// initialization. 4139 static ImplicitConversionSequence 4140 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4141 SourceLocation DeclLoc, 4142 bool SuppressUserConversions, 4143 bool AllowExplicit) { 4144 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4145 4146 // Most paths end in a failed conversion. 4147 ImplicitConversionSequence ICS; 4148 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4149 4150 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4151 QualType T2 = Init->getType(); 4152 4153 // If the initializer is the address of an overloaded function, try 4154 // to resolve the overloaded function. If all goes well, T2 is the 4155 // type of the resulting function. 4156 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4157 DeclAccessPair Found; 4158 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4159 false, Found)) 4160 T2 = Fn->getType(); 4161 } 4162 4163 // Compute some basic properties of the types and the initializer. 4164 bool isRValRef = DeclType->isRValueReferenceType(); 4165 bool DerivedToBase = false; 4166 bool ObjCConversion = false; 4167 bool ObjCLifetimeConversion = false; 4168 Expr::Classification InitCategory = Init->Classify(S.Context); 4169 Sema::ReferenceCompareResult RefRelationship 4170 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4171 ObjCConversion, ObjCLifetimeConversion); 4172 4173 4174 // C++0x [dcl.init.ref]p5: 4175 // A reference to type "cv1 T1" is initialized by an expression 4176 // of type "cv2 T2" as follows: 4177 4178 // -- If reference is an lvalue reference and the initializer expression 4179 if (!isRValRef) { 4180 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4181 // reference-compatible with "cv2 T2," or 4182 // 4183 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4184 if (InitCategory.isLValue() && 4185 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4186 // C++ [over.ics.ref]p1: 4187 // When a parameter of reference type binds directly (8.5.3) 4188 // to an argument expression, the implicit conversion sequence 4189 // is the identity conversion, unless the argument expression 4190 // has a type that is a derived class of the parameter type, 4191 // in which case the implicit conversion sequence is a 4192 // derived-to-base Conversion (13.3.3.1). 4193 ICS.setStandard(); 4194 ICS.Standard.First = ICK_Identity; 4195 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4196 : ObjCConversion? ICK_Compatible_Conversion 4197 : ICK_Identity; 4198 ICS.Standard.Third = ICK_Identity; 4199 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4200 ICS.Standard.setToType(0, T2); 4201 ICS.Standard.setToType(1, T1); 4202 ICS.Standard.setToType(2, T1); 4203 ICS.Standard.ReferenceBinding = true; 4204 ICS.Standard.DirectBinding = true; 4205 ICS.Standard.IsLvalueReference = !isRValRef; 4206 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4207 ICS.Standard.BindsToRvalue = false; 4208 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4209 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4210 ICS.Standard.CopyConstructor = 0; 4211 4212 // Nothing more to do: the inaccessibility/ambiguity check for 4213 // derived-to-base conversions is suppressed when we're 4214 // computing the implicit conversion sequence (C++ 4215 // [over.best.ics]p2). 4216 return ICS; 4217 } 4218 4219 // -- has a class type (i.e., T2 is a class type), where T1 is 4220 // not reference-related to T2, and can be implicitly 4221 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4222 // is reference-compatible with "cv3 T3" 92) (this 4223 // conversion is selected by enumerating the applicable 4224 // conversion functions (13.3.1.6) and choosing the best 4225 // one through overload resolution (13.3)), 4226 if (!SuppressUserConversions && T2->isRecordType() && 4227 !S.RequireCompleteType(DeclLoc, T2, 0) && 4228 RefRelationship == Sema::Ref_Incompatible) { 4229 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4230 Init, T2, /*AllowRvalues=*/false, 4231 AllowExplicit)) 4232 return ICS; 4233 } 4234 } 4235 4236 // -- Otherwise, the reference shall be an lvalue reference to a 4237 // non-volatile const type (i.e., cv1 shall be const), or the reference 4238 // shall be an rvalue reference. 4239 // 4240 // We actually handle one oddity of C++ [over.ics.ref] at this 4241 // point, which is that, due to p2 (which short-circuits reference 4242 // binding by only attempting a simple conversion for non-direct 4243 // bindings) and p3's strange wording, we allow a const volatile 4244 // reference to bind to an rvalue. Hence the check for the presence 4245 // of "const" rather than checking for "const" being the only 4246 // qualifier. 4247 // This is also the point where rvalue references and lvalue inits no longer 4248 // go together. 4249 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4250 return ICS; 4251 4252 // -- If the initializer expression 4253 // 4254 // -- is an xvalue, class prvalue, array prvalue or function 4255 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4256 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4257 (InitCategory.isXValue() || 4258 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4259 (InitCategory.isLValue() && T2->isFunctionType()))) { 4260 ICS.setStandard(); 4261 ICS.Standard.First = ICK_Identity; 4262 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4263 : ObjCConversion? ICK_Compatible_Conversion 4264 : ICK_Identity; 4265 ICS.Standard.Third = ICK_Identity; 4266 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4267 ICS.Standard.setToType(0, T2); 4268 ICS.Standard.setToType(1, T1); 4269 ICS.Standard.setToType(2, T1); 4270 ICS.Standard.ReferenceBinding = true; 4271 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4272 // binding unless we're binding to a class prvalue. 4273 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4274 // allow the use of rvalue references in C++98/03 for the benefit of 4275 // standard library implementors; therefore, we need the xvalue check here. 4276 ICS.Standard.DirectBinding = 4277 S.getLangOpts().CPlusPlus11 || 4278 (InitCategory.isPRValue() && !T2->isRecordType()); 4279 ICS.Standard.IsLvalueReference = !isRValRef; 4280 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4281 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4282 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4283 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4284 ICS.Standard.CopyConstructor = 0; 4285 return ICS; 4286 } 4287 4288 // -- has a class type (i.e., T2 is a class type), where T1 is not 4289 // reference-related to T2, and can be implicitly converted to 4290 // an xvalue, class prvalue, or function lvalue of type 4291 // "cv3 T3", where "cv1 T1" is reference-compatible with 4292 // "cv3 T3", 4293 // 4294 // then the reference is bound to the value of the initializer 4295 // expression in the first case and to the result of the conversion 4296 // in the second case (or, in either case, to an appropriate base 4297 // class subobject). 4298 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4299 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4300 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4301 Init, T2, /*AllowRvalues=*/true, 4302 AllowExplicit)) { 4303 // In the second case, if the reference is an rvalue reference 4304 // and the second standard conversion sequence of the 4305 // user-defined conversion sequence includes an lvalue-to-rvalue 4306 // conversion, the program is ill-formed. 4307 if (ICS.isUserDefined() && isRValRef && 4308 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4309 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4310 4311 return ICS; 4312 } 4313 4314 // -- Otherwise, a temporary of type "cv1 T1" is created and 4315 // initialized from the initializer expression using the 4316 // rules for a non-reference copy initialization (8.5). The 4317 // reference is then bound to the temporary. If T1 is 4318 // reference-related to T2, cv1 must be the same 4319 // cv-qualification as, or greater cv-qualification than, 4320 // cv2; otherwise, the program is ill-formed. 4321 if (RefRelationship == Sema::Ref_Related) { 4322 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4323 // we would be reference-compatible or reference-compatible with 4324 // added qualification. But that wasn't the case, so the reference 4325 // initialization fails. 4326 // 4327 // Note that we only want to check address spaces and cvr-qualifiers here. 4328 // ObjC GC and lifetime qualifiers aren't important. 4329 Qualifiers T1Quals = T1.getQualifiers(); 4330 Qualifiers T2Quals = T2.getQualifiers(); 4331 T1Quals.removeObjCGCAttr(); 4332 T1Quals.removeObjCLifetime(); 4333 T2Quals.removeObjCGCAttr(); 4334 T2Quals.removeObjCLifetime(); 4335 if (!T1Quals.compatiblyIncludes(T2Quals)) 4336 return ICS; 4337 } 4338 4339 // If at least one of the types is a class type, the types are not 4340 // related, and we aren't allowed any user conversions, the 4341 // reference binding fails. This case is important for breaking 4342 // recursion, since TryImplicitConversion below will attempt to 4343 // create a temporary through the use of a copy constructor. 4344 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4345 (T1->isRecordType() || T2->isRecordType())) 4346 return ICS; 4347 4348 // If T1 is reference-related to T2 and the reference is an rvalue 4349 // reference, the initializer expression shall not be an lvalue. 4350 if (RefRelationship >= Sema::Ref_Related && 4351 isRValRef && Init->Classify(S.Context).isLValue()) 4352 return ICS; 4353 4354 // C++ [over.ics.ref]p2: 4355 // When a parameter of reference type is not bound directly to 4356 // an argument expression, the conversion sequence is the one 4357 // required to convert the argument expression to the 4358 // underlying type of the reference according to 4359 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4360 // to copy-initializing a temporary of the underlying type with 4361 // the argument expression. Any difference in top-level 4362 // cv-qualification is subsumed by the initialization itself 4363 // and does not constitute a conversion. 4364 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4365 /*AllowExplicit=*/false, 4366 /*InOverloadResolution=*/false, 4367 /*CStyle=*/false, 4368 /*AllowObjCWritebackConversion=*/false); 4369 4370 // Of course, that's still a reference binding. 4371 if (ICS.isStandard()) { 4372 ICS.Standard.ReferenceBinding = true; 4373 ICS.Standard.IsLvalueReference = !isRValRef; 4374 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4375 ICS.Standard.BindsToRvalue = true; 4376 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4377 ICS.Standard.ObjCLifetimeConversionBinding = false; 4378 } else if (ICS.isUserDefined()) { 4379 // Don't allow rvalue references to bind to lvalues. 4380 if (DeclType->isRValueReferenceType()) { 4381 if (const ReferenceType *RefType 4382 = ICS.UserDefined.ConversionFunction->getResultType() 4383 ->getAs<LValueReferenceType>()) { 4384 if (!RefType->getPointeeType()->isFunctionType()) { 4385 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4386 DeclType); 4387 return ICS; 4388 } 4389 } 4390 } 4391 4392 ICS.UserDefined.After.ReferenceBinding = true; 4393 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4394 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4395 ICS.UserDefined.After.BindsToRvalue = true; 4396 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4397 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4398 } 4399 4400 return ICS; 4401 } 4402 4403 static ImplicitConversionSequence 4404 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4405 bool SuppressUserConversions, 4406 bool InOverloadResolution, 4407 bool AllowObjCWritebackConversion, 4408 bool AllowExplicit = false); 4409 4410 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4411 /// initializer list From. 4412 static ImplicitConversionSequence 4413 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4414 bool SuppressUserConversions, 4415 bool InOverloadResolution, 4416 bool AllowObjCWritebackConversion) { 4417 // C++11 [over.ics.list]p1: 4418 // When an argument is an initializer list, it is not an expression and 4419 // special rules apply for converting it to a parameter type. 4420 4421 ImplicitConversionSequence Result; 4422 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4423 Result.setListInitializationSequence(); 4424 4425 // We need a complete type for what follows. Incomplete types can never be 4426 // initialized from init lists. 4427 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4428 return Result; 4429 4430 // C++11 [over.ics.list]p2: 4431 // If the parameter type is std::initializer_list<X> or "array of X" and 4432 // all the elements can be implicitly converted to X, the implicit 4433 // conversion sequence is the worst conversion necessary to convert an 4434 // element of the list to X. 4435 bool toStdInitializerList = false; 4436 QualType X; 4437 if (ToType->isArrayType()) 4438 X = S.Context.getAsArrayType(ToType)->getElementType(); 4439 else 4440 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4441 if (!X.isNull()) { 4442 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4443 Expr *Init = From->getInit(i); 4444 ImplicitConversionSequence ICS = 4445 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4446 InOverloadResolution, 4447 AllowObjCWritebackConversion); 4448 // If a single element isn't convertible, fail. 4449 if (ICS.isBad()) { 4450 Result = ICS; 4451 break; 4452 } 4453 // Otherwise, look for the worst conversion. 4454 if (Result.isBad() || 4455 CompareImplicitConversionSequences(S, ICS, Result) == 4456 ImplicitConversionSequence::Worse) 4457 Result = ICS; 4458 } 4459 4460 // For an empty list, we won't have computed any conversion sequence. 4461 // Introduce the identity conversion sequence. 4462 if (From->getNumInits() == 0) { 4463 Result.setStandard(); 4464 Result.Standard.setAsIdentityConversion(); 4465 Result.Standard.setFromType(ToType); 4466 Result.Standard.setAllToTypes(ToType); 4467 } 4468 4469 Result.setListInitializationSequence(); 4470 Result.setStdInitializerListElement(toStdInitializerList); 4471 return Result; 4472 } 4473 4474 // C++11 [over.ics.list]p3: 4475 // Otherwise, if the parameter is a non-aggregate class X and overload 4476 // resolution chooses a single best constructor [...] the implicit 4477 // conversion sequence is a user-defined conversion sequence. If multiple 4478 // constructors are viable but none is better than the others, the 4479 // implicit conversion sequence is a user-defined conversion sequence. 4480 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4481 // This function can deal with initializer lists. 4482 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4483 /*AllowExplicit=*/false, 4484 InOverloadResolution, /*CStyle=*/false, 4485 AllowObjCWritebackConversion); 4486 Result.setListInitializationSequence(); 4487 return Result; 4488 } 4489 4490 // C++11 [over.ics.list]p4: 4491 // Otherwise, if the parameter has an aggregate type which can be 4492 // initialized from the initializer list [...] the implicit conversion 4493 // sequence is a user-defined conversion sequence. 4494 if (ToType->isAggregateType()) { 4495 // Type is an aggregate, argument is an init list. At this point it comes 4496 // down to checking whether the initialization works. 4497 // FIXME: Find out whether this parameter is consumed or not. 4498 InitializedEntity Entity = 4499 InitializedEntity::InitializeParameter(S.Context, ToType, 4500 /*Consumed=*/false); 4501 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4502 Result.setUserDefined(); 4503 Result.UserDefined.Before.setAsIdentityConversion(); 4504 // Initializer lists don't have a type. 4505 Result.UserDefined.Before.setFromType(QualType()); 4506 Result.UserDefined.Before.setAllToTypes(QualType()); 4507 4508 Result.UserDefined.After.setAsIdentityConversion(); 4509 Result.UserDefined.After.setFromType(ToType); 4510 Result.UserDefined.After.setAllToTypes(ToType); 4511 Result.UserDefined.ConversionFunction = 0; 4512 } 4513 return Result; 4514 } 4515 4516 // C++11 [over.ics.list]p5: 4517 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4518 if (ToType->isReferenceType()) { 4519 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4520 // mention initializer lists in any way. So we go by what list- 4521 // initialization would do and try to extrapolate from that. 4522 4523 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4524 4525 // If the initializer list has a single element that is reference-related 4526 // to the parameter type, we initialize the reference from that. 4527 if (From->getNumInits() == 1) { 4528 Expr *Init = From->getInit(0); 4529 4530 QualType T2 = Init->getType(); 4531 4532 // If the initializer is the address of an overloaded function, try 4533 // to resolve the overloaded function. If all goes well, T2 is the 4534 // type of the resulting function. 4535 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4536 DeclAccessPair Found; 4537 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4538 Init, ToType, false, Found)) 4539 T2 = Fn->getType(); 4540 } 4541 4542 // Compute some basic properties of the types and the initializer. 4543 bool dummy1 = false; 4544 bool dummy2 = false; 4545 bool dummy3 = false; 4546 Sema::ReferenceCompareResult RefRelationship 4547 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4548 dummy2, dummy3); 4549 4550 if (RefRelationship >= Sema::Ref_Related) 4551 return TryReferenceInit(S, Init, ToType, 4552 /*FIXME:*/From->getLocStart(), 4553 SuppressUserConversions, 4554 /*AllowExplicit=*/false); 4555 } 4556 4557 // Otherwise, we bind the reference to a temporary created from the 4558 // initializer list. 4559 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4560 InOverloadResolution, 4561 AllowObjCWritebackConversion); 4562 if (Result.isFailure()) 4563 return Result; 4564 assert(!Result.isEllipsis() && 4565 "Sub-initialization cannot result in ellipsis conversion."); 4566 4567 // Can we even bind to a temporary? 4568 if (ToType->isRValueReferenceType() || 4569 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4570 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4571 Result.UserDefined.After; 4572 SCS.ReferenceBinding = true; 4573 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4574 SCS.BindsToRvalue = true; 4575 SCS.BindsToFunctionLvalue = false; 4576 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4577 SCS.ObjCLifetimeConversionBinding = false; 4578 } else 4579 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4580 From, ToType); 4581 return Result; 4582 } 4583 4584 // C++11 [over.ics.list]p6: 4585 // Otherwise, if the parameter type is not a class: 4586 if (!ToType->isRecordType()) { 4587 // - if the initializer list has one element, the implicit conversion 4588 // sequence is the one required to convert the element to the 4589 // parameter type. 4590 unsigned NumInits = From->getNumInits(); 4591 if (NumInits == 1) 4592 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4593 SuppressUserConversions, 4594 InOverloadResolution, 4595 AllowObjCWritebackConversion); 4596 // - if the initializer list has no elements, the implicit conversion 4597 // sequence is the identity conversion. 4598 else if (NumInits == 0) { 4599 Result.setStandard(); 4600 Result.Standard.setAsIdentityConversion(); 4601 Result.Standard.setFromType(ToType); 4602 Result.Standard.setAllToTypes(ToType); 4603 } 4604 Result.setListInitializationSequence(); 4605 return Result; 4606 } 4607 4608 // C++11 [over.ics.list]p7: 4609 // In all cases other than those enumerated above, no conversion is possible 4610 return Result; 4611 } 4612 4613 /// TryCopyInitialization - Try to copy-initialize a value of type 4614 /// ToType from the expression From. Return the implicit conversion 4615 /// sequence required to pass this argument, which may be a bad 4616 /// conversion sequence (meaning that the argument cannot be passed to 4617 /// a parameter of this type). If @p SuppressUserConversions, then we 4618 /// do not permit any user-defined conversion sequences. 4619 static ImplicitConversionSequence 4620 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4621 bool SuppressUserConversions, 4622 bool InOverloadResolution, 4623 bool AllowObjCWritebackConversion, 4624 bool AllowExplicit) { 4625 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4626 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4627 InOverloadResolution,AllowObjCWritebackConversion); 4628 4629 if (ToType->isReferenceType()) 4630 return TryReferenceInit(S, From, ToType, 4631 /*FIXME:*/From->getLocStart(), 4632 SuppressUserConversions, 4633 AllowExplicit); 4634 4635 return TryImplicitConversion(S, From, ToType, 4636 SuppressUserConversions, 4637 /*AllowExplicit=*/false, 4638 InOverloadResolution, 4639 /*CStyle=*/false, 4640 AllowObjCWritebackConversion); 4641 } 4642 4643 static bool TryCopyInitialization(const CanQualType FromQTy, 4644 const CanQualType ToQTy, 4645 Sema &S, 4646 SourceLocation Loc, 4647 ExprValueKind FromVK) { 4648 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4649 ImplicitConversionSequence ICS = 4650 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4651 4652 return !ICS.isBad(); 4653 } 4654 4655 /// TryObjectArgumentInitialization - Try to initialize the object 4656 /// parameter of the given member function (@c Method) from the 4657 /// expression @p From. 4658 static ImplicitConversionSequence 4659 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4660 Expr::Classification FromClassification, 4661 CXXMethodDecl *Method, 4662 CXXRecordDecl *ActingContext) { 4663 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4664 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4665 // const volatile object. 4666 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4667 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4668 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4669 4670 // Set up the conversion sequence as a "bad" conversion, to allow us 4671 // to exit early. 4672 ImplicitConversionSequence ICS; 4673 4674 // We need to have an object of class type. 4675 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4676 FromType = PT->getPointeeType(); 4677 4678 // When we had a pointer, it's implicitly dereferenced, so we 4679 // better have an lvalue. 4680 assert(FromClassification.isLValue()); 4681 } 4682 4683 assert(FromType->isRecordType()); 4684 4685 // C++0x [over.match.funcs]p4: 4686 // For non-static member functions, the type of the implicit object 4687 // parameter is 4688 // 4689 // - "lvalue reference to cv X" for functions declared without a 4690 // ref-qualifier or with the & ref-qualifier 4691 // - "rvalue reference to cv X" for functions declared with the && 4692 // ref-qualifier 4693 // 4694 // where X is the class of which the function is a member and cv is the 4695 // cv-qualification on the member function declaration. 4696 // 4697 // However, when finding an implicit conversion sequence for the argument, we 4698 // are not allowed to create temporaries or perform user-defined conversions 4699 // (C++ [over.match.funcs]p5). We perform a simplified version of 4700 // reference binding here, that allows class rvalues to bind to 4701 // non-constant references. 4702 4703 // First check the qualifiers. 4704 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4705 if (ImplicitParamType.getCVRQualifiers() 4706 != FromTypeCanon.getLocalCVRQualifiers() && 4707 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4708 ICS.setBad(BadConversionSequence::bad_qualifiers, 4709 FromType, ImplicitParamType); 4710 return ICS; 4711 } 4712 4713 // Check that we have either the same type or a derived type. It 4714 // affects the conversion rank. 4715 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4716 ImplicitConversionKind SecondKind; 4717 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4718 SecondKind = ICK_Identity; 4719 } else if (S.IsDerivedFrom(FromType, ClassType)) 4720 SecondKind = ICK_Derived_To_Base; 4721 else { 4722 ICS.setBad(BadConversionSequence::unrelated_class, 4723 FromType, ImplicitParamType); 4724 return ICS; 4725 } 4726 4727 // Check the ref-qualifier. 4728 switch (Method->getRefQualifier()) { 4729 case RQ_None: 4730 // Do nothing; we don't care about lvalueness or rvalueness. 4731 break; 4732 4733 case RQ_LValue: 4734 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4735 // non-const lvalue reference cannot bind to an rvalue 4736 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4737 ImplicitParamType); 4738 return ICS; 4739 } 4740 break; 4741 4742 case RQ_RValue: 4743 if (!FromClassification.isRValue()) { 4744 // rvalue reference cannot bind to an lvalue 4745 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4746 ImplicitParamType); 4747 return ICS; 4748 } 4749 break; 4750 } 4751 4752 // Success. Mark this as a reference binding. 4753 ICS.setStandard(); 4754 ICS.Standard.setAsIdentityConversion(); 4755 ICS.Standard.Second = SecondKind; 4756 ICS.Standard.setFromType(FromType); 4757 ICS.Standard.setAllToTypes(ImplicitParamType); 4758 ICS.Standard.ReferenceBinding = true; 4759 ICS.Standard.DirectBinding = true; 4760 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4761 ICS.Standard.BindsToFunctionLvalue = false; 4762 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4763 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4764 = (Method->getRefQualifier() == RQ_None); 4765 return ICS; 4766 } 4767 4768 /// PerformObjectArgumentInitialization - Perform initialization of 4769 /// the implicit object parameter for the given Method with the given 4770 /// expression. 4771 ExprResult 4772 Sema::PerformObjectArgumentInitialization(Expr *From, 4773 NestedNameSpecifier *Qualifier, 4774 NamedDecl *FoundDecl, 4775 CXXMethodDecl *Method) { 4776 QualType FromRecordType, DestType; 4777 QualType ImplicitParamRecordType = 4778 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4779 4780 Expr::Classification FromClassification; 4781 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4782 FromRecordType = PT->getPointeeType(); 4783 DestType = Method->getThisType(Context); 4784 FromClassification = Expr::Classification::makeSimpleLValue(); 4785 } else { 4786 FromRecordType = From->getType(); 4787 DestType = ImplicitParamRecordType; 4788 FromClassification = From->Classify(Context); 4789 } 4790 4791 // Note that we always use the true parent context when performing 4792 // the actual argument initialization. 4793 ImplicitConversionSequence ICS 4794 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4795 Method, Method->getParent()); 4796 if (ICS.isBad()) { 4797 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4798 Qualifiers FromQs = FromRecordType.getQualifiers(); 4799 Qualifiers ToQs = DestType.getQualifiers(); 4800 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4801 if (CVR) { 4802 Diag(From->getLocStart(), 4803 diag::err_member_function_call_bad_cvr) 4804 << Method->getDeclName() << FromRecordType << (CVR - 1) 4805 << From->getSourceRange(); 4806 Diag(Method->getLocation(), diag::note_previous_decl) 4807 << Method->getDeclName(); 4808 return ExprError(); 4809 } 4810 } 4811 4812 return Diag(From->getLocStart(), 4813 diag::err_implicit_object_parameter_init) 4814 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4815 } 4816 4817 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4818 ExprResult FromRes = 4819 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4820 if (FromRes.isInvalid()) 4821 return ExprError(); 4822 From = FromRes.take(); 4823 } 4824 4825 if (!Context.hasSameType(From->getType(), DestType)) 4826 From = ImpCastExprToType(From, DestType, CK_NoOp, 4827 From->getValueKind()).take(); 4828 return Owned(From); 4829 } 4830 4831 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4832 /// expression From to bool (C++0x [conv]p3). 4833 static ImplicitConversionSequence 4834 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4835 // FIXME: This is pretty broken. 4836 return TryImplicitConversion(S, From, S.Context.BoolTy, 4837 // FIXME: Are these flags correct? 4838 /*SuppressUserConversions=*/false, 4839 /*AllowExplicit=*/true, 4840 /*InOverloadResolution=*/false, 4841 /*CStyle=*/false, 4842 /*AllowObjCWritebackConversion=*/false); 4843 } 4844 4845 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4846 /// of the expression From to bool (C++0x [conv]p3). 4847 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4848 if (checkPlaceholderForOverload(*this, From)) 4849 return ExprError(); 4850 4851 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4852 if (!ICS.isBad()) 4853 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4854 4855 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4856 return Diag(From->getLocStart(), 4857 diag::err_typecheck_bool_condition) 4858 << From->getType() << From->getSourceRange(); 4859 return ExprError(); 4860 } 4861 4862 /// Check that the specified conversion is permitted in a converted constant 4863 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4864 /// is acceptable. 4865 static bool CheckConvertedConstantConversions(Sema &S, 4866 StandardConversionSequence &SCS) { 4867 // Since we know that the target type is an integral or unscoped enumeration 4868 // type, most conversion kinds are impossible. All possible First and Third 4869 // conversions are fine. 4870 switch (SCS.Second) { 4871 case ICK_Identity: 4872 case ICK_Integral_Promotion: 4873 case ICK_Integral_Conversion: 4874 case ICK_Zero_Event_Conversion: 4875 return true; 4876 4877 case ICK_Boolean_Conversion: 4878 // Conversion from an integral or unscoped enumeration type to bool is 4879 // classified as ICK_Boolean_Conversion, but it's also an integral 4880 // conversion, so it's permitted in a converted constant expression. 4881 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4882 SCS.getToType(2)->isBooleanType(); 4883 4884 case ICK_Floating_Integral: 4885 case ICK_Complex_Real: 4886 return false; 4887 4888 case ICK_Lvalue_To_Rvalue: 4889 case ICK_Array_To_Pointer: 4890 case ICK_Function_To_Pointer: 4891 case ICK_NoReturn_Adjustment: 4892 case ICK_Qualification: 4893 case ICK_Compatible_Conversion: 4894 case ICK_Vector_Conversion: 4895 case ICK_Vector_Splat: 4896 case ICK_Derived_To_Base: 4897 case ICK_Pointer_Conversion: 4898 case ICK_Pointer_Member: 4899 case ICK_Block_Pointer_Conversion: 4900 case ICK_Writeback_Conversion: 4901 case ICK_Floating_Promotion: 4902 case ICK_Complex_Promotion: 4903 case ICK_Complex_Conversion: 4904 case ICK_Floating_Conversion: 4905 case ICK_TransparentUnionConversion: 4906 llvm_unreachable("unexpected second conversion kind"); 4907 4908 case ICK_Num_Conversion_Kinds: 4909 break; 4910 } 4911 4912 llvm_unreachable("unknown conversion kind"); 4913 } 4914 4915 /// CheckConvertedConstantExpression - Check that the expression From is a 4916 /// converted constant expression of type T, perform the conversion and produce 4917 /// the converted expression, per C++11 [expr.const]p3. 4918 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4919 llvm::APSInt &Value, 4920 CCEKind CCE) { 4921 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4922 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4923 4924 if (checkPlaceholderForOverload(*this, From)) 4925 return ExprError(); 4926 4927 // C++11 [expr.const]p3 with proposed wording fixes: 4928 // A converted constant expression of type T is a core constant expression, 4929 // implicitly converted to a prvalue of type T, where the converted 4930 // expression is a literal constant expression and the implicit conversion 4931 // sequence contains only user-defined conversions, lvalue-to-rvalue 4932 // conversions, integral promotions, and integral conversions other than 4933 // narrowing conversions. 4934 ImplicitConversionSequence ICS = 4935 TryImplicitConversion(From, T, 4936 /*SuppressUserConversions=*/false, 4937 /*AllowExplicit=*/false, 4938 /*InOverloadResolution=*/false, 4939 /*CStyle=*/false, 4940 /*AllowObjcWritebackConversion=*/false); 4941 StandardConversionSequence *SCS = 0; 4942 switch (ICS.getKind()) { 4943 case ImplicitConversionSequence::StandardConversion: 4944 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4945 return Diag(From->getLocStart(), 4946 diag::err_typecheck_converted_constant_expression_disallowed) 4947 << From->getType() << From->getSourceRange() << T; 4948 SCS = &ICS.Standard; 4949 break; 4950 case ImplicitConversionSequence::UserDefinedConversion: 4951 // We are converting from class type to an integral or enumeration type, so 4952 // the Before sequence must be trivial. 4953 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4954 return Diag(From->getLocStart(), 4955 diag::err_typecheck_converted_constant_expression_disallowed) 4956 << From->getType() << From->getSourceRange() << T; 4957 SCS = &ICS.UserDefined.After; 4958 break; 4959 case ImplicitConversionSequence::AmbiguousConversion: 4960 case ImplicitConversionSequence::BadConversion: 4961 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4962 return Diag(From->getLocStart(), 4963 diag::err_typecheck_converted_constant_expression) 4964 << From->getType() << From->getSourceRange() << T; 4965 return ExprError(); 4966 4967 case ImplicitConversionSequence::EllipsisConversion: 4968 llvm_unreachable("ellipsis conversion in converted constant expression"); 4969 } 4970 4971 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4972 if (Result.isInvalid()) 4973 return Result; 4974 4975 // Check for a narrowing implicit conversion. 4976 APValue PreNarrowingValue; 4977 QualType PreNarrowingType; 4978 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4979 PreNarrowingType)) { 4980 case NK_Variable_Narrowing: 4981 // Implicit conversion to a narrower type, and the value is not a constant 4982 // expression. We'll diagnose this in a moment. 4983 case NK_Not_Narrowing: 4984 break; 4985 4986 case NK_Constant_Narrowing: 4987 Diag(From->getLocStart(), 4988 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4989 diag::err_cce_narrowing) 4990 << CCE << /*Constant*/1 4991 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4992 break; 4993 4994 case NK_Type_Narrowing: 4995 Diag(From->getLocStart(), 4996 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4997 diag::err_cce_narrowing) 4998 << CCE << /*Constant*/0 << From->getType() << T; 4999 break; 5000 } 5001 5002 // Check the expression is a constant expression. 5003 SmallVector<PartialDiagnosticAt, 8> Notes; 5004 Expr::EvalResult Eval; 5005 Eval.Diag = &Notes; 5006 5007 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5008 // The expression can't be folded, so we can't keep it at this position in 5009 // the AST. 5010 Result = ExprError(); 5011 } else { 5012 Value = Eval.Val.getInt(); 5013 5014 if (Notes.empty()) { 5015 // It's a constant expression. 5016 return Result; 5017 } 5018 } 5019 5020 // It's not a constant expression. Produce an appropriate diagnostic. 5021 if (Notes.size() == 1 && 5022 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5023 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5024 else { 5025 Diag(From->getLocStart(), diag::err_expr_not_cce) 5026 << CCE << From->getSourceRange(); 5027 for (unsigned I = 0; I < Notes.size(); ++I) 5028 Diag(Notes[I].first, Notes[I].second); 5029 } 5030 return Result; 5031 } 5032 5033 /// dropPointerConversions - If the given standard conversion sequence 5034 /// involves any pointer conversions, remove them. This may change 5035 /// the result type of the conversion sequence. 5036 static void dropPointerConversion(StandardConversionSequence &SCS) { 5037 if (SCS.Second == ICK_Pointer_Conversion) { 5038 SCS.Second = ICK_Identity; 5039 SCS.Third = ICK_Identity; 5040 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5041 } 5042 } 5043 5044 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5045 /// convert the expression From to an Objective-C pointer type. 5046 static ImplicitConversionSequence 5047 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5048 // Do an implicit conversion to 'id'. 5049 QualType Ty = S.Context.getObjCIdType(); 5050 ImplicitConversionSequence ICS 5051 = TryImplicitConversion(S, From, Ty, 5052 // FIXME: Are these flags correct? 5053 /*SuppressUserConversions=*/false, 5054 /*AllowExplicit=*/true, 5055 /*InOverloadResolution=*/false, 5056 /*CStyle=*/false, 5057 /*AllowObjCWritebackConversion=*/false); 5058 5059 // Strip off any final conversions to 'id'. 5060 switch (ICS.getKind()) { 5061 case ImplicitConversionSequence::BadConversion: 5062 case ImplicitConversionSequence::AmbiguousConversion: 5063 case ImplicitConversionSequence::EllipsisConversion: 5064 break; 5065 5066 case ImplicitConversionSequence::UserDefinedConversion: 5067 dropPointerConversion(ICS.UserDefined.After); 5068 break; 5069 5070 case ImplicitConversionSequence::StandardConversion: 5071 dropPointerConversion(ICS.Standard); 5072 break; 5073 } 5074 5075 return ICS; 5076 } 5077 5078 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5079 /// conversion of the expression From to an Objective-C pointer type. 5080 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5081 if (checkPlaceholderForOverload(*this, From)) 5082 return ExprError(); 5083 5084 QualType Ty = Context.getObjCIdType(); 5085 ImplicitConversionSequence ICS = 5086 TryContextuallyConvertToObjCPointer(*this, From); 5087 if (!ICS.isBad()) 5088 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5089 return ExprError(); 5090 } 5091 5092 /// Determine whether the provided type is an integral type, or an enumeration 5093 /// type of a permitted flavor. 5094 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5095 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5096 : T->isIntegralOrUnscopedEnumerationType(); 5097 } 5098 5099 static ExprResult 5100 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5101 Sema::ContextualImplicitConverter &Converter, 5102 QualType T, UnresolvedSetImpl &ViableConversions) { 5103 5104 if (Converter.Suppress) 5105 return ExprError(); 5106 5107 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5108 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5109 CXXConversionDecl *Conv = 5110 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5111 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5112 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5113 } 5114 return SemaRef.Owned(From); 5115 } 5116 5117 static bool 5118 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5119 Sema::ContextualImplicitConverter &Converter, 5120 QualType T, bool HadMultipleCandidates, 5121 UnresolvedSetImpl &ExplicitConversions) { 5122 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5123 DeclAccessPair Found = ExplicitConversions[0]; 5124 CXXConversionDecl *Conversion = 5125 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5126 5127 // The user probably meant to invoke the given explicit 5128 // conversion; use it. 5129 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5130 std::string TypeStr; 5131 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5132 5133 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5134 << FixItHint::CreateInsertion(From->getLocStart(), 5135 "static_cast<" + TypeStr + ">(") 5136 << FixItHint::CreateInsertion( 5137 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5138 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5139 5140 // If we aren't in a SFINAE context, build a call to the 5141 // explicit conversion function. 5142 if (SemaRef.isSFINAEContext()) 5143 return true; 5144 5145 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5146 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5147 HadMultipleCandidates); 5148 if (Result.isInvalid()) 5149 return true; 5150 // Record usage of conversion in an implicit cast. 5151 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5152 CK_UserDefinedConversion, Result.get(), 0, 5153 Result.get()->getValueKind()); 5154 } 5155 return false; 5156 } 5157 5158 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5159 Sema::ContextualImplicitConverter &Converter, 5160 QualType T, bool HadMultipleCandidates, 5161 DeclAccessPair &Found) { 5162 CXXConversionDecl *Conversion = 5163 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5164 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5165 5166 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5167 if (!Converter.SuppressConversion) { 5168 if (SemaRef.isSFINAEContext()) 5169 return true; 5170 5171 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5172 << From->getSourceRange(); 5173 } 5174 5175 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5176 HadMultipleCandidates); 5177 if (Result.isInvalid()) 5178 return true; 5179 // Record usage of conversion in an implicit cast. 5180 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5181 CK_UserDefinedConversion, Result.get(), 0, 5182 Result.get()->getValueKind()); 5183 return false; 5184 } 5185 5186 static ExprResult finishContextualImplicitConversion( 5187 Sema &SemaRef, SourceLocation Loc, Expr *From, 5188 Sema::ContextualImplicitConverter &Converter) { 5189 if (!Converter.match(From->getType()) && !Converter.Suppress) 5190 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5191 << From->getSourceRange(); 5192 5193 return SemaRef.DefaultLvalueConversion(From); 5194 } 5195 5196 static void 5197 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5198 UnresolvedSetImpl &ViableConversions, 5199 OverloadCandidateSet &CandidateSet) { 5200 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5201 DeclAccessPair FoundDecl = ViableConversions[I]; 5202 NamedDecl *D = FoundDecl.getDecl(); 5203 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5204 if (isa<UsingShadowDecl>(D)) 5205 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5206 5207 CXXConversionDecl *Conv; 5208 FunctionTemplateDecl *ConvTemplate; 5209 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5210 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5211 else 5212 Conv = cast<CXXConversionDecl>(D); 5213 5214 if (ConvTemplate) 5215 SemaRef.AddTemplateConversionCandidate( 5216 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet); 5217 else 5218 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5219 ToType, CandidateSet); 5220 } 5221 } 5222 5223 /// \brief Attempt to convert the given expression to a type which is accepted 5224 /// by the given converter. 5225 /// 5226 /// This routine will attempt to convert an expression of class type to a 5227 /// type accepted by the specified converter. In C++11 and before, the class 5228 /// must have a single non-explicit conversion function converting to a matching 5229 /// type. In C++1y, there can be multiple such conversion functions, but only 5230 /// one target type. 5231 /// 5232 /// \param Loc The source location of the construct that requires the 5233 /// conversion. 5234 /// 5235 /// \param From The expression we're converting from. 5236 /// 5237 /// \param Converter Used to control and diagnose the conversion process. 5238 /// 5239 /// \returns The expression, converted to an integral or enumeration type if 5240 /// successful. 5241 ExprResult Sema::PerformContextualImplicitConversion( 5242 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5243 // We can't perform any more checking for type-dependent expressions. 5244 if (From->isTypeDependent()) 5245 return Owned(From); 5246 5247 // Process placeholders immediately. 5248 if (From->hasPlaceholderType()) { 5249 ExprResult result = CheckPlaceholderExpr(From); 5250 if (result.isInvalid()) 5251 return result; 5252 From = result.take(); 5253 } 5254 5255 // If the expression already has a matching type, we're golden. 5256 QualType T = From->getType(); 5257 if (Converter.match(T)) 5258 return DefaultLvalueConversion(From); 5259 5260 // FIXME: Check for missing '()' if T is a function type? 5261 5262 // We can only perform contextual implicit conversions on objects of class 5263 // type. 5264 const RecordType *RecordTy = T->getAs<RecordType>(); 5265 if (!RecordTy || !getLangOpts().CPlusPlus) { 5266 if (!Converter.Suppress) 5267 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5268 return Owned(From); 5269 } 5270 5271 // We must have a complete class type. 5272 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5273 ContextualImplicitConverter &Converter; 5274 Expr *From; 5275 5276 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5277 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5278 5279 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5280 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5281 } 5282 } IncompleteDiagnoser(Converter, From); 5283 5284 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5285 return Owned(From); 5286 5287 // Look for a conversion to an integral or enumeration type. 5288 UnresolvedSet<4> 5289 ViableConversions; // These are *potentially* viable in C++1y. 5290 UnresolvedSet<4> ExplicitConversions; 5291 std::pair<CXXRecordDecl::conversion_iterator, 5292 CXXRecordDecl::conversion_iterator> Conversions = 5293 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5294 5295 bool HadMultipleCandidates = 5296 (std::distance(Conversions.first, Conversions.second) > 1); 5297 5298 // To check that there is only one target type, in C++1y: 5299 QualType ToType; 5300 bool HasUniqueTargetType = true; 5301 5302 // Collect explicit or viable (potentially in C++1y) conversions. 5303 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5304 E = Conversions.second; 5305 I != E; ++I) { 5306 NamedDecl *D = (*I)->getUnderlyingDecl(); 5307 CXXConversionDecl *Conversion; 5308 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5309 if (ConvTemplate) { 5310 if (getLangOpts().CPlusPlus1y) 5311 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5312 else 5313 continue; // C++11 does not consider conversion operator templates(?). 5314 } else 5315 Conversion = cast<CXXConversionDecl>(D); 5316 5317 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5318 "Conversion operator templates are considered potentially " 5319 "viable in C++1y"); 5320 5321 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5322 if (Converter.match(CurToType) || ConvTemplate) { 5323 5324 if (Conversion->isExplicit()) { 5325 // FIXME: For C++1y, do we need this restriction? 5326 // cf. diagnoseNoViableConversion() 5327 if (!ConvTemplate) 5328 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5329 } else { 5330 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5331 if (ToType.isNull()) 5332 ToType = CurToType.getUnqualifiedType(); 5333 else if (HasUniqueTargetType && 5334 (CurToType.getUnqualifiedType() != ToType)) 5335 HasUniqueTargetType = false; 5336 } 5337 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5338 } 5339 } 5340 } 5341 5342 if (getLangOpts().CPlusPlus1y) { 5343 // C++1y [conv]p6: 5344 // ... An expression e of class type E appearing in such a context 5345 // is said to be contextually implicitly converted to a specified 5346 // type T and is well-formed if and only if e can be implicitly 5347 // converted to a type T that is determined as follows: E is searched 5348 // for conversion functions whose return type is cv T or reference to 5349 // cv T such that T is allowed by the context. There shall be 5350 // exactly one such T. 5351 5352 // If no unique T is found: 5353 if (ToType.isNull()) { 5354 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5355 HadMultipleCandidates, 5356 ExplicitConversions)) 5357 return ExprError(); 5358 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5359 } 5360 5361 // If more than one unique Ts are found: 5362 if (!HasUniqueTargetType) 5363 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5364 ViableConversions); 5365 5366 // If one unique T is found: 5367 // First, build a candidate set from the previously recorded 5368 // potentially viable conversions. 5369 OverloadCandidateSet CandidateSet(Loc); 5370 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5371 CandidateSet); 5372 5373 // Then, perform overload resolution over the candidate set. 5374 OverloadCandidateSet::iterator Best; 5375 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5376 case OR_Success: { 5377 // Apply this conversion. 5378 DeclAccessPair Found = 5379 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5380 if (recordConversion(*this, Loc, From, Converter, T, 5381 HadMultipleCandidates, Found)) 5382 return ExprError(); 5383 break; 5384 } 5385 case OR_Ambiguous: 5386 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5387 ViableConversions); 5388 case OR_No_Viable_Function: 5389 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5390 HadMultipleCandidates, 5391 ExplicitConversions)) 5392 return ExprError(); 5393 // fall through 'OR_Deleted' case. 5394 case OR_Deleted: 5395 // We'll complain below about a non-integral condition type. 5396 break; 5397 } 5398 } else { 5399 switch (ViableConversions.size()) { 5400 case 0: { 5401 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5402 HadMultipleCandidates, 5403 ExplicitConversions)) 5404 return ExprError(); 5405 5406 // We'll complain below about a non-integral condition type. 5407 break; 5408 } 5409 case 1: { 5410 // Apply this conversion. 5411 DeclAccessPair Found = ViableConversions[0]; 5412 if (recordConversion(*this, Loc, From, Converter, T, 5413 HadMultipleCandidates, Found)) 5414 return ExprError(); 5415 break; 5416 } 5417 default: 5418 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5419 ViableConversions); 5420 } 5421 } 5422 5423 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5424 } 5425 5426 /// AddOverloadCandidate - Adds the given function to the set of 5427 /// candidate functions, using the given function call arguments. If 5428 /// @p SuppressUserConversions, then don't allow user-defined 5429 /// conversions via constructors or conversion operators. 5430 /// 5431 /// \param PartialOverloading true if we are performing "partial" overloading 5432 /// based on an incomplete set of function arguments. This feature is used by 5433 /// code completion. 5434 void 5435 Sema::AddOverloadCandidate(FunctionDecl *Function, 5436 DeclAccessPair FoundDecl, 5437 ArrayRef<Expr *> Args, 5438 OverloadCandidateSet& CandidateSet, 5439 bool SuppressUserConversions, 5440 bool PartialOverloading, 5441 bool AllowExplicit) { 5442 const FunctionProtoType* Proto 5443 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5444 assert(Proto && "Functions without a prototype cannot be overloaded"); 5445 assert(!Function->getDescribedFunctionTemplate() && 5446 "Use AddTemplateOverloadCandidate for function templates"); 5447 5448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5449 if (!isa<CXXConstructorDecl>(Method)) { 5450 // If we get here, it's because we're calling a member function 5451 // that is named without a member access expression (e.g., 5452 // "this->f") that was either written explicitly or created 5453 // implicitly. This can happen with a qualified call to a member 5454 // function, e.g., X::f(). We use an empty type for the implied 5455 // object argument (C++ [over.call.func]p3), and the acting context 5456 // is irrelevant. 5457 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5458 QualType(), Expr::Classification::makeSimpleLValue(), 5459 Args, CandidateSet, SuppressUserConversions); 5460 return; 5461 } 5462 // We treat a constructor like a non-member function, since its object 5463 // argument doesn't participate in overload resolution. 5464 } 5465 5466 if (!CandidateSet.isNewCandidate(Function)) 5467 return; 5468 5469 // Overload resolution is always an unevaluated context. 5470 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5471 5472 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5473 // C++ [class.copy]p3: 5474 // A member function template is never instantiated to perform the copy 5475 // of a class object to an object of its class type. 5476 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5477 if (Args.size() == 1 && 5478 Constructor->isSpecializationCopyingObject() && 5479 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5480 IsDerivedFrom(Args[0]->getType(), ClassType))) 5481 return; 5482 } 5483 5484 // Add this candidate 5485 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5486 Candidate.FoundDecl = FoundDecl; 5487 Candidate.Function = Function; 5488 Candidate.Viable = true; 5489 Candidate.IsSurrogate = false; 5490 Candidate.IgnoreObjectArgument = false; 5491 Candidate.ExplicitCallArguments = Args.size(); 5492 5493 unsigned NumArgsInProto = Proto->getNumArgs(); 5494 5495 // (C++ 13.3.2p2): A candidate function having fewer than m 5496 // parameters is viable only if it has an ellipsis in its parameter 5497 // list (8.3.5). 5498 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5499 !Proto->isVariadic()) { 5500 Candidate.Viable = false; 5501 Candidate.FailureKind = ovl_fail_too_many_arguments; 5502 return; 5503 } 5504 5505 // (C++ 13.3.2p2): A candidate function having more than m parameters 5506 // is viable only if the (m+1)st parameter has a default argument 5507 // (8.3.6). For the purposes of overload resolution, the 5508 // parameter list is truncated on the right, so that there are 5509 // exactly m parameters. 5510 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5511 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5512 // Not enough arguments. 5513 Candidate.Viable = false; 5514 Candidate.FailureKind = ovl_fail_too_few_arguments; 5515 return; 5516 } 5517 5518 // (CUDA B.1): Check for invalid calls between targets. 5519 if (getLangOpts().CUDA) 5520 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5521 if (CheckCUDATarget(Caller, Function)) { 5522 Candidate.Viable = false; 5523 Candidate.FailureKind = ovl_fail_bad_target; 5524 return; 5525 } 5526 5527 // Determine the implicit conversion sequences for each of the 5528 // arguments. 5529 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5530 if (ArgIdx < NumArgsInProto) { 5531 // (C++ 13.3.2p3): for F to be a viable function, there shall 5532 // exist for each argument an implicit conversion sequence 5533 // (13.3.3.1) that converts that argument to the corresponding 5534 // parameter of F. 5535 QualType ParamType = Proto->getArgType(ArgIdx); 5536 Candidate.Conversions[ArgIdx] 5537 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5538 SuppressUserConversions, 5539 /*InOverloadResolution=*/true, 5540 /*AllowObjCWritebackConversion=*/ 5541 getLangOpts().ObjCAutoRefCount, 5542 AllowExplicit); 5543 if (Candidate.Conversions[ArgIdx].isBad()) { 5544 Candidate.Viable = false; 5545 Candidate.FailureKind = ovl_fail_bad_conversion; 5546 break; 5547 } 5548 } else { 5549 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5550 // argument for which there is no corresponding parameter is 5551 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5552 Candidate.Conversions[ArgIdx].setEllipsis(); 5553 } 5554 } 5555 } 5556 5557 /// \brief Add all of the function declarations in the given function set to 5558 /// the overload canddiate set. 5559 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5560 ArrayRef<Expr *> Args, 5561 OverloadCandidateSet& CandidateSet, 5562 bool SuppressUserConversions, 5563 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5564 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5565 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5567 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5568 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5569 cast<CXXMethodDecl>(FD)->getParent(), 5570 Args[0]->getType(), Args[0]->Classify(Context), 5571 Args.slice(1), CandidateSet, 5572 SuppressUserConversions); 5573 else 5574 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5575 SuppressUserConversions); 5576 } else { 5577 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5578 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5579 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5580 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5581 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5582 ExplicitTemplateArgs, 5583 Args[0]->getType(), 5584 Args[0]->Classify(Context), Args.slice(1), 5585 CandidateSet, SuppressUserConversions); 5586 else 5587 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5588 ExplicitTemplateArgs, Args, 5589 CandidateSet, SuppressUserConversions); 5590 } 5591 } 5592 } 5593 5594 /// AddMethodCandidate - Adds a named decl (which is some kind of 5595 /// method) as a method candidate to the given overload set. 5596 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5597 QualType ObjectType, 5598 Expr::Classification ObjectClassification, 5599 ArrayRef<Expr *> Args, 5600 OverloadCandidateSet& CandidateSet, 5601 bool SuppressUserConversions) { 5602 NamedDecl *Decl = FoundDecl.getDecl(); 5603 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5604 5605 if (isa<UsingShadowDecl>(Decl)) 5606 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5607 5608 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5609 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5610 "Expected a member function template"); 5611 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5612 /*ExplicitArgs*/ 0, 5613 ObjectType, ObjectClassification, 5614 Args, CandidateSet, 5615 SuppressUserConversions); 5616 } else { 5617 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5618 ObjectType, ObjectClassification, 5619 Args, 5620 CandidateSet, SuppressUserConversions); 5621 } 5622 } 5623 5624 /// AddMethodCandidate - Adds the given C++ member function to the set 5625 /// of candidate functions, using the given function call arguments 5626 /// and the object argument (@c Object). For example, in a call 5627 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5628 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5629 /// allow user-defined conversions via constructors or conversion 5630 /// operators. 5631 void 5632 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5633 CXXRecordDecl *ActingContext, QualType ObjectType, 5634 Expr::Classification ObjectClassification, 5635 ArrayRef<Expr *> Args, 5636 OverloadCandidateSet& CandidateSet, 5637 bool SuppressUserConversions) { 5638 const FunctionProtoType* Proto 5639 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5640 assert(Proto && "Methods without a prototype cannot be overloaded"); 5641 assert(!isa<CXXConstructorDecl>(Method) && 5642 "Use AddOverloadCandidate for constructors"); 5643 5644 if (!CandidateSet.isNewCandidate(Method)) 5645 return; 5646 5647 // Overload resolution is always an unevaluated context. 5648 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5649 5650 // Add this candidate 5651 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5652 Candidate.FoundDecl = FoundDecl; 5653 Candidate.Function = Method; 5654 Candidate.IsSurrogate = false; 5655 Candidate.IgnoreObjectArgument = false; 5656 Candidate.ExplicitCallArguments = Args.size(); 5657 5658 unsigned NumArgsInProto = Proto->getNumArgs(); 5659 5660 // (C++ 13.3.2p2): A candidate function having fewer than m 5661 // parameters is viable only if it has an ellipsis in its parameter 5662 // list (8.3.5). 5663 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5664 Candidate.Viable = false; 5665 Candidate.FailureKind = ovl_fail_too_many_arguments; 5666 return; 5667 } 5668 5669 // (C++ 13.3.2p2): A candidate function having more than m parameters 5670 // is viable only if the (m+1)st parameter has a default argument 5671 // (8.3.6). For the purposes of overload resolution, the 5672 // parameter list is truncated on the right, so that there are 5673 // exactly m parameters. 5674 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5675 if (Args.size() < MinRequiredArgs) { 5676 // Not enough arguments. 5677 Candidate.Viable = false; 5678 Candidate.FailureKind = ovl_fail_too_few_arguments; 5679 return; 5680 } 5681 5682 Candidate.Viable = true; 5683 5684 if (Method->isStatic() || ObjectType.isNull()) 5685 // The implicit object argument is ignored. 5686 Candidate.IgnoreObjectArgument = true; 5687 else { 5688 // Determine the implicit conversion sequence for the object 5689 // parameter. 5690 Candidate.Conversions[0] 5691 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5692 Method, ActingContext); 5693 if (Candidate.Conversions[0].isBad()) { 5694 Candidate.Viable = false; 5695 Candidate.FailureKind = ovl_fail_bad_conversion; 5696 return; 5697 } 5698 } 5699 5700 // Determine the implicit conversion sequences for each of the 5701 // arguments. 5702 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5703 if (ArgIdx < NumArgsInProto) { 5704 // (C++ 13.3.2p3): for F to be a viable function, there shall 5705 // exist for each argument an implicit conversion sequence 5706 // (13.3.3.1) that converts that argument to the corresponding 5707 // parameter of F. 5708 QualType ParamType = Proto->getArgType(ArgIdx); 5709 Candidate.Conversions[ArgIdx + 1] 5710 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5711 SuppressUserConversions, 5712 /*InOverloadResolution=*/true, 5713 /*AllowObjCWritebackConversion=*/ 5714 getLangOpts().ObjCAutoRefCount); 5715 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5716 Candidate.Viable = false; 5717 Candidate.FailureKind = ovl_fail_bad_conversion; 5718 break; 5719 } 5720 } else { 5721 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5722 // argument for which there is no corresponding parameter is 5723 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5724 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5725 } 5726 } 5727 } 5728 5729 /// \brief Add a C++ member function template as a candidate to the candidate 5730 /// set, using template argument deduction to produce an appropriate member 5731 /// function template specialization. 5732 void 5733 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5734 DeclAccessPair FoundDecl, 5735 CXXRecordDecl *ActingContext, 5736 TemplateArgumentListInfo *ExplicitTemplateArgs, 5737 QualType ObjectType, 5738 Expr::Classification ObjectClassification, 5739 ArrayRef<Expr *> Args, 5740 OverloadCandidateSet& CandidateSet, 5741 bool SuppressUserConversions) { 5742 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5743 return; 5744 5745 // C++ [over.match.funcs]p7: 5746 // In each case where a candidate is a function template, candidate 5747 // function template specializations are generated using template argument 5748 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5749 // candidate functions in the usual way.113) A given name can refer to one 5750 // or more function templates and also to a set of overloaded non-template 5751 // functions. In such a case, the candidate functions generated from each 5752 // function template are combined with the set of non-template candidate 5753 // functions. 5754 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5755 FunctionDecl *Specialization = 0; 5756 if (TemplateDeductionResult Result 5757 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5758 Specialization, Info)) { 5759 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5760 Candidate.FoundDecl = FoundDecl; 5761 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5762 Candidate.Viable = false; 5763 Candidate.FailureKind = ovl_fail_bad_deduction; 5764 Candidate.IsSurrogate = false; 5765 Candidate.IgnoreObjectArgument = false; 5766 Candidate.ExplicitCallArguments = Args.size(); 5767 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5768 Info); 5769 return; 5770 } 5771 5772 // Add the function template specialization produced by template argument 5773 // deduction as a candidate. 5774 assert(Specialization && "Missing member function template specialization?"); 5775 assert(isa<CXXMethodDecl>(Specialization) && 5776 "Specialization is not a member function?"); 5777 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5778 ActingContext, ObjectType, ObjectClassification, Args, 5779 CandidateSet, SuppressUserConversions); 5780 } 5781 5782 /// \brief Add a C++ function template specialization as a candidate 5783 /// in the candidate set, using template argument deduction to produce 5784 /// an appropriate function template specialization. 5785 void 5786 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5787 DeclAccessPair FoundDecl, 5788 TemplateArgumentListInfo *ExplicitTemplateArgs, 5789 ArrayRef<Expr *> Args, 5790 OverloadCandidateSet& CandidateSet, 5791 bool SuppressUserConversions) { 5792 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5793 return; 5794 5795 // C++ [over.match.funcs]p7: 5796 // In each case where a candidate is a function template, candidate 5797 // function template specializations are generated using template argument 5798 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5799 // candidate functions in the usual way.113) A given name can refer to one 5800 // or more function templates and also to a set of overloaded non-template 5801 // functions. In such a case, the candidate functions generated from each 5802 // function template are combined with the set of non-template candidate 5803 // functions. 5804 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5805 FunctionDecl *Specialization = 0; 5806 if (TemplateDeductionResult Result 5807 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5808 Specialization, Info)) { 5809 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5810 Candidate.FoundDecl = FoundDecl; 5811 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5812 Candidate.Viable = false; 5813 Candidate.FailureKind = ovl_fail_bad_deduction; 5814 Candidate.IsSurrogate = false; 5815 Candidate.IgnoreObjectArgument = false; 5816 Candidate.ExplicitCallArguments = Args.size(); 5817 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5818 Info); 5819 return; 5820 } 5821 5822 // Add the function template specialization produced by template argument 5823 // deduction as a candidate. 5824 assert(Specialization && "Missing function template specialization?"); 5825 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5826 SuppressUserConversions); 5827 } 5828 5829 /// AddConversionCandidate - Add a C++ conversion function as a 5830 /// candidate in the candidate set (C++ [over.match.conv], 5831 /// C++ [over.match.copy]). From is the expression we're converting from, 5832 /// and ToType is the type that we're eventually trying to convert to 5833 /// (which may or may not be the same type as the type that the 5834 /// conversion function produces). 5835 void 5836 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5837 DeclAccessPair FoundDecl, 5838 CXXRecordDecl *ActingContext, 5839 Expr *From, QualType ToType, 5840 OverloadCandidateSet& CandidateSet) { 5841 assert(!Conversion->getDescribedFunctionTemplate() && 5842 "Conversion function templates use AddTemplateConversionCandidate"); 5843 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5844 if (!CandidateSet.isNewCandidate(Conversion)) 5845 return; 5846 5847 // If the conversion function has an undeduced return type, trigger its 5848 // deduction now. 5849 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5850 if (DeduceReturnType(Conversion, From->getExprLoc())) 5851 return; 5852 ConvType = Conversion->getConversionType().getNonReferenceType(); 5853 } 5854 5855 // Overload resolution is always an unevaluated context. 5856 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5857 5858 // Add this candidate 5859 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5860 Candidate.FoundDecl = FoundDecl; 5861 Candidate.Function = Conversion; 5862 Candidate.IsSurrogate = false; 5863 Candidate.IgnoreObjectArgument = false; 5864 Candidate.FinalConversion.setAsIdentityConversion(); 5865 Candidate.FinalConversion.setFromType(ConvType); 5866 Candidate.FinalConversion.setAllToTypes(ToType); 5867 Candidate.Viable = true; 5868 Candidate.ExplicitCallArguments = 1; 5869 5870 // C++ [over.match.funcs]p4: 5871 // For conversion functions, the function is considered to be a member of 5872 // the class of the implicit implied object argument for the purpose of 5873 // defining the type of the implicit object parameter. 5874 // 5875 // Determine the implicit conversion sequence for the implicit 5876 // object parameter. 5877 QualType ImplicitParamType = From->getType(); 5878 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5879 ImplicitParamType = FromPtrType->getPointeeType(); 5880 CXXRecordDecl *ConversionContext 5881 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5882 5883 Candidate.Conversions[0] 5884 = TryObjectArgumentInitialization(*this, From->getType(), 5885 From->Classify(Context), 5886 Conversion, ConversionContext); 5887 5888 if (Candidate.Conversions[0].isBad()) { 5889 Candidate.Viable = false; 5890 Candidate.FailureKind = ovl_fail_bad_conversion; 5891 return; 5892 } 5893 5894 // We won't go through a user-define type conversion function to convert a 5895 // derived to base as such conversions are given Conversion Rank. They only 5896 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5897 QualType FromCanon 5898 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5899 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5900 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5901 Candidate.Viable = false; 5902 Candidate.FailureKind = ovl_fail_trivial_conversion; 5903 return; 5904 } 5905 5906 // To determine what the conversion from the result of calling the 5907 // conversion function to the type we're eventually trying to 5908 // convert to (ToType), we need to synthesize a call to the 5909 // conversion function and attempt copy initialization from it. This 5910 // makes sure that we get the right semantics with respect to 5911 // lvalues/rvalues and the type. Fortunately, we can allocate this 5912 // call on the stack and we don't need its arguments to be 5913 // well-formed. 5914 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5915 VK_LValue, From->getLocStart()); 5916 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5917 Context.getPointerType(Conversion->getType()), 5918 CK_FunctionToPointerDecay, 5919 &ConversionRef, VK_RValue); 5920 5921 QualType ConversionType = Conversion->getConversionType(); 5922 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5923 Candidate.Viable = false; 5924 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5925 return; 5926 } 5927 5928 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5929 5930 // Note that it is safe to allocate CallExpr on the stack here because 5931 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5932 // allocator). 5933 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5934 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 5935 From->getLocStart()); 5936 ImplicitConversionSequence ICS = 5937 TryCopyInitialization(*this, &Call, ToType, 5938 /*SuppressUserConversions=*/true, 5939 /*InOverloadResolution=*/false, 5940 /*AllowObjCWritebackConversion=*/false); 5941 5942 switch (ICS.getKind()) { 5943 case ImplicitConversionSequence::StandardConversion: 5944 Candidate.FinalConversion = ICS.Standard; 5945 5946 // C++ [over.ics.user]p3: 5947 // If the user-defined conversion is specified by a specialization of a 5948 // conversion function template, the second standard conversion sequence 5949 // shall have exact match rank. 5950 if (Conversion->getPrimaryTemplate() && 5951 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5952 Candidate.Viable = false; 5953 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5954 } 5955 5956 // C++0x [dcl.init.ref]p5: 5957 // In the second case, if the reference is an rvalue reference and 5958 // the second standard conversion sequence of the user-defined 5959 // conversion sequence includes an lvalue-to-rvalue conversion, the 5960 // program is ill-formed. 5961 if (ToType->isRValueReferenceType() && 5962 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5963 Candidate.Viable = false; 5964 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5965 } 5966 break; 5967 5968 case ImplicitConversionSequence::BadConversion: 5969 Candidate.Viable = false; 5970 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5971 break; 5972 5973 default: 5974 llvm_unreachable( 5975 "Can only end up with a standard conversion sequence or failure"); 5976 } 5977 } 5978 5979 /// \brief Adds a conversion function template specialization 5980 /// candidate to the overload set, using template argument deduction 5981 /// to deduce the template arguments of the conversion function 5982 /// template from the type that we are converting to (C++ 5983 /// [temp.deduct.conv]). 5984 void 5985 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5986 DeclAccessPair FoundDecl, 5987 CXXRecordDecl *ActingDC, 5988 Expr *From, QualType ToType, 5989 OverloadCandidateSet &CandidateSet) { 5990 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5991 "Only conversion function templates permitted here"); 5992 5993 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5994 return; 5995 5996 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5997 CXXConversionDecl *Specialization = 0; 5998 if (TemplateDeductionResult Result 5999 = DeduceTemplateArguments(FunctionTemplate, ToType, 6000 Specialization, Info)) { 6001 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6002 Candidate.FoundDecl = FoundDecl; 6003 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6004 Candidate.Viable = false; 6005 Candidate.FailureKind = ovl_fail_bad_deduction; 6006 Candidate.IsSurrogate = false; 6007 Candidate.IgnoreObjectArgument = false; 6008 Candidate.ExplicitCallArguments = 1; 6009 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6010 Info); 6011 return; 6012 } 6013 6014 // Add the conversion function template specialization produced by 6015 // template argument deduction as a candidate. 6016 assert(Specialization && "Missing function template specialization?"); 6017 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6018 CandidateSet); 6019 } 6020 6021 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6022 /// converts the given @c Object to a function pointer via the 6023 /// conversion function @c Conversion, and then attempts to call it 6024 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6025 /// the type of function that we'll eventually be calling. 6026 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6027 DeclAccessPair FoundDecl, 6028 CXXRecordDecl *ActingContext, 6029 const FunctionProtoType *Proto, 6030 Expr *Object, 6031 ArrayRef<Expr *> Args, 6032 OverloadCandidateSet& CandidateSet) { 6033 if (!CandidateSet.isNewCandidate(Conversion)) 6034 return; 6035 6036 // Overload resolution is always an unevaluated context. 6037 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6038 6039 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6040 Candidate.FoundDecl = FoundDecl; 6041 Candidate.Function = 0; 6042 Candidate.Surrogate = Conversion; 6043 Candidate.Viable = true; 6044 Candidate.IsSurrogate = true; 6045 Candidate.IgnoreObjectArgument = false; 6046 Candidate.ExplicitCallArguments = Args.size(); 6047 6048 // Determine the implicit conversion sequence for the implicit 6049 // object parameter. 6050 ImplicitConversionSequence ObjectInit 6051 = TryObjectArgumentInitialization(*this, Object->getType(), 6052 Object->Classify(Context), 6053 Conversion, ActingContext); 6054 if (ObjectInit.isBad()) { 6055 Candidate.Viable = false; 6056 Candidate.FailureKind = ovl_fail_bad_conversion; 6057 Candidate.Conversions[0] = ObjectInit; 6058 return; 6059 } 6060 6061 // The first conversion is actually a user-defined conversion whose 6062 // first conversion is ObjectInit's standard conversion (which is 6063 // effectively a reference binding). Record it as such. 6064 Candidate.Conversions[0].setUserDefined(); 6065 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6066 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6067 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6068 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6069 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6070 Candidate.Conversions[0].UserDefined.After 6071 = Candidate.Conversions[0].UserDefined.Before; 6072 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6073 6074 // Find the 6075 unsigned NumArgsInProto = Proto->getNumArgs(); 6076 6077 // (C++ 13.3.2p2): A candidate function having fewer than m 6078 // parameters is viable only if it has an ellipsis in its parameter 6079 // list (8.3.5). 6080 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6081 Candidate.Viable = false; 6082 Candidate.FailureKind = ovl_fail_too_many_arguments; 6083 return; 6084 } 6085 6086 // Function types don't have any default arguments, so just check if 6087 // we have enough arguments. 6088 if (Args.size() < NumArgsInProto) { 6089 // Not enough arguments. 6090 Candidate.Viable = false; 6091 Candidate.FailureKind = ovl_fail_too_few_arguments; 6092 return; 6093 } 6094 6095 // Determine the implicit conversion sequences for each of the 6096 // arguments. 6097 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6098 if (ArgIdx < NumArgsInProto) { 6099 // (C++ 13.3.2p3): for F to be a viable function, there shall 6100 // exist for each argument an implicit conversion sequence 6101 // (13.3.3.1) that converts that argument to the corresponding 6102 // parameter of F. 6103 QualType ParamType = Proto->getArgType(ArgIdx); 6104 Candidate.Conversions[ArgIdx + 1] 6105 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6106 /*SuppressUserConversions=*/false, 6107 /*InOverloadResolution=*/false, 6108 /*AllowObjCWritebackConversion=*/ 6109 getLangOpts().ObjCAutoRefCount); 6110 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6111 Candidate.Viable = false; 6112 Candidate.FailureKind = ovl_fail_bad_conversion; 6113 break; 6114 } 6115 } else { 6116 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6117 // argument for which there is no corresponding parameter is 6118 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6119 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6120 } 6121 } 6122 } 6123 6124 /// \brief Add overload candidates for overloaded operators that are 6125 /// member functions. 6126 /// 6127 /// Add the overloaded operator candidates that are member functions 6128 /// for the operator Op that was used in an operator expression such 6129 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6130 /// CandidateSet will store the added overload candidates. (C++ 6131 /// [over.match.oper]). 6132 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6133 SourceLocation OpLoc, 6134 ArrayRef<Expr *> Args, 6135 OverloadCandidateSet& CandidateSet, 6136 SourceRange OpRange) { 6137 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6138 6139 // C++ [over.match.oper]p3: 6140 // For a unary operator @ with an operand of a type whose 6141 // cv-unqualified version is T1, and for a binary operator @ with 6142 // a left operand of a type whose cv-unqualified version is T1 and 6143 // a right operand of a type whose cv-unqualified version is T2, 6144 // three sets of candidate functions, designated member 6145 // candidates, non-member candidates and built-in candidates, are 6146 // constructed as follows: 6147 QualType T1 = Args[0]->getType(); 6148 6149 // -- If T1 is a complete class type or a class currently being 6150 // defined, the set of member candidates is the result of the 6151 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6152 // the set of member candidates is empty. 6153 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6154 // Complete the type if it can be completed. 6155 RequireCompleteType(OpLoc, T1, 0); 6156 // If the type is neither complete nor being defined, bail out now. 6157 if (!T1Rec->getDecl()->getDefinition()) 6158 return; 6159 6160 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6161 LookupQualifiedName(Operators, T1Rec->getDecl()); 6162 Operators.suppressDiagnostics(); 6163 6164 for (LookupResult::iterator Oper = Operators.begin(), 6165 OperEnd = Operators.end(); 6166 Oper != OperEnd; 6167 ++Oper) 6168 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6169 Args[0]->Classify(Context), 6170 Args.slice(1), 6171 CandidateSet, 6172 /* SuppressUserConversions = */ false); 6173 } 6174 } 6175 6176 /// AddBuiltinCandidate - Add a candidate for a built-in 6177 /// operator. ResultTy and ParamTys are the result and parameter types 6178 /// of the built-in candidate, respectively. Args and NumArgs are the 6179 /// arguments being passed to the candidate. IsAssignmentOperator 6180 /// should be true when this built-in candidate is an assignment 6181 /// operator. NumContextualBoolArguments is the number of arguments 6182 /// (at the beginning of the argument list) that will be contextually 6183 /// converted to bool. 6184 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6185 ArrayRef<Expr *> Args, 6186 OverloadCandidateSet& CandidateSet, 6187 bool IsAssignmentOperator, 6188 unsigned NumContextualBoolArguments) { 6189 // Overload resolution is always an unevaluated context. 6190 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6191 6192 // Add this candidate 6193 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6194 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6195 Candidate.Function = 0; 6196 Candidate.IsSurrogate = false; 6197 Candidate.IgnoreObjectArgument = false; 6198 Candidate.BuiltinTypes.ResultTy = ResultTy; 6199 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6200 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6201 6202 // Determine the implicit conversion sequences for each of the 6203 // arguments. 6204 Candidate.Viable = true; 6205 Candidate.ExplicitCallArguments = Args.size(); 6206 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6207 // C++ [over.match.oper]p4: 6208 // For the built-in assignment operators, conversions of the 6209 // left operand are restricted as follows: 6210 // -- no temporaries are introduced to hold the left operand, and 6211 // -- no user-defined conversions are applied to the left 6212 // operand to achieve a type match with the left-most 6213 // parameter of a built-in candidate. 6214 // 6215 // We block these conversions by turning off user-defined 6216 // conversions, since that is the only way that initialization of 6217 // a reference to a non-class type can occur from something that 6218 // is not of the same type. 6219 if (ArgIdx < NumContextualBoolArguments) { 6220 assert(ParamTys[ArgIdx] == Context.BoolTy && 6221 "Contextual conversion to bool requires bool type"); 6222 Candidate.Conversions[ArgIdx] 6223 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6224 } else { 6225 Candidate.Conversions[ArgIdx] 6226 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6227 ArgIdx == 0 && IsAssignmentOperator, 6228 /*InOverloadResolution=*/false, 6229 /*AllowObjCWritebackConversion=*/ 6230 getLangOpts().ObjCAutoRefCount); 6231 } 6232 if (Candidate.Conversions[ArgIdx].isBad()) { 6233 Candidate.Viable = false; 6234 Candidate.FailureKind = ovl_fail_bad_conversion; 6235 break; 6236 } 6237 } 6238 } 6239 6240 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6241 /// candidate operator functions for built-in operators (C++ 6242 /// [over.built]). The types are separated into pointer types and 6243 /// enumeration types. 6244 class BuiltinCandidateTypeSet { 6245 /// TypeSet - A set of types. 6246 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6247 6248 /// PointerTypes - The set of pointer types that will be used in the 6249 /// built-in candidates. 6250 TypeSet PointerTypes; 6251 6252 /// MemberPointerTypes - The set of member pointer types that will be 6253 /// used in the built-in candidates. 6254 TypeSet MemberPointerTypes; 6255 6256 /// EnumerationTypes - The set of enumeration types that will be 6257 /// used in the built-in candidates. 6258 TypeSet EnumerationTypes; 6259 6260 /// \brief The set of vector types that will be used in the built-in 6261 /// candidates. 6262 TypeSet VectorTypes; 6263 6264 /// \brief A flag indicating non-record types are viable candidates 6265 bool HasNonRecordTypes; 6266 6267 /// \brief A flag indicating whether either arithmetic or enumeration types 6268 /// were present in the candidate set. 6269 bool HasArithmeticOrEnumeralTypes; 6270 6271 /// \brief A flag indicating whether the nullptr type was present in the 6272 /// candidate set. 6273 bool HasNullPtrType; 6274 6275 /// Sema - The semantic analysis instance where we are building the 6276 /// candidate type set. 6277 Sema &SemaRef; 6278 6279 /// Context - The AST context in which we will build the type sets. 6280 ASTContext &Context; 6281 6282 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6283 const Qualifiers &VisibleQuals); 6284 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6285 6286 public: 6287 /// iterator - Iterates through the types that are part of the set. 6288 typedef TypeSet::iterator iterator; 6289 6290 BuiltinCandidateTypeSet(Sema &SemaRef) 6291 : HasNonRecordTypes(false), 6292 HasArithmeticOrEnumeralTypes(false), 6293 HasNullPtrType(false), 6294 SemaRef(SemaRef), 6295 Context(SemaRef.Context) { } 6296 6297 void AddTypesConvertedFrom(QualType Ty, 6298 SourceLocation Loc, 6299 bool AllowUserConversions, 6300 bool AllowExplicitConversions, 6301 const Qualifiers &VisibleTypeConversionsQuals); 6302 6303 /// pointer_begin - First pointer type found; 6304 iterator pointer_begin() { return PointerTypes.begin(); } 6305 6306 /// pointer_end - Past the last pointer type found; 6307 iterator pointer_end() { return PointerTypes.end(); } 6308 6309 /// member_pointer_begin - First member pointer type found; 6310 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6311 6312 /// member_pointer_end - Past the last member pointer type found; 6313 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6314 6315 /// enumeration_begin - First enumeration type found; 6316 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6317 6318 /// enumeration_end - Past the last enumeration type found; 6319 iterator enumeration_end() { return EnumerationTypes.end(); } 6320 6321 iterator vector_begin() { return VectorTypes.begin(); } 6322 iterator vector_end() { return VectorTypes.end(); } 6323 6324 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6325 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6326 bool hasNullPtrType() const { return HasNullPtrType; } 6327 }; 6328 6329 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6330 /// the set of pointer types along with any more-qualified variants of 6331 /// that type. For example, if @p Ty is "int const *", this routine 6332 /// will add "int const *", "int const volatile *", "int const 6333 /// restrict *", and "int const volatile restrict *" to the set of 6334 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6335 /// false otherwise. 6336 /// 6337 /// FIXME: what to do about extended qualifiers? 6338 bool 6339 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6340 const Qualifiers &VisibleQuals) { 6341 6342 // Insert this type. 6343 if (!PointerTypes.insert(Ty)) 6344 return false; 6345 6346 QualType PointeeTy; 6347 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6348 bool buildObjCPtr = false; 6349 if (!PointerTy) { 6350 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6351 PointeeTy = PTy->getPointeeType(); 6352 buildObjCPtr = true; 6353 } else { 6354 PointeeTy = PointerTy->getPointeeType(); 6355 } 6356 6357 // Don't add qualified variants of arrays. For one, they're not allowed 6358 // (the qualifier would sink to the element type), and for another, the 6359 // only overload situation where it matters is subscript or pointer +- int, 6360 // and those shouldn't have qualifier variants anyway. 6361 if (PointeeTy->isArrayType()) 6362 return true; 6363 6364 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6365 bool hasVolatile = VisibleQuals.hasVolatile(); 6366 bool hasRestrict = VisibleQuals.hasRestrict(); 6367 6368 // Iterate through all strict supersets of BaseCVR. 6369 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6370 if ((CVR | BaseCVR) != CVR) continue; 6371 // Skip over volatile if no volatile found anywhere in the types. 6372 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6373 6374 // Skip over restrict if no restrict found anywhere in the types, or if 6375 // the type cannot be restrict-qualified. 6376 if ((CVR & Qualifiers::Restrict) && 6377 (!hasRestrict || 6378 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6379 continue; 6380 6381 // Build qualified pointee type. 6382 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6383 6384 // Build qualified pointer type. 6385 QualType QPointerTy; 6386 if (!buildObjCPtr) 6387 QPointerTy = Context.getPointerType(QPointeeTy); 6388 else 6389 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6390 6391 // Insert qualified pointer type. 6392 PointerTypes.insert(QPointerTy); 6393 } 6394 6395 return true; 6396 } 6397 6398 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6399 /// to the set of pointer types along with any more-qualified variants of 6400 /// that type. For example, if @p Ty is "int const *", this routine 6401 /// will add "int const *", "int const volatile *", "int const 6402 /// restrict *", and "int const volatile restrict *" to the set of 6403 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6404 /// false otherwise. 6405 /// 6406 /// FIXME: what to do about extended qualifiers? 6407 bool 6408 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6409 QualType Ty) { 6410 // Insert this type. 6411 if (!MemberPointerTypes.insert(Ty)) 6412 return false; 6413 6414 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6415 assert(PointerTy && "type was not a member pointer type!"); 6416 6417 QualType PointeeTy = PointerTy->getPointeeType(); 6418 // Don't add qualified variants of arrays. For one, they're not allowed 6419 // (the qualifier would sink to the element type), and for another, the 6420 // only overload situation where it matters is subscript or pointer +- int, 6421 // and those shouldn't have qualifier variants anyway. 6422 if (PointeeTy->isArrayType()) 6423 return true; 6424 const Type *ClassTy = PointerTy->getClass(); 6425 6426 // Iterate through all strict supersets of the pointee type's CVR 6427 // qualifiers. 6428 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6429 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6430 if ((CVR | BaseCVR) != CVR) continue; 6431 6432 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6433 MemberPointerTypes.insert( 6434 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6435 } 6436 6437 return true; 6438 } 6439 6440 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6441 /// Ty can be implicit converted to the given set of @p Types. We're 6442 /// primarily interested in pointer types and enumeration types. We also 6443 /// take member pointer types, for the conditional operator. 6444 /// AllowUserConversions is true if we should look at the conversion 6445 /// functions of a class type, and AllowExplicitConversions if we 6446 /// should also include the explicit conversion functions of a class 6447 /// type. 6448 void 6449 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6450 SourceLocation Loc, 6451 bool AllowUserConversions, 6452 bool AllowExplicitConversions, 6453 const Qualifiers &VisibleQuals) { 6454 // Only deal with canonical types. 6455 Ty = Context.getCanonicalType(Ty); 6456 6457 // Look through reference types; they aren't part of the type of an 6458 // expression for the purposes of conversions. 6459 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6460 Ty = RefTy->getPointeeType(); 6461 6462 // If we're dealing with an array type, decay to the pointer. 6463 if (Ty->isArrayType()) 6464 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6465 6466 // Otherwise, we don't care about qualifiers on the type. 6467 Ty = Ty.getLocalUnqualifiedType(); 6468 6469 // Flag if we ever add a non-record type. 6470 const RecordType *TyRec = Ty->getAs<RecordType>(); 6471 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6472 6473 // Flag if we encounter an arithmetic type. 6474 HasArithmeticOrEnumeralTypes = 6475 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6476 6477 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6478 PointerTypes.insert(Ty); 6479 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6480 // Insert our type, and its more-qualified variants, into the set 6481 // of types. 6482 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6483 return; 6484 } else if (Ty->isMemberPointerType()) { 6485 // Member pointers are far easier, since the pointee can't be converted. 6486 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6487 return; 6488 } else if (Ty->isEnumeralType()) { 6489 HasArithmeticOrEnumeralTypes = true; 6490 EnumerationTypes.insert(Ty); 6491 } else if (Ty->isVectorType()) { 6492 // We treat vector types as arithmetic types in many contexts as an 6493 // extension. 6494 HasArithmeticOrEnumeralTypes = true; 6495 VectorTypes.insert(Ty); 6496 } else if (Ty->isNullPtrType()) { 6497 HasNullPtrType = true; 6498 } else if (AllowUserConversions && TyRec) { 6499 // No conversion functions in incomplete types. 6500 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6501 return; 6502 6503 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6504 std::pair<CXXRecordDecl::conversion_iterator, 6505 CXXRecordDecl::conversion_iterator> 6506 Conversions = ClassDecl->getVisibleConversionFunctions(); 6507 for (CXXRecordDecl::conversion_iterator 6508 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6509 NamedDecl *D = I.getDecl(); 6510 if (isa<UsingShadowDecl>(D)) 6511 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6512 6513 // Skip conversion function templates; they don't tell us anything 6514 // about which builtin types we can convert to. 6515 if (isa<FunctionTemplateDecl>(D)) 6516 continue; 6517 6518 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6519 if (AllowExplicitConversions || !Conv->isExplicit()) { 6520 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6521 VisibleQuals); 6522 } 6523 } 6524 } 6525 } 6526 6527 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6528 /// the volatile- and non-volatile-qualified assignment operators for the 6529 /// given type to the candidate set. 6530 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6531 QualType T, 6532 ArrayRef<Expr *> Args, 6533 OverloadCandidateSet &CandidateSet) { 6534 QualType ParamTypes[2]; 6535 6536 // T& operator=(T&, T) 6537 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6538 ParamTypes[1] = T; 6539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6540 /*IsAssignmentOperator=*/true); 6541 6542 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6543 // volatile T& operator=(volatile T&, T) 6544 ParamTypes[0] 6545 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6546 ParamTypes[1] = T; 6547 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6548 /*IsAssignmentOperator=*/true); 6549 } 6550 } 6551 6552 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6553 /// if any, found in visible type conversion functions found in ArgExpr's type. 6554 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6555 Qualifiers VRQuals; 6556 const RecordType *TyRec; 6557 if (const MemberPointerType *RHSMPType = 6558 ArgExpr->getType()->getAs<MemberPointerType>()) 6559 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6560 else 6561 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6562 if (!TyRec) { 6563 // Just to be safe, assume the worst case. 6564 VRQuals.addVolatile(); 6565 VRQuals.addRestrict(); 6566 return VRQuals; 6567 } 6568 6569 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6570 if (!ClassDecl->hasDefinition()) 6571 return VRQuals; 6572 6573 std::pair<CXXRecordDecl::conversion_iterator, 6574 CXXRecordDecl::conversion_iterator> 6575 Conversions = ClassDecl->getVisibleConversionFunctions(); 6576 6577 for (CXXRecordDecl::conversion_iterator 6578 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6579 NamedDecl *D = I.getDecl(); 6580 if (isa<UsingShadowDecl>(D)) 6581 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6582 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6583 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6584 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6585 CanTy = ResTypeRef->getPointeeType(); 6586 // Need to go down the pointer/mempointer chain and add qualifiers 6587 // as see them. 6588 bool done = false; 6589 while (!done) { 6590 if (CanTy.isRestrictQualified()) 6591 VRQuals.addRestrict(); 6592 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6593 CanTy = ResTypePtr->getPointeeType(); 6594 else if (const MemberPointerType *ResTypeMPtr = 6595 CanTy->getAs<MemberPointerType>()) 6596 CanTy = ResTypeMPtr->getPointeeType(); 6597 else 6598 done = true; 6599 if (CanTy.isVolatileQualified()) 6600 VRQuals.addVolatile(); 6601 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6602 return VRQuals; 6603 } 6604 } 6605 } 6606 return VRQuals; 6607 } 6608 6609 namespace { 6610 6611 /// \brief Helper class to manage the addition of builtin operator overload 6612 /// candidates. It provides shared state and utility methods used throughout 6613 /// the process, as well as a helper method to add each group of builtin 6614 /// operator overloads from the standard to a candidate set. 6615 class BuiltinOperatorOverloadBuilder { 6616 // Common instance state available to all overload candidate addition methods. 6617 Sema &S; 6618 ArrayRef<Expr *> Args; 6619 Qualifiers VisibleTypeConversionsQuals; 6620 bool HasArithmeticOrEnumeralCandidateType; 6621 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6622 OverloadCandidateSet &CandidateSet; 6623 6624 // Define some constants used to index and iterate over the arithemetic types 6625 // provided via the getArithmeticType() method below. 6626 // The "promoted arithmetic types" are the arithmetic 6627 // types are that preserved by promotion (C++ [over.built]p2). 6628 static const unsigned FirstIntegralType = 3; 6629 static const unsigned LastIntegralType = 20; 6630 static const unsigned FirstPromotedIntegralType = 3, 6631 LastPromotedIntegralType = 11; 6632 static const unsigned FirstPromotedArithmeticType = 0, 6633 LastPromotedArithmeticType = 11; 6634 static const unsigned NumArithmeticTypes = 20; 6635 6636 /// \brief Get the canonical type for a given arithmetic type index. 6637 CanQualType getArithmeticType(unsigned index) { 6638 assert(index < NumArithmeticTypes); 6639 static CanQualType ASTContext::* const 6640 ArithmeticTypes[NumArithmeticTypes] = { 6641 // Start of promoted types. 6642 &ASTContext::FloatTy, 6643 &ASTContext::DoubleTy, 6644 &ASTContext::LongDoubleTy, 6645 6646 // Start of integral types. 6647 &ASTContext::IntTy, 6648 &ASTContext::LongTy, 6649 &ASTContext::LongLongTy, 6650 &ASTContext::Int128Ty, 6651 &ASTContext::UnsignedIntTy, 6652 &ASTContext::UnsignedLongTy, 6653 &ASTContext::UnsignedLongLongTy, 6654 &ASTContext::UnsignedInt128Ty, 6655 // End of promoted types. 6656 6657 &ASTContext::BoolTy, 6658 &ASTContext::CharTy, 6659 &ASTContext::WCharTy, 6660 &ASTContext::Char16Ty, 6661 &ASTContext::Char32Ty, 6662 &ASTContext::SignedCharTy, 6663 &ASTContext::ShortTy, 6664 &ASTContext::UnsignedCharTy, 6665 &ASTContext::UnsignedShortTy, 6666 // End of integral types. 6667 // FIXME: What about complex? What about half? 6668 }; 6669 return S.Context.*ArithmeticTypes[index]; 6670 } 6671 6672 /// \brief Gets the canonical type resulting from the usual arithemetic 6673 /// converions for the given arithmetic types. 6674 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6675 // Accelerator table for performing the usual arithmetic conversions. 6676 // The rules are basically: 6677 // - if either is floating-point, use the wider floating-point 6678 // - if same signedness, use the higher rank 6679 // - if same size, use unsigned of the higher rank 6680 // - use the larger type 6681 // These rules, together with the axiom that higher ranks are 6682 // never smaller, are sufficient to precompute all of these results 6683 // *except* when dealing with signed types of higher rank. 6684 // (we could precompute SLL x UI for all known platforms, but it's 6685 // better not to make any assumptions). 6686 // We assume that int128 has a higher rank than long long on all platforms. 6687 enum PromotedType { 6688 Dep=-1, 6689 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6690 }; 6691 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6692 [LastPromotedArithmeticType] = { 6693 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6694 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6695 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6696 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6697 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6698 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6699 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6700 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6701 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6702 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6703 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6704 }; 6705 6706 assert(L < LastPromotedArithmeticType); 6707 assert(R < LastPromotedArithmeticType); 6708 int Idx = ConversionsTable[L][R]; 6709 6710 // Fast path: the table gives us a concrete answer. 6711 if (Idx != Dep) return getArithmeticType(Idx); 6712 6713 // Slow path: we need to compare widths. 6714 // An invariant is that the signed type has higher rank. 6715 CanQualType LT = getArithmeticType(L), 6716 RT = getArithmeticType(R); 6717 unsigned LW = S.Context.getIntWidth(LT), 6718 RW = S.Context.getIntWidth(RT); 6719 6720 // If they're different widths, use the signed type. 6721 if (LW > RW) return LT; 6722 else if (LW < RW) return RT; 6723 6724 // Otherwise, use the unsigned type of the signed type's rank. 6725 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6726 assert(L == SLL || R == SLL); 6727 return S.Context.UnsignedLongLongTy; 6728 } 6729 6730 /// \brief Helper method to factor out the common pattern of adding overloads 6731 /// for '++' and '--' builtin operators. 6732 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6733 bool HasVolatile, 6734 bool HasRestrict) { 6735 QualType ParamTypes[2] = { 6736 S.Context.getLValueReferenceType(CandidateTy), 6737 S.Context.IntTy 6738 }; 6739 6740 // Non-volatile version. 6741 if (Args.size() == 1) 6742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6743 else 6744 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6745 6746 // Use a heuristic to reduce number of builtin candidates in the set: 6747 // add volatile version only if there are conversions to a volatile type. 6748 if (HasVolatile) { 6749 ParamTypes[0] = 6750 S.Context.getLValueReferenceType( 6751 S.Context.getVolatileType(CandidateTy)); 6752 if (Args.size() == 1) 6753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6754 else 6755 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6756 } 6757 6758 // Add restrict version only if there are conversions to a restrict type 6759 // and our candidate type is a non-restrict-qualified pointer. 6760 if (HasRestrict && CandidateTy->isAnyPointerType() && 6761 !CandidateTy.isRestrictQualified()) { 6762 ParamTypes[0] 6763 = S.Context.getLValueReferenceType( 6764 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6765 if (Args.size() == 1) 6766 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6767 else 6768 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6769 6770 if (HasVolatile) { 6771 ParamTypes[0] 6772 = S.Context.getLValueReferenceType( 6773 S.Context.getCVRQualifiedType(CandidateTy, 6774 (Qualifiers::Volatile | 6775 Qualifiers::Restrict))); 6776 if (Args.size() == 1) 6777 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6778 else 6779 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6780 } 6781 } 6782 6783 } 6784 6785 public: 6786 BuiltinOperatorOverloadBuilder( 6787 Sema &S, ArrayRef<Expr *> Args, 6788 Qualifiers VisibleTypeConversionsQuals, 6789 bool HasArithmeticOrEnumeralCandidateType, 6790 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6791 OverloadCandidateSet &CandidateSet) 6792 : S(S), Args(Args), 6793 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6794 HasArithmeticOrEnumeralCandidateType( 6795 HasArithmeticOrEnumeralCandidateType), 6796 CandidateTypes(CandidateTypes), 6797 CandidateSet(CandidateSet) { 6798 // Validate some of our static helper constants in debug builds. 6799 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6800 "Invalid first promoted integral type"); 6801 assert(getArithmeticType(LastPromotedIntegralType - 1) 6802 == S.Context.UnsignedInt128Ty && 6803 "Invalid last promoted integral type"); 6804 assert(getArithmeticType(FirstPromotedArithmeticType) 6805 == S.Context.FloatTy && 6806 "Invalid first promoted arithmetic type"); 6807 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6808 == S.Context.UnsignedInt128Ty && 6809 "Invalid last promoted arithmetic type"); 6810 } 6811 6812 // C++ [over.built]p3: 6813 // 6814 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6815 // is either volatile or empty, there exist candidate operator 6816 // functions of the form 6817 // 6818 // VQ T& operator++(VQ T&); 6819 // T operator++(VQ T&, int); 6820 // 6821 // C++ [over.built]p4: 6822 // 6823 // For every pair (T, VQ), where T is an arithmetic type other 6824 // than bool, and VQ is either volatile or empty, there exist 6825 // candidate operator functions of the form 6826 // 6827 // VQ T& operator--(VQ T&); 6828 // T operator--(VQ T&, int); 6829 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6830 if (!HasArithmeticOrEnumeralCandidateType) 6831 return; 6832 6833 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6834 Arith < NumArithmeticTypes; ++Arith) { 6835 addPlusPlusMinusMinusStyleOverloads( 6836 getArithmeticType(Arith), 6837 VisibleTypeConversionsQuals.hasVolatile(), 6838 VisibleTypeConversionsQuals.hasRestrict()); 6839 } 6840 } 6841 6842 // C++ [over.built]p5: 6843 // 6844 // For every pair (T, VQ), where T is a cv-qualified or 6845 // cv-unqualified object type, and VQ is either volatile or 6846 // empty, there exist candidate operator functions of the form 6847 // 6848 // T*VQ& operator++(T*VQ&); 6849 // T*VQ& operator--(T*VQ&); 6850 // T* operator++(T*VQ&, int); 6851 // T* operator--(T*VQ&, int); 6852 void addPlusPlusMinusMinusPointerOverloads() { 6853 for (BuiltinCandidateTypeSet::iterator 6854 Ptr = CandidateTypes[0].pointer_begin(), 6855 PtrEnd = CandidateTypes[0].pointer_end(); 6856 Ptr != PtrEnd; ++Ptr) { 6857 // Skip pointer types that aren't pointers to object types. 6858 if (!(*Ptr)->getPointeeType()->isObjectType()) 6859 continue; 6860 6861 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6862 (!(*Ptr).isVolatileQualified() && 6863 VisibleTypeConversionsQuals.hasVolatile()), 6864 (!(*Ptr).isRestrictQualified() && 6865 VisibleTypeConversionsQuals.hasRestrict())); 6866 } 6867 } 6868 6869 // C++ [over.built]p6: 6870 // For every cv-qualified or cv-unqualified object type T, there 6871 // exist candidate operator functions of the form 6872 // 6873 // T& operator*(T*); 6874 // 6875 // C++ [over.built]p7: 6876 // For every function type T that does not have cv-qualifiers or a 6877 // ref-qualifier, there exist candidate operator functions of the form 6878 // T& operator*(T*); 6879 void addUnaryStarPointerOverloads() { 6880 for (BuiltinCandidateTypeSet::iterator 6881 Ptr = CandidateTypes[0].pointer_begin(), 6882 PtrEnd = CandidateTypes[0].pointer_end(); 6883 Ptr != PtrEnd; ++Ptr) { 6884 QualType ParamTy = *Ptr; 6885 QualType PointeeTy = ParamTy->getPointeeType(); 6886 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6887 continue; 6888 6889 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6890 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6891 continue; 6892 6893 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6894 &ParamTy, Args, CandidateSet); 6895 } 6896 } 6897 6898 // C++ [over.built]p9: 6899 // For every promoted arithmetic type T, there exist candidate 6900 // operator functions of the form 6901 // 6902 // T operator+(T); 6903 // T operator-(T); 6904 void addUnaryPlusOrMinusArithmeticOverloads() { 6905 if (!HasArithmeticOrEnumeralCandidateType) 6906 return; 6907 6908 for (unsigned Arith = FirstPromotedArithmeticType; 6909 Arith < LastPromotedArithmeticType; ++Arith) { 6910 QualType ArithTy = getArithmeticType(Arith); 6911 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6912 } 6913 6914 // Extension: We also add these operators for vector types. 6915 for (BuiltinCandidateTypeSet::iterator 6916 Vec = CandidateTypes[0].vector_begin(), 6917 VecEnd = CandidateTypes[0].vector_end(); 6918 Vec != VecEnd; ++Vec) { 6919 QualType VecTy = *Vec; 6920 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6921 } 6922 } 6923 6924 // C++ [over.built]p8: 6925 // For every type T, there exist candidate operator functions of 6926 // the form 6927 // 6928 // T* operator+(T*); 6929 void addUnaryPlusPointerOverloads() { 6930 for (BuiltinCandidateTypeSet::iterator 6931 Ptr = CandidateTypes[0].pointer_begin(), 6932 PtrEnd = CandidateTypes[0].pointer_end(); 6933 Ptr != PtrEnd; ++Ptr) { 6934 QualType ParamTy = *Ptr; 6935 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 6936 } 6937 } 6938 6939 // C++ [over.built]p10: 6940 // For every promoted integral type T, there exist candidate 6941 // operator functions of the form 6942 // 6943 // T operator~(T); 6944 void addUnaryTildePromotedIntegralOverloads() { 6945 if (!HasArithmeticOrEnumeralCandidateType) 6946 return; 6947 6948 for (unsigned Int = FirstPromotedIntegralType; 6949 Int < LastPromotedIntegralType; ++Int) { 6950 QualType IntTy = getArithmeticType(Int); 6951 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 6952 } 6953 6954 // Extension: We also add this operator for vector types. 6955 for (BuiltinCandidateTypeSet::iterator 6956 Vec = CandidateTypes[0].vector_begin(), 6957 VecEnd = CandidateTypes[0].vector_end(); 6958 Vec != VecEnd; ++Vec) { 6959 QualType VecTy = *Vec; 6960 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6961 } 6962 } 6963 6964 // C++ [over.match.oper]p16: 6965 // For every pointer to member type T, there exist candidate operator 6966 // functions of the form 6967 // 6968 // bool operator==(T,T); 6969 // bool operator!=(T,T); 6970 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6971 /// Set of (canonical) types that we've already handled. 6972 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6973 6974 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6975 for (BuiltinCandidateTypeSet::iterator 6976 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6977 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6978 MemPtr != MemPtrEnd; 6979 ++MemPtr) { 6980 // Don't add the same builtin candidate twice. 6981 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6982 continue; 6983 6984 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6985 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6986 } 6987 } 6988 } 6989 6990 // C++ [over.built]p15: 6991 // 6992 // For every T, where T is an enumeration type, a pointer type, or 6993 // std::nullptr_t, there exist candidate operator functions of the form 6994 // 6995 // bool operator<(T, T); 6996 // bool operator>(T, T); 6997 // bool operator<=(T, T); 6998 // bool operator>=(T, T); 6999 // bool operator==(T, T); 7000 // bool operator!=(T, T); 7001 void addRelationalPointerOrEnumeralOverloads() { 7002 // C++ [over.match.oper]p3: 7003 // [...]the built-in candidates include all of the candidate operator 7004 // functions defined in 13.6 that, compared to the given operator, [...] 7005 // do not have the same parameter-type-list as any non-template non-member 7006 // candidate. 7007 // 7008 // Note that in practice, this only affects enumeration types because there 7009 // aren't any built-in candidates of record type, and a user-defined operator 7010 // must have an operand of record or enumeration type. Also, the only other 7011 // overloaded operator with enumeration arguments, operator=, 7012 // cannot be overloaded for enumeration types, so this is the only place 7013 // where we must suppress candidates like this. 7014 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7015 UserDefinedBinaryOperators; 7016 7017 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7018 if (CandidateTypes[ArgIdx].enumeration_begin() != 7019 CandidateTypes[ArgIdx].enumeration_end()) { 7020 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7021 CEnd = CandidateSet.end(); 7022 C != CEnd; ++C) { 7023 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7024 continue; 7025 7026 if (C->Function->isFunctionTemplateSpecialization()) 7027 continue; 7028 7029 QualType FirstParamType = 7030 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7031 QualType SecondParamType = 7032 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7033 7034 // Skip if either parameter isn't of enumeral type. 7035 if (!FirstParamType->isEnumeralType() || 7036 !SecondParamType->isEnumeralType()) 7037 continue; 7038 7039 // Add this operator to the set of known user-defined operators. 7040 UserDefinedBinaryOperators.insert( 7041 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7042 S.Context.getCanonicalType(SecondParamType))); 7043 } 7044 } 7045 } 7046 7047 /// Set of (canonical) types that we've already handled. 7048 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7049 7050 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7051 for (BuiltinCandidateTypeSet::iterator 7052 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7053 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7054 Ptr != PtrEnd; ++Ptr) { 7055 // Don't add the same builtin candidate twice. 7056 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7057 continue; 7058 7059 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7060 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7061 } 7062 for (BuiltinCandidateTypeSet::iterator 7063 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7064 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7065 Enum != EnumEnd; ++Enum) { 7066 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7067 7068 // Don't add the same builtin candidate twice, or if a user defined 7069 // candidate exists. 7070 if (!AddedTypes.insert(CanonType) || 7071 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7072 CanonType))) 7073 continue; 7074 7075 QualType ParamTypes[2] = { *Enum, *Enum }; 7076 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7077 } 7078 7079 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7080 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7081 if (AddedTypes.insert(NullPtrTy) && 7082 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7083 NullPtrTy))) { 7084 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7085 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7086 CandidateSet); 7087 } 7088 } 7089 } 7090 } 7091 7092 // C++ [over.built]p13: 7093 // 7094 // For every cv-qualified or cv-unqualified object type T 7095 // there exist candidate operator functions of the form 7096 // 7097 // T* operator+(T*, ptrdiff_t); 7098 // T& operator[](T*, ptrdiff_t); [BELOW] 7099 // T* operator-(T*, ptrdiff_t); 7100 // T* operator+(ptrdiff_t, T*); 7101 // T& operator[](ptrdiff_t, T*); [BELOW] 7102 // 7103 // C++ [over.built]p14: 7104 // 7105 // For every T, where T is a pointer to object type, there 7106 // exist candidate operator functions of the form 7107 // 7108 // ptrdiff_t operator-(T, T); 7109 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7110 /// Set of (canonical) types that we've already handled. 7111 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7112 7113 for (int Arg = 0; Arg < 2; ++Arg) { 7114 QualType AsymetricParamTypes[2] = { 7115 S.Context.getPointerDiffType(), 7116 S.Context.getPointerDiffType(), 7117 }; 7118 for (BuiltinCandidateTypeSet::iterator 7119 Ptr = CandidateTypes[Arg].pointer_begin(), 7120 PtrEnd = CandidateTypes[Arg].pointer_end(); 7121 Ptr != PtrEnd; ++Ptr) { 7122 QualType PointeeTy = (*Ptr)->getPointeeType(); 7123 if (!PointeeTy->isObjectType()) 7124 continue; 7125 7126 AsymetricParamTypes[Arg] = *Ptr; 7127 if (Arg == 0 || Op == OO_Plus) { 7128 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7129 // T* operator+(ptrdiff_t, T*); 7130 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7131 } 7132 if (Op == OO_Minus) { 7133 // ptrdiff_t operator-(T, T); 7134 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7135 continue; 7136 7137 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7138 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7139 Args, CandidateSet); 7140 } 7141 } 7142 } 7143 } 7144 7145 // C++ [over.built]p12: 7146 // 7147 // For every pair of promoted arithmetic types L and R, there 7148 // exist candidate operator functions of the form 7149 // 7150 // LR operator*(L, R); 7151 // LR operator/(L, R); 7152 // LR operator+(L, R); 7153 // LR operator-(L, R); 7154 // bool operator<(L, R); 7155 // bool operator>(L, R); 7156 // bool operator<=(L, R); 7157 // bool operator>=(L, R); 7158 // bool operator==(L, R); 7159 // bool operator!=(L, R); 7160 // 7161 // where LR is the result of the usual arithmetic conversions 7162 // between types L and R. 7163 // 7164 // C++ [over.built]p24: 7165 // 7166 // For every pair of promoted arithmetic types L and R, there exist 7167 // candidate operator functions of the form 7168 // 7169 // LR operator?(bool, L, R); 7170 // 7171 // where LR is the result of the usual arithmetic conversions 7172 // between types L and R. 7173 // Our candidates ignore the first parameter. 7174 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7175 if (!HasArithmeticOrEnumeralCandidateType) 7176 return; 7177 7178 for (unsigned Left = FirstPromotedArithmeticType; 7179 Left < LastPromotedArithmeticType; ++Left) { 7180 for (unsigned Right = FirstPromotedArithmeticType; 7181 Right < LastPromotedArithmeticType; ++Right) { 7182 QualType LandR[2] = { getArithmeticType(Left), 7183 getArithmeticType(Right) }; 7184 QualType Result = 7185 isComparison ? S.Context.BoolTy 7186 : getUsualArithmeticConversions(Left, Right); 7187 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7188 } 7189 } 7190 7191 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7192 // conditional operator for vector types. 7193 for (BuiltinCandidateTypeSet::iterator 7194 Vec1 = CandidateTypes[0].vector_begin(), 7195 Vec1End = CandidateTypes[0].vector_end(); 7196 Vec1 != Vec1End; ++Vec1) { 7197 for (BuiltinCandidateTypeSet::iterator 7198 Vec2 = CandidateTypes[1].vector_begin(), 7199 Vec2End = CandidateTypes[1].vector_end(); 7200 Vec2 != Vec2End; ++Vec2) { 7201 QualType LandR[2] = { *Vec1, *Vec2 }; 7202 QualType Result = S.Context.BoolTy; 7203 if (!isComparison) { 7204 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7205 Result = *Vec1; 7206 else 7207 Result = *Vec2; 7208 } 7209 7210 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7211 } 7212 } 7213 } 7214 7215 // C++ [over.built]p17: 7216 // 7217 // For every pair of promoted integral types L and R, there 7218 // exist candidate operator functions of the form 7219 // 7220 // LR operator%(L, R); 7221 // LR operator&(L, R); 7222 // LR operator^(L, R); 7223 // LR operator|(L, R); 7224 // L operator<<(L, R); 7225 // L operator>>(L, R); 7226 // 7227 // where LR is the result of the usual arithmetic conversions 7228 // between types L and R. 7229 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7230 if (!HasArithmeticOrEnumeralCandidateType) 7231 return; 7232 7233 for (unsigned Left = FirstPromotedIntegralType; 7234 Left < LastPromotedIntegralType; ++Left) { 7235 for (unsigned Right = FirstPromotedIntegralType; 7236 Right < LastPromotedIntegralType; ++Right) { 7237 QualType LandR[2] = { getArithmeticType(Left), 7238 getArithmeticType(Right) }; 7239 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7240 ? LandR[0] 7241 : getUsualArithmeticConversions(Left, Right); 7242 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7243 } 7244 } 7245 } 7246 7247 // C++ [over.built]p20: 7248 // 7249 // For every pair (T, VQ), where T is an enumeration or 7250 // pointer to member type and VQ is either volatile or 7251 // empty, there exist candidate operator functions of the form 7252 // 7253 // VQ T& operator=(VQ T&, T); 7254 void addAssignmentMemberPointerOrEnumeralOverloads() { 7255 /// Set of (canonical) types that we've already handled. 7256 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7257 7258 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7259 for (BuiltinCandidateTypeSet::iterator 7260 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7261 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7262 Enum != EnumEnd; ++Enum) { 7263 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7264 continue; 7265 7266 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7267 } 7268 7269 for (BuiltinCandidateTypeSet::iterator 7270 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7271 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7272 MemPtr != MemPtrEnd; ++MemPtr) { 7273 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7274 continue; 7275 7276 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7277 } 7278 } 7279 } 7280 7281 // C++ [over.built]p19: 7282 // 7283 // For every pair (T, VQ), where T is any type and VQ is either 7284 // volatile or empty, there exist candidate operator functions 7285 // of the form 7286 // 7287 // T*VQ& operator=(T*VQ&, T*); 7288 // 7289 // C++ [over.built]p21: 7290 // 7291 // For every pair (T, VQ), where T is a cv-qualified or 7292 // cv-unqualified object type and VQ is either volatile or 7293 // empty, there exist candidate operator functions of the form 7294 // 7295 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7296 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7297 void addAssignmentPointerOverloads(bool isEqualOp) { 7298 /// Set of (canonical) types that we've already handled. 7299 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7300 7301 for (BuiltinCandidateTypeSet::iterator 7302 Ptr = CandidateTypes[0].pointer_begin(), 7303 PtrEnd = CandidateTypes[0].pointer_end(); 7304 Ptr != PtrEnd; ++Ptr) { 7305 // If this is operator=, keep track of the builtin candidates we added. 7306 if (isEqualOp) 7307 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7308 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7309 continue; 7310 7311 // non-volatile version 7312 QualType ParamTypes[2] = { 7313 S.Context.getLValueReferenceType(*Ptr), 7314 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7315 }; 7316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7317 /*IsAssigmentOperator=*/ isEqualOp); 7318 7319 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7320 VisibleTypeConversionsQuals.hasVolatile(); 7321 if (NeedVolatile) { 7322 // volatile version 7323 ParamTypes[0] = 7324 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7325 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7326 /*IsAssigmentOperator=*/isEqualOp); 7327 } 7328 7329 if (!(*Ptr).isRestrictQualified() && 7330 VisibleTypeConversionsQuals.hasRestrict()) { 7331 // restrict version 7332 ParamTypes[0] 7333 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7334 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7335 /*IsAssigmentOperator=*/isEqualOp); 7336 7337 if (NeedVolatile) { 7338 // volatile restrict version 7339 ParamTypes[0] 7340 = S.Context.getLValueReferenceType( 7341 S.Context.getCVRQualifiedType(*Ptr, 7342 (Qualifiers::Volatile | 7343 Qualifiers::Restrict))); 7344 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7345 /*IsAssigmentOperator=*/isEqualOp); 7346 } 7347 } 7348 } 7349 7350 if (isEqualOp) { 7351 for (BuiltinCandidateTypeSet::iterator 7352 Ptr = CandidateTypes[1].pointer_begin(), 7353 PtrEnd = CandidateTypes[1].pointer_end(); 7354 Ptr != PtrEnd; ++Ptr) { 7355 // Make sure we don't add the same candidate twice. 7356 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7357 continue; 7358 7359 QualType ParamTypes[2] = { 7360 S.Context.getLValueReferenceType(*Ptr), 7361 *Ptr, 7362 }; 7363 7364 // non-volatile version 7365 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7366 /*IsAssigmentOperator=*/true); 7367 7368 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7369 VisibleTypeConversionsQuals.hasVolatile(); 7370 if (NeedVolatile) { 7371 // volatile version 7372 ParamTypes[0] = 7373 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7375 /*IsAssigmentOperator=*/true); 7376 } 7377 7378 if (!(*Ptr).isRestrictQualified() && 7379 VisibleTypeConversionsQuals.hasRestrict()) { 7380 // restrict version 7381 ParamTypes[0] 7382 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7383 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7384 /*IsAssigmentOperator=*/true); 7385 7386 if (NeedVolatile) { 7387 // volatile restrict version 7388 ParamTypes[0] 7389 = S.Context.getLValueReferenceType( 7390 S.Context.getCVRQualifiedType(*Ptr, 7391 (Qualifiers::Volatile | 7392 Qualifiers::Restrict))); 7393 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7394 /*IsAssigmentOperator=*/true); 7395 } 7396 } 7397 } 7398 } 7399 } 7400 7401 // C++ [over.built]p18: 7402 // 7403 // For every triple (L, VQ, R), where L is an arithmetic type, 7404 // VQ is either volatile or empty, and R is a promoted 7405 // arithmetic type, there exist candidate operator functions of 7406 // the form 7407 // 7408 // VQ L& operator=(VQ L&, R); 7409 // VQ L& operator*=(VQ L&, R); 7410 // VQ L& operator/=(VQ L&, R); 7411 // VQ L& operator+=(VQ L&, R); 7412 // VQ L& operator-=(VQ L&, R); 7413 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7414 if (!HasArithmeticOrEnumeralCandidateType) 7415 return; 7416 7417 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7418 for (unsigned Right = FirstPromotedArithmeticType; 7419 Right < LastPromotedArithmeticType; ++Right) { 7420 QualType ParamTypes[2]; 7421 ParamTypes[1] = getArithmeticType(Right); 7422 7423 // Add this built-in operator as a candidate (VQ is empty). 7424 ParamTypes[0] = 7425 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7427 /*IsAssigmentOperator=*/isEqualOp); 7428 7429 // Add this built-in operator as a candidate (VQ is 'volatile'). 7430 if (VisibleTypeConversionsQuals.hasVolatile()) { 7431 ParamTypes[0] = 7432 S.Context.getVolatileType(getArithmeticType(Left)); 7433 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7435 /*IsAssigmentOperator=*/isEqualOp); 7436 } 7437 } 7438 } 7439 7440 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7441 for (BuiltinCandidateTypeSet::iterator 7442 Vec1 = CandidateTypes[0].vector_begin(), 7443 Vec1End = CandidateTypes[0].vector_end(); 7444 Vec1 != Vec1End; ++Vec1) { 7445 for (BuiltinCandidateTypeSet::iterator 7446 Vec2 = CandidateTypes[1].vector_begin(), 7447 Vec2End = CandidateTypes[1].vector_end(); 7448 Vec2 != Vec2End; ++Vec2) { 7449 QualType ParamTypes[2]; 7450 ParamTypes[1] = *Vec2; 7451 // Add this built-in operator as a candidate (VQ is empty). 7452 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7453 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7454 /*IsAssigmentOperator=*/isEqualOp); 7455 7456 // Add this built-in operator as a candidate (VQ is 'volatile'). 7457 if (VisibleTypeConversionsQuals.hasVolatile()) { 7458 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7459 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7460 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7461 /*IsAssigmentOperator=*/isEqualOp); 7462 } 7463 } 7464 } 7465 } 7466 7467 // C++ [over.built]p22: 7468 // 7469 // For every triple (L, VQ, R), where L is an integral type, VQ 7470 // is either volatile or empty, and R is a promoted integral 7471 // type, there exist candidate operator functions of the form 7472 // 7473 // VQ L& operator%=(VQ L&, R); 7474 // VQ L& operator<<=(VQ L&, R); 7475 // VQ L& operator>>=(VQ L&, R); 7476 // VQ L& operator&=(VQ L&, R); 7477 // VQ L& operator^=(VQ L&, R); 7478 // VQ L& operator|=(VQ L&, R); 7479 void addAssignmentIntegralOverloads() { 7480 if (!HasArithmeticOrEnumeralCandidateType) 7481 return; 7482 7483 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7484 for (unsigned Right = FirstPromotedIntegralType; 7485 Right < LastPromotedIntegralType; ++Right) { 7486 QualType ParamTypes[2]; 7487 ParamTypes[1] = getArithmeticType(Right); 7488 7489 // Add this built-in operator as a candidate (VQ is empty). 7490 ParamTypes[0] = 7491 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7492 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7493 if (VisibleTypeConversionsQuals.hasVolatile()) { 7494 // Add this built-in operator as a candidate (VQ is 'volatile'). 7495 ParamTypes[0] = getArithmeticType(Left); 7496 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7497 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7498 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7499 } 7500 } 7501 } 7502 } 7503 7504 // C++ [over.operator]p23: 7505 // 7506 // There also exist candidate operator functions of the form 7507 // 7508 // bool operator!(bool); 7509 // bool operator&&(bool, bool); 7510 // bool operator||(bool, bool); 7511 void addExclaimOverload() { 7512 QualType ParamTy = S.Context.BoolTy; 7513 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7514 /*IsAssignmentOperator=*/false, 7515 /*NumContextualBoolArguments=*/1); 7516 } 7517 void addAmpAmpOrPipePipeOverload() { 7518 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7519 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7520 /*IsAssignmentOperator=*/false, 7521 /*NumContextualBoolArguments=*/2); 7522 } 7523 7524 // C++ [over.built]p13: 7525 // 7526 // For every cv-qualified or cv-unqualified object type T there 7527 // exist candidate operator functions of the form 7528 // 7529 // T* operator+(T*, ptrdiff_t); [ABOVE] 7530 // T& operator[](T*, ptrdiff_t); 7531 // T* operator-(T*, ptrdiff_t); [ABOVE] 7532 // T* operator+(ptrdiff_t, T*); [ABOVE] 7533 // T& operator[](ptrdiff_t, T*); 7534 void addSubscriptOverloads() { 7535 for (BuiltinCandidateTypeSet::iterator 7536 Ptr = CandidateTypes[0].pointer_begin(), 7537 PtrEnd = CandidateTypes[0].pointer_end(); 7538 Ptr != PtrEnd; ++Ptr) { 7539 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7540 QualType PointeeType = (*Ptr)->getPointeeType(); 7541 if (!PointeeType->isObjectType()) 7542 continue; 7543 7544 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7545 7546 // T& operator[](T*, ptrdiff_t) 7547 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7548 } 7549 7550 for (BuiltinCandidateTypeSet::iterator 7551 Ptr = CandidateTypes[1].pointer_begin(), 7552 PtrEnd = CandidateTypes[1].pointer_end(); 7553 Ptr != PtrEnd; ++Ptr) { 7554 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7555 QualType PointeeType = (*Ptr)->getPointeeType(); 7556 if (!PointeeType->isObjectType()) 7557 continue; 7558 7559 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7560 7561 // T& operator[](ptrdiff_t, T*) 7562 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7563 } 7564 } 7565 7566 // C++ [over.built]p11: 7567 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7568 // C1 is the same type as C2 or is a derived class of C2, T is an object 7569 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7570 // there exist candidate operator functions of the form 7571 // 7572 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7573 // 7574 // where CV12 is the union of CV1 and CV2. 7575 void addArrowStarOverloads() { 7576 for (BuiltinCandidateTypeSet::iterator 7577 Ptr = CandidateTypes[0].pointer_begin(), 7578 PtrEnd = CandidateTypes[0].pointer_end(); 7579 Ptr != PtrEnd; ++Ptr) { 7580 QualType C1Ty = (*Ptr); 7581 QualType C1; 7582 QualifierCollector Q1; 7583 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7584 if (!isa<RecordType>(C1)) 7585 continue; 7586 // heuristic to reduce number of builtin candidates in the set. 7587 // Add volatile/restrict version only if there are conversions to a 7588 // volatile/restrict type. 7589 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7590 continue; 7591 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7592 continue; 7593 for (BuiltinCandidateTypeSet::iterator 7594 MemPtr = CandidateTypes[1].member_pointer_begin(), 7595 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7596 MemPtr != MemPtrEnd; ++MemPtr) { 7597 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7598 QualType C2 = QualType(mptr->getClass(), 0); 7599 C2 = C2.getUnqualifiedType(); 7600 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7601 break; 7602 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7603 // build CV12 T& 7604 QualType T = mptr->getPointeeType(); 7605 if (!VisibleTypeConversionsQuals.hasVolatile() && 7606 T.isVolatileQualified()) 7607 continue; 7608 if (!VisibleTypeConversionsQuals.hasRestrict() && 7609 T.isRestrictQualified()) 7610 continue; 7611 T = Q1.apply(S.Context, T); 7612 QualType ResultTy = S.Context.getLValueReferenceType(T); 7613 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7614 } 7615 } 7616 } 7617 7618 // Note that we don't consider the first argument, since it has been 7619 // contextually converted to bool long ago. The candidates below are 7620 // therefore added as binary. 7621 // 7622 // C++ [over.built]p25: 7623 // For every type T, where T is a pointer, pointer-to-member, or scoped 7624 // enumeration type, there exist candidate operator functions of the form 7625 // 7626 // T operator?(bool, T, T); 7627 // 7628 void addConditionalOperatorOverloads() { 7629 /// Set of (canonical) types that we've already handled. 7630 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7631 7632 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7633 for (BuiltinCandidateTypeSet::iterator 7634 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7635 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7636 Ptr != PtrEnd; ++Ptr) { 7637 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7638 continue; 7639 7640 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7641 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7642 } 7643 7644 for (BuiltinCandidateTypeSet::iterator 7645 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7646 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7647 MemPtr != MemPtrEnd; ++MemPtr) { 7648 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7649 continue; 7650 7651 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7652 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7653 } 7654 7655 if (S.getLangOpts().CPlusPlus11) { 7656 for (BuiltinCandidateTypeSet::iterator 7657 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7658 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7659 Enum != EnumEnd; ++Enum) { 7660 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7661 continue; 7662 7663 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7664 continue; 7665 7666 QualType ParamTypes[2] = { *Enum, *Enum }; 7667 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7668 } 7669 } 7670 } 7671 } 7672 }; 7673 7674 } // end anonymous namespace 7675 7676 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7677 /// operator overloads to the candidate set (C++ [over.built]), based 7678 /// on the operator @p Op and the arguments given. For example, if the 7679 /// operator is a binary '+', this routine might add "int 7680 /// operator+(int, int)" to cover integer addition. 7681 void 7682 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7683 SourceLocation OpLoc, 7684 llvm::ArrayRef<Expr *> Args, 7685 OverloadCandidateSet& CandidateSet) { 7686 // Find all of the types that the arguments can convert to, but only 7687 // if the operator we're looking at has built-in operator candidates 7688 // that make use of these types. Also record whether we encounter non-record 7689 // candidate types or either arithmetic or enumeral candidate types. 7690 Qualifiers VisibleTypeConversionsQuals; 7691 VisibleTypeConversionsQuals.addConst(); 7692 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7693 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7694 7695 bool HasNonRecordCandidateType = false; 7696 bool HasArithmeticOrEnumeralCandidateType = false; 7697 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7698 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7699 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7700 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7701 OpLoc, 7702 true, 7703 (Op == OO_Exclaim || 7704 Op == OO_AmpAmp || 7705 Op == OO_PipePipe), 7706 VisibleTypeConversionsQuals); 7707 HasNonRecordCandidateType = HasNonRecordCandidateType || 7708 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7709 HasArithmeticOrEnumeralCandidateType = 7710 HasArithmeticOrEnumeralCandidateType || 7711 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7712 } 7713 7714 // Exit early when no non-record types have been added to the candidate set 7715 // for any of the arguments to the operator. 7716 // 7717 // We can't exit early for !, ||, or &&, since there we have always have 7718 // 'bool' overloads. 7719 if (!HasNonRecordCandidateType && 7720 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7721 return; 7722 7723 // Setup an object to manage the common state for building overloads. 7724 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7725 VisibleTypeConversionsQuals, 7726 HasArithmeticOrEnumeralCandidateType, 7727 CandidateTypes, CandidateSet); 7728 7729 // Dispatch over the operation to add in only those overloads which apply. 7730 switch (Op) { 7731 case OO_None: 7732 case NUM_OVERLOADED_OPERATORS: 7733 llvm_unreachable("Expected an overloaded operator"); 7734 7735 case OO_New: 7736 case OO_Delete: 7737 case OO_Array_New: 7738 case OO_Array_Delete: 7739 case OO_Call: 7740 llvm_unreachable( 7741 "Special operators don't use AddBuiltinOperatorCandidates"); 7742 7743 case OO_Comma: 7744 case OO_Arrow: 7745 // C++ [over.match.oper]p3: 7746 // -- For the operator ',', the unary operator '&', or the 7747 // operator '->', the built-in candidates set is empty. 7748 break; 7749 7750 case OO_Plus: // '+' is either unary or binary 7751 if (Args.size() == 1) 7752 OpBuilder.addUnaryPlusPointerOverloads(); 7753 // Fall through. 7754 7755 case OO_Minus: // '-' is either unary or binary 7756 if (Args.size() == 1) { 7757 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7758 } else { 7759 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7760 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7761 } 7762 break; 7763 7764 case OO_Star: // '*' is either unary or binary 7765 if (Args.size() == 1) 7766 OpBuilder.addUnaryStarPointerOverloads(); 7767 else 7768 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7769 break; 7770 7771 case OO_Slash: 7772 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7773 break; 7774 7775 case OO_PlusPlus: 7776 case OO_MinusMinus: 7777 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7778 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7779 break; 7780 7781 case OO_EqualEqual: 7782 case OO_ExclaimEqual: 7783 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7784 // Fall through. 7785 7786 case OO_Less: 7787 case OO_Greater: 7788 case OO_LessEqual: 7789 case OO_GreaterEqual: 7790 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7791 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7792 break; 7793 7794 case OO_Percent: 7795 case OO_Caret: 7796 case OO_Pipe: 7797 case OO_LessLess: 7798 case OO_GreaterGreater: 7799 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7800 break; 7801 7802 case OO_Amp: // '&' is either unary or binary 7803 if (Args.size() == 1) 7804 // C++ [over.match.oper]p3: 7805 // -- For the operator ',', the unary operator '&', or the 7806 // operator '->', the built-in candidates set is empty. 7807 break; 7808 7809 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7810 break; 7811 7812 case OO_Tilde: 7813 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7814 break; 7815 7816 case OO_Equal: 7817 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7818 // Fall through. 7819 7820 case OO_PlusEqual: 7821 case OO_MinusEqual: 7822 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7823 // Fall through. 7824 7825 case OO_StarEqual: 7826 case OO_SlashEqual: 7827 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7828 break; 7829 7830 case OO_PercentEqual: 7831 case OO_LessLessEqual: 7832 case OO_GreaterGreaterEqual: 7833 case OO_AmpEqual: 7834 case OO_CaretEqual: 7835 case OO_PipeEqual: 7836 OpBuilder.addAssignmentIntegralOverloads(); 7837 break; 7838 7839 case OO_Exclaim: 7840 OpBuilder.addExclaimOverload(); 7841 break; 7842 7843 case OO_AmpAmp: 7844 case OO_PipePipe: 7845 OpBuilder.addAmpAmpOrPipePipeOverload(); 7846 break; 7847 7848 case OO_Subscript: 7849 OpBuilder.addSubscriptOverloads(); 7850 break; 7851 7852 case OO_ArrowStar: 7853 OpBuilder.addArrowStarOverloads(); 7854 break; 7855 7856 case OO_Conditional: 7857 OpBuilder.addConditionalOperatorOverloads(); 7858 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7859 break; 7860 } 7861 } 7862 7863 /// \brief Add function candidates found via argument-dependent lookup 7864 /// to the set of overloading candidates. 7865 /// 7866 /// This routine performs argument-dependent name lookup based on the 7867 /// given function name (which may also be an operator name) and adds 7868 /// all of the overload candidates found by ADL to the overload 7869 /// candidate set (C++ [basic.lookup.argdep]). 7870 void 7871 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7872 bool Operator, SourceLocation Loc, 7873 ArrayRef<Expr *> Args, 7874 TemplateArgumentListInfo *ExplicitTemplateArgs, 7875 OverloadCandidateSet& CandidateSet, 7876 bool PartialOverloading) { 7877 ADLResult Fns; 7878 7879 // FIXME: This approach for uniquing ADL results (and removing 7880 // redundant candidates from the set) relies on pointer-equality, 7881 // which means we need to key off the canonical decl. However, 7882 // always going back to the canonical decl might not get us the 7883 // right set of default arguments. What default arguments are 7884 // we supposed to consider on ADL candidates, anyway? 7885 7886 // FIXME: Pass in the explicit template arguments? 7887 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7888 7889 // Erase all of the candidates we already knew about. 7890 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7891 CandEnd = CandidateSet.end(); 7892 Cand != CandEnd; ++Cand) 7893 if (Cand->Function) { 7894 Fns.erase(Cand->Function); 7895 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7896 Fns.erase(FunTmpl); 7897 } 7898 7899 // For each of the ADL candidates we found, add it to the overload 7900 // set. 7901 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7902 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7903 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7904 if (ExplicitTemplateArgs) 7905 continue; 7906 7907 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7908 PartialOverloading); 7909 } else 7910 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7911 FoundDecl, ExplicitTemplateArgs, 7912 Args, CandidateSet); 7913 } 7914 } 7915 7916 /// isBetterOverloadCandidate - Determines whether the first overload 7917 /// candidate is a better candidate than the second (C++ 13.3.3p1). 7918 bool 7919 isBetterOverloadCandidate(Sema &S, 7920 const OverloadCandidate &Cand1, 7921 const OverloadCandidate &Cand2, 7922 SourceLocation Loc, 7923 bool UserDefinedConversion) { 7924 // Define viable functions to be better candidates than non-viable 7925 // functions. 7926 if (!Cand2.Viable) 7927 return Cand1.Viable; 7928 else if (!Cand1.Viable) 7929 return false; 7930 7931 // C++ [over.match.best]p1: 7932 // 7933 // -- if F is a static member function, ICS1(F) is defined such 7934 // that ICS1(F) is neither better nor worse than ICS1(G) for 7935 // any function G, and, symmetrically, ICS1(G) is neither 7936 // better nor worse than ICS1(F). 7937 unsigned StartArg = 0; 7938 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7939 StartArg = 1; 7940 7941 // C++ [over.match.best]p1: 7942 // A viable function F1 is defined to be a better function than another 7943 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7944 // conversion sequence than ICSi(F2), and then... 7945 unsigned NumArgs = Cand1.NumConversions; 7946 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7947 bool HasBetterConversion = false; 7948 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7949 switch (CompareImplicitConversionSequences(S, 7950 Cand1.Conversions[ArgIdx], 7951 Cand2.Conversions[ArgIdx])) { 7952 case ImplicitConversionSequence::Better: 7953 // Cand1 has a better conversion sequence. 7954 HasBetterConversion = true; 7955 break; 7956 7957 case ImplicitConversionSequence::Worse: 7958 // Cand1 can't be better than Cand2. 7959 return false; 7960 7961 case ImplicitConversionSequence::Indistinguishable: 7962 // Do nothing. 7963 break; 7964 } 7965 } 7966 7967 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7968 // ICSj(F2), or, if not that, 7969 if (HasBetterConversion) 7970 return true; 7971 7972 // - F1 is a non-template function and F2 is a function template 7973 // specialization, or, if not that, 7974 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7975 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7976 return true; 7977 7978 // -- F1 and F2 are function template specializations, and the function 7979 // template for F1 is more specialized than the template for F2 7980 // according to the partial ordering rules described in 14.5.5.2, or, 7981 // if not that, 7982 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7983 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7984 if (FunctionTemplateDecl *BetterTemplate 7985 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7986 Cand2.Function->getPrimaryTemplate(), 7987 Loc, 7988 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7989 : TPOC_Call, 7990 Cand1.ExplicitCallArguments)) 7991 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7992 } 7993 7994 // -- the context is an initialization by user-defined conversion 7995 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7996 // from the return type of F1 to the destination type (i.e., 7997 // the type of the entity being initialized) is a better 7998 // conversion sequence than the standard conversion sequence 7999 // from the return type of F2 to the destination type. 8000 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8001 isa<CXXConversionDecl>(Cand1.Function) && 8002 isa<CXXConversionDecl>(Cand2.Function)) { 8003 // First check whether we prefer one of the conversion functions over the 8004 // other. This only distinguishes the results in non-standard, extension 8005 // cases such as the conversion from a lambda closure type to a function 8006 // pointer or block. 8007 ImplicitConversionSequence::CompareKind FuncResult 8008 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8009 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8010 return FuncResult; 8011 8012 switch (CompareStandardConversionSequences(S, 8013 Cand1.FinalConversion, 8014 Cand2.FinalConversion)) { 8015 case ImplicitConversionSequence::Better: 8016 // Cand1 has a better conversion sequence. 8017 return true; 8018 8019 case ImplicitConversionSequence::Worse: 8020 // Cand1 can't be better than Cand2. 8021 return false; 8022 8023 case ImplicitConversionSequence::Indistinguishable: 8024 // Do nothing 8025 break; 8026 } 8027 } 8028 8029 return false; 8030 } 8031 8032 /// \brief Computes the best viable function (C++ 13.3.3) 8033 /// within an overload candidate set. 8034 /// 8035 /// \param Loc The location of the function name (or operator symbol) for 8036 /// which overload resolution occurs. 8037 /// 8038 /// \param Best If overload resolution was successful or found a deleted 8039 /// function, \p Best points to the candidate function found. 8040 /// 8041 /// \returns The result of overload resolution. 8042 OverloadingResult 8043 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8044 iterator &Best, 8045 bool UserDefinedConversion) { 8046 // Find the best viable function. 8047 Best = end(); 8048 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8049 if (Cand->Viable) 8050 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8051 UserDefinedConversion)) 8052 Best = Cand; 8053 } 8054 8055 // If we didn't find any viable functions, abort. 8056 if (Best == end()) 8057 return OR_No_Viable_Function; 8058 8059 // Make sure that this function is better than every other viable 8060 // function. If not, we have an ambiguity. 8061 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8062 if (Cand->Viable && 8063 Cand != Best && 8064 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8065 UserDefinedConversion)) { 8066 Best = end(); 8067 return OR_Ambiguous; 8068 } 8069 } 8070 8071 // Best is the best viable function. 8072 if (Best->Function && 8073 (Best->Function->isDeleted() || 8074 S.isFunctionConsideredUnavailable(Best->Function))) 8075 return OR_Deleted; 8076 8077 return OR_Success; 8078 } 8079 8080 namespace { 8081 8082 enum OverloadCandidateKind { 8083 oc_function, 8084 oc_method, 8085 oc_constructor, 8086 oc_function_template, 8087 oc_method_template, 8088 oc_constructor_template, 8089 oc_implicit_default_constructor, 8090 oc_implicit_copy_constructor, 8091 oc_implicit_move_constructor, 8092 oc_implicit_copy_assignment, 8093 oc_implicit_move_assignment, 8094 oc_implicit_inherited_constructor 8095 }; 8096 8097 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8098 FunctionDecl *Fn, 8099 std::string &Description) { 8100 bool isTemplate = false; 8101 8102 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8103 isTemplate = true; 8104 Description = S.getTemplateArgumentBindingsText( 8105 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8106 } 8107 8108 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8109 if (!Ctor->isImplicit()) 8110 return isTemplate ? oc_constructor_template : oc_constructor; 8111 8112 if (Ctor->getInheritedConstructor()) 8113 return oc_implicit_inherited_constructor; 8114 8115 if (Ctor->isDefaultConstructor()) 8116 return oc_implicit_default_constructor; 8117 8118 if (Ctor->isMoveConstructor()) 8119 return oc_implicit_move_constructor; 8120 8121 assert(Ctor->isCopyConstructor() && 8122 "unexpected sort of implicit constructor"); 8123 return oc_implicit_copy_constructor; 8124 } 8125 8126 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8127 // This actually gets spelled 'candidate function' for now, but 8128 // it doesn't hurt to split it out. 8129 if (!Meth->isImplicit()) 8130 return isTemplate ? oc_method_template : oc_method; 8131 8132 if (Meth->isMoveAssignmentOperator()) 8133 return oc_implicit_move_assignment; 8134 8135 if (Meth->isCopyAssignmentOperator()) 8136 return oc_implicit_copy_assignment; 8137 8138 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8139 return oc_method; 8140 } 8141 8142 return isTemplate ? oc_function_template : oc_function; 8143 } 8144 8145 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8146 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8147 if (!Ctor) return; 8148 8149 Ctor = Ctor->getInheritedConstructor(); 8150 if (!Ctor) return; 8151 8152 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8153 } 8154 8155 } // end anonymous namespace 8156 8157 // Notes the location of an overload candidate. 8158 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8159 std::string FnDesc; 8160 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8161 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8162 << (unsigned) K << FnDesc; 8163 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8164 Diag(Fn->getLocation(), PD); 8165 MaybeEmitInheritedConstructorNote(*this, Fn); 8166 } 8167 8168 //Notes the location of all overload candidates designated through 8169 // OverloadedExpr 8170 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8171 assert(OverloadedExpr->getType() == Context.OverloadTy); 8172 8173 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8174 OverloadExpr *OvlExpr = Ovl.Expression; 8175 8176 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8177 IEnd = OvlExpr->decls_end(); 8178 I != IEnd; ++I) { 8179 if (FunctionTemplateDecl *FunTmpl = 8180 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8181 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8182 } else if (FunctionDecl *Fun 8183 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8184 NoteOverloadCandidate(Fun, DestType); 8185 } 8186 } 8187 } 8188 8189 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8190 /// "lead" diagnostic; it will be given two arguments, the source and 8191 /// target types of the conversion. 8192 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8193 Sema &S, 8194 SourceLocation CaretLoc, 8195 const PartialDiagnostic &PDiag) const { 8196 S.Diag(CaretLoc, PDiag) 8197 << Ambiguous.getFromType() << Ambiguous.getToType(); 8198 // FIXME: The note limiting machinery is borrowed from 8199 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8200 // refactoring here. 8201 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8202 unsigned CandsShown = 0; 8203 AmbiguousConversionSequence::const_iterator I, E; 8204 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8205 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8206 break; 8207 ++CandsShown; 8208 S.NoteOverloadCandidate(*I); 8209 } 8210 if (I != E) 8211 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8212 } 8213 8214 namespace { 8215 8216 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8217 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8218 assert(Conv.isBad()); 8219 assert(Cand->Function && "for now, candidate must be a function"); 8220 FunctionDecl *Fn = Cand->Function; 8221 8222 // There's a conversion slot for the object argument if this is a 8223 // non-constructor method. Note that 'I' corresponds the 8224 // conversion-slot index. 8225 bool isObjectArgument = false; 8226 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8227 if (I == 0) 8228 isObjectArgument = true; 8229 else 8230 I--; 8231 } 8232 8233 std::string FnDesc; 8234 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8235 8236 Expr *FromExpr = Conv.Bad.FromExpr; 8237 QualType FromTy = Conv.Bad.getFromType(); 8238 QualType ToTy = Conv.Bad.getToType(); 8239 8240 if (FromTy == S.Context.OverloadTy) { 8241 assert(FromExpr && "overload set argument came from implicit argument?"); 8242 Expr *E = FromExpr->IgnoreParens(); 8243 if (isa<UnaryOperator>(E)) 8244 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8245 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8246 8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8248 << (unsigned) FnKind << FnDesc 8249 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8250 << ToTy << Name << I+1; 8251 MaybeEmitInheritedConstructorNote(S, Fn); 8252 return; 8253 } 8254 8255 // Do some hand-waving analysis to see if the non-viability is due 8256 // to a qualifier mismatch. 8257 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8258 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8259 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8260 CToTy = RT->getPointeeType(); 8261 else { 8262 // TODO: detect and diagnose the full richness of const mismatches. 8263 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8264 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8265 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8266 } 8267 8268 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8269 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8270 Qualifiers FromQs = CFromTy.getQualifiers(); 8271 Qualifiers ToQs = CToTy.getQualifiers(); 8272 8273 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8274 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8275 << (unsigned) FnKind << FnDesc 8276 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8277 << FromTy 8278 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8279 << (unsigned) isObjectArgument << I+1; 8280 MaybeEmitInheritedConstructorNote(S, Fn); 8281 return; 8282 } 8283 8284 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8286 << (unsigned) FnKind << FnDesc 8287 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8288 << FromTy 8289 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8290 << (unsigned) isObjectArgument << I+1; 8291 MaybeEmitInheritedConstructorNote(S, Fn); 8292 return; 8293 } 8294 8295 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8297 << (unsigned) FnKind << FnDesc 8298 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8299 << FromTy 8300 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8301 << (unsigned) isObjectArgument << I+1; 8302 MaybeEmitInheritedConstructorNote(S, Fn); 8303 return; 8304 } 8305 8306 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8307 assert(CVR && "unexpected qualifiers mismatch"); 8308 8309 if (isObjectArgument) { 8310 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8311 << (unsigned) FnKind << FnDesc 8312 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8313 << FromTy << (CVR - 1); 8314 } else { 8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8316 << (unsigned) FnKind << FnDesc 8317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8318 << FromTy << (CVR - 1) << I+1; 8319 } 8320 MaybeEmitInheritedConstructorNote(S, Fn); 8321 return; 8322 } 8323 8324 // Special diagnostic for failure to convert an initializer list, since 8325 // telling the user that it has type void is not useful. 8326 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8327 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8328 << (unsigned) FnKind << FnDesc 8329 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8330 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8331 MaybeEmitInheritedConstructorNote(S, Fn); 8332 return; 8333 } 8334 8335 // Diagnose references or pointers to incomplete types differently, 8336 // since it's far from impossible that the incompleteness triggered 8337 // the failure. 8338 QualType TempFromTy = FromTy.getNonReferenceType(); 8339 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8340 TempFromTy = PTy->getPointeeType(); 8341 if (TempFromTy->isIncompleteType()) { 8342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8343 << (unsigned) FnKind << FnDesc 8344 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8345 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8346 MaybeEmitInheritedConstructorNote(S, Fn); 8347 return; 8348 } 8349 8350 // Diagnose base -> derived pointer conversions. 8351 unsigned BaseToDerivedConversion = 0; 8352 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8353 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8354 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8355 FromPtrTy->getPointeeType()) && 8356 !FromPtrTy->getPointeeType()->isIncompleteType() && 8357 !ToPtrTy->getPointeeType()->isIncompleteType() && 8358 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8359 FromPtrTy->getPointeeType())) 8360 BaseToDerivedConversion = 1; 8361 } 8362 } else if (const ObjCObjectPointerType *FromPtrTy 8363 = FromTy->getAs<ObjCObjectPointerType>()) { 8364 if (const ObjCObjectPointerType *ToPtrTy 8365 = ToTy->getAs<ObjCObjectPointerType>()) 8366 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8367 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8368 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8369 FromPtrTy->getPointeeType()) && 8370 FromIface->isSuperClassOf(ToIface)) 8371 BaseToDerivedConversion = 2; 8372 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8373 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8374 !FromTy->isIncompleteType() && 8375 !ToRefTy->getPointeeType()->isIncompleteType() && 8376 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8377 BaseToDerivedConversion = 3; 8378 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8379 ToTy.getNonReferenceType().getCanonicalType() == 8380 FromTy.getNonReferenceType().getCanonicalType()) { 8381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8382 << (unsigned) FnKind << FnDesc 8383 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8384 << (unsigned) isObjectArgument << I + 1; 8385 MaybeEmitInheritedConstructorNote(S, Fn); 8386 return; 8387 } 8388 } 8389 8390 if (BaseToDerivedConversion) { 8391 S.Diag(Fn->getLocation(), 8392 diag::note_ovl_candidate_bad_base_to_derived_conv) 8393 << (unsigned) FnKind << FnDesc 8394 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8395 << (BaseToDerivedConversion - 1) 8396 << FromTy << ToTy << I+1; 8397 MaybeEmitInheritedConstructorNote(S, Fn); 8398 return; 8399 } 8400 8401 if (isa<ObjCObjectPointerType>(CFromTy) && 8402 isa<PointerType>(CToTy)) { 8403 Qualifiers FromQs = CFromTy.getQualifiers(); 8404 Qualifiers ToQs = CToTy.getQualifiers(); 8405 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8406 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8407 << (unsigned) FnKind << FnDesc 8408 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8409 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8410 MaybeEmitInheritedConstructorNote(S, Fn); 8411 return; 8412 } 8413 } 8414 8415 // Emit the generic diagnostic and, optionally, add the hints to it. 8416 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8417 FDiag << (unsigned) FnKind << FnDesc 8418 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8419 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8420 << (unsigned) (Cand->Fix.Kind); 8421 8422 // If we can fix the conversion, suggest the FixIts. 8423 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8424 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8425 FDiag << *HI; 8426 S.Diag(Fn->getLocation(), FDiag); 8427 8428 MaybeEmitInheritedConstructorNote(S, Fn); 8429 } 8430 8431 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8432 unsigned NumFormalArgs) { 8433 // TODO: treat calls to a missing default constructor as a special case 8434 8435 FunctionDecl *Fn = Cand->Function; 8436 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8437 8438 unsigned MinParams = Fn->getMinRequiredArguments(); 8439 8440 // With invalid overloaded operators, it's possible that we think we 8441 // have an arity mismatch when it fact it looks like we have the 8442 // right number of arguments, because only overloaded operators have 8443 // the weird behavior of overloading member and non-member functions. 8444 // Just don't report anything. 8445 if (Fn->isInvalidDecl() && 8446 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8447 return; 8448 8449 // at least / at most / exactly 8450 unsigned mode, modeCount; 8451 if (NumFormalArgs < MinParams) { 8452 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8453 (Cand->FailureKind == ovl_fail_bad_deduction && 8454 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8455 if (MinParams != FnTy->getNumArgs() || 8456 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8457 mode = 0; // "at least" 8458 else 8459 mode = 2; // "exactly" 8460 modeCount = MinParams; 8461 } else { 8462 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8463 (Cand->FailureKind == ovl_fail_bad_deduction && 8464 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8465 if (MinParams != FnTy->getNumArgs()) 8466 mode = 1; // "at most" 8467 else 8468 mode = 2; // "exactly" 8469 modeCount = FnTy->getNumArgs(); 8470 } 8471 8472 std::string Description; 8473 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8474 8475 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8477 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8478 << Fn->getParamDecl(0) << NumFormalArgs; 8479 else 8480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8481 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8482 << modeCount << NumFormalArgs; 8483 MaybeEmitInheritedConstructorNote(S, Fn); 8484 } 8485 8486 /// Diagnose a failed template-argument deduction. 8487 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8488 unsigned NumArgs) { 8489 FunctionDecl *Fn = Cand->Function; // pattern 8490 8491 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8492 NamedDecl *ParamD; 8493 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8494 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8495 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8496 switch (Cand->DeductionFailure.Result) { 8497 case Sema::TDK_Success: 8498 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8499 8500 case Sema::TDK_Incomplete: { 8501 assert(ParamD && "no parameter found for incomplete deduction result"); 8502 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8503 << ParamD->getDeclName(); 8504 MaybeEmitInheritedConstructorNote(S, Fn); 8505 return; 8506 } 8507 8508 case Sema::TDK_Underqualified: { 8509 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8510 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8511 8512 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8513 8514 // Param will have been canonicalized, but it should just be a 8515 // qualified version of ParamD, so move the qualifiers to that. 8516 QualifierCollector Qs; 8517 Qs.strip(Param); 8518 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8519 assert(S.Context.hasSameType(Param, NonCanonParam)); 8520 8521 // Arg has also been canonicalized, but there's nothing we can do 8522 // about that. It also doesn't matter as much, because it won't 8523 // have any template parameters in it (because deduction isn't 8524 // done on dependent types). 8525 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8526 8527 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8528 << ParamD->getDeclName() << Arg << NonCanonParam; 8529 MaybeEmitInheritedConstructorNote(S, Fn); 8530 return; 8531 } 8532 8533 case Sema::TDK_Inconsistent: { 8534 assert(ParamD && "no parameter found for inconsistent deduction result"); 8535 int which = 0; 8536 if (isa<TemplateTypeParmDecl>(ParamD)) 8537 which = 0; 8538 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8539 which = 1; 8540 else { 8541 which = 2; 8542 } 8543 8544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8545 << which << ParamD->getDeclName() 8546 << *Cand->DeductionFailure.getFirstArg() 8547 << *Cand->DeductionFailure.getSecondArg(); 8548 MaybeEmitInheritedConstructorNote(S, Fn); 8549 return; 8550 } 8551 8552 case Sema::TDK_InvalidExplicitArguments: 8553 assert(ParamD && "no parameter found for invalid explicit arguments"); 8554 if (ParamD->getDeclName()) 8555 S.Diag(Fn->getLocation(), 8556 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8557 << ParamD->getDeclName(); 8558 else { 8559 int index = 0; 8560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8561 index = TTP->getIndex(); 8562 else if (NonTypeTemplateParmDecl *NTTP 8563 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8564 index = NTTP->getIndex(); 8565 else 8566 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8567 S.Diag(Fn->getLocation(), 8568 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8569 << (index + 1); 8570 } 8571 MaybeEmitInheritedConstructorNote(S, Fn); 8572 return; 8573 8574 case Sema::TDK_TooManyArguments: 8575 case Sema::TDK_TooFewArguments: 8576 DiagnoseArityMismatch(S, Cand, NumArgs); 8577 return; 8578 8579 case Sema::TDK_InstantiationDepth: 8580 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8581 MaybeEmitInheritedConstructorNote(S, Fn); 8582 return; 8583 8584 case Sema::TDK_SubstitutionFailure: { 8585 // Format the template argument list into the argument string. 8586 SmallString<128> TemplateArgString; 8587 if (TemplateArgumentList *Args = 8588 Cand->DeductionFailure.getTemplateArgumentList()) { 8589 TemplateArgString = " "; 8590 TemplateArgString += S.getTemplateArgumentBindingsText( 8591 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8592 } 8593 8594 // If this candidate was disabled by enable_if, say so. 8595 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8596 if (PDiag && PDiag->second.getDiagID() == 8597 diag::err_typename_nested_not_found_enable_if) { 8598 // FIXME: Use the source range of the condition, and the fully-qualified 8599 // name of the enable_if template. These are both present in PDiag. 8600 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8601 << "'enable_if'" << TemplateArgString; 8602 return; 8603 } 8604 8605 // Format the SFINAE diagnostic into the argument string. 8606 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8607 // formatted message in another diagnostic. 8608 SmallString<128> SFINAEArgString; 8609 SourceRange R; 8610 if (PDiag) { 8611 SFINAEArgString = ": "; 8612 R = SourceRange(PDiag->first, PDiag->first); 8613 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8614 } 8615 8616 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8617 << TemplateArgString << SFINAEArgString << R; 8618 MaybeEmitInheritedConstructorNote(S, Fn); 8619 return; 8620 } 8621 8622 case Sema::TDK_FailedOverloadResolution: { 8623 OverloadExpr::FindResult R = 8624 OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8625 S.Diag(Fn->getLocation(), 8626 diag::note_ovl_candidate_failed_overload_resolution) 8627 << R.Expression->getName(); 8628 return; 8629 } 8630 8631 case Sema::TDK_NonDeducedMismatch: { 8632 // FIXME: Provide a source location to indicate what we couldn't match. 8633 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg(); 8634 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg(); 8635 if (FirstTA.getKind() == TemplateArgument::Template && 8636 SecondTA.getKind() == TemplateArgument::Template) { 8637 TemplateName FirstTN = FirstTA.getAsTemplate(); 8638 TemplateName SecondTN = SecondTA.getAsTemplate(); 8639 if (FirstTN.getKind() == TemplateName::Template && 8640 SecondTN.getKind() == TemplateName::Template) { 8641 if (FirstTN.getAsTemplateDecl()->getName() == 8642 SecondTN.getAsTemplateDecl()->getName()) { 8643 // FIXME: This fixes a bad diagnostic where both templates are named 8644 // the same. This particular case is a bit difficult since: 8645 // 1) It is passed as a string to the diagnostic printer. 8646 // 2) The diagnostic printer only attempts to find a better 8647 // name for types, not decls. 8648 // Ideally, this should folded into the diagnostic printer. 8649 S.Diag(Fn->getLocation(), 8650 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8651 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8652 return; 8653 } 8654 } 8655 } 8656 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8657 << FirstTA << SecondTA; 8658 return; 8659 } 8660 // TODO: diagnose these individually, then kill off 8661 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8662 case Sema::TDK_MiscellaneousDeductionFailure: 8663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8664 MaybeEmitInheritedConstructorNote(S, Fn); 8665 return; 8666 } 8667 } 8668 8669 /// CUDA: diagnose an invalid call across targets. 8670 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8671 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8672 FunctionDecl *Callee = Cand->Function; 8673 8674 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8675 CalleeTarget = S.IdentifyCUDATarget(Callee); 8676 8677 std::string FnDesc; 8678 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8679 8680 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8681 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8682 } 8683 8684 /// Generates a 'note' diagnostic for an overload candidate. We've 8685 /// already generated a primary error at the call site. 8686 /// 8687 /// It really does need to be a single diagnostic with its caret 8688 /// pointed at the candidate declaration. Yes, this creates some 8689 /// major challenges of technical writing. Yes, this makes pointing 8690 /// out problems with specific arguments quite awkward. It's still 8691 /// better than generating twenty screens of text for every failed 8692 /// overload. 8693 /// 8694 /// It would be great to be able to express per-candidate problems 8695 /// more richly for those diagnostic clients that cared, but we'd 8696 /// still have to be just as careful with the default diagnostics. 8697 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8698 unsigned NumArgs) { 8699 FunctionDecl *Fn = Cand->Function; 8700 8701 // Note deleted candidates, but only if they're viable. 8702 if (Cand->Viable && (Fn->isDeleted() || 8703 S.isFunctionConsideredUnavailable(Fn))) { 8704 std::string FnDesc; 8705 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8706 8707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8708 << FnKind << FnDesc 8709 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8710 MaybeEmitInheritedConstructorNote(S, Fn); 8711 return; 8712 } 8713 8714 // We don't really have anything else to say about viable candidates. 8715 if (Cand->Viable) { 8716 S.NoteOverloadCandidate(Fn); 8717 return; 8718 } 8719 8720 switch (Cand->FailureKind) { 8721 case ovl_fail_too_many_arguments: 8722 case ovl_fail_too_few_arguments: 8723 return DiagnoseArityMismatch(S, Cand, NumArgs); 8724 8725 case ovl_fail_bad_deduction: 8726 return DiagnoseBadDeduction(S, Cand, NumArgs); 8727 8728 case ovl_fail_trivial_conversion: 8729 case ovl_fail_bad_final_conversion: 8730 case ovl_fail_final_conversion_not_exact: 8731 return S.NoteOverloadCandidate(Fn); 8732 8733 case ovl_fail_bad_conversion: { 8734 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8735 for (unsigned N = Cand->NumConversions; I != N; ++I) 8736 if (Cand->Conversions[I].isBad()) 8737 return DiagnoseBadConversion(S, Cand, I); 8738 8739 // FIXME: this currently happens when we're called from SemaInit 8740 // when user-conversion overload fails. Figure out how to handle 8741 // those conditions and diagnose them well. 8742 return S.NoteOverloadCandidate(Fn); 8743 } 8744 8745 case ovl_fail_bad_target: 8746 return DiagnoseBadTarget(S, Cand); 8747 } 8748 } 8749 8750 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8751 // Desugar the type of the surrogate down to a function type, 8752 // retaining as many typedefs as possible while still showing 8753 // the function type (and, therefore, its parameter types). 8754 QualType FnType = Cand->Surrogate->getConversionType(); 8755 bool isLValueReference = false; 8756 bool isRValueReference = false; 8757 bool isPointer = false; 8758 if (const LValueReferenceType *FnTypeRef = 8759 FnType->getAs<LValueReferenceType>()) { 8760 FnType = FnTypeRef->getPointeeType(); 8761 isLValueReference = true; 8762 } else if (const RValueReferenceType *FnTypeRef = 8763 FnType->getAs<RValueReferenceType>()) { 8764 FnType = FnTypeRef->getPointeeType(); 8765 isRValueReference = true; 8766 } 8767 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8768 FnType = FnTypePtr->getPointeeType(); 8769 isPointer = true; 8770 } 8771 // Desugar down to a function type. 8772 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8773 // Reconstruct the pointer/reference as appropriate. 8774 if (isPointer) FnType = S.Context.getPointerType(FnType); 8775 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8776 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8777 8778 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8779 << FnType; 8780 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8781 } 8782 8783 void NoteBuiltinOperatorCandidate(Sema &S, 8784 StringRef Opc, 8785 SourceLocation OpLoc, 8786 OverloadCandidate *Cand) { 8787 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8788 std::string TypeStr("operator"); 8789 TypeStr += Opc; 8790 TypeStr += "("; 8791 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8792 if (Cand->NumConversions == 1) { 8793 TypeStr += ")"; 8794 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8795 } else { 8796 TypeStr += ", "; 8797 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8798 TypeStr += ")"; 8799 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8800 } 8801 } 8802 8803 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8804 OverloadCandidate *Cand) { 8805 unsigned NoOperands = Cand->NumConversions; 8806 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8807 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8808 if (ICS.isBad()) break; // all meaningless after first invalid 8809 if (!ICS.isAmbiguous()) continue; 8810 8811 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8812 S.PDiag(diag::note_ambiguous_type_conversion)); 8813 } 8814 } 8815 8816 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8817 if (Cand->Function) 8818 return Cand->Function->getLocation(); 8819 if (Cand->IsSurrogate) 8820 return Cand->Surrogate->getLocation(); 8821 return SourceLocation(); 8822 } 8823 8824 static unsigned 8825 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8826 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8827 case Sema::TDK_Success: 8828 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8829 8830 case Sema::TDK_Invalid: 8831 case Sema::TDK_Incomplete: 8832 return 1; 8833 8834 case Sema::TDK_Underqualified: 8835 case Sema::TDK_Inconsistent: 8836 return 2; 8837 8838 case Sema::TDK_SubstitutionFailure: 8839 case Sema::TDK_NonDeducedMismatch: 8840 case Sema::TDK_MiscellaneousDeductionFailure: 8841 return 3; 8842 8843 case Sema::TDK_InstantiationDepth: 8844 case Sema::TDK_FailedOverloadResolution: 8845 return 4; 8846 8847 case Sema::TDK_InvalidExplicitArguments: 8848 return 5; 8849 8850 case Sema::TDK_TooManyArguments: 8851 case Sema::TDK_TooFewArguments: 8852 return 6; 8853 } 8854 llvm_unreachable("Unhandled deduction result"); 8855 } 8856 8857 struct CompareOverloadCandidatesForDisplay { 8858 Sema &S; 8859 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8860 8861 bool operator()(const OverloadCandidate *L, 8862 const OverloadCandidate *R) { 8863 // Fast-path this check. 8864 if (L == R) return false; 8865 8866 // Order first by viability. 8867 if (L->Viable) { 8868 if (!R->Viable) return true; 8869 8870 // TODO: introduce a tri-valued comparison for overload 8871 // candidates. Would be more worthwhile if we had a sort 8872 // that could exploit it. 8873 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8874 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8875 } else if (R->Viable) 8876 return false; 8877 8878 assert(L->Viable == R->Viable); 8879 8880 // Criteria by which we can sort non-viable candidates: 8881 if (!L->Viable) { 8882 // 1. Arity mismatches come after other candidates. 8883 if (L->FailureKind == ovl_fail_too_many_arguments || 8884 L->FailureKind == ovl_fail_too_few_arguments) 8885 return false; 8886 if (R->FailureKind == ovl_fail_too_many_arguments || 8887 R->FailureKind == ovl_fail_too_few_arguments) 8888 return true; 8889 8890 // 2. Bad conversions come first and are ordered by the number 8891 // of bad conversions and quality of good conversions. 8892 if (L->FailureKind == ovl_fail_bad_conversion) { 8893 if (R->FailureKind != ovl_fail_bad_conversion) 8894 return true; 8895 8896 // The conversion that can be fixed with a smaller number of changes, 8897 // comes first. 8898 unsigned numLFixes = L->Fix.NumConversionsFixed; 8899 unsigned numRFixes = R->Fix.NumConversionsFixed; 8900 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8901 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8902 if (numLFixes != numRFixes) { 8903 if (numLFixes < numRFixes) 8904 return true; 8905 else 8906 return false; 8907 } 8908 8909 // If there's any ordering between the defined conversions... 8910 // FIXME: this might not be transitive. 8911 assert(L->NumConversions == R->NumConversions); 8912 8913 int leftBetter = 0; 8914 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8915 for (unsigned E = L->NumConversions; I != E; ++I) { 8916 switch (CompareImplicitConversionSequences(S, 8917 L->Conversions[I], 8918 R->Conversions[I])) { 8919 case ImplicitConversionSequence::Better: 8920 leftBetter++; 8921 break; 8922 8923 case ImplicitConversionSequence::Worse: 8924 leftBetter--; 8925 break; 8926 8927 case ImplicitConversionSequence::Indistinguishable: 8928 break; 8929 } 8930 } 8931 if (leftBetter > 0) return true; 8932 if (leftBetter < 0) return false; 8933 8934 } else if (R->FailureKind == ovl_fail_bad_conversion) 8935 return false; 8936 8937 if (L->FailureKind == ovl_fail_bad_deduction) { 8938 if (R->FailureKind != ovl_fail_bad_deduction) 8939 return true; 8940 8941 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8942 return RankDeductionFailure(L->DeductionFailure) 8943 < RankDeductionFailure(R->DeductionFailure); 8944 } else if (R->FailureKind == ovl_fail_bad_deduction) 8945 return false; 8946 8947 // TODO: others? 8948 } 8949 8950 // Sort everything else by location. 8951 SourceLocation LLoc = GetLocationForCandidate(L); 8952 SourceLocation RLoc = GetLocationForCandidate(R); 8953 8954 // Put candidates without locations (e.g. builtins) at the end. 8955 if (LLoc.isInvalid()) return false; 8956 if (RLoc.isInvalid()) return true; 8957 8958 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8959 } 8960 }; 8961 8962 /// CompleteNonViableCandidate - Normally, overload resolution only 8963 /// computes up to the first. Produces the FixIt set if possible. 8964 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8965 ArrayRef<Expr *> Args) { 8966 assert(!Cand->Viable); 8967 8968 // Don't do anything on failures other than bad conversion. 8969 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8970 8971 // We only want the FixIts if all the arguments can be corrected. 8972 bool Unfixable = false; 8973 // Use a implicit copy initialization to check conversion fixes. 8974 Cand->Fix.setConversionChecker(TryCopyInitialization); 8975 8976 // Skip forward to the first bad conversion. 8977 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8978 unsigned ConvCount = Cand->NumConversions; 8979 while (true) { 8980 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8981 ConvIdx++; 8982 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8983 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8984 break; 8985 } 8986 } 8987 8988 if (ConvIdx == ConvCount) 8989 return; 8990 8991 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8992 "remaining conversion is initialized?"); 8993 8994 // FIXME: this should probably be preserved from the overload 8995 // operation somehow. 8996 bool SuppressUserConversions = false; 8997 8998 const FunctionProtoType* Proto; 8999 unsigned ArgIdx = ConvIdx; 9000 9001 if (Cand->IsSurrogate) { 9002 QualType ConvType 9003 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9004 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9005 ConvType = ConvPtrType->getPointeeType(); 9006 Proto = ConvType->getAs<FunctionProtoType>(); 9007 ArgIdx--; 9008 } else if (Cand->Function) { 9009 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9010 if (isa<CXXMethodDecl>(Cand->Function) && 9011 !isa<CXXConstructorDecl>(Cand->Function)) 9012 ArgIdx--; 9013 } else { 9014 // Builtin binary operator with a bad first conversion. 9015 assert(ConvCount <= 3); 9016 for (; ConvIdx != ConvCount; ++ConvIdx) 9017 Cand->Conversions[ConvIdx] 9018 = TryCopyInitialization(S, Args[ConvIdx], 9019 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9020 SuppressUserConversions, 9021 /*InOverloadResolution*/ true, 9022 /*AllowObjCWritebackConversion=*/ 9023 S.getLangOpts().ObjCAutoRefCount); 9024 return; 9025 } 9026 9027 // Fill in the rest of the conversions. 9028 unsigned NumArgsInProto = Proto->getNumArgs(); 9029 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9030 if (ArgIdx < NumArgsInProto) { 9031 Cand->Conversions[ConvIdx] 9032 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9033 SuppressUserConversions, 9034 /*InOverloadResolution=*/true, 9035 /*AllowObjCWritebackConversion=*/ 9036 S.getLangOpts().ObjCAutoRefCount); 9037 // Store the FixIt in the candidate if it exists. 9038 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9039 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9040 } 9041 else 9042 Cand->Conversions[ConvIdx].setEllipsis(); 9043 } 9044 } 9045 9046 } // end anonymous namespace 9047 9048 /// PrintOverloadCandidates - When overload resolution fails, prints 9049 /// diagnostic messages containing the candidates in the candidate 9050 /// set. 9051 void OverloadCandidateSet::NoteCandidates(Sema &S, 9052 OverloadCandidateDisplayKind OCD, 9053 ArrayRef<Expr *> Args, 9054 StringRef Opc, 9055 SourceLocation OpLoc) { 9056 // Sort the candidates by viability and position. Sorting directly would 9057 // be prohibitive, so we make a set of pointers and sort those. 9058 SmallVector<OverloadCandidate*, 32> Cands; 9059 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9060 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9061 if (Cand->Viable) 9062 Cands.push_back(Cand); 9063 else if (OCD == OCD_AllCandidates) { 9064 CompleteNonViableCandidate(S, Cand, Args); 9065 if (Cand->Function || Cand->IsSurrogate) 9066 Cands.push_back(Cand); 9067 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9068 // want to list every possible builtin candidate. 9069 } 9070 } 9071 9072 std::sort(Cands.begin(), Cands.end(), 9073 CompareOverloadCandidatesForDisplay(S)); 9074 9075 bool ReportedAmbiguousConversions = false; 9076 9077 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9078 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9079 unsigned CandsShown = 0; 9080 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9081 OverloadCandidate *Cand = *I; 9082 9083 // Set an arbitrary limit on the number of candidate functions we'll spam 9084 // the user with. FIXME: This limit should depend on details of the 9085 // candidate list. 9086 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9087 break; 9088 } 9089 ++CandsShown; 9090 9091 if (Cand->Function) 9092 NoteFunctionCandidate(S, Cand, Args.size()); 9093 else if (Cand->IsSurrogate) 9094 NoteSurrogateCandidate(S, Cand); 9095 else { 9096 assert(Cand->Viable && 9097 "Non-viable built-in candidates are not added to Cands."); 9098 // Generally we only see ambiguities including viable builtin 9099 // operators if overload resolution got screwed up by an 9100 // ambiguous user-defined conversion. 9101 // 9102 // FIXME: It's quite possible for different conversions to see 9103 // different ambiguities, though. 9104 if (!ReportedAmbiguousConversions) { 9105 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9106 ReportedAmbiguousConversions = true; 9107 } 9108 9109 // If this is a viable builtin, print it. 9110 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9111 } 9112 } 9113 9114 if (I != E) 9115 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9116 } 9117 9118 // [PossiblyAFunctionType] --> [Return] 9119 // NonFunctionType --> NonFunctionType 9120 // R (A) --> R(A) 9121 // R (*)(A) --> R (A) 9122 // R (&)(A) --> R (A) 9123 // R (S::*)(A) --> R (A) 9124 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9125 QualType Ret = PossiblyAFunctionType; 9126 if (const PointerType *ToTypePtr = 9127 PossiblyAFunctionType->getAs<PointerType>()) 9128 Ret = ToTypePtr->getPointeeType(); 9129 else if (const ReferenceType *ToTypeRef = 9130 PossiblyAFunctionType->getAs<ReferenceType>()) 9131 Ret = ToTypeRef->getPointeeType(); 9132 else if (const MemberPointerType *MemTypePtr = 9133 PossiblyAFunctionType->getAs<MemberPointerType>()) 9134 Ret = MemTypePtr->getPointeeType(); 9135 Ret = 9136 Context.getCanonicalType(Ret).getUnqualifiedType(); 9137 return Ret; 9138 } 9139 9140 // A helper class to help with address of function resolution 9141 // - allows us to avoid passing around all those ugly parameters 9142 class AddressOfFunctionResolver 9143 { 9144 Sema& S; 9145 Expr* SourceExpr; 9146 const QualType& TargetType; 9147 QualType TargetFunctionType; // Extracted function type from target type 9148 9149 bool Complain; 9150 //DeclAccessPair& ResultFunctionAccessPair; 9151 ASTContext& Context; 9152 9153 bool TargetTypeIsNonStaticMemberFunction; 9154 bool FoundNonTemplateFunction; 9155 9156 OverloadExpr::FindResult OvlExprInfo; 9157 OverloadExpr *OvlExpr; 9158 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9159 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9160 9161 public: 9162 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9163 const QualType& TargetType, bool Complain) 9164 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9165 Complain(Complain), Context(S.getASTContext()), 9166 TargetTypeIsNonStaticMemberFunction( 9167 !!TargetType->getAs<MemberPointerType>()), 9168 FoundNonTemplateFunction(false), 9169 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9170 OvlExpr(OvlExprInfo.Expression) 9171 { 9172 ExtractUnqualifiedFunctionTypeFromTargetType(); 9173 9174 if (!TargetFunctionType->isFunctionType()) { 9175 if (OvlExpr->hasExplicitTemplateArgs()) { 9176 DeclAccessPair dap; 9177 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9178 OvlExpr, false, &dap) ) { 9179 9180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9181 if (!Method->isStatic()) { 9182 // If the target type is a non-function type and the function 9183 // found is a non-static member function, pretend as if that was 9184 // the target, it's the only possible type to end up with. 9185 TargetTypeIsNonStaticMemberFunction = true; 9186 9187 // And skip adding the function if its not in the proper form. 9188 // We'll diagnose this due to an empty set of functions. 9189 if (!OvlExprInfo.HasFormOfMemberPointer) 9190 return; 9191 } 9192 } 9193 9194 Matches.push_back(std::make_pair(dap,Fn)); 9195 } 9196 } 9197 return; 9198 } 9199 9200 if (OvlExpr->hasExplicitTemplateArgs()) 9201 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9202 9203 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9204 // C++ [over.over]p4: 9205 // If more than one function is selected, [...] 9206 if (Matches.size() > 1) { 9207 if (FoundNonTemplateFunction) 9208 EliminateAllTemplateMatches(); 9209 else 9210 EliminateAllExceptMostSpecializedTemplate(); 9211 } 9212 } 9213 } 9214 9215 private: 9216 bool isTargetTypeAFunction() const { 9217 return TargetFunctionType->isFunctionType(); 9218 } 9219 9220 // [ToType] [Return] 9221 9222 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9223 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9224 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9225 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9226 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9227 } 9228 9229 // return true if any matching specializations were found 9230 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9231 const DeclAccessPair& CurAccessFunPair) { 9232 if (CXXMethodDecl *Method 9233 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9234 // Skip non-static function templates when converting to pointer, and 9235 // static when converting to member pointer. 9236 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9237 return false; 9238 } 9239 else if (TargetTypeIsNonStaticMemberFunction) 9240 return false; 9241 9242 // C++ [over.over]p2: 9243 // If the name is a function template, template argument deduction is 9244 // done (14.8.2.2), and if the argument deduction succeeds, the 9245 // resulting template argument list is used to generate a single 9246 // function template specialization, which is added to the set of 9247 // overloaded functions considered. 9248 FunctionDecl *Specialization = 0; 9249 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9250 if (Sema::TemplateDeductionResult Result 9251 = S.DeduceTemplateArguments(FunctionTemplate, 9252 &OvlExplicitTemplateArgs, 9253 TargetFunctionType, Specialization, 9254 Info, /*InOverloadResolution=*/true)) { 9255 // FIXME: make a note of the failed deduction for diagnostics. 9256 (void)Result; 9257 return false; 9258 } 9259 9260 // Template argument deduction ensures that we have an exact match or 9261 // compatible pointer-to-function arguments that would be adjusted by ICS. 9262 // This function template specicalization works. 9263 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9264 assert(S.isSameOrCompatibleFunctionType( 9265 Context.getCanonicalType(Specialization->getType()), 9266 Context.getCanonicalType(TargetFunctionType))); 9267 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9268 return true; 9269 } 9270 9271 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9272 const DeclAccessPair& CurAccessFunPair) { 9273 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9274 // Skip non-static functions when converting to pointer, and static 9275 // when converting to member pointer. 9276 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9277 return false; 9278 } 9279 else if (TargetTypeIsNonStaticMemberFunction) 9280 return false; 9281 9282 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9283 if (S.getLangOpts().CUDA) 9284 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9285 if (S.CheckCUDATarget(Caller, FunDecl)) 9286 return false; 9287 9288 // If any candidate has a placeholder return type, trigger its deduction 9289 // now. 9290 if (S.getLangOpts().CPlusPlus1y && 9291 FunDecl->getResultType()->isUndeducedType() && 9292 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9293 return false; 9294 9295 QualType ResultTy; 9296 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9297 FunDecl->getType()) || 9298 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9299 ResultTy)) { 9300 Matches.push_back(std::make_pair(CurAccessFunPair, 9301 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9302 FoundNonTemplateFunction = true; 9303 return true; 9304 } 9305 } 9306 9307 return false; 9308 } 9309 9310 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9311 bool Ret = false; 9312 9313 // If the overload expression doesn't have the form of a pointer to 9314 // member, don't try to convert it to a pointer-to-member type. 9315 if (IsInvalidFormOfPointerToMemberFunction()) 9316 return false; 9317 9318 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9319 E = OvlExpr->decls_end(); 9320 I != E; ++I) { 9321 // Look through any using declarations to find the underlying function. 9322 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9323 9324 // C++ [over.over]p3: 9325 // Non-member functions and static member functions match 9326 // targets of type "pointer-to-function" or "reference-to-function." 9327 // Nonstatic member functions match targets of 9328 // type "pointer-to-member-function." 9329 // Note that according to DR 247, the containing class does not matter. 9330 if (FunctionTemplateDecl *FunctionTemplate 9331 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9332 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9333 Ret = true; 9334 } 9335 // If we have explicit template arguments supplied, skip non-templates. 9336 else if (!OvlExpr->hasExplicitTemplateArgs() && 9337 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9338 Ret = true; 9339 } 9340 assert(Ret || Matches.empty()); 9341 return Ret; 9342 } 9343 9344 void EliminateAllExceptMostSpecializedTemplate() { 9345 // [...] and any given function template specialization F1 is 9346 // eliminated if the set contains a second function template 9347 // specialization whose function template is more specialized 9348 // than the function template of F1 according to the partial 9349 // ordering rules of 14.5.5.2. 9350 9351 // The algorithm specified above is quadratic. We instead use a 9352 // two-pass algorithm (similar to the one used to identify the 9353 // best viable function in an overload set) that identifies the 9354 // best function template (if it exists). 9355 9356 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9357 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9358 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9359 9360 UnresolvedSetIterator Result = 9361 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9362 TPOC_Other, 0, SourceExpr->getLocStart(), 9363 S.PDiag(), 9364 S.PDiag(diag::err_addr_ovl_ambiguous) 9365 << Matches[0].second->getDeclName(), 9366 S.PDiag(diag::note_ovl_candidate) 9367 << (unsigned) oc_function_template, 9368 Complain, TargetFunctionType); 9369 9370 if (Result != MatchesCopy.end()) { 9371 // Make it the first and only element 9372 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9373 Matches[0].second = cast<FunctionDecl>(*Result); 9374 Matches.resize(1); 9375 } 9376 } 9377 9378 void EliminateAllTemplateMatches() { 9379 // [...] any function template specializations in the set are 9380 // eliminated if the set also contains a non-template function, [...] 9381 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9382 if (Matches[I].second->getPrimaryTemplate() == 0) 9383 ++I; 9384 else { 9385 Matches[I] = Matches[--N]; 9386 Matches.set_size(N); 9387 } 9388 } 9389 } 9390 9391 public: 9392 void ComplainNoMatchesFound() const { 9393 assert(Matches.empty()); 9394 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9395 << OvlExpr->getName() << TargetFunctionType 9396 << OvlExpr->getSourceRange(); 9397 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9398 } 9399 9400 bool IsInvalidFormOfPointerToMemberFunction() const { 9401 return TargetTypeIsNonStaticMemberFunction && 9402 !OvlExprInfo.HasFormOfMemberPointer; 9403 } 9404 9405 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9406 // TODO: Should we condition this on whether any functions might 9407 // have matched, or is it more appropriate to do that in callers? 9408 // TODO: a fixit wouldn't hurt. 9409 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9410 << TargetType << OvlExpr->getSourceRange(); 9411 } 9412 9413 void ComplainOfInvalidConversion() const { 9414 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9415 << OvlExpr->getName() << TargetType; 9416 } 9417 9418 void ComplainMultipleMatchesFound() const { 9419 assert(Matches.size() > 1); 9420 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9421 << OvlExpr->getName() 9422 << OvlExpr->getSourceRange(); 9423 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9424 } 9425 9426 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9427 9428 int getNumMatches() const { return Matches.size(); } 9429 9430 FunctionDecl* getMatchingFunctionDecl() const { 9431 if (Matches.size() != 1) return 0; 9432 return Matches[0].second; 9433 } 9434 9435 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9436 if (Matches.size() != 1) return 0; 9437 return &Matches[0].first; 9438 } 9439 }; 9440 9441 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9442 /// an overloaded function (C++ [over.over]), where @p From is an 9443 /// expression with overloaded function type and @p ToType is the type 9444 /// we're trying to resolve to. For example: 9445 /// 9446 /// @code 9447 /// int f(double); 9448 /// int f(int); 9449 /// 9450 /// int (*pfd)(double) = f; // selects f(double) 9451 /// @endcode 9452 /// 9453 /// This routine returns the resulting FunctionDecl if it could be 9454 /// resolved, and NULL otherwise. When @p Complain is true, this 9455 /// routine will emit diagnostics if there is an error. 9456 FunctionDecl * 9457 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9458 QualType TargetType, 9459 bool Complain, 9460 DeclAccessPair &FoundResult, 9461 bool *pHadMultipleCandidates) { 9462 assert(AddressOfExpr->getType() == Context.OverloadTy); 9463 9464 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9465 Complain); 9466 int NumMatches = Resolver.getNumMatches(); 9467 FunctionDecl* Fn = 0; 9468 if (NumMatches == 0 && Complain) { 9469 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9470 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9471 else 9472 Resolver.ComplainNoMatchesFound(); 9473 } 9474 else if (NumMatches > 1 && Complain) 9475 Resolver.ComplainMultipleMatchesFound(); 9476 else if (NumMatches == 1) { 9477 Fn = Resolver.getMatchingFunctionDecl(); 9478 assert(Fn); 9479 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9480 if (Complain) 9481 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9482 } 9483 9484 if (pHadMultipleCandidates) 9485 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9486 return Fn; 9487 } 9488 9489 /// \brief Given an expression that refers to an overloaded function, try to 9490 /// resolve that overloaded function expression down to a single function. 9491 /// 9492 /// This routine can only resolve template-ids that refer to a single function 9493 /// template, where that template-id refers to a single template whose template 9494 /// arguments are either provided by the template-id or have defaults, 9495 /// as described in C++0x [temp.arg.explicit]p3. 9496 FunctionDecl * 9497 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9498 bool Complain, 9499 DeclAccessPair *FoundResult) { 9500 // C++ [over.over]p1: 9501 // [...] [Note: any redundant set of parentheses surrounding the 9502 // overloaded function name is ignored (5.1). ] 9503 // C++ [over.over]p1: 9504 // [...] The overloaded function name can be preceded by the & 9505 // operator. 9506 9507 // If we didn't actually find any template-ids, we're done. 9508 if (!ovl->hasExplicitTemplateArgs()) 9509 return 0; 9510 9511 TemplateArgumentListInfo ExplicitTemplateArgs; 9512 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9513 9514 // Look through all of the overloaded functions, searching for one 9515 // whose type matches exactly. 9516 FunctionDecl *Matched = 0; 9517 for (UnresolvedSetIterator I = ovl->decls_begin(), 9518 E = ovl->decls_end(); I != E; ++I) { 9519 // C++0x [temp.arg.explicit]p3: 9520 // [...] In contexts where deduction is done and fails, or in contexts 9521 // where deduction is not done, if a template argument list is 9522 // specified and it, along with any default template arguments, 9523 // identifies a single function template specialization, then the 9524 // template-id is an lvalue for the function template specialization. 9525 FunctionTemplateDecl *FunctionTemplate 9526 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9527 9528 // C++ [over.over]p2: 9529 // If the name is a function template, template argument deduction is 9530 // done (14.8.2.2), and if the argument deduction succeeds, the 9531 // resulting template argument list is used to generate a single 9532 // function template specialization, which is added to the set of 9533 // overloaded functions considered. 9534 FunctionDecl *Specialization = 0; 9535 TemplateDeductionInfo Info(ovl->getNameLoc()); 9536 if (TemplateDeductionResult Result 9537 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9538 Specialization, Info, 9539 /*InOverloadResolution=*/true)) { 9540 // FIXME: make a note of the failed deduction for diagnostics. 9541 (void)Result; 9542 continue; 9543 } 9544 9545 assert(Specialization && "no specialization and no error?"); 9546 9547 // Multiple matches; we can't resolve to a single declaration. 9548 if (Matched) { 9549 if (Complain) { 9550 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9551 << ovl->getName(); 9552 NoteAllOverloadCandidates(ovl); 9553 } 9554 return 0; 9555 } 9556 9557 Matched = Specialization; 9558 if (FoundResult) *FoundResult = I.getPair(); 9559 } 9560 9561 if (Matched && getLangOpts().CPlusPlus1y && 9562 Matched->getResultType()->isUndeducedType() && 9563 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9564 return 0; 9565 9566 return Matched; 9567 } 9568 9569 9570 9571 9572 // Resolve and fix an overloaded expression that can be resolved 9573 // because it identifies a single function template specialization. 9574 // 9575 // Last three arguments should only be supplied if Complain = true 9576 // 9577 // Return true if it was logically possible to so resolve the 9578 // expression, regardless of whether or not it succeeded. Always 9579 // returns true if 'complain' is set. 9580 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9581 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9582 bool complain, const SourceRange& OpRangeForComplaining, 9583 QualType DestTypeForComplaining, 9584 unsigned DiagIDForComplaining) { 9585 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9586 9587 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9588 9589 DeclAccessPair found; 9590 ExprResult SingleFunctionExpression; 9591 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9592 ovl.Expression, /*complain*/ false, &found)) { 9593 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9594 SrcExpr = ExprError(); 9595 return true; 9596 } 9597 9598 // It is only correct to resolve to an instance method if we're 9599 // resolving a form that's permitted to be a pointer to member. 9600 // Otherwise we'll end up making a bound member expression, which 9601 // is illegal in all the contexts we resolve like this. 9602 if (!ovl.HasFormOfMemberPointer && 9603 isa<CXXMethodDecl>(fn) && 9604 cast<CXXMethodDecl>(fn)->isInstance()) { 9605 if (!complain) return false; 9606 9607 Diag(ovl.Expression->getExprLoc(), 9608 diag::err_bound_member_function) 9609 << 0 << ovl.Expression->getSourceRange(); 9610 9611 // TODO: I believe we only end up here if there's a mix of 9612 // static and non-static candidates (otherwise the expression 9613 // would have 'bound member' type, not 'overload' type). 9614 // Ideally we would note which candidate was chosen and why 9615 // the static candidates were rejected. 9616 SrcExpr = ExprError(); 9617 return true; 9618 } 9619 9620 // Fix the expression to refer to 'fn'. 9621 SingleFunctionExpression = 9622 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9623 9624 // If desired, do function-to-pointer decay. 9625 if (doFunctionPointerConverion) { 9626 SingleFunctionExpression = 9627 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9628 if (SingleFunctionExpression.isInvalid()) { 9629 SrcExpr = ExprError(); 9630 return true; 9631 } 9632 } 9633 } 9634 9635 if (!SingleFunctionExpression.isUsable()) { 9636 if (complain) { 9637 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9638 << ovl.Expression->getName() 9639 << DestTypeForComplaining 9640 << OpRangeForComplaining 9641 << ovl.Expression->getQualifierLoc().getSourceRange(); 9642 NoteAllOverloadCandidates(SrcExpr.get()); 9643 9644 SrcExpr = ExprError(); 9645 return true; 9646 } 9647 9648 return false; 9649 } 9650 9651 SrcExpr = SingleFunctionExpression; 9652 return true; 9653 } 9654 9655 /// \brief Add a single candidate to the overload set. 9656 static void AddOverloadedCallCandidate(Sema &S, 9657 DeclAccessPair FoundDecl, 9658 TemplateArgumentListInfo *ExplicitTemplateArgs, 9659 ArrayRef<Expr *> Args, 9660 OverloadCandidateSet &CandidateSet, 9661 bool PartialOverloading, 9662 bool KnownValid) { 9663 NamedDecl *Callee = FoundDecl.getDecl(); 9664 if (isa<UsingShadowDecl>(Callee)) 9665 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9666 9667 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9668 if (ExplicitTemplateArgs) { 9669 assert(!KnownValid && "Explicit template arguments?"); 9670 return; 9671 } 9672 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9673 PartialOverloading); 9674 return; 9675 } 9676 9677 if (FunctionTemplateDecl *FuncTemplate 9678 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9679 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9680 ExplicitTemplateArgs, Args, CandidateSet); 9681 return; 9682 } 9683 9684 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9685 } 9686 9687 /// \brief Add the overload candidates named by callee and/or found by argument 9688 /// dependent lookup to the given overload set. 9689 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9690 ArrayRef<Expr *> Args, 9691 OverloadCandidateSet &CandidateSet, 9692 bool PartialOverloading) { 9693 9694 #ifndef NDEBUG 9695 // Verify that ArgumentDependentLookup is consistent with the rules 9696 // in C++0x [basic.lookup.argdep]p3: 9697 // 9698 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9699 // and let Y be the lookup set produced by argument dependent 9700 // lookup (defined as follows). If X contains 9701 // 9702 // -- a declaration of a class member, or 9703 // 9704 // -- a block-scope function declaration that is not a 9705 // using-declaration, or 9706 // 9707 // -- a declaration that is neither a function or a function 9708 // template 9709 // 9710 // then Y is empty. 9711 9712 if (ULE->requiresADL()) { 9713 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9714 E = ULE->decls_end(); I != E; ++I) { 9715 assert(!(*I)->getDeclContext()->isRecord()); 9716 assert(isa<UsingShadowDecl>(*I) || 9717 !(*I)->getDeclContext()->isFunctionOrMethod()); 9718 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9719 } 9720 } 9721 #endif 9722 9723 // It would be nice to avoid this copy. 9724 TemplateArgumentListInfo TABuffer; 9725 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9726 if (ULE->hasExplicitTemplateArgs()) { 9727 ULE->copyTemplateArgumentsInto(TABuffer); 9728 ExplicitTemplateArgs = &TABuffer; 9729 } 9730 9731 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9732 E = ULE->decls_end(); I != E; ++I) 9733 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9734 CandidateSet, PartialOverloading, 9735 /*KnownValid*/ true); 9736 9737 if (ULE->requiresADL()) 9738 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9739 ULE->getExprLoc(), 9740 Args, ExplicitTemplateArgs, 9741 CandidateSet, PartialOverloading); 9742 } 9743 9744 /// Determine whether a declaration with the specified name could be moved into 9745 /// a different namespace. 9746 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 9747 switch (Name.getCXXOverloadedOperator()) { 9748 case OO_New: case OO_Array_New: 9749 case OO_Delete: case OO_Array_Delete: 9750 return false; 9751 9752 default: 9753 return true; 9754 } 9755 } 9756 9757 /// Attempt to recover from an ill-formed use of a non-dependent name in a 9758 /// template, where the non-dependent name was declared after the template 9759 /// was defined. This is common in code written for a compilers which do not 9760 /// correctly implement two-stage name lookup. 9761 /// 9762 /// Returns true if a viable candidate was found and a diagnostic was issued. 9763 static bool 9764 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9765 const CXXScopeSpec &SS, LookupResult &R, 9766 TemplateArgumentListInfo *ExplicitTemplateArgs, 9767 ArrayRef<Expr *> Args) { 9768 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9769 return false; 9770 9771 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9772 if (DC->isTransparentContext()) 9773 continue; 9774 9775 SemaRef.LookupQualifiedName(R, DC); 9776 9777 if (!R.empty()) { 9778 R.suppressDiagnostics(); 9779 9780 if (isa<CXXRecordDecl>(DC)) { 9781 // Don't diagnose names we find in classes; we get much better 9782 // diagnostics for these from DiagnoseEmptyLookup. 9783 R.clear(); 9784 return false; 9785 } 9786 9787 OverloadCandidateSet Candidates(FnLoc); 9788 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9789 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9790 ExplicitTemplateArgs, Args, 9791 Candidates, false, /*KnownValid*/ false); 9792 9793 OverloadCandidateSet::iterator Best; 9794 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9795 // No viable functions. Don't bother the user with notes for functions 9796 // which don't work and shouldn't be found anyway. 9797 R.clear(); 9798 return false; 9799 } 9800 9801 // Find the namespaces where ADL would have looked, and suggest 9802 // declaring the function there instead. 9803 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9804 Sema::AssociatedClassSet AssociatedClasses; 9805 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9806 AssociatedNamespaces, 9807 AssociatedClasses); 9808 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9809 if (canBeDeclaredInNamespace(R.getLookupName())) { 9810 DeclContext *Std = SemaRef.getStdNamespace(); 9811 for (Sema::AssociatedNamespaceSet::iterator 9812 it = AssociatedNamespaces.begin(), 9813 end = AssociatedNamespaces.end(); it != end; ++it) { 9814 // Never suggest declaring a function within namespace 'std'. 9815 if (Std && Std->Encloses(*it)) 9816 continue; 9817 9818 // Never suggest declaring a function within a namespace with a 9819 // reserved name, like __gnu_cxx. 9820 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9821 if (NS && 9822 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9823 continue; 9824 9825 SuggestedNamespaces.insert(*it); 9826 } 9827 } 9828 9829 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9830 << R.getLookupName(); 9831 if (SuggestedNamespaces.empty()) { 9832 SemaRef.Diag(Best->Function->getLocation(), 9833 diag::note_not_found_by_two_phase_lookup) 9834 << R.getLookupName() << 0; 9835 } else if (SuggestedNamespaces.size() == 1) { 9836 SemaRef.Diag(Best->Function->getLocation(), 9837 diag::note_not_found_by_two_phase_lookup) 9838 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9839 } else { 9840 // FIXME: It would be useful to list the associated namespaces here, 9841 // but the diagnostics infrastructure doesn't provide a way to produce 9842 // a localized representation of a list of items. 9843 SemaRef.Diag(Best->Function->getLocation(), 9844 diag::note_not_found_by_two_phase_lookup) 9845 << R.getLookupName() << 2; 9846 } 9847 9848 // Try to recover by calling this function. 9849 return true; 9850 } 9851 9852 R.clear(); 9853 } 9854 9855 return false; 9856 } 9857 9858 /// Attempt to recover from ill-formed use of a non-dependent operator in a 9859 /// template, where the non-dependent operator was declared after the template 9860 /// was defined. 9861 /// 9862 /// Returns true if a viable candidate was found and a diagnostic was issued. 9863 static bool 9864 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9865 SourceLocation OpLoc, 9866 ArrayRef<Expr *> Args) { 9867 DeclarationName OpName = 9868 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9869 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9870 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9871 /*ExplicitTemplateArgs=*/0, Args); 9872 } 9873 9874 namespace { 9875 // Callback to limit the allowed keywords and to only accept typo corrections 9876 // that are keywords or whose decls refer to functions (or template functions) 9877 // that accept the given number of arguments. 9878 class RecoveryCallCCC : public CorrectionCandidateCallback { 9879 public: 9880 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9881 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9882 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9883 WantRemainingKeywords = false; 9884 } 9885 9886 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9887 if (!candidate.getCorrectionDecl()) 9888 return candidate.isKeyword(); 9889 9890 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9891 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9892 FunctionDecl *FD = 0; 9893 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9894 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9895 FD = FTD->getTemplatedDecl(); 9896 if (!HasExplicitTemplateArgs && !FD) { 9897 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9898 // If the Decl is neither a function nor a template function, 9899 // determine if it is a pointer or reference to a function. If so, 9900 // check against the number of arguments expected for the pointee. 9901 QualType ValType = cast<ValueDecl>(ND)->getType(); 9902 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9903 ValType = ValType->getPointeeType(); 9904 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9905 if (FPT->getNumArgs() == NumArgs) 9906 return true; 9907 } 9908 } 9909 if (FD && FD->getNumParams() >= NumArgs && 9910 FD->getMinRequiredArguments() <= NumArgs) 9911 return true; 9912 } 9913 return false; 9914 } 9915 9916 private: 9917 unsigned NumArgs; 9918 bool HasExplicitTemplateArgs; 9919 }; 9920 9921 // Callback that effectively disabled typo correction 9922 class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9923 public: 9924 NoTypoCorrectionCCC() { 9925 WantTypeSpecifiers = false; 9926 WantExpressionKeywords = false; 9927 WantCXXNamedCasts = false; 9928 WantRemainingKeywords = false; 9929 } 9930 9931 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9932 return false; 9933 } 9934 }; 9935 9936 class BuildRecoveryCallExprRAII { 9937 Sema &SemaRef; 9938 public: 9939 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9940 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9941 SemaRef.IsBuildingRecoveryCallExpr = true; 9942 } 9943 9944 ~BuildRecoveryCallExprRAII() { 9945 SemaRef.IsBuildingRecoveryCallExpr = false; 9946 } 9947 }; 9948 9949 } 9950 9951 /// Attempts to recover from a call where no functions were found. 9952 /// 9953 /// Returns true if new candidates were found. 9954 static ExprResult 9955 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9956 UnresolvedLookupExpr *ULE, 9957 SourceLocation LParenLoc, 9958 llvm::MutableArrayRef<Expr *> Args, 9959 SourceLocation RParenLoc, 9960 bool EmptyLookup, bool AllowTypoCorrection) { 9961 // Do not try to recover if it is already building a recovery call. 9962 // This stops infinite loops for template instantiations like 9963 // 9964 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9965 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9966 // 9967 if (SemaRef.IsBuildingRecoveryCallExpr) 9968 return ExprError(); 9969 BuildRecoveryCallExprRAII RCE(SemaRef); 9970 9971 CXXScopeSpec SS; 9972 SS.Adopt(ULE->getQualifierLoc()); 9973 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9974 9975 TemplateArgumentListInfo TABuffer; 9976 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9977 if (ULE->hasExplicitTemplateArgs()) { 9978 ULE->copyTemplateArgumentsInto(TABuffer); 9979 ExplicitTemplateArgs = &TABuffer; 9980 } 9981 9982 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9983 Sema::LookupOrdinaryName); 9984 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9985 NoTypoCorrectionCCC RejectAll; 9986 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9987 (CorrectionCandidateCallback*)&Validator : 9988 (CorrectionCandidateCallback*)&RejectAll; 9989 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9990 ExplicitTemplateArgs, Args) && 9991 (!EmptyLookup || 9992 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9993 ExplicitTemplateArgs, Args))) 9994 return ExprError(); 9995 9996 assert(!R.empty() && "lookup results empty despite recovery"); 9997 9998 // Build an implicit member call if appropriate. Just drop the 9999 // casts and such from the call, we don't really care. 10000 ExprResult NewFn = ExprError(); 10001 if ((*R.begin())->isCXXClassMember()) 10002 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10003 R, ExplicitTemplateArgs); 10004 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10005 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10006 ExplicitTemplateArgs); 10007 else 10008 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10009 10010 if (NewFn.isInvalid()) 10011 return ExprError(); 10012 10013 // This shouldn't cause an infinite loop because we're giving it 10014 // an expression with viable lookup results, which should never 10015 // end up here. 10016 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10017 MultiExprArg(Args.data(), Args.size()), 10018 RParenLoc); 10019 } 10020 10021 /// \brief Constructs and populates an OverloadedCandidateSet from 10022 /// the given function. 10023 /// \returns true when an the ExprResult output parameter has been set. 10024 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10025 UnresolvedLookupExpr *ULE, 10026 MultiExprArg Args, 10027 SourceLocation RParenLoc, 10028 OverloadCandidateSet *CandidateSet, 10029 ExprResult *Result) { 10030 #ifndef NDEBUG 10031 if (ULE->requiresADL()) { 10032 // To do ADL, we must have found an unqualified name. 10033 assert(!ULE->getQualifier() && "qualified name with ADL"); 10034 10035 // We don't perform ADL for implicit declarations of builtins. 10036 // Verify that this was correctly set up. 10037 FunctionDecl *F; 10038 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10039 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10040 F->getBuiltinID() && F->isImplicit()) 10041 llvm_unreachable("performing ADL for builtin"); 10042 10043 // We don't perform ADL in C. 10044 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10045 } 10046 #endif 10047 10048 UnbridgedCastsSet UnbridgedCasts; 10049 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10050 *Result = ExprError(); 10051 return true; 10052 } 10053 10054 // Add the functions denoted by the callee to the set of candidate 10055 // functions, including those from argument-dependent lookup. 10056 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10057 10058 // If we found nothing, try to recover. 10059 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10060 // out if it fails. 10061 if (CandidateSet->empty()) { 10062 // In Microsoft mode, if we are inside a template class member function then 10063 // create a type dependent CallExpr. The goal is to postpone name lookup 10064 // to instantiation time to be able to search into type dependent base 10065 // classes. 10066 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 10067 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10068 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10069 Context.DependentTy, VK_RValue, 10070 RParenLoc); 10071 CE->setTypeDependent(true); 10072 *Result = Owned(CE); 10073 return true; 10074 } 10075 return false; 10076 } 10077 10078 UnbridgedCasts.restore(); 10079 return false; 10080 } 10081 10082 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10083 /// the completed call expression. If overload resolution fails, emits 10084 /// diagnostics and returns ExprError() 10085 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10086 UnresolvedLookupExpr *ULE, 10087 SourceLocation LParenLoc, 10088 MultiExprArg Args, 10089 SourceLocation RParenLoc, 10090 Expr *ExecConfig, 10091 OverloadCandidateSet *CandidateSet, 10092 OverloadCandidateSet::iterator *Best, 10093 OverloadingResult OverloadResult, 10094 bool AllowTypoCorrection) { 10095 if (CandidateSet->empty()) 10096 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10097 RParenLoc, /*EmptyLookup=*/true, 10098 AllowTypoCorrection); 10099 10100 switch (OverloadResult) { 10101 case OR_Success: { 10102 FunctionDecl *FDecl = (*Best)->Function; 10103 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10104 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10105 return ExprError(); 10106 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10107 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10108 ExecConfig); 10109 } 10110 10111 case OR_No_Viable_Function: { 10112 // Try to recover by looking for viable functions which the user might 10113 // have meant to call. 10114 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10115 Args, RParenLoc, 10116 /*EmptyLookup=*/false, 10117 AllowTypoCorrection); 10118 if (!Recovery.isInvalid()) 10119 return Recovery; 10120 10121 SemaRef.Diag(Fn->getLocStart(), 10122 diag::err_ovl_no_viable_function_in_call) 10123 << ULE->getName() << Fn->getSourceRange(); 10124 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10125 break; 10126 } 10127 10128 case OR_Ambiguous: 10129 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10130 << ULE->getName() << Fn->getSourceRange(); 10131 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10132 break; 10133 10134 case OR_Deleted: { 10135 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10136 << (*Best)->Function->isDeleted() 10137 << ULE->getName() 10138 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10139 << Fn->getSourceRange(); 10140 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10141 10142 // We emitted an error for the unvailable/deleted function call but keep 10143 // the call in the AST. 10144 FunctionDecl *FDecl = (*Best)->Function; 10145 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10146 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10147 ExecConfig); 10148 } 10149 } 10150 10151 // Overload resolution failed. 10152 return ExprError(); 10153 } 10154 10155 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10156 /// (which eventually refers to the declaration Func) and the call 10157 /// arguments Args/NumArgs, attempt to resolve the function call down 10158 /// to a specific function. If overload resolution succeeds, returns 10159 /// the call expression produced by overload resolution. 10160 /// Otherwise, emits diagnostics and returns ExprError. 10161 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10162 UnresolvedLookupExpr *ULE, 10163 SourceLocation LParenLoc, 10164 MultiExprArg Args, 10165 SourceLocation RParenLoc, 10166 Expr *ExecConfig, 10167 bool AllowTypoCorrection) { 10168 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10169 ExprResult result; 10170 10171 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10172 &result)) 10173 return result; 10174 10175 OverloadCandidateSet::iterator Best; 10176 OverloadingResult OverloadResult = 10177 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10178 10179 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10180 RParenLoc, ExecConfig, &CandidateSet, 10181 &Best, OverloadResult, 10182 AllowTypoCorrection); 10183 } 10184 10185 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10186 return Functions.size() > 1 || 10187 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10188 } 10189 10190 /// \brief Create a unary operation that may resolve to an overloaded 10191 /// operator. 10192 /// 10193 /// \param OpLoc The location of the operator itself (e.g., '*'). 10194 /// 10195 /// \param OpcIn The UnaryOperator::Opcode that describes this 10196 /// operator. 10197 /// 10198 /// \param Fns The set of non-member functions that will be 10199 /// considered by overload resolution. The caller needs to build this 10200 /// set based on the context using, e.g., 10201 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10202 /// set should not contain any member functions; those will be added 10203 /// by CreateOverloadedUnaryOp(). 10204 /// 10205 /// \param Input The input argument. 10206 ExprResult 10207 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10208 const UnresolvedSetImpl &Fns, 10209 Expr *Input) { 10210 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10211 10212 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10213 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10214 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10215 // TODO: provide better source location info. 10216 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10217 10218 if (checkPlaceholderForOverload(*this, Input)) 10219 return ExprError(); 10220 10221 Expr *Args[2] = { Input, 0 }; 10222 unsigned NumArgs = 1; 10223 10224 // For post-increment and post-decrement, add the implicit '0' as 10225 // the second argument, so that we know this is a post-increment or 10226 // post-decrement. 10227 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10228 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10229 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10230 SourceLocation()); 10231 NumArgs = 2; 10232 } 10233 10234 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10235 10236 if (Input->isTypeDependent()) { 10237 if (Fns.empty()) 10238 return Owned(new (Context) UnaryOperator(Input, 10239 Opc, 10240 Context.DependentTy, 10241 VK_RValue, OK_Ordinary, 10242 OpLoc)); 10243 10244 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10245 UnresolvedLookupExpr *Fn 10246 = UnresolvedLookupExpr::Create(Context, NamingClass, 10247 NestedNameSpecifierLoc(), OpNameInfo, 10248 /*ADL*/ true, IsOverloaded(Fns), 10249 Fns.begin(), Fns.end()); 10250 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10251 Context.DependentTy, 10252 VK_RValue, 10253 OpLoc, false)); 10254 } 10255 10256 // Build an empty overload set. 10257 OverloadCandidateSet CandidateSet(OpLoc); 10258 10259 // Add the candidates from the given function set. 10260 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10261 10262 // Add operator candidates that are member functions. 10263 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10264 10265 // Add candidates from ADL. 10266 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10267 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10268 CandidateSet); 10269 10270 // Add builtin operator candidates. 10271 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10272 10273 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10274 10275 // Perform overload resolution. 10276 OverloadCandidateSet::iterator Best; 10277 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10278 case OR_Success: { 10279 // We found a built-in operator or an overloaded operator. 10280 FunctionDecl *FnDecl = Best->Function; 10281 10282 if (FnDecl) { 10283 // We matched an overloaded operator. Build a call to that 10284 // operator. 10285 10286 // Convert the arguments. 10287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10288 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10289 10290 ExprResult InputRes = 10291 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10292 Best->FoundDecl, Method); 10293 if (InputRes.isInvalid()) 10294 return ExprError(); 10295 Input = InputRes.take(); 10296 } else { 10297 // Convert the arguments. 10298 ExprResult InputInit 10299 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10300 Context, 10301 FnDecl->getParamDecl(0)), 10302 SourceLocation(), 10303 Input); 10304 if (InputInit.isInvalid()) 10305 return ExprError(); 10306 Input = InputInit.take(); 10307 } 10308 10309 // Determine the result type. 10310 QualType ResultTy = FnDecl->getResultType(); 10311 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10312 ResultTy = ResultTy.getNonLValueExprType(Context); 10313 10314 // Build the actual expression node. 10315 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10316 HadMultipleCandidates, OpLoc); 10317 if (FnExpr.isInvalid()) 10318 return ExprError(); 10319 10320 Args[0] = Input; 10321 CallExpr *TheCall = 10322 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10323 ResultTy, VK, OpLoc, false); 10324 10325 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10326 FnDecl)) 10327 return ExprError(); 10328 10329 return MaybeBindToTemporary(TheCall); 10330 } else { 10331 // We matched a built-in operator. Convert the arguments, then 10332 // break out so that we will build the appropriate built-in 10333 // operator node. 10334 ExprResult InputRes = 10335 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10336 Best->Conversions[0], AA_Passing); 10337 if (InputRes.isInvalid()) 10338 return ExprError(); 10339 Input = InputRes.take(); 10340 break; 10341 } 10342 } 10343 10344 case OR_No_Viable_Function: 10345 // This is an erroneous use of an operator which can be overloaded by 10346 // a non-member function. Check for non-member operators which were 10347 // defined too late to be candidates. 10348 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10349 // FIXME: Recover by calling the found function. 10350 return ExprError(); 10351 10352 // No viable function; fall through to handling this as a 10353 // built-in operator, which will produce an error message for us. 10354 break; 10355 10356 case OR_Ambiguous: 10357 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10358 << UnaryOperator::getOpcodeStr(Opc) 10359 << Input->getType() 10360 << Input->getSourceRange(); 10361 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10362 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10363 return ExprError(); 10364 10365 case OR_Deleted: 10366 Diag(OpLoc, diag::err_ovl_deleted_oper) 10367 << Best->Function->isDeleted() 10368 << UnaryOperator::getOpcodeStr(Opc) 10369 << getDeletedOrUnavailableSuffix(Best->Function) 10370 << Input->getSourceRange(); 10371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10372 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10373 return ExprError(); 10374 } 10375 10376 // Either we found no viable overloaded operator or we matched a 10377 // built-in operator. In either case, fall through to trying to 10378 // build a built-in operation. 10379 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10380 } 10381 10382 /// \brief Create a binary operation that may resolve to an overloaded 10383 /// operator. 10384 /// 10385 /// \param OpLoc The location of the operator itself (e.g., '+'). 10386 /// 10387 /// \param OpcIn The BinaryOperator::Opcode that describes this 10388 /// operator. 10389 /// 10390 /// \param Fns The set of non-member functions that will be 10391 /// considered by overload resolution. The caller needs to build this 10392 /// set based on the context using, e.g., 10393 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10394 /// set should not contain any member functions; those will be added 10395 /// by CreateOverloadedBinOp(). 10396 /// 10397 /// \param LHS Left-hand argument. 10398 /// \param RHS Right-hand argument. 10399 ExprResult 10400 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10401 unsigned OpcIn, 10402 const UnresolvedSetImpl &Fns, 10403 Expr *LHS, Expr *RHS) { 10404 Expr *Args[2] = { LHS, RHS }; 10405 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10406 10407 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10408 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10409 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10410 10411 // If either side is type-dependent, create an appropriate dependent 10412 // expression. 10413 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10414 if (Fns.empty()) { 10415 // If there are no functions to store, just build a dependent 10416 // BinaryOperator or CompoundAssignment. 10417 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10418 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10419 Context.DependentTy, 10420 VK_RValue, OK_Ordinary, 10421 OpLoc, 10422 FPFeatures.fp_contract)); 10423 10424 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10425 Context.DependentTy, 10426 VK_LValue, 10427 OK_Ordinary, 10428 Context.DependentTy, 10429 Context.DependentTy, 10430 OpLoc, 10431 FPFeatures.fp_contract)); 10432 } 10433 10434 // FIXME: save results of ADL from here? 10435 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10436 // TODO: provide better source location info in DNLoc component. 10437 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10438 UnresolvedLookupExpr *Fn 10439 = UnresolvedLookupExpr::Create(Context, NamingClass, 10440 NestedNameSpecifierLoc(), OpNameInfo, 10441 /*ADL*/ true, IsOverloaded(Fns), 10442 Fns.begin(), Fns.end()); 10443 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10444 Context.DependentTy, VK_RValue, 10445 OpLoc, FPFeatures.fp_contract)); 10446 } 10447 10448 // Always do placeholder-like conversions on the RHS. 10449 if (checkPlaceholderForOverload(*this, Args[1])) 10450 return ExprError(); 10451 10452 // Do placeholder-like conversion on the LHS; note that we should 10453 // not get here with a PseudoObject LHS. 10454 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10455 if (checkPlaceholderForOverload(*this, Args[0])) 10456 return ExprError(); 10457 10458 // If this is the assignment operator, we only perform overload resolution 10459 // if the left-hand side is a class or enumeration type. This is actually 10460 // a hack. The standard requires that we do overload resolution between the 10461 // various built-in candidates, but as DR507 points out, this can lead to 10462 // problems. So we do it this way, which pretty much follows what GCC does. 10463 // Note that we go the traditional code path for compound assignment forms. 10464 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10465 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10466 10467 // If this is the .* operator, which is not overloadable, just 10468 // create a built-in binary operator. 10469 if (Opc == BO_PtrMemD) 10470 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10471 10472 // Build an empty overload set. 10473 OverloadCandidateSet CandidateSet(OpLoc); 10474 10475 // Add the candidates from the given function set. 10476 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10477 10478 // Add operator candidates that are member functions. 10479 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10480 10481 // Add candidates from ADL. 10482 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10483 OpLoc, Args, 10484 /*ExplicitTemplateArgs*/ 0, 10485 CandidateSet); 10486 10487 // Add builtin operator candidates. 10488 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10489 10490 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10491 10492 // Perform overload resolution. 10493 OverloadCandidateSet::iterator Best; 10494 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10495 case OR_Success: { 10496 // We found a built-in operator or an overloaded operator. 10497 FunctionDecl *FnDecl = Best->Function; 10498 10499 if (FnDecl) { 10500 // We matched an overloaded operator. Build a call to that 10501 // operator. 10502 10503 // Convert the arguments. 10504 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10505 // Best->Access is only meaningful for class members. 10506 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10507 10508 ExprResult Arg1 = 10509 PerformCopyInitialization( 10510 InitializedEntity::InitializeParameter(Context, 10511 FnDecl->getParamDecl(0)), 10512 SourceLocation(), Owned(Args[1])); 10513 if (Arg1.isInvalid()) 10514 return ExprError(); 10515 10516 ExprResult Arg0 = 10517 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10518 Best->FoundDecl, Method); 10519 if (Arg0.isInvalid()) 10520 return ExprError(); 10521 Args[0] = Arg0.takeAs<Expr>(); 10522 Args[1] = RHS = Arg1.takeAs<Expr>(); 10523 } else { 10524 // Convert the arguments. 10525 ExprResult Arg0 = PerformCopyInitialization( 10526 InitializedEntity::InitializeParameter(Context, 10527 FnDecl->getParamDecl(0)), 10528 SourceLocation(), Owned(Args[0])); 10529 if (Arg0.isInvalid()) 10530 return ExprError(); 10531 10532 ExprResult Arg1 = 10533 PerformCopyInitialization( 10534 InitializedEntity::InitializeParameter(Context, 10535 FnDecl->getParamDecl(1)), 10536 SourceLocation(), Owned(Args[1])); 10537 if (Arg1.isInvalid()) 10538 return ExprError(); 10539 Args[0] = LHS = Arg0.takeAs<Expr>(); 10540 Args[1] = RHS = Arg1.takeAs<Expr>(); 10541 } 10542 10543 // Determine the result type. 10544 QualType ResultTy = FnDecl->getResultType(); 10545 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10546 ResultTy = ResultTy.getNonLValueExprType(Context); 10547 10548 // Build the actual expression node. 10549 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10550 Best->FoundDecl, 10551 HadMultipleCandidates, OpLoc); 10552 if (FnExpr.isInvalid()) 10553 return ExprError(); 10554 10555 CXXOperatorCallExpr *TheCall = 10556 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10557 Args, ResultTy, VK, OpLoc, 10558 FPFeatures.fp_contract); 10559 10560 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10561 FnDecl)) 10562 return ExprError(); 10563 10564 ArrayRef<const Expr *> ArgsArray(Args, 2); 10565 // Cut off the implicit 'this'. 10566 if (isa<CXXMethodDecl>(FnDecl)) 10567 ArgsArray = ArgsArray.slice(1); 10568 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10569 TheCall->getSourceRange(), VariadicDoesNotApply); 10570 10571 return MaybeBindToTemporary(TheCall); 10572 } else { 10573 // We matched a built-in operator. Convert the arguments, then 10574 // break out so that we will build the appropriate built-in 10575 // operator node. 10576 ExprResult ArgsRes0 = 10577 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10578 Best->Conversions[0], AA_Passing); 10579 if (ArgsRes0.isInvalid()) 10580 return ExprError(); 10581 Args[0] = ArgsRes0.take(); 10582 10583 ExprResult ArgsRes1 = 10584 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10585 Best->Conversions[1], AA_Passing); 10586 if (ArgsRes1.isInvalid()) 10587 return ExprError(); 10588 Args[1] = ArgsRes1.take(); 10589 break; 10590 } 10591 } 10592 10593 case OR_No_Viable_Function: { 10594 // C++ [over.match.oper]p9: 10595 // If the operator is the operator , [...] and there are no 10596 // viable functions, then the operator is assumed to be the 10597 // built-in operator and interpreted according to clause 5. 10598 if (Opc == BO_Comma) 10599 break; 10600 10601 // For class as left operand for assignment or compound assigment 10602 // operator do not fall through to handling in built-in, but report that 10603 // no overloaded assignment operator found 10604 ExprResult Result = ExprError(); 10605 if (Args[0]->getType()->isRecordType() && 10606 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10607 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10608 << BinaryOperator::getOpcodeStr(Opc) 10609 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10610 } else { 10611 // This is an erroneous use of an operator which can be overloaded by 10612 // a non-member function. Check for non-member operators which were 10613 // defined too late to be candidates. 10614 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10615 // FIXME: Recover by calling the found function. 10616 return ExprError(); 10617 10618 // No viable function; try to create a built-in operation, which will 10619 // produce an error. Then, show the non-viable candidates. 10620 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10621 } 10622 assert(Result.isInvalid() && 10623 "C++ binary operator overloading is missing candidates!"); 10624 if (Result.isInvalid()) 10625 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10626 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10627 return Result; 10628 } 10629 10630 case OR_Ambiguous: 10631 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10632 << BinaryOperator::getOpcodeStr(Opc) 10633 << Args[0]->getType() << Args[1]->getType() 10634 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10635 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10636 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10637 return ExprError(); 10638 10639 case OR_Deleted: 10640 if (isImplicitlyDeleted(Best->Function)) { 10641 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10642 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10643 << Context.getRecordType(Method->getParent()) 10644 << getSpecialMember(Method); 10645 10646 // The user probably meant to call this special member. Just 10647 // explain why it's deleted. 10648 NoteDeletedFunction(Method); 10649 return ExprError(); 10650 } else { 10651 Diag(OpLoc, diag::err_ovl_deleted_oper) 10652 << Best->Function->isDeleted() 10653 << BinaryOperator::getOpcodeStr(Opc) 10654 << getDeletedOrUnavailableSuffix(Best->Function) 10655 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10656 } 10657 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10658 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10659 return ExprError(); 10660 } 10661 10662 // We matched a built-in operator; build it. 10663 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10664 } 10665 10666 ExprResult 10667 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10668 SourceLocation RLoc, 10669 Expr *Base, Expr *Idx) { 10670 Expr *Args[2] = { Base, Idx }; 10671 DeclarationName OpName = 10672 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10673 10674 // If either side is type-dependent, create an appropriate dependent 10675 // expression. 10676 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10677 10678 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10679 // CHECKME: no 'operator' keyword? 10680 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10681 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10682 UnresolvedLookupExpr *Fn 10683 = UnresolvedLookupExpr::Create(Context, NamingClass, 10684 NestedNameSpecifierLoc(), OpNameInfo, 10685 /*ADL*/ true, /*Overloaded*/ false, 10686 UnresolvedSetIterator(), 10687 UnresolvedSetIterator()); 10688 // Can't add any actual overloads yet 10689 10690 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10691 Args, 10692 Context.DependentTy, 10693 VK_RValue, 10694 RLoc, false)); 10695 } 10696 10697 // Handle placeholders on both operands. 10698 if (checkPlaceholderForOverload(*this, Args[0])) 10699 return ExprError(); 10700 if (checkPlaceholderForOverload(*this, Args[1])) 10701 return ExprError(); 10702 10703 // Build an empty overload set. 10704 OverloadCandidateSet CandidateSet(LLoc); 10705 10706 // Subscript can only be overloaded as a member function. 10707 10708 // Add operator candidates that are member functions. 10709 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10710 10711 // Add builtin operator candidates. 10712 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10713 10714 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10715 10716 // Perform overload resolution. 10717 OverloadCandidateSet::iterator Best; 10718 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10719 case OR_Success: { 10720 // We found a built-in operator or an overloaded operator. 10721 FunctionDecl *FnDecl = Best->Function; 10722 10723 if (FnDecl) { 10724 // We matched an overloaded operator. Build a call to that 10725 // operator. 10726 10727 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10728 10729 // Convert the arguments. 10730 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10731 ExprResult Arg0 = 10732 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10733 Best->FoundDecl, Method); 10734 if (Arg0.isInvalid()) 10735 return ExprError(); 10736 Args[0] = Arg0.take(); 10737 10738 // Convert the arguments. 10739 ExprResult InputInit 10740 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10741 Context, 10742 FnDecl->getParamDecl(0)), 10743 SourceLocation(), 10744 Owned(Args[1])); 10745 if (InputInit.isInvalid()) 10746 return ExprError(); 10747 10748 Args[1] = InputInit.takeAs<Expr>(); 10749 10750 // Determine the result type 10751 QualType ResultTy = FnDecl->getResultType(); 10752 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10753 ResultTy = ResultTy.getNonLValueExprType(Context); 10754 10755 // Build the actual expression node. 10756 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10757 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10758 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10759 Best->FoundDecl, 10760 HadMultipleCandidates, 10761 OpLocInfo.getLoc(), 10762 OpLocInfo.getInfo()); 10763 if (FnExpr.isInvalid()) 10764 return ExprError(); 10765 10766 CXXOperatorCallExpr *TheCall = 10767 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10768 FnExpr.take(), Args, 10769 ResultTy, VK, RLoc, 10770 false); 10771 10772 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10773 FnDecl)) 10774 return ExprError(); 10775 10776 return MaybeBindToTemporary(TheCall); 10777 } else { 10778 // We matched a built-in operator. Convert the arguments, then 10779 // break out so that we will build the appropriate built-in 10780 // operator node. 10781 ExprResult ArgsRes0 = 10782 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10783 Best->Conversions[0], AA_Passing); 10784 if (ArgsRes0.isInvalid()) 10785 return ExprError(); 10786 Args[0] = ArgsRes0.take(); 10787 10788 ExprResult ArgsRes1 = 10789 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10790 Best->Conversions[1], AA_Passing); 10791 if (ArgsRes1.isInvalid()) 10792 return ExprError(); 10793 Args[1] = ArgsRes1.take(); 10794 10795 break; 10796 } 10797 } 10798 10799 case OR_No_Viable_Function: { 10800 if (CandidateSet.empty()) 10801 Diag(LLoc, diag::err_ovl_no_oper) 10802 << Args[0]->getType() << /*subscript*/ 0 10803 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10804 else 10805 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10806 << Args[0]->getType() 10807 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10809 "[]", LLoc); 10810 return ExprError(); 10811 } 10812 10813 case OR_Ambiguous: 10814 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10815 << "[]" 10816 << Args[0]->getType() << Args[1]->getType() 10817 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10818 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10819 "[]", LLoc); 10820 return ExprError(); 10821 10822 case OR_Deleted: 10823 Diag(LLoc, diag::err_ovl_deleted_oper) 10824 << Best->Function->isDeleted() << "[]" 10825 << getDeletedOrUnavailableSuffix(Best->Function) 10826 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10828 "[]", LLoc); 10829 return ExprError(); 10830 } 10831 10832 // We matched a built-in operator; build it. 10833 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10834 } 10835 10836 /// BuildCallToMemberFunction - Build a call to a member 10837 /// function. MemExpr is the expression that refers to the member 10838 /// function (and includes the object parameter), Args/NumArgs are the 10839 /// arguments to the function call (not including the object 10840 /// parameter). The caller needs to validate that the member 10841 /// expression refers to a non-static member function or an overloaded 10842 /// member function. 10843 ExprResult 10844 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10845 SourceLocation LParenLoc, 10846 MultiExprArg Args, 10847 SourceLocation RParenLoc) { 10848 assert(MemExprE->getType() == Context.BoundMemberTy || 10849 MemExprE->getType() == Context.OverloadTy); 10850 10851 // Dig out the member expression. This holds both the object 10852 // argument and the member function we're referring to. 10853 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10854 10855 // Determine whether this is a call to a pointer-to-member function. 10856 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10857 assert(op->getType() == Context.BoundMemberTy); 10858 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10859 10860 QualType fnType = 10861 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10862 10863 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10864 QualType resultType = proto->getCallResultType(Context); 10865 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10866 10867 // Check that the object type isn't more qualified than the 10868 // member function we're calling. 10869 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10870 10871 QualType objectType = op->getLHS()->getType(); 10872 if (op->getOpcode() == BO_PtrMemI) 10873 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10874 Qualifiers objectQuals = objectType.getQualifiers(); 10875 10876 Qualifiers difference = objectQuals - funcQuals; 10877 difference.removeObjCGCAttr(); 10878 difference.removeAddressSpace(); 10879 if (difference) { 10880 std::string qualsString = difference.getAsString(); 10881 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10882 << fnType.getUnqualifiedType() 10883 << qualsString 10884 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10885 } 10886 10887 CXXMemberCallExpr *call 10888 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 10889 resultType, valueKind, RParenLoc); 10890 10891 if (CheckCallReturnType(proto->getResultType(), 10892 op->getRHS()->getLocStart(), 10893 call, 0)) 10894 return ExprError(); 10895 10896 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 10897 return ExprError(); 10898 10899 if (CheckOtherCall(call, proto)) 10900 return ExprError(); 10901 10902 return MaybeBindToTemporary(call); 10903 } 10904 10905 UnbridgedCastsSet UnbridgedCasts; 10906 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 10907 return ExprError(); 10908 10909 MemberExpr *MemExpr; 10910 CXXMethodDecl *Method = 0; 10911 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10912 NestedNameSpecifier *Qualifier = 0; 10913 if (isa<MemberExpr>(NakedMemExpr)) { 10914 MemExpr = cast<MemberExpr>(NakedMemExpr); 10915 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10916 FoundDecl = MemExpr->getFoundDecl(); 10917 Qualifier = MemExpr->getQualifier(); 10918 UnbridgedCasts.restore(); 10919 } else { 10920 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10921 Qualifier = UnresExpr->getQualifier(); 10922 10923 QualType ObjectType = UnresExpr->getBaseType(); 10924 Expr::Classification ObjectClassification 10925 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10926 : UnresExpr->getBase()->Classify(Context); 10927 10928 // Add overload candidates 10929 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10930 10931 // FIXME: avoid copy. 10932 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10933 if (UnresExpr->hasExplicitTemplateArgs()) { 10934 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10935 TemplateArgs = &TemplateArgsBuffer; 10936 } 10937 10938 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10939 E = UnresExpr->decls_end(); I != E; ++I) { 10940 10941 NamedDecl *Func = *I; 10942 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10943 if (isa<UsingShadowDecl>(Func)) 10944 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10945 10946 10947 // Microsoft supports direct constructor calls. 10948 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10949 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10950 Args, CandidateSet); 10951 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10952 // If explicit template arguments were provided, we can't call a 10953 // non-template member function. 10954 if (TemplateArgs) 10955 continue; 10956 10957 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10958 ObjectClassification, Args, CandidateSet, 10959 /*SuppressUserConversions=*/false); 10960 } else { 10961 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10962 I.getPair(), ActingDC, TemplateArgs, 10963 ObjectType, ObjectClassification, 10964 Args, CandidateSet, 10965 /*SuppressUsedConversions=*/false); 10966 } 10967 } 10968 10969 DeclarationName DeclName = UnresExpr->getMemberName(); 10970 10971 UnbridgedCasts.restore(); 10972 10973 OverloadCandidateSet::iterator Best; 10974 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10975 Best)) { 10976 case OR_Success: 10977 Method = cast<CXXMethodDecl>(Best->Function); 10978 FoundDecl = Best->FoundDecl; 10979 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10980 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 10981 return ExprError(); 10982 // If FoundDecl is different from Method (such as if one is a template 10983 // and the other a specialization), make sure DiagnoseUseOfDecl is 10984 // called on both. 10985 // FIXME: This would be more comprehensively addressed by modifying 10986 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 10987 // being used. 10988 if (Method != FoundDecl.getDecl() && 10989 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 10990 return ExprError(); 10991 break; 10992 10993 case OR_No_Viable_Function: 10994 Diag(UnresExpr->getMemberLoc(), 10995 diag::err_ovl_no_viable_member_function_in_call) 10996 << DeclName << MemExprE->getSourceRange(); 10997 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 10998 // FIXME: Leaking incoming expressions! 10999 return ExprError(); 11000 11001 case OR_Ambiguous: 11002 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11003 << DeclName << MemExprE->getSourceRange(); 11004 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11005 // FIXME: Leaking incoming expressions! 11006 return ExprError(); 11007 11008 case OR_Deleted: 11009 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11010 << Best->Function->isDeleted() 11011 << DeclName 11012 << getDeletedOrUnavailableSuffix(Best->Function) 11013 << MemExprE->getSourceRange(); 11014 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11015 // FIXME: Leaking incoming expressions! 11016 return ExprError(); 11017 } 11018 11019 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11020 11021 // If overload resolution picked a static member, build a 11022 // non-member call based on that function. 11023 if (Method->isStatic()) { 11024 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11025 RParenLoc); 11026 } 11027 11028 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11029 } 11030 11031 QualType ResultType = Method->getResultType(); 11032 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11033 ResultType = ResultType.getNonLValueExprType(Context); 11034 11035 assert(Method && "Member call to something that isn't a method?"); 11036 CXXMemberCallExpr *TheCall = 11037 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11038 ResultType, VK, RParenLoc); 11039 11040 // Check for a valid return type. 11041 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11042 TheCall, Method)) 11043 return ExprError(); 11044 11045 // Convert the object argument (for a non-static member function call). 11046 // We only need to do this if there was actually an overload; otherwise 11047 // it was done at lookup. 11048 if (!Method->isStatic()) { 11049 ExprResult ObjectArg = 11050 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11051 FoundDecl, Method); 11052 if (ObjectArg.isInvalid()) 11053 return ExprError(); 11054 MemExpr->setBase(ObjectArg.take()); 11055 } 11056 11057 // Convert the rest of the arguments 11058 const FunctionProtoType *Proto = 11059 Method->getType()->getAs<FunctionProtoType>(); 11060 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11061 RParenLoc)) 11062 return ExprError(); 11063 11064 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11065 11066 if (CheckFunctionCall(Method, TheCall, Proto)) 11067 return ExprError(); 11068 11069 if ((isa<CXXConstructorDecl>(CurContext) || 11070 isa<CXXDestructorDecl>(CurContext)) && 11071 TheCall->getMethodDecl()->isPure()) { 11072 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11073 11074 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11075 Diag(MemExpr->getLocStart(), 11076 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11077 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11078 << MD->getParent()->getDeclName(); 11079 11080 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11081 } 11082 } 11083 return MaybeBindToTemporary(TheCall); 11084 } 11085 11086 /// BuildCallToObjectOfClassType - Build a call to an object of class 11087 /// type (C++ [over.call.object]), which can end up invoking an 11088 /// overloaded function call operator (@c operator()) or performing a 11089 /// user-defined conversion on the object argument. 11090 ExprResult 11091 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11092 SourceLocation LParenLoc, 11093 MultiExprArg Args, 11094 SourceLocation RParenLoc) { 11095 if (checkPlaceholderForOverload(*this, Obj)) 11096 return ExprError(); 11097 ExprResult Object = Owned(Obj); 11098 11099 UnbridgedCastsSet UnbridgedCasts; 11100 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11101 return ExprError(); 11102 11103 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11104 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11105 11106 // C++ [over.call.object]p1: 11107 // If the primary-expression E in the function call syntax 11108 // evaluates to a class object of type "cv T", then the set of 11109 // candidate functions includes at least the function call 11110 // operators of T. The function call operators of T are obtained by 11111 // ordinary lookup of the name operator() in the context of 11112 // (E).operator(). 11113 OverloadCandidateSet CandidateSet(LParenLoc); 11114 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11115 11116 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11117 diag::err_incomplete_object_call, Object.get())) 11118 return true; 11119 11120 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11121 LookupQualifiedName(R, Record->getDecl()); 11122 R.suppressDiagnostics(); 11123 11124 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11125 Oper != OperEnd; ++Oper) { 11126 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11127 Object.get()->Classify(Context), 11128 Args, CandidateSet, 11129 /*SuppressUserConversions=*/ false); 11130 } 11131 11132 // C++ [over.call.object]p2: 11133 // In addition, for each (non-explicit in C++0x) conversion function 11134 // declared in T of the form 11135 // 11136 // operator conversion-type-id () cv-qualifier; 11137 // 11138 // where cv-qualifier is the same cv-qualification as, or a 11139 // greater cv-qualification than, cv, and where conversion-type-id 11140 // denotes the type "pointer to function of (P1,...,Pn) returning 11141 // R", or the type "reference to pointer to function of 11142 // (P1,...,Pn) returning R", or the type "reference to function 11143 // of (P1,...,Pn) returning R", a surrogate call function [...] 11144 // is also considered as a candidate function. Similarly, 11145 // surrogate call functions are added to the set of candidate 11146 // functions for each conversion function declared in an 11147 // accessible base class provided the function is not hidden 11148 // within T by another intervening declaration. 11149 std::pair<CXXRecordDecl::conversion_iterator, 11150 CXXRecordDecl::conversion_iterator> Conversions 11151 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11152 for (CXXRecordDecl::conversion_iterator 11153 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11154 NamedDecl *D = *I; 11155 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11156 if (isa<UsingShadowDecl>(D)) 11157 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11158 11159 // Skip over templated conversion functions; they aren't 11160 // surrogates. 11161 if (isa<FunctionTemplateDecl>(D)) 11162 continue; 11163 11164 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11165 if (!Conv->isExplicit()) { 11166 // Strip the reference type (if any) and then the pointer type (if 11167 // any) to get down to what might be a function type. 11168 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11169 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11170 ConvType = ConvPtrType->getPointeeType(); 11171 11172 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11173 { 11174 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11175 Object.get(), Args, CandidateSet); 11176 } 11177 } 11178 } 11179 11180 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11181 11182 // Perform overload resolution. 11183 OverloadCandidateSet::iterator Best; 11184 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11185 Best)) { 11186 case OR_Success: 11187 // Overload resolution succeeded; we'll build the appropriate call 11188 // below. 11189 break; 11190 11191 case OR_No_Viable_Function: 11192 if (CandidateSet.empty()) 11193 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11194 << Object.get()->getType() << /*call*/ 1 11195 << Object.get()->getSourceRange(); 11196 else 11197 Diag(Object.get()->getLocStart(), 11198 diag::err_ovl_no_viable_object_call) 11199 << Object.get()->getType() << Object.get()->getSourceRange(); 11200 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11201 break; 11202 11203 case OR_Ambiguous: 11204 Diag(Object.get()->getLocStart(), 11205 diag::err_ovl_ambiguous_object_call) 11206 << Object.get()->getType() << Object.get()->getSourceRange(); 11207 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11208 break; 11209 11210 case OR_Deleted: 11211 Diag(Object.get()->getLocStart(), 11212 diag::err_ovl_deleted_object_call) 11213 << Best->Function->isDeleted() 11214 << Object.get()->getType() 11215 << getDeletedOrUnavailableSuffix(Best->Function) 11216 << Object.get()->getSourceRange(); 11217 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11218 break; 11219 } 11220 11221 if (Best == CandidateSet.end()) 11222 return true; 11223 11224 UnbridgedCasts.restore(); 11225 11226 if (Best->Function == 0) { 11227 // Since there is no function declaration, this is one of the 11228 // surrogate candidates. Dig out the conversion function. 11229 CXXConversionDecl *Conv 11230 = cast<CXXConversionDecl>( 11231 Best->Conversions[0].UserDefined.ConversionFunction); 11232 11233 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11234 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11235 return ExprError(); 11236 assert(Conv == Best->FoundDecl.getDecl() && 11237 "Found Decl & conversion-to-functionptr should be same, right?!"); 11238 // We selected one of the surrogate functions that converts the 11239 // object parameter to a function pointer. Perform the conversion 11240 // on the object argument, then let ActOnCallExpr finish the job. 11241 11242 // Create an implicit member expr to refer to the conversion operator. 11243 // and then call it. 11244 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11245 Conv, HadMultipleCandidates); 11246 if (Call.isInvalid()) 11247 return ExprError(); 11248 // Record usage of conversion in an implicit cast. 11249 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11250 CK_UserDefinedConversion, 11251 Call.get(), 0, VK_RValue)); 11252 11253 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11254 } 11255 11256 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11257 11258 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11259 // that calls this method, using Object for the implicit object 11260 // parameter and passing along the remaining arguments. 11261 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11262 11263 // An error diagnostic has already been printed when parsing the declaration. 11264 if (Method->isInvalidDecl()) 11265 return ExprError(); 11266 11267 const FunctionProtoType *Proto = 11268 Method->getType()->getAs<FunctionProtoType>(); 11269 11270 unsigned NumArgsInProto = Proto->getNumArgs(); 11271 unsigned NumArgsToCheck = Args.size(); 11272 11273 // Build the full argument list for the method call (the 11274 // implicit object parameter is placed at the beginning of the 11275 // list). 11276 Expr **MethodArgs; 11277 if (Args.size() < NumArgsInProto) { 11278 NumArgsToCheck = NumArgsInProto; 11279 MethodArgs = new Expr*[NumArgsInProto + 1]; 11280 } else { 11281 MethodArgs = new Expr*[Args.size() + 1]; 11282 } 11283 MethodArgs[0] = Object.get(); 11284 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx) 11285 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11286 11287 DeclarationNameInfo OpLocInfo( 11288 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11289 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11290 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11291 HadMultipleCandidates, 11292 OpLocInfo.getLoc(), 11293 OpLocInfo.getInfo()); 11294 if (NewFn.isInvalid()) 11295 return true; 11296 11297 // Once we've built TheCall, all of the expressions are properly 11298 // owned. 11299 QualType ResultTy = Method->getResultType(); 11300 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11301 ResultTy = ResultTy.getNonLValueExprType(Context); 11302 11303 CXXOperatorCallExpr *TheCall = 11304 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11305 llvm::makeArrayRef(MethodArgs, Args.size()+1), 11306 ResultTy, VK, RParenLoc, false); 11307 delete [] MethodArgs; 11308 11309 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11310 Method)) 11311 return true; 11312 11313 // We may have default arguments. If so, we need to allocate more 11314 // slots in the call for them. 11315 if (Args.size() < NumArgsInProto) 11316 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11317 else if (Args.size() > NumArgsInProto) 11318 NumArgsToCheck = NumArgsInProto; 11319 11320 bool IsError = false; 11321 11322 // Initialize the implicit object parameter. 11323 ExprResult ObjRes = 11324 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11325 Best->FoundDecl, Method); 11326 if (ObjRes.isInvalid()) 11327 IsError = true; 11328 else 11329 Object = ObjRes; 11330 TheCall->setArg(0, Object.take()); 11331 11332 // Check the argument types. 11333 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11334 Expr *Arg; 11335 if (i < Args.size()) { 11336 Arg = Args[i]; 11337 11338 // Pass the argument. 11339 11340 ExprResult InputInit 11341 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11342 Context, 11343 Method->getParamDecl(i)), 11344 SourceLocation(), Arg); 11345 11346 IsError |= InputInit.isInvalid(); 11347 Arg = InputInit.takeAs<Expr>(); 11348 } else { 11349 ExprResult DefArg 11350 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11351 if (DefArg.isInvalid()) { 11352 IsError = true; 11353 break; 11354 } 11355 11356 Arg = DefArg.takeAs<Expr>(); 11357 } 11358 11359 TheCall->setArg(i + 1, Arg); 11360 } 11361 11362 // If this is a variadic call, handle args passed through "...". 11363 if (Proto->isVariadic()) { 11364 // Promote the arguments (C99 6.5.2.2p7). 11365 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11366 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11367 IsError |= Arg.isInvalid(); 11368 TheCall->setArg(i + 1, Arg.take()); 11369 } 11370 } 11371 11372 if (IsError) return true; 11373 11374 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11375 11376 if (CheckFunctionCall(Method, TheCall, Proto)) 11377 return true; 11378 11379 return MaybeBindToTemporary(TheCall); 11380 } 11381 11382 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11383 /// (if one exists), where @c Base is an expression of class type and 11384 /// @c Member is the name of the member we're trying to find. 11385 ExprResult 11386 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11387 assert(Base->getType()->isRecordType() && 11388 "left-hand side must have class type"); 11389 11390 if (checkPlaceholderForOverload(*this, Base)) 11391 return ExprError(); 11392 11393 SourceLocation Loc = Base->getExprLoc(); 11394 11395 // C++ [over.ref]p1: 11396 // 11397 // [...] An expression x->m is interpreted as (x.operator->())->m 11398 // for a class object x of type T if T::operator->() exists and if 11399 // the operator is selected as the best match function by the 11400 // overload resolution mechanism (13.3). 11401 DeclarationName OpName = 11402 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11403 OverloadCandidateSet CandidateSet(Loc); 11404 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11405 11406 if (RequireCompleteType(Loc, Base->getType(), 11407 diag::err_typecheck_incomplete_tag, Base)) 11408 return ExprError(); 11409 11410 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11411 LookupQualifiedName(R, BaseRecord->getDecl()); 11412 R.suppressDiagnostics(); 11413 11414 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11415 Oper != OperEnd; ++Oper) { 11416 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11417 None, CandidateSet, /*SuppressUserConversions=*/false); 11418 } 11419 11420 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11421 11422 // Perform overload resolution. 11423 OverloadCandidateSet::iterator Best; 11424 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11425 case OR_Success: 11426 // Overload resolution succeeded; we'll build the call below. 11427 break; 11428 11429 case OR_No_Viable_Function: 11430 if (CandidateSet.empty()) 11431 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11432 << Base->getType() << Base->getSourceRange(); 11433 else 11434 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11435 << "operator->" << Base->getSourceRange(); 11436 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11437 return ExprError(); 11438 11439 case OR_Ambiguous: 11440 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11441 << "->" << Base->getType() << Base->getSourceRange(); 11442 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11443 return ExprError(); 11444 11445 case OR_Deleted: 11446 Diag(OpLoc, diag::err_ovl_deleted_oper) 11447 << Best->Function->isDeleted() 11448 << "->" 11449 << getDeletedOrUnavailableSuffix(Best->Function) 11450 << Base->getSourceRange(); 11451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11452 return ExprError(); 11453 } 11454 11455 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11456 11457 // Convert the object parameter. 11458 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11459 ExprResult BaseResult = 11460 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11461 Best->FoundDecl, Method); 11462 if (BaseResult.isInvalid()) 11463 return ExprError(); 11464 Base = BaseResult.take(); 11465 11466 // Build the operator call. 11467 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11468 HadMultipleCandidates, OpLoc); 11469 if (FnExpr.isInvalid()) 11470 return ExprError(); 11471 11472 QualType ResultTy = Method->getResultType(); 11473 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11474 ResultTy = ResultTy.getNonLValueExprType(Context); 11475 CXXOperatorCallExpr *TheCall = 11476 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11477 Base, ResultTy, VK, OpLoc, false); 11478 11479 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11480 Method)) 11481 return ExprError(); 11482 11483 return MaybeBindToTemporary(TheCall); 11484 } 11485 11486 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11487 /// a literal operator described by the provided lookup results. 11488 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11489 DeclarationNameInfo &SuffixInfo, 11490 ArrayRef<Expr*> Args, 11491 SourceLocation LitEndLoc, 11492 TemplateArgumentListInfo *TemplateArgs) { 11493 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11494 11495 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11496 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11497 TemplateArgs); 11498 11499 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11500 11501 // Perform overload resolution. This will usually be trivial, but might need 11502 // to perform substitutions for a literal operator template. 11503 OverloadCandidateSet::iterator Best; 11504 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11505 case OR_Success: 11506 case OR_Deleted: 11507 break; 11508 11509 case OR_No_Viable_Function: 11510 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11511 << R.getLookupName(); 11512 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11513 return ExprError(); 11514 11515 case OR_Ambiguous: 11516 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11517 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11518 return ExprError(); 11519 } 11520 11521 FunctionDecl *FD = Best->Function; 11522 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11523 HadMultipleCandidates, 11524 SuffixInfo.getLoc(), 11525 SuffixInfo.getInfo()); 11526 if (Fn.isInvalid()) 11527 return true; 11528 11529 // Check the argument types. This should almost always be a no-op, except 11530 // that array-to-pointer decay is applied to string literals. 11531 Expr *ConvArgs[2]; 11532 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11533 ExprResult InputInit = PerformCopyInitialization( 11534 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11535 SourceLocation(), Args[ArgIdx]); 11536 if (InputInit.isInvalid()) 11537 return true; 11538 ConvArgs[ArgIdx] = InputInit.take(); 11539 } 11540 11541 QualType ResultTy = FD->getResultType(); 11542 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11543 ResultTy = ResultTy.getNonLValueExprType(Context); 11544 11545 UserDefinedLiteral *UDL = 11546 new (Context) UserDefinedLiteral(Context, Fn.take(), 11547 llvm::makeArrayRef(ConvArgs, Args.size()), 11548 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11549 11550 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11551 return ExprError(); 11552 11553 if (CheckFunctionCall(FD, UDL, NULL)) 11554 return ExprError(); 11555 11556 return MaybeBindToTemporary(UDL); 11557 } 11558 11559 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11560 /// given LookupResult is non-empty, it is assumed to describe a member which 11561 /// will be invoked. Otherwise, the function will be found via argument 11562 /// dependent lookup. 11563 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11564 /// otherwise CallExpr is set to ExprError() and some non-success value 11565 /// is returned. 11566 Sema::ForRangeStatus 11567 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11568 SourceLocation RangeLoc, VarDecl *Decl, 11569 BeginEndFunction BEF, 11570 const DeclarationNameInfo &NameInfo, 11571 LookupResult &MemberLookup, 11572 OverloadCandidateSet *CandidateSet, 11573 Expr *Range, ExprResult *CallExpr) { 11574 CandidateSet->clear(); 11575 if (!MemberLookup.empty()) { 11576 ExprResult MemberRef = 11577 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11578 /*IsPtr=*/false, CXXScopeSpec(), 11579 /*TemplateKWLoc=*/SourceLocation(), 11580 /*FirstQualifierInScope=*/0, 11581 MemberLookup, 11582 /*TemplateArgs=*/0); 11583 if (MemberRef.isInvalid()) { 11584 *CallExpr = ExprError(); 11585 Diag(Range->getLocStart(), diag::note_in_for_range) 11586 << RangeLoc << BEF << Range->getType(); 11587 return FRS_DiagnosticIssued; 11588 } 11589 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11590 if (CallExpr->isInvalid()) { 11591 *CallExpr = ExprError(); 11592 Diag(Range->getLocStart(), diag::note_in_for_range) 11593 << RangeLoc << BEF << Range->getType(); 11594 return FRS_DiagnosticIssued; 11595 } 11596 } else { 11597 UnresolvedSet<0> FoundNames; 11598 UnresolvedLookupExpr *Fn = 11599 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11600 NestedNameSpecifierLoc(), NameInfo, 11601 /*NeedsADL=*/true, /*Overloaded=*/false, 11602 FoundNames.begin(), FoundNames.end()); 11603 11604 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 11605 CandidateSet, CallExpr); 11606 if (CandidateSet->empty() || CandidateSetError) { 11607 *CallExpr = ExprError(); 11608 return FRS_NoViableFunction; 11609 } 11610 OverloadCandidateSet::iterator Best; 11611 OverloadingResult OverloadResult = 11612 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11613 11614 if (OverloadResult == OR_No_Viable_Function) { 11615 *CallExpr = ExprError(); 11616 return FRS_NoViableFunction; 11617 } 11618 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 11619 Loc, 0, CandidateSet, &Best, 11620 OverloadResult, 11621 /*AllowTypoCorrection=*/false); 11622 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11623 *CallExpr = ExprError(); 11624 Diag(Range->getLocStart(), diag::note_in_for_range) 11625 << RangeLoc << BEF << Range->getType(); 11626 return FRS_DiagnosticIssued; 11627 } 11628 } 11629 return FRS_Success; 11630 } 11631 11632 11633 /// FixOverloadedFunctionReference - E is an expression that refers to 11634 /// a C++ overloaded function (possibly with some parentheses and 11635 /// perhaps a '&' around it). We have resolved the overloaded function 11636 /// to the function declaration Fn, so patch up the expression E to 11637 /// refer (possibly indirectly) to Fn. Returns the new expr. 11638 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11639 FunctionDecl *Fn) { 11640 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11641 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11642 Found, Fn); 11643 if (SubExpr == PE->getSubExpr()) 11644 return PE; 11645 11646 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11647 } 11648 11649 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11650 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11651 Found, Fn); 11652 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11653 SubExpr->getType()) && 11654 "Implicit cast type cannot be determined from overload"); 11655 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11656 if (SubExpr == ICE->getSubExpr()) 11657 return ICE; 11658 11659 return ImplicitCastExpr::Create(Context, ICE->getType(), 11660 ICE->getCastKind(), 11661 SubExpr, 0, 11662 ICE->getValueKind()); 11663 } 11664 11665 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11666 assert(UnOp->getOpcode() == UO_AddrOf && 11667 "Can only take the address of an overloaded function"); 11668 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11669 if (Method->isStatic()) { 11670 // Do nothing: static member functions aren't any different 11671 // from non-member functions. 11672 } else { 11673 // Fix the sub expression, which really has to be an 11674 // UnresolvedLookupExpr holding an overloaded member function 11675 // or template. 11676 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11677 Found, Fn); 11678 if (SubExpr == UnOp->getSubExpr()) 11679 return UnOp; 11680 11681 assert(isa<DeclRefExpr>(SubExpr) 11682 && "fixed to something other than a decl ref"); 11683 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11684 && "fixed to a member ref with no nested name qualifier"); 11685 11686 // We have taken the address of a pointer to member 11687 // function. Perform the computation here so that we get the 11688 // appropriate pointer to member type. 11689 QualType ClassType 11690 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11691 QualType MemPtrType 11692 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11693 11694 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11695 VK_RValue, OK_Ordinary, 11696 UnOp->getOperatorLoc()); 11697 } 11698 } 11699 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11700 Found, Fn); 11701 if (SubExpr == UnOp->getSubExpr()) 11702 return UnOp; 11703 11704 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11705 Context.getPointerType(SubExpr->getType()), 11706 VK_RValue, OK_Ordinary, 11707 UnOp->getOperatorLoc()); 11708 } 11709 11710 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11711 // FIXME: avoid copy. 11712 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11713 if (ULE->hasExplicitTemplateArgs()) { 11714 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11715 TemplateArgs = &TemplateArgsBuffer; 11716 } 11717 11718 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11719 ULE->getQualifierLoc(), 11720 ULE->getTemplateKeywordLoc(), 11721 Fn, 11722 /*enclosing*/ false, // FIXME? 11723 ULE->getNameLoc(), 11724 Fn->getType(), 11725 VK_LValue, 11726 Found.getDecl(), 11727 TemplateArgs); 11728 MarkDeclRefReferenced(DRE); 11729 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11730 return DRE; 11731 } 11732 11733 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11734 // FIXME: avoid copy. 11735 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11736 if (MemExpr->hasExplicitTemplateArgs()) { 11737 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11738 TemplateArgs = &TemplateArgsBuffer; 11739 } 11740 11741 Expr *Base; 11742 11743 // If we're filling in a static method where we used to have an 11744 // implicit member access, rewrite to a simple decl ref. 11745 if (MemExpr->isImplicitAccess()) { 11746 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11747 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11748 MemExpr->getQualifierLoc(), 11749 MemExpr->getTemplateKeywordLoc(), 11750 Fn, 11751 /*enclosing*/ false, 11752 MemExpr->getMemberLoc(), 11753 Fn->getType(), 11754 VK_LValue, 11755 Found.getDecl(), 11756 TemplateArgs); 11757 MarkDeclRefReferenced(DRE); 11758 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11759 return DRE; 11760 } else { 11761 SourceLocation Loc = MemExpr->getMemberLoc(); 11762 if (MemExpr->getQualifier()) 11763 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11764 CheckCXXThisCapture(Loc); 11765 Base = new (Context) CXXThisExpr(Loc, 11766 MemExpr->getBaseType(), 11767 /*isImplicit=*/true); 11768 } 11769 } else 11770 Base = MemExpr->getBase(); 11771 11772 ExprValueKind valueKind; 11773 QualType type; 11774 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11775 valueKind = VK_LValue; 11776 type = Fn->getType(); 11777 } else { 11778 valueKind = VK_RValue; 11779 type = Context.BoundMemberTy; 11780 } 11781 11782 MemberExpr *ME = MemberExpr::Create(Context, Base, 11783 MemExpr->isArrow(), 11784 MemExpr->getQualifierLoc(), 11785 MemExpr->getTemplateKeywordLoc(), 11786 Fn, 11787 Found, 11788 MemExpr->getMemberNameInfo(), 11789 TemplateArgs, 11790 type, valueKind, OK_Ordinary); 11791 ME->setHadMultipleCandidates(true); 11792 MarkMemberReferenced(ME); 11793 return ME; 11794 } 11795 11796 llvm_unreachable("Invalid reference to overloaded function"); 11797 } 11798 11799 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11800 DeclAccessPair Found, 11801 FunctionDecl *Fn) { 11802 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11803 } 11804 11805 } // end namespace clang 11806