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/Basic/TargetInfo.h" 25 #include "clang/Lex/Preprocessor.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 37 namespace clang { 38 using namespace sema; 39 40 /// A convenience routine for creating a decayed reference to a function. 41 static ExprResult 42 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 43 bool HadMultipleCandidates, 44 SourceLocation Loc = SourceLocation(), 45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 46 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 47 return ExprError(); 48 // If FoundDecl is different from Fn (such as if one is a template 49 // and the other a specialization), make sure DiagnoseUseOfDecl is 50 // called on both. 51 // FIXME: This would be more comprehensively addressed by modifying 52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 53 // being used. 54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 55 return ExprError(); 56 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 57 VK_LValue, Loc, LocInfo); 58 if (HadMultipleCandidates) 59 DRE->setHadMultipleCandidates(true); 60 61 S.MarkDeclRefReferenced(DRE); 62 63 ExprResult E = S.Owned(DRE); 64 E = S.DefaultFunctionArrayConversion(E.take()); 65 if (E.isInvalid()) 66 return ExprError(); 67 return E; 68 } 69 70 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 71 bool InOverloadResolution, 72 StandardConversionSequence &SCS, 73 bool CStyle, 74 bool AllowObjCWritebackConversion); 75 76 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 77 QualType &ToType, 78 bool InOverloadResolution, 79 StandardConversionSequence &SCS, 80 bool CStyle); 81 static OverloadingResult 82 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 83 UserDefinedConversionSequence& User, 84 OverloadCandidateSet& Conversions, 85 bool AllowExplicit, 86 bool AllowObjCConversionOnExplicit); 87 88 89 static ImplicitConversionSequence::CompareKind 90 CompareStandardConversionSequences(Sema &S, 91 const StandardConversionSequence& SCS1, 92 const StandardConversionSequence& SCS2); 93 94 static ImplicitConversionSequence::CompareKind 95 CompareQualificationConversions(Sema &S, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareDerivedToBaseConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 105 106 /// GetConversionCategory - Retrieve the implicit conversion 107 /// category corresponding to the given implicit conversion kind. 108 ImplicitConversionCategory 109 GetConversionCategory(ImplicitConversionKind Kind) { 110 static const ImplicitConversionCategory 111 Category[(int)ICK_Num_Conversion_Kinds] = { 112 ICC_Identity, 113 ICC_Lvalue_Transformation, 114 ICC_Lvalue_Transformation, 115 ICC_Lvalue_Transformation, 116 ICC_Identity, 117 ICC_Qualification_Adjustment, 118 ICC_Promotion, 119 ICC_Promotion, 120 ICC_Promotion, 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 ICC_Conversion, 133 ICC_Conversion 134 }; 135 return Category[(int)Kind]; 136 } 137 138 /// GetConversionRank - Retrieve the implicit conversion rank 139 /// corresponding to the given implicit conversion kind. 140 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 141 static const ImplicitConversionRank 142 Rank[(int)ICK_Num_Conversion_Kinds] = { 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Exact_Match, 148 ICR_Exact_Match, 149 ICR_Promotion, 150 ICR_Promotion, 151 ICR_Promotion, 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_Conversion, 162 ICR_Conversion, 163 ICR_Complex_Real_Conversion, 164 ICR_Conversion, 165 ICR_Conversion, 166 ICR_Writeback_Conversion 167 }; 168 return Rank[(int)Kind]; 169 } 170 171 /// GetImplicitConversionName - Return the name of this kind of 172 /// implicit conversion. 173 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 175 "No conversion", 176 "Lvalue-to-rvalue", 177 "Array-to-pointer", 178 "Function-to-pointer", 179 "Noreturn adjustment", 180 "Qualification", 181 "Integral promotion", 182 "Floating point promotion", 183 "Complex promotion", 184 "Integral conversion", 185 "Floating conversion", 186 "Complex conversion", 187 "Floating-integral conversion", 188 "Pointer conversion", 189 "Pointer-to-member conversion", 190 "Boolean conversion", 191 "Compatible-types conversion", 192 "Derived-to-base conversion", 193 "Vector conversion", 194 "Vector splat", 195 "Complex-real conversion", 196 "Block Pointer conversion", 197 "Transparent Union Conversion" 198 "Writeback conversion" 199 }; 200 return Name[Kind]; 201 } 202 203 /// StandardConversionSequence - Set the standard conversion 204 /// sequence to the identity conversion. 205 void StandardConversionSequence::setAsIdentityConversion() { 206 First = ICK_Identity; 207 Second = ICK_Identity; 208 Third = ICK_Identity; 209 DeprecatedStringLiteralToCharPtr = false; 210 QualificationIncludesObjCLifetime = false; 211 ReferenceBinding = false; 212 DirectBinding = false; 213 IsLvalueReference = true; 214 BindsToFunctionLvalue = false; 215 BindsToRvalue = false; 216 BindsImplicitObjectArgumentWithoutRefQualifier = false; 217 ObjCLifetimeConversionBinding = false; 218 CopyConstructor = 0; 219 } 220 221 /// getRank - Retrieve the rank of this standard conversion sequence 222 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 223 /// implicit conversions. 224 ImplicitConversionRank StandardConversionSequence::getRank() const { 225 ImplicitConversionRank Rank = ICR_Exact_Match; 226 if (GetConversionRank(First) > Rank) 227 Rank = GetConversionRank(First); 228 if (GetConversionRank(Second) > Rank) 229 Rank = GetConversionRank(Second); 230 if (GetConversionRank(Third) > Rank) 231 Rank = GetConversionRank(Third); 232 return Rank; 233 } 234 235 /// isPointerConversionToBool - Determines whether this conversion is 236 /// a conversion of a pointer or pointer-to-member to bool. This is 237 /// used as part of the ranking of standard conversion sequences 238 /// (C++ 13.3.3.2p4). 239 bool StandardConversionSequence::isPointerConversionToBool() const { 240 // Note that FromType has not necessarily been transformed by the 241 // array-to-pointer or function-to-pointer implicit conversions, so 242 // check for their presence as well as checking whether FromType is 243 // a pointer. 244 if (getToType(1)->isBooleanType() && 245 (getFromType()->isPointerType() || 246 getFromType()->isObjCObjectPointerType() || 247 getFromType()->isBlockPointerType() || 248 getFromType()->isNullPtrType() || 249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 250 return true; 251 252 return false; 253 } 254 255 /// isPointerConversionToVoidPointer - Determines whether this 256 /// conversion is a conversion of a pointer to a void pointer. This is 257 /// used as part of the ranking of standard conversion sequences (C++ 258 /// 13.3.3.2p4). 259 bool 260 StandardConversionSequence:: 261 isPointerConversionToVoidPointer(ASTContext& Context) const { 262 QualType FromType = getFromType(); 263 QualType ToType = getToType(1); 264 265 // Note that FromType has not necessarily been transformed by the 266 // array-to-pointer implicit conversion, so check for its presence 267 // and redo the conversion to get a pointer. 268 if (First == ICK_Array_To_Pointer) 269 FromType = Context.getArrayDecayedType(FromType); 270 271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 273 return ToPtrType->getPointeeType()->isVoidType(); 274 275 return false; 276 } 277 278 /// Skip any implicit casts which could be either part of a narrowing conversion 279 /// or after one in an implicit conversion. 280 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 282 switch (ICE->getCastKind()) { 283 case CK_NoOp: 284 case CK_IntegralCast: 285 case CK_IntegralToBoolean: 286 case CK_IntegralToFloating: 287 case CK_FloatingToIntegral: 288 case CK_FloatingToBoolean: 289 case CK_FloatingCast: 290 Converted = ICE->getSubExpr(); 291 continue; 292 293 default: 294 return Converted; 295 } 296 } 297 298 return Converted; 299 } 300 301 /// Check if this standard conversion sequence represents a narrowing 302 /// conversion, according to C++11 [dcl.init.list]p7. 303 /// 304 /// \param Ctx The AST context. 305 /// \param Converted The result of applying this standard conversion sequence. 306 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 307 /// value of the expression prior to the narrowing conversion. 308 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 309 /// type of the expression prior to the narrowing conversion. 310 NarrowingKind 311 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 312 const Expr *Converted, 313 APValue &ConstantValue, 314 QualType &ConstantType) const { 315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 316 317 // C++11 [dcl.init.list]p7: 318 // A narrowing conversion is an implicit conversion ... 319 QualType FromType = getToType(0); 320 QualType ToType = getToType(1); 321 switch (Second) { 322 // -- from a floating-point type to an integer type, or 323 // 324 // -- from an integer type or unscoped enumeration type to a floating-point 325 // type, except where the source is a constant expression and the actual 326 // value after conversion will fit into the target type and will produce 327 // the original value when converted back to the original type, or 328 case ICK_Floating_Integral: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 332 llvm::APSInt IntConstantValue; 333 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 334 if (Initializer && 335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 336 // Convert the integer to the floating type. 337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 339 llvm::APFloat::rmNearestTiesToEven); 340 // And back. 341 llvm::APSInt ConvertedValue = IntConstantValue; 342 bool ignored; 343 Result.convertToInteger(ConvertedValue, 344 llvm::APFloat::rmTowardZero, &ignored); 345 // If the resulting value is different, this was a narrowing conversion. 346 if (IntConstantValue != ConvertedValue) { 347 ConstantValue = APValue(IntConstantValue); 348 ConstantType = Initializer->getType(); 349 return NK_Constant_Narrowing; 350 } 351 } else { 352 // Variables are always narrowings. 353 return NK_Variable_Narrowing; 354 } 355 } 356 return NK_Not_Narrowing; 357 358 // -- from long double to double or float, or from double to float, except 359 // where the source is a constant expression and the actual value after 360 // conversion is within the range of values that can be represented (even 361 // if it cannot be represented exactly), or 362 case ICK_Floating_Conversion: 363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 365 // FromType is larger than ToType. 366 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 368 // Constant! 369 assert(ConstantValue.isFloat()); 370 llvm::APFloat FloatVal = ConstantValue.getFloat(); 371 // Convert the source value into the target type. 372 bool ignored; 373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 374 Ctx.getFloatTypeSemantics(ToType), 375 llvm::APFloat::rmNearestTiesToEven, &ignored); 376 // If there was no overflow, the source value is within the range of 377 // values that can be represented. 378 if (ConvertStatus & llvm::APFloat::opOverflow) { 379 ConstantType = Initializer->getType(); 380 return NK_Constant_Narrowing; 381 } 382 } else { 383 return NK_Variable_Narrowing; 384 } 385 } 386 return NK_Not_Narrowing; 387 388 // -- from an integer type or unscoped enumeration type to an integer type 389 // that cannot represent all the values of the original type, except where 390 // the source is a constant expression and the actual value after 391 // conversion will fit into the target type and will produce the original 392 // value when converted back to the original type. 393 case ICK_Boolean_Conversion: // Bools are integers too. 394 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 395 // Boolean conversions can be from pointers and pointers to members 396 // [conv.bool], and those aren't considered narrowing conversions. 397 return NK_Not_Narrowing; 398 } // Otherwise, fall through to the integral case. 399 case ICK_Integral_Conversion: { 400 assert(FromType->isIntegralOrUnscopedEnumerationType()); 401 assert(ToType->isIntegralOrUnscopedEnumerationType()); 402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 403 const unsigned FromWidth = Ctx.getIntWidth(FromType); 404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 405 const unsigned ToWidth = Ctx.getIntWidth(ToType); 406 407 if (FromWidth > ToWidth || 408 (FromWidth == ToWidth && FromSigned != ToSigned) || 409 (FromSigned && !ToSigned)) { 410 // Not all values of FromType can be represented in ToType. 411 llvm::APSInt InitializerValue; 412 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 414 // Such conversions on variables are always narrowing. 415 return NK_Variable_Narrowing; 416 } 417 bool Narrowing = false; 418 if (FromWidth < ToWidth) { 419 // Negative -> unsigned is narrowing. Otherwise, more bits is never 420 // narrowing. 421 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 422 Narrowing = true; 423 } else { 424 // Add a bit to the InitializerValue so we don't have to worry about 425 // signed vs. unsigned comparisons. 426 InitializerValue = InitializerValue.extend( 427 InitializerValue.getBitWidth() + 1); 428 // Convert the initializer to and from the target width and signed-ness. 429 llvm::APSInt ConvertedValue = InitializerValue; 430 ConvertedValue = ConvertedValue.trunc(ToWidth); 431 ConvertedValue.setIsSigned(ToSigned); 432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 433 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 434 // If the result is different, this was a narrowing conversion. 435 if (ConvertedValue != InitializerValue) 436 Narrowing = true; 437 } 438 if (Narrowing) { 439 ConstantType = Initializer->getType(); 440 ConstantValue = APValue(InitializerValue); 441 return NK_Constant_Narrowing; 442 } 443 } 444 return NK_Not_Narrowing; 445 } 446 447 default: 448 // Other kinds of conversions are not narrowings. 449 return NK_Not_Narrowing; 450 } 451 } 452 453 /// dump - Print this standard conversion sequence to standard 454 /// error. Useful for debugging overloading issues. 455 void StandardConversionSequence::dump() const { 456 raw_ostream &OS = llvm::errs(); 457 bool PrintedSomething = false; 458 if (First != ICK_Identity) { 459 OS << GetImplicitConversionName(First); 460 PrintedSomething = true; 461 } 462 463 if (Second != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Second); 468 469 if (CopyConstructor) { 470 OS << " (by copy constructor)"; 471 } else if (DirectBinding) { 472 OS << " (direct reference binding)"; 473 } else if (ReferenceBinding) { 474 OS << " (reference binding)"; 475 } 476 PrintedSomething = true; 477 } 478 479 if (Third != ICK_Identity) { 480 if (PrintedSomething) { 481 OS << " -> "; 482 } 483 OS << GetImplicitConversionName(Third); 484 PrintedSomething = true; 485 } 486 487 if (!PrintedSomething) { 488 OS << "No conversions required"; 489 } 490 } 491 492 /// dump - Print this user-defined conversion sequence to standard 493 /// error. Useful for debugging overloading issues. 494 void UserDefinedConversionSequence::dump() const { 495 raw_ostream &OS = llvm::errs(); 496 if (Before.First || Before.Second || Before.Third) { 497 Before.dump(); 498 OS << " -> "; 499 } 500 if (ConversionFunction) 501 OS << '\'' << *ConversionFunction << '\''; 502 else 503 OS << "aggregate initialization"; 504 if (After.First || After.Second || After.Third) { 505 OS << " -> "; 506 After.dump(); 507 } 508 } 509 510 /// dump - Print this implicit conversion sequence to standard 511 /// error. Useful for debugging overloading issues. 512 void ImplicitConversionSequence::dump() const { 513 raw_ostream &OS = llvm::errs(); 514 if (isStdInitializerListElement()) 515 OS << "Worst std::initializer_list element conversion: "; 516 switch (ConversionKind) { 517 case StandardConversion: 518 OS << "Standard conversion: "; 519 Standard.dump(); 520 break; 521 case UserDefinedConversion: 522 OS << "User-defined conversion: "; 523 UserDefined.dump(); 524 break; 525 case EllipsisConversion: 526 OS << "Ellipsis conversion"; 527 break; 528 case AmbiguousConversion: 529 OS << "Ambiguous conversion"; 530 break; 531 case BadConversion: 532 OS << "Bad conversion"; 533 break; 534 } 535 536 OS << "\n"; 537 } 538 539 void AmbiguousConversionSequence::construct() { 540 new (&conversions()) ConversionSet(); 541 } 542 543 void AmbiguousConversionSequence::destruct() { 544 conversions().~ConversionSet(); 545 } 546 547 void 548 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 549 FromTypePtr = O.FromTypePtr; 550 ToTypePtr = O.ToTypePtr; 551 new (&conversions()) ConversionSet(O.conversions()); 552 } 553 554 namespace { 555 // Structure used by DeductionFailureInfo to store 556 // template argument information. 557 struct DFIArguments { 558 TemplateArgument FirstArg; 559 TemplateArgument SecondArg; 560 }; 561 // Structure used by DeductionFailureInfo to store 562 // template parameter and template argument information. 563 struct DFIParamWithArguments : DFIArguments { 564 TemplateParameter Param; 565 }; 566 } 567 568 /// \brief Convert from Sema's representation of template deduction information 569 /// to the form used in overload-candidate information. 570 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 571 Sema::TemplateDeductionResult TDK, 572 TemplateDeductionInfo &Info) { 573 DeductionFailureInfo Result; 574 Result.Result = static_cast<unsigned>(TDK); 575 Result.HasDiagnostic = false; 576 Result.Data = 0; 577 switch (TDK) { 578 case Sema::TDK_Success: 579 case Sema::TDK_Invalid: 580 case Sema::TDK_InstantiationDepth: 581 case Sema::TDK_TooManyArguments: 582 case Sema::TDK_TooFewArguments: 583 break; 584 585 case Sema::TDK_Incomplete: 586 case Sema::TDK_InvalidExplicitArguments: 587 Result.Data = Info.Param.getOpaqueValue(); 588 break; 589 590 case Sema::TDK_NonDeducedMismatch: { 591 // FIXME: Should allocate from normal heap so that we can free this later. 592 DFIArguments *Saved = new (Context) DFIArguments; 593 Saved->FirstArg = Info.FirstArg; 594 Saved->SecondArg = Info.SecondArg; 595 Result.Data = Saved; 596 break; 597 } 598 599 case Sema::TDK_Inconsistent: 600 case Sema::TDK_Underqualified: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 603 Saved->Param = Info.Param; 604 Saved->FirstArg = Info.FirstArg; 605 Saved->SecondArg = Info.SecondArg; 606 Result.Data = Saved; 607 break; 608 } 609 610 case Sema::TDK_SubstitutionFailure: 611 Result.Data = Info.take(); 612 if (Info.hasSFINAEDiagnostic()) { 613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 614 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 615 Info.takeSFINAEDiagnostic(*Diag); 616 Result.HasDiagnostic = true; 617 } 618 break; 619 620 case Sema::TDK_FailedOverloadResolution: 621 Result.Data = Info.Expression; 622 break; 623 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 break; 626 } 627 628 return Result; 629 } 630 631 void DeductionFailureInfo::Destroy() { 632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 633 case Sema::TDK_Success: 634 case Sema::TDK_Invalid: 635 case Sema::TDK_InstantiationDepth: 636 case Sema::TDK_Incomplete: 637 case Sema::TDK_TooManyArguments: 638 case Sema::TDK_TooFewArguments: 639 case Sema::TDK_InvalidExplicitArguments: 640 case Sema::TDK_FailedOverloadResolution: 641 break; 642 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: 645 case Sema::TDK_NonDeducedMismatch: 646 // FIXME: Destroy the data? 647 Data = 0; 648 break; 649 650 case Sema::TDK_SubstitutionFailure: 651 // FIXME: Destroy the template argument list? 652 Data = 0; 653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 654 Diag->~PartialDiagnosticAt(); 655 HasDiagnostic = false; 656 } 657 break; 658 659 // Unhandled 660 case Sema::TDK_MiscellaneousDeductionFailure: 661 break; 662 } 663 } 664 665 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 666 if (HasDiagnostic) 667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 668 return 0; 669 } 670 671 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 673 case Sema::TDK_Success: 674 case Sema::TDK_Invalid: 675 case Sema::TDK_InstantiationDepth: 676 case Sema::TDK_TooManyArguments: 677 case Sema::TDK_TooFewArguments: 678 case Sema::TDK_SubstitutionFailure: 679 case Sema::TDK_NonDeducedMismatch: 680 case Sema::TDK_FailedOverloadResolution: 681 return TemplateParameter(); 682 683 case Sema::TDK_Incomplete: 684 case Sema::TDK_InvalidExplicitArguments: 685 return TemplateParameter::getFromOpaqueValue(Data); 686 687 case Sema::TDK_Inconsistent: 688 case Sema::TDK_Underqualified: 689 return static_cast<DFIParamWithArguments*>(Data)->Param; 690 691 // Unhandled 692 case Sema::TDK_MiscellaneousDeductionFailure: 693 break; 694 } 695 696 return TemplateParameter(); 697 } 698 699 TemplateArgumentList *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 *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 *DeductionFailureInfo::getSecondArg() { 752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 753 case Sema::TDK_Success: 754 case Sema::TDK_Invalid: 755 case Sema::TDK_InstantiationDepth: 756 case Sema::TDK_Incomplete: 757 case Sema::TDK_TooManyArguments: 758 case Sema::TDK_TooFewArguments: 759 case Sema::TDK_InvalidExplicitArguments: 760 case Sema::TDK_SubstitutionFailure: 761 case Sema::TDK_FailedOverloadResolution: 762 return 0; 763 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 case Sema::TDK_NonDeducedMismatch: 767 return &static_cast<DFIArguments*>(Data)->SecondArg; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return 0; 775 } 776 777 Expr *DeductionFailureInfo::getExpr() { 778 if (static_cast<Sema::TemplateDeductionResult>(Result) == 779 Sema::TDK_FailedOverloadResolution) 780 return static_cast<Expr*>(Data); 781 782 return 0; 783 } 784 785 void OverloadCandidateSet::destroyCandidates() { 786 for (iterator i = begin(), e = end(); i != e; ++i) { 787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 788 i->Conversions[ii].~ImplicitConversionSequence(); 789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 790 i->DeductionFailure.Destroy(); 791 } 792 } 793 794 void OverloadCandidateSet::clear() { 795 destroyCandidates(); 796 NumInlineSequences = 0; 797 Candidates.clear(); 798 Functions.clear(); 799 } 800 801 namespace { 802 class UnbridgedCastsSet { 803 struct Entry { 804 Expr **Addr; 805 Expr *Saved; 806 }; 807 SmallVector<Entry, 2> Entries; 808 809 public: 810 void save(Sema &S, Expr *&E) { 811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 812 Entry entry = { &E, E }; 813 Entries.push_back(entry); 814 E = S.stripARCUnbridgedCast(E); 815 } 816 817 void restore() { 818 for (SmallVectorImpl<Entry>::iterator 819 i = Entries.begin(), e = Entries.end(); i != e; ++i) 820 *i->Addr = i->Saved; 821 } 822 }; 823 } 824 825 /// checkPlaceholderForOverload - Do any interesting placeholder-like 826 /// preprocessing on the given expression. 827 /// 828 /// \param unbridgedCasts a collection to which to add unbridged casts; 829 /// without this, they will be immediately diagnosed as errors 830 /// 831 /// Return true on unrecoverable error. 832 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 833 UnbridgedCastsSet *unbridgedCasts = 0) { 834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 835 // We can't handle overloaded expressions here because overload 836 // resolution might reasonably tweak them. 837 if (placeholder->getKind() == BuiltinType::Overload) return false; 838 839 // If the context potentially accepts unbridged ARC casts, strip 840 // the unbridged cast and add it to the collection for later restoration. 841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 842 unbridgedCasts) { 843 unbridgedCasts->save(S, E); 844 return false; 845 } 846 847 // Go ahead and check everything else. 848 ExprResult result = S.CheckPlaceholderExpr(E); 849 if (result.isInvalid()) 850 return true; 851 852 E = result.take(); 853 return false; 854 } 855 856 // Nothing to do. 857 return false; 858 } 859 860 /// checkArgPlaceholdersForOverload - Check a set of call operands for 861 /// placeholders. 862 static bool checkArgPlaceholdersForOverload(Sema &S, 863 MultiExprArg Args, 864 UnbridgedCastsSet &unbridged) { 865 for (unsigned i = 0, e = Args.size(); i != e; ++i) 866 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 867 return true; 868 869 return false; 870 } 871 872 // IsOverload - Determine whether the given New declaration is an 873 // overload of the declarations in Old. This routine returns false if 874 // New and Old cannot be overloaded, e.g., if New has the same 875 // signature as some function in Old (C++ 1.3.10) or if the Old 876 // declarations aren't functions (or function templates) at all. When 877 // it does return false, MatchedDecl will point to the decl that New 878 // cannot be overloaded with. This decl may be a UsingShadowDecl on 879 // top of the underlying declaration. 880 // 881 // Example: Given the following input: 882 // 883 // void f(int, float); // #1 884 // void f(int, int); // #2 885 // int f(int, int); // #3 886 // 887 // When we process #1, there is no previous declaration of "f", 888 // so IsOverload will not be used. 889 // 890 // When we process #2, Old contains only the FunctionDecl for #1. By 891 // comparing the parameter types, we see that #1 and #2 are overloaded 892 // (since they have different signatures), so this routine returns 893 // false; MatchedDecl is unchanged. 894 // 895 // When we process #3, Old is an overload set containing #1 and #2. We 896 // compare the signatures of #3 to #1 (they're overloaded, so we do 897 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 898 // identical (return types of functions are not part of the 899 // signature), IsOverload returns false and MatchedDecl will be set to 900 // point to the FunctionDecl for #2. 901 // 902 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 903 // into a class by a using declaration. The rules for whether to hide 904 // shadow declarations ignore some properties which otherwise figure 905 // into a function template's signature. 906 Sema::OverloadKind 907 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 908 NamedDecl *&Match, bool NewIsUsingDecl) { 909 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 910 I != E; ++I) { 911 NamedDecl *OldD = *I; 912 913 bool OldIsUsingDecl = false; 914 if (isa<UsingShadowDecl>(OldD)) { 915 OldIsUsingDecl = true; 916 917 // We can always introduce two using declarations into the same 918 // context, even if they have identical signatures. 919 if (NewIsUsingDecl) continue; 920 921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 922 } 923 924 // If either declaration was introduced by a using declaration, 925 // we'll need to use slightly different rules for matching. 926 // Essentially, these rules are the normal rules, except that 927 // function templates hide function templates with different 928 // return types or template parameter lists. 929 bool UseMemberUsingDeclRules = 930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 931 !New->getFriendObjectKind(); 932 933 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 934 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 935 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 937 continue; 938 } 939 940 Match = *I; 941 return Ovl_Match; 942 } 943 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 944 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 945 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 946 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 947 continue; 948 } 949 950 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 951 continue; 952 953 Match = *I; 954 return Ovl_Match; 955 } 956 } else if (isa<UsingDecl>(OldD)) { 957 // We can overload with these, which can show up when doing 958 // redeclaration checks for UsingDecls. 959 assert(Old.getLookupKind() == LookupUsingDeclName); 960 } else if (isa<TagDecl>(OldD)) { 961 // We can always overload with tags by hiding them. 962 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 963 // Optimistically assume that an unresolved using decl will 964 // overload; if it doesn't, we'll have to diagnose during 965 // template instantiation. 966 } else { 967 // (C++ 13p1): 968 // Only function declarations can be overloaded; object and type 969 // declarations cannot be overloaded. 970 Match = *I; 971 return Ovl_NonFunction; 972 } 973 } 974 975 return Ovl_Overload; 976 } 977 978 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 979 bool UseUsingDeclRules) { 980 // C++ [basic.start.main]p2: This function shall not be overloaded. 981 if (New->isMain()) 982 return false; 983 984 // MSVCRT user defined entry points cannot be overloaded. 985 if (New->isMSVCRTEntryPoint()) 986 return false; 987 988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 990 991 // C++ [temp.fct]p2: 992 // A function template can be overloaded with other function templates 993 // and with normal (non-template) functions. 994 if ((OldTemplate == 0) != (NewTemplate == 0)) 995 return true; 996 997 // Is the function New an overload of the function Old? 998 QualType OldQType = Context.getCanonicalType(Old->getType()); 999 QualType NewQType = Context.getCanonicalType(New->getType()); 1000 1001 // Compare the signatures (C++ 1.3.10) of the two functions to 1002 // determine whether they are overloads. If we find any mismatch 1003 // in the signature, they are overloads. 1004 1005 // If either of these functions is a K&R-style function (no 1006 // prototype), then we consider them to have matching signatures. 1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1008 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1009 return false; 1010 1011 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1012 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1013 1014 // The signature of a function includes the types of its 1015 // parameters (C++ 1.3.10), which includes the presence or absence 1016 // of the ellipsis; see C++ DR 357). 1017 if (OldQType != NewQType && 1018 (OldType->getNumArgs() != NewType->getNumArgs() || 1019 OldType->isVariadic() != NewType->isVariadic() || 1020 !FunctionArgTypesAreEqual(OldType, NewType))) 1021 return true; 1022 1023 // C++ [temp.over.link]p4: 1024 // The signature of a function template consists of its function 1025 // signature, its return type and its template parameter list. The names 1026 // of the template parameters are significant only for establishing the 1027 // relationship between the template parameters and the rest of the 1028 // signature. 1029 // 1030 // We check the return type and template parameter lists for function 1031 // templates first; the remaining checks follow. 1032 // 1033 // However, we don't consider either of these when deciding whether 1034 // a member introduced by a shadow declaration is hidden. 1035 if (!UseUsingDeclRules && NewTemplate && 1036 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1037 OldTemplate->getTemplateParameters(), 1038 false, TPL_TemplateMatch) || 1039 OldType->getResultType() != NewType->getResultType())) 1040 return true; 1041 1042 // If the function is a class member, its signature includes the 1043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1044 // 1045 // As part of this, also check whether one of the member functions 1046 // is static, in which case they are not overloads (C++ 1047 // 13.1p2). While not part of the definition of the signature, 1048 // this check is important to determine whether these functions 1049 // can be overloaded. 1050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1052 if (OldMethod && NewMethod && 1053 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1055 if (!UseUsingDeclRules && 1056 (OldMethod->getRefQualifier() == RQ_None || 1057 NewMethod->getRefQualifier() == RQ_None)) { 1058 // C++0x [over.load]p2: 1059 // - Member function declarations with the same name and the same 1060 // parameter-type-list as well as member function template 1061 // declarations with the same name, the same parameter-type-list, and 1062 // the same template parameter lists cannot be overloaded if any of 1063 // them, but not all, have a ref-qualifier (8.3.5). 1064 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1066 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1067 } 1068 return true; 1069 } 1070 1071 // We may not have applied the implicit const for a constexpr member 1072 // function yet (because we haven't yet resolved whether this is a static 1073 // or non-static member function). Add it now, on the assumption that this 1074 // is a redeclaration of OldMethod. 1075 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1076 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1077 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1078 !isa<CXXConstructorDecl>(NewMethod)) 1079 NewQuals |= Qualifiers::Const; 1080 1081 // We do not allow overloading based off of '__restrict'. 1082 OldQuals &= ~Qualifiers::Restrict; 1083 NewQuals &= ~Qualifiers::Restrict; 1084 if (OldQuals != NewQuals) 1085 return true; 1086 } 1087 1088 // enable_if attributes are an order-sensitive part of the signature. 1089 for (specific_attr_iterator<EnableIfAttr> 1090 NewI = New->specific_attr_begin<EnableIfAttr>(), 1091 NewE = New->specific_attr_end<EnableIfAttr>(), 1092 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1093 OldE = Old->specific_attr_end<EnableIfAttr>(); 1094 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1095 if (NewI == NewE || OldI == OldE) 1096 return true; 1097 llvm::FoldingSetNodeID NewID, OldID; 1098 NewI->getCond()->Profile(NewID, Context, true); 1099 OldI->getCond()->Profile(OldID, Context, true); 1100 if (!(NewID == OldID)) 1101 return true; 1102 } 1103 1104 // The signatures match; this is not an overload. 1105 return false; 1106 } 1107 1108 /// \brief Checks availability of the function depending on the current 1109 /// function context. Inside an unavailable function, unavailability is ignored. 1110 /// 1111 /// \returns true if \arg FD is unavailable and current context is inside 1112 /// an available function, false otherwise. 1113 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1114 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1115 } 1116 1117 /// \brief Tries a user-defined conversion from From to ToType. 1118 /// 1119 /// Produces an implicit conversion sequence for when a standard conversion 1120 /// is not an option. See TryImplicitConversion for more information. 1121 static ImplicitConversionSequence 1122 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1123 bool SuppressUserConversions, 1124 bool AllowExplicit, 1125 bool InOverloadResolution, 1126 bool CStyle, 1127 bool AllowObjCWritebackConversion, 1128 bool AllowObjCConversionOnExplicit) { 1129 ImplicitConversionSequence ICS; 1130 1131 if (SuppressUserConversions) { 1132 // We're not in the case above, so there is no conversion that 1133 // we can perform. 1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1135 return ICS; 1136 } 1137 1138 // Attempt user-defined conversion. 1139 OverloadCandidateSet Conversions(From->getExprLoc()); 1140 OverloadingResult UserDefResult 1141 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1142 AllowExplicit, AllowObjCConversionOnExplicit); 1143 1144 if (UserDefResult == OR_Success) { 1145 ICS.setUserDefined(); 1146 // C++ [over.ics.user]p4: 1147 // A conversion of an expression of class type to the same class 1148 // type is given Exact Match rank, and a conversion of an 1149 // expression of class type to a base class of that type is 1150 // given Conversion rank, in spite of the fact that a copy 1151 // constructor (i.e., a user-defined conversion function) is 1152 // called for those cases. 1153 if (CXXConstructorDecl *Constructor 1154 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1155 QualType FromCanon 1156 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1157 QualType ToCanon 1158 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1159 if (Constructor->isCopyConstructor() && 1160 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1161 // Turn this into a "standard" conversion sequence, so that it 1162 // gets ranked with standard conversion sequences. 1163 ICS.setStandard(); 1164 ICS.Standard.setAsIdentityConversion(); 1165 ICS.Standard.setFromType(From->getType()); 1166 ICS.Standard.setAllToTypes(ToType); 1167 ICS.Standard.CopyConstructor = Constructor; 1168 if (ToCanon != FromCanon) 1169 ICS.Standard.Second = ICK_Derived_To_Base; 1170 } 1171 } 1172 1173 // C++ [over.best.ics]p4: 1174 // However, when considering the argument of a user-defined 1175 // conversion function that is a candidate by 13.3.1.3 when 1176 // invoked for the copying of the temporary in the second step 1177 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1178 // 13.3.1.6 in all cases, only standard conversion sequences and 1179 // ellipsis conversion sequences are allowed. 1180 if (SuppressUserConversions && ICS.isUserDefined()) { 1181 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1182 } 1183 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1184 ICS.setAmbiguous(); 1185 ICS.Ambiguous.setFromType(From->getType()); 1186 ICS.Ambiguous.setToType(ToType); 1187 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1188 Cand != Conversions.end(); ++Cand) 1189 if (Cand->Viable) 1190 ICS.Ambiguous.addConversion(Cand->Function); 1191 } else { 1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1193 } 1194 1195 return ICS; 1196 } 1197 1198 /// TryImplicitConversion - Attempt to perform an implicit conversion 1199 /// from the given expression (Expr) to the given type (ToType). This 1200 /// function returns an implicit conversion sequence that can be used 1201 /// to perform the initialization. Given 1202 /// 1203 /// void f(float f); 1204 /// void g(int i) { f(i); } 1205 /// 1206 /// this routine would produce an implicit conversion sequence to 1207 /// describe the initialization of f from i, which will be a standard 1208 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1209 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1210 // 1211 /// Note that this routine only determines how the conversion can be 1212 /// performed; it does not actually perform the conversion. As such, 1213 /// it will not produce any diagnostics if no conversion is available, 1214 /// but will instead return an implicit conversion sequence of kind 1215 /// "BadConversion". 1216 /// 1217 /// If @p SuppressUserConversions, then user-defined conversions are 1218 /// not permitted. 1219 /// If @p AllowExplicit, then explicit user-defined conversions are 1220 /// permitted. 1221 /// 1222 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1223 /// writeback conversion, which allows __autoreleasing id* parameters to 1224 /// be initialized with __strong id* or __weak id* arguments. 1225 static ImplicitConversionSequence 1226 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1227 bool SuppressUserConversions, 1228 bool AllowExplicit, 1229 bool InOverloadResolution, 1230 bool CStyle, 1231 bool AllowObjCWritebackConversion, 1232 bool AllowObjCConversionOnExplicit) { 1233 ImplicitConversionSequence ICS; 1234 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1235 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1236 ICS.setStandard(); 1237 return ICS; 1238 } 1239 1240 if (!S.getLangOpts().CPlusPlus) { 1241 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1242 return ICS; 1243 } 1244 1245 // C++ [over.ics.user]p4: 1246 // A conversion of an expression of class type to the same class 1247 // type is given Exact Match rank, and a conversion of an 1248 // expression of class type to a base class of that type is 1249 // given Conversion rank, in spite of the fact that a copy/move 1250 // constructor (i.e., a user-defined conversion function) is 1251 // called for those cases. 1252 QualType FromType = From->getType(); 1253 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1254 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1255 S.IsDerivedFrom(FromType, ToType))) { 1256 ICS.setStandard(); 1257 ICS.Standard.setAsIdentityConversion(); 1258 ICS.Standard.setFromType(FromType); 1259 ICS.Standard.setAllToTypes(ToType); 1260 1261 // We don't actually check at this point whether there is a valid 1262 // copy/move constructor, since overloading just assumes that it 1263 // exists. When we actually perform initialization, we'll find the 1264 // appropriate constructor to copy the returned object, if needed. 1265 ICS.Standard.CopyConstructor = 0; 1266 1267 // Determine whether this is considered a derived-to-base conversion. 1268 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1269 ICS.Standard.Second = ICK_Derived_To_Base; 1270 1271 return ICS; 1272 } 1273 1274 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1275 AllowExplicit, InOverloadResolution, CStyle, 1276 AllowObjCWritebackConversion, 1277 AllowObjCConversionOnExplicit); 1278 } 1279 1280 ImplicitConversionSequence 1281 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1282 bool SuppressUserConversions, 1283 bool AllowExplicit, 1284 bool InOverloadResolution, 1285 bool CStyle, 1286 bool AllowObjCWritebackConversion) { 1287 return clang::TryImplicitConversion(*this, From, ToType, 1288 SuppressUserConversions, AllowExplicit, 1289 InOverloadResolution, CStyle, 1290 AllowObjCWritebackConversion, 1291 /*AllowObjCConversionOnExplicit=*/false); 1292 } 1293 1294 /// PerformImplicitConversion - Perform an implicit conversion of the 1295 /// expression From to the type ToType. Returns the 1296 /// converted expression. Flavor is the kind of conversion we're 1297 /// performing, used in the error message. If @p AllowExplicit, 1298 /// explicit user-defined conversions are permitted. 1299 ExprResult 1300 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1301 AssignmentAction Action, bool AllowExplicit) { 1302 ImplicitConversionSequence ICS; 1303 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1304 } 1305 1306 ExprResult 1307 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1308 AssignmentAction Action, bool AllowExplicit, 1309 ImplicitConversionSequence& ICS) { 1310 if (checkPlaceholderForOverload(*this, From)) 1311 return ExprError(); 1312 1313 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1314 bool AllowObjCWritebackConversion 1315 = getLangOpts().ObjCAutoRefCount && 1316 (Action == AA_Passing || Action == AA_Sending); 1317 if (getLangOpts().ObjC1) 1318 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1319 ToType, From->getType(), From); 1320 ICS = clang::TryImplicitConversion(*this, From, ToType, 1321 /*SuppressUserConversions=*/false, 1322 AllowExplicit, 1323 /*InOverloadResolution=*/false, 1324 /*CStyle=*/false, 1325 AllowObjCWritebackConversion, 1326 /*AllowObjCConversionOnExplicit=*/false); 1327 return PerformImplicitConversion(From, ToType, ICS, Action); 1328 } 1329 1330 /// \brief Determine whether the conversion from FromType to ToType is a valid 1331 /// conversion that strips "noreturn" off the nested function type. 1332 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1333 QualType &ResultTy) { 1334 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1335 return false; 1336 1337 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1338 // where F adds one of the following at most once: 1339 // - a pointer 1340 // - a member pointer 1341 // - a block pointer 1342 CanQualType CanTo = Context.getCanonicalType(ToType); 1343 CanQualType CanFrom = Context.getCanonicalType(FromType); 1344 Type::TypeClass TyClass = CanTo->getTypeClass(); 1345 if (TyClass != CanFrom->getTypeClass()) return false; 1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1347 if (TyClass == Type::Pointer) { 1348 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1349 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1350 } else if (TyClass == Type::BlockPointer) { 1351 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1352 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1353 } else if (TyClass == Type::MemberPointer) { 1354 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1355 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1356 } else { 1357 return false; 1358 } 1359 1360 TyClass = CanTo->getTypeClass(); 1361 if (TyClass != CanFrom->getTypeClass()) return false; 1362 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1363 return false; 1364 } 1365 1366 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1367 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1368 if (!EInfo.getNoReturn()) return false; 1369 1370 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1371 assert(QualType(FromFn, 0).isCanonical()); 1372 if (QualType(FromFn, 0) != CanTo) return false; 1373 1374 ResultTy = ToType; 1375 return true; 1376 } 1377 1378 /// \brief Determine whether the conversion from FromType to ToType is a valid 1379 /// vector conversion. 1380 /// 1381 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1382 /// conversion. 1383 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1384 QualType ToType, ImplicitConversionKind &ICK) { 1385 // We need at least one of these types to be a vector type to have a vector 1386 // conversion. 1387 if (!ToType->isVectorType() && !FromType->isVectorType()) 1388 return false; 1389 1390 // Identical types require no conversions. 1391 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1392 return false; 1393 1394 // There are no conversions between extended vector types, only identity. 1395 if (ToType->isExtVectorType()) { 1396 // There are no conversions between extended vector types other than the 1397 // identity conversion. 1398 if (FromType->isExtVectorType()) 1399 return false; 1400 1401 // Vector splat from any arithmetic type to a vector. 1402 if (FromType->isArithmeticType()) { 1403 ICK = ICK_Vector_Splat; 1404 return true; 1405 } 1406 } 1407 1408 // We can perform the conversion between vector types in the following cases: 1409 // 1)vector types are equivalent AltiVec and GCC vector types 1410 // 2)lax vector conversions are permitted and the vector types are of the 1411 // same size 1412 if (ToType->isVectorType() && FromType->isVectorType()) { 1413 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1414 (Context.getLangOpts().LaxVectorConversions && 1415 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1416 ICK = ICK_Vector_Conversion; 1417 return true; 1418 } 1419 } 1420 1421 return false; 1422 } 1423 1424 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1425 bool InOverloadResolution, 1426 StandardConversionSequence &SCS, 1427 bool CStyle); 1428 1429 /// IsStandardConversion - Determines whether there is a standard 1430 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1431 /// expression From to the type ToType. Standard conversion sequences 1432 /// only consider non-class types; for conversions that involve class 1433 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1434 /// contain the standard conversion sequence required to perform this 1435 /// conversion and this routine will return true. Otherwise, this 1436 /// routine will return false and the value of SCS is unspecified. 1437 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1438 bool InOverloadResolution, 1439 StandardConversionSequence &SCS, 1440 bool CStyle, 1441 bool AllowObjCWritebackConversion) { 1442 QualType FromType = From->getType(); 1443 1444 // Standard conversions (C++ [conv]) 1445 SCS.setAsIdentityConversion(); 1446 SCS.IncompatibleObjC = false; 1447 SCS.setFromType(FromType); 1448 SCS.CopyConstructor = 0; 1449 1450 // There are no standard conversions for class types in C++, so 1451 // abort early. When overloading in C, however, we do permit 1452 if (FromType->isRecordType() || ToType->isRecordType()) { 1453 if (S.getLangOpts().CPlusPlus) 1454 return false; 1455 1456 // When we're overloading in C, we allow, as standard conversions, 1457 } 1458 1459 // The first conversion can be an lvalue-to-rvalue conversion, 1460 // array-to-pointer conversion, or function-to-pointer conversion 1461 // (C++ 4p1). 1462 1463 if (FromType == S.Context.OverloadTy) { 1464 DeclAccessPair AccessPair; 1465 if (FunctionDecl *Fn 1466 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1467 AccessPair)) { 1468 // We were able to resolve the address of the overloaded function, 1469 // so we can convert to the type of that function. 1470 FromType = Fn->getType(); 1471 1472 // we can sometimes resolve &foo<int> regardless of ToType, so check 1473 // if the type matches (identity) or we are converting to bool 1474 if (!S.Context.hasSameUnqualifiedType( 1475 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1476 QualType resultTy; 1477 // if the function type matches except for [[noreturn]], it's ok 1478 if (!S.IsNoReturnConversion(FromType, 1479 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1480 // otherwise, only a boolean conversion is standard 1481 if (!ToType->isBooleanType()) 1482 return false; 1483 } 1484 1485 // Check if the "from" expression is taking the address of an overloaded 1486 // function and recompute the FromType accordingly. Take advantage of the 1487 // fact that non-static member functions *must* have such an address-of 1488 // expression. 1489 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1490 if (Method && !Method->isStatic()) { 1491 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1492 "Non-unary operator on non-static member address"); 1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1494 == UO_AddrOf && 1495 "Non-address-of operator on non-static member address"); 1496 const Type *ClassType 1497 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1498 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1499 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1500 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1501 UO_AddrOf && 1502 "Non-address-of operator for overloaded function expression"); 1503 FromType = S.Context.getPointerType(FromType); 1504 } 1505 1506 // Check that we've computed the proper type after overload resolution. 1507 assert(S.Context.hasSameType( 1508 FromType, 1509 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1510 } else { 1511 return false; 1512 } 1513 } 1514 // Lvalue-to-rvalue conversion (C++11 4.1): 1515 // A glvalue (3.10) of a non-function, non-array type T can 1516 // be converted to a prvalue. 1517 bool argIsLValue = From->isGLValue(); 1518 if (argIsLValue && 1519 !FromType->isFunctionType() && !FromType->isArrayType() && 1520 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1521 SCS.First = ICK_Lvalue_To_Rvalue; 1522 1523 // C11 6.3.2.1p2: 1524 // ... if the lvalue has atomic type, the value has the non-atomic version 1525 // of the type of the lvalue ... 1526 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1527 FromType = Atomic->getValueType(); 1528 1529 // If T is a non-class type, the type of the rvalue is the 1530 // cv-unqualified version of T. Otherwise, the type of the rvalue 1531 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1532 // just strip the qualifiers because they don't matter. 1533 FromType = FromType.getUnqualifiedType(); 1534 } else if (FromType->isArrayType()) { 1535 // Array-to-pointer conversion (C++ 4.2) 1536 SCS.First = ICK_Array_To_Pointer; 1537 1538 // An lvalue or rvalue of type "array of N T" or "array of unknown 1539 // bound of T" can be converted to an rvalue of type "pointer to 1540 // T" (C++ 4.2p1). 1541 FromType = S.Context.getArrayDecayedType(FromType); 1542 1543 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1544 // This conversion is deprecated in C++03 (D.4) 1545 SCS.DeprecatedStringLiteralToCharPtr = true; 1546 1547 // For the purpose of ranking in overload resolution 1548 // (13.3.3.1.1), this conversion is considered an 1549 // array-to-pointer conversion followed by a qualification 1550 // conversion (4.4). (C++ 4.2p2) 1551 SCS.Second = ICK_Identity; 1552 SCS.Third = ICK_Qualification; 1553 SCS.QualificationIncludesObjCLifetime = false; 1554 SCS.setAllToTypes(FromType); 1555 return true; 1556 } 1557 } else if (FromType->isFunctionType() && argIsLValue) { 1558 // Function-to-pointer conversion (C++ 4.3). 1559 SCS.First = ICK_Function_To_Pointer; 1560 1561 // An lvalue of function type T can be converted to an rvalue of 1562 // type "pointer to T." The result is a pointer to the 1563 // function. (C++ 4.3p1). 1564 FromType = S.Context.getPointerType(FromType); 1565 } else { 1566 // We don't require any conversions for the first step. 1567 SCS.First = ICK_Identity; 1568 } 1569 SCS.setToType(0, FromType); 1570 1571 // The second conversion can be an integral promotion, floating 1572 // point promotion, integral conversion, floating point conversion, 1573 // floating-integral conversion, pointer conversion, 1574 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1575 // For overloading in C, this can also be a "compatible-type" 1576 // conversion. 1577 bool IncompatibleObjC = false; 1578 ImplicitConversionKind SecondICK = ICK_Identity; 1579 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1580 // The unqualified versions of the types are the same: there's no 1581 // conversion to do. 1582 SCS.Second = ICK_Identity; 1583 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1584 // Integral promotion (C++ 4.5). 1585 SCS.Second = ICK_Integral_Promotion; 1586 FromType = ToType.getUnqualifiedType(); 1587 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1588 // Floating point promotion (C++ 4.6). 1589 SCS.Second = ICK_Floating_Promotion; 1590 FromType = ToType.getUnqualifiedType(); 1591 } else if (S.IsComplexPromotion(FromType, ToType)) { 1592 // Complex promotion (Clang extension) 1593 SCS.Second = ICK_Complex_Promotion; 1594 FromType = ToType.getUnqualifiedType(); 1595 } else if (ToType->isBooleanType() && 1596 (FromType->isArithmeticType() || 1597 FromType->isAnyPointerType() || 1598 FromType->isBlockPointerType() || 1599 FromType->isMemberPointerType() || 1600 FromType->isNullPtrType())) { 1601 // Boolean conversions (C++ 4.12). 1602 SCS.Second = ICK_Boolean_Conversion; 1603 FromType = S.Context.BoolTy; 1604 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1605 ToType->isIntegralType(S.Context)) { 1606 // Integral conversions (C++ 4.7). 1607 SCS.Second = ICK_Integral_Conversion; 1608 FromType = ToType.getUnqualifiedType(); 1609 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1610 // Complex conversions (C99 6.3.1.6) 1611 SCS.Second = ICK_Complex_Conversion; 1612 FromType = ToType.getUnqualifiedType(); 1613 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1614 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1615 // Complex-real conversions (C99 6.3.1.7) 1616 SCS.Second = ICK_Complex_Real; 1617 FromType = ToType.getUnqualifiedType(); 1618 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1619 // Floating point conversions (C++ 4.8). 1620 SCS.Second = ICK_Floating_Conversion; 1621 FromType = ToType.getUnqualifiedType(); 1622 } else if ((FromType->isRealFloatingType() && 1623 ToType->isIntegralType(S.Context)) || 1624 (FromType->isIntegralOrUnscopedEnumerationType() && 1625 ToType->isRealFloatingType())) { 1626 // Floating-integral conversions (C++ 4.9). 1627 SCS.Second = ICK_Floating_Integral; 1628 FromType = ToType.getUnqualifiedType(); 1629 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1630 SCS.Second = ICK_Block_Pointer_Conversion; 1631 } else if (AllowObjCWritebackConversion && 1632 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1633 SCS.Second = ICK_Writeback_Conversion; 1634 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1635 FromType, IncompatibleObjC)) { 1636 // Pointer conversions (C++ 4.10). 1637 SCS.Second = ICK_Pointer_Conversion; 1638 SCS.IncompatibleObjC = IncompatibleObjC; 1639 FromType = FromType.getUnqualifiedType(); 1640 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1641 InOverloadResolution, FromType)) { 1642 // Pointer to member conversions (4.11). 1643 SCS.Second = ICK_Pointer_Member; 1644 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1645 SCS.Second = SecondICK; 1646 FromType = ToType.getUnqualifiedType(); 1647 } else if (!S.getLangOpts().CPlusPlus && 1648 S.Context.typesAreCompatible(ToType, FromType)) { 1649 // Compatible conversions (Clang extension for C function overloading) 1650 SCS.Second = ICK_Compatible_Conversion; 1651 FromType = ToType.getUnqualifiedType(); 1652 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1653 // Treat a conversion that strips "noreturn" as an identity conversion. 1654 SCS.Second = ICK_NoReturn_Adjustment; 1655 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1656 InOverloadResolution, 1657 SCS, CStyle)) { 1658 SCS.Second = ICK_TransparentUnionConversion; 1659 FromType = ToType; 1660 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1661 CStyle)) { 1662 // tryAtomicConversion has updated the standard conversion sequence 1663 // appropriately. 1664 return true; 1665 } else if (ToType->isEventT() && 1666 From->isIntegerConstantExpr(S.getASTContext()) && 1667 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1668 SCS.Second = ICK_Zero_Event_Conversion; 1669 FromType = ToType; 1670 } else { 1671 // No second conversion required. 1672 SCS.Second = ICK_Identity; 1673 } 1674 SCS.setToType(1, FromType); 1675 1676 QualType CanonFrom; 1677 QualType CanonTo; 1678 // The third conversion can be a qualification conversion (C++ 4p1). 1679 bool ObjCLifetimeConversion; 1680 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1681 ObjCLifetimeConversion)) { 1682 SCS.Third = ICK_Qualification; 1683 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1684 FromType = ToType; 1685 CanonFrom = S.Context.getCanonicalType(FromType); 1686 CanonTo = S.Context.getCanonicalType(ToType); 1687 } else { 1688 // No conversion required 1689 SCS.Third = ICK_Identity; 1690 1691 // C++ [over.best.ics]p6: 1692 // [...] Any difference in top-level cv-qualification is 1693 // subsumed by the initialization itself and does not constitute 1694 // a conversion. [...] 1695 CanonFrom = S.Context.getCanonicalType(FromType); 1696 CanonTo = S.Context.getCanonicalType(ToType); 1697 if (CanonFrom.getLocalUnqualifiedType() 1698 == CanonTo.getLocalUnqualifiedType() && 1699 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1700 FromType = ToType; 1701 CanonFrom = CanonTo; 1702 } 1703 } 1704 SCS.setToType(2, FromType); 1705 1706 // If we have not converted the argument type to the parameter type, 1707 // this is a bad conversion sequence. 1708 if (CanonFrom != CanonTo) 1709 return false; 1710 1711 return true; 1712 } 1713 1714 static bool 1715 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1716 QualType &ToType, 1717 bool InOverloadResolution, 1718 StandardConversionSequence &SCS, 1719 bool CStyle) { 1720 1721 const RecordType *UT = ToType->getAsUnionType(); 1722 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1723 return false; 1724 // The field to initialize within the transparent union. 1725 RecordDecl *UD = UT->getDecl(); 1726 // It's compatible if the expression matches any of the fields. 1727 for (RecordDecl::field_iterator it = UD->field_begin(), 1728 itend = UD->field_end(); 1729 it != itend; ++it) { 1730 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1731 CStyle, /*ObjCWritebackConversion=*/false)) { 1732 ToType = it->getType(); 1733 return true; 1734 } 1735 } 1736 return false; 1737 } 1738 1739 /// IsIntegralPromotion - Determines whether the conversion from the 1740 /// expression From (whose potentially-adjusted type is FromType) to 1741 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1742 /// sets PromotedType to the promoted type. 1743 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1744 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1745 // All integers are built-in. 1746 if (!To) { 1747 return false; 1748 } 1749 1750 // An rvalue of type char, signed char, unsigned char, short int, or 1751 // unsigned short int can be converted to an rvalue of type int if 1752 // int can represent all the values of the source type; otherwise, 1753 // the source rvalue can be converted to an rvalue of type unsigned 1754 // int (C++ 4.5p1). 1755 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1756 !FromType->isEnumeralType()) { 1757 if (// We can promote any signed, promotable integer type to an int 1758 (FromType->isSignedIntegerType() || 1759 // We can promote any unsigned integer type whose size is 1760 // less than int to an int. 1761 (!FromType->isSignedIntegerType() && 1762 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1763 return To->getKind() == BuiltinType::Int; 1764 } 1765 1766 return To->getKind() == BuiltinType::UInt; 1767 } 1768 1769 // C++11 [conv.prom]p3: 1770 // A prvalue of an unscoped enumeration type whose underlying type is not 1771 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1772 // following types that can represent all the values of the enumeration 1773 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1774 // unsigned int, long int, unsigned long int, long long int, or unsigned 1775 // long long int. If none of the types in that list can represent all the 1776 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1777 // type can be converted to an rvalue a prvalue of the extended integer type 1778 // with lowest integer conversion rank (4.13) greater than the rank of long 1779 // long in which all the values of the enumeration can be represented. If 1780 // there are two such extended types, the signed one is chosen. 1781 // C++11 [conv.prom]p4: 1782 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1783 // can be converted to a prvalue of its underlying type. Moreover, if 1784 // integral promotion can be applied to its underlying type, a prvalue of an 1785 // unscoped enumeration type whose underlying type is fixed can also be 1786 // converted to a prvalue of the promoted underlying type. 1787 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1788 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1789 // provided for a scoped enumeration. 1790 if (FromEnumType->getDecl()->isScoped()) 1791 return false; 1792 1793 // We can perform an integral promotion to the underlying type of the enum, 1794 // even if that's not the promoted type. 1795 if (FromEnumType->getDecl()->isFixed()) { 1796 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1797 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1798 IsIntegralPromotion(From, Underlying, ToType); 1799 } 1800 1801 // We have already pre-calculated the promotion type, so this is trivial. 1802 if (ToType->isIntegerType() && 1803 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1804 return Context.hasSameUnqualifiedType(ToType, 1805 FromEnumType->getDecl()->getPromotionType()); 1806 } 1807 1808 // C++0x [conv.prom]p2: 1809 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1810 // to an rvalue a prvalue of the first of the following types that can 1811 // represent all the values of its underlying type: int, unsigned int, 1812 // long int, unsigned long int, long long int, or unsigned long long int. 1813 // If none of the types in that list can represent all the values of its 1814 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1815 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1816 // type. 1817 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1818 ToType->isIntegerType()) { 1819 // Determine whether the type we're converting from is signed or 1820 // unsigned. 1821 bool FromIsSigned = FromType->isSignedIntegerType(); 1822 uint64_t FromSize = Context.getTypeSize(FromType); 1823 1824 // The types we'll try to promote to, in the appropriate 1825 // order. Try each of these types. 1826 QualType PromoteTypes[6] = { 1827 Context.IntTy, Context.UnsignedIntTy, 1828 Context.LongTy, Context.UnsignedLongTy , 1829 Context.LongLongTy, Context.UnsignedLongLongTy 1830 }; 1831 for (int Idx = 0; Idx < 6; ++Idx) { 1832 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1833 if (FromSize < ToSize || 1834 (FromSize == ToSize && 1835 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1836 // We found the type that we can promote to. If this is the 1837 // type we wanted, we have a promotion. Otherwise, no 1838 // promotion. 1839 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1840 } 1841 } 1842 } 1843 1844 // An rvalue for an integral bit-field (9.6) can be converted to an 1845 // rvalue of type int if int can represent all the values of the 1846 // bit-field; otherwise, it can be converted to unsigned int if 1847 // unsigned int can represent all the values of the bit-field. If 1848 // the bit-field is larger yet, no integral promotion applies to 1849 // it. If the bit-field has an enumerated type, it is treated as any 1850 // other value of that type for promotion purposes (C++ 4.5p3). 1851 // FIXME: We should delay checking of bit-fields until we actually perform the 1852 // conversion. 1853 using llvm::APSInt; 1854 if (From) 1855 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1856 APSInt BitWidth; 1857 if (FromType->isIntegralType(Context) && 1858 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1859 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1860 ToSize = Context.getTypeSize(ToType); 1861 1862 // Are we promoting to an int from a bitfield that fits in an int? 1863 if (BitWidth < ToSize || 1864 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1865 return To->getKind() == BuiltinType::Int; 1866 } 1867 1868 // Are we promoting to an unsigned int from an unsigned bitfield 1869 // that fits into an unsigned int? 1870 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1871 return To->getKind() == BuiltinType::UInt; 1872 } 1873 1874 return false; 1875 } 1876 } 1877 1878 // An rvalue of type bool can be converted to an rvalue of type int, 1879 // with false becoming zero and true becoming one (C++ 4.5p4). 1880 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1881 return true; 1882 } 1883 1884 return false; 1885 } 1886 1887 /// IsFloatingPointPromotion - Determines whether the conversion from 1888 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1889 /// returns true and sets PromotedType to the promoted type. 1890 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1891 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1892 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1893 /// An rvalue of type float can be converted to an rvalue of type 1894 /// double. (C++ 4.6p1). 1895 if (FromBuiltin->getKind() == BuiltinType::Float && 1896 ToBuiltin->getKind() == BuiltinType::Double) 1897 return true; 1898 1899 // C99 6.3.1.5p1: 1900 // When a float is promoted to double or long double, or a 1901 // double is promoted to long double [...]. 1902 if (!getLangOpts().CPlusPlus && 1903 (FromBuiltin->getKind() == BuiltinType::Float || 1904 FromBuiltin->getKind() == BuiltinType::Double) && 1905 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1906 return true; 1907 1908 // Half can be promoted to float. 1909 if (!getLangOpts().NativeHalfType && 1910 FromBuiltin->getKind() == BuiltinType::Half && 1911 ToBuiltin->getKind() == BuiltinType::Float) 1912 return true; 1913 } 1914 1915 return false; 1916 } 1917 1918 /// \brief Determine if a conversion is a complex promotion. 1919 /// 1920 /// A complex promotion is defined as a complex -> complex conversion 1921 /// where the conversion between the underlying real types is a 1922 /// floating-point or integral promotion. 1923 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1924 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1925 if (!FromComplex) 1926 return false; 1927 1928 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1929 if (!ToComplex) 1930 return false; 1931 1932 return IsFloatingPointPromotion(FromComplex->getElementType(), 1933 ToComplex->getElementType()) || 1934 IsIntegralPromotion(0, FromComplex->getElementType(), 1935 ToComplex->getElementType()); 1936 } 1937 1938 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1939 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1940 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1941 /// if non-empty, will be a pointer to ToType that may or may not have 1942 /// the right set of qualifiers on its pointee. 1943 /// 1944 static QualType 1945 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1946 QualType ToPointee, QualType ToType, 1947 ASTContext &Context, 1948 bool StripObjCLifetime = false) { 1949 assert((FromPtr->getTypeClass() == Type::Pointer || 1950 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1951 "Invalid similarly-qualified pointer type"); 1952 1953 /// Conversions to 'id' subsume cv-qualifier conversions. 1954 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1955 return ToType.getUnqualifiedType(); 1956 1957 QualType CanonFromPointee 1958 = Context.getCanonicalType(FromPtr->getPointeeType()); 1959 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1960 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1961 1962 if (StripObjCLifetime) 1963 Quals.removeObjCLifetime(); 1964 1965 // Exact qualifier match -> return the pointer type we're converting to. 1966 if (CanonToPointee.getLocalQualifiers() == Quals) { 1967 // ToType is exactly what we need. Return it. 1968 if (!ToType.isNull()) 1969 return ToType.getUnqualifiedType(); 1970 1971 // Build a pointer to ToPointee. It has the right qualifiers 1972 // already. 1973 if (isa<ObjCObjectPointerType>(ToType)) 1974 return Context.getObjCObjectPointerType(ToPointee); 1975 return Context.getPointerType(ToPointee); 1976 } 1977 1978 // Just build a canonical type that has the right qualifiers. 1979 QualType QualifiedCanonToPointee 1980 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1981 1982 if (isa<ObjCObjectPointerType>(ToType)) 1983 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1984 return Context.getPointerType(QualifiedCanonToPointee); 1985 } 1986 1987 static bool isNullPointerConstantForConversion(Expr *Expr, 1988 bool InOverloadResolution, 1989 ASTContext &Context) { 1990 // Handle value-dependent integral null pointer constants correctly. 1991 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1992 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1993 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1994 return !InOverloadResolution; 1995 1996 return Expr->isNullPointerConstant(Context, 1997 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1998 : Expr::NPC_ValueDependentIsNull); 1999 } 2000 2001 /// IsPointerConversion - Determines whether the conversion of the 2002 /// expression From, which has the (possibly adjusted) type FromType, 2003 /// can be converted to the type ToType via a pointer conversion (C++ 2004 /// 4.10). If so, returns true and places the converted type (that 2005 /// might differ from ToType in its cv-qualifiers at some level) into 2006 /// ConvertedType. 2007 /// 2008 /// This routine also supports conversions to and from block pointers 2009 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2010 /// pointers to interfaces. FIXME: Once we've determined the 2011 /// appropriate overloading rules for Objective-C, we may want to 2012 /// split the Objective-C checks into a different routine; however, 2013 /// GCC seems to consider all of these conversions to be pointer 2014 /// conversions, so for now they live here. IncompatibleObjC will be 2015 /// set if the conversion is an allowed Objective-C conversion that 2016 /// should result in a warning. 2017 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2018 bool InOverloadResolution, 2019 QualType& ConvertedType, 2020 bool &IncompatibleObjC) { 2021 IncompatibleObjC = false; 2022 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2023 IncompatibleObjC)) 2024 return true; 2025 2026 // Conversion from a null pointer constant to any Objective-C pointer type. 2027 if (ToType->isObjCObjectPointerType() && 2028 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2029 ConvertedType = ToType; 2030 return true; 2031 } 2032 2033 // Blocks: Block pointers can be converted to void*. 2034 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2035 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2036 ConvertedType = ToType; 2037 return true; 2038 } 2039 // Blocks: A null pointer constant can be converted to a block 2040 // pointer type. 2041 if (ToType->isBlockPointerType() && 2042 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2043 ConvertedType = ToType; 2044 return true; 2045 } 2046 2047 // If the left-hand-side is nullptr_t, the right side can be a null 2048 // pointer constant. 2049 if (ToType->isNullPtrType() && 2050 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2051 ConvertedType = ToType; 2052 return true; 2053 } 2054 2055 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2056 if (!ToTypePtr) 2057 return false; 2058 2059 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2060 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2061 ConvertedType = ToType; 2062 return true; 2063 } 2064 2065 // Beyond this point, both types need to be pointers 2066 // , including objective-c pointers. 2067 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2068 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2069 !getLangOpts().ObjCAutoRefCount) { 2070 ConvertedType = BuildSimilarlyQualifiedPointerType( 2071 FromType->getAs<ObjCObjectPointerType>(), 2072 ToPointeeType, 2073 ToType, Context); 2074 return true; 2075 } 2076 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2077 if (!FromTypePtr) 2078 return false; 2079 2080 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2081 2082 // If the unqualified pointee types are the same, this can't be a 2083 // pointer conversion, so don't do all of the work below. 2084 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2085 return false; 2086 2087 // An rvalue of type "pointer to cv T," where T is an object type, 2088 // can be converted to an rvalue of type "pointer to cv void" (C++ 2089 // 4.10p2). 2090 if (FromPointeeType->isIncompleteOrObjectType() && 2091 ToPointeeType->isVoidType()) { 2092 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2093 ToPointeeType, 2094 ToType, Context, 2095 /*StripObjCLifetime=*/true); 2096 return true; 2097 } 2098 2099 // MSVC allows implicit function to void* type conversion. 2100 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2101 ToPointeeType->isVoidType()) { 2102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2103 ToPointeeType, 2104 ToType, Context); 2105 return true; 2106 } 2107 2108 // When we're overloading in C, we allow a special kind of pointer 2109 // conversion for compatible-but-not-identical pointee types. 2110 if (!getLangOpts().CPlusPlus && 2111 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2113 ToPointeeType, 2114 ToType, Context); 2115 return true; 2116 } 2117 2118 // C++ [conv.ptr]p3: 2119 // 2120 // An rvalue of type "pointer to cv D," where D is a class type, 2121 // can be converted to an rvalue of type "pointer to cv B," where 2122 // B is a base class (clause 10) of D. If B is an inaccessible 2123 // (clause 11) or ambiguous (10.2) base class of D, a program that 2124 // necessitates this conversion is ill-formed. The result of the 2125 // conversion is a pointer to the base class sub-object of the 2126 // derived class object. The null pointer value is converted to 2127 // the null pointer value of the destination type. 2128 // 2129 // Note that we do not check for ambiguity or inaccessibility 2130 // here. That is handled by CheckPointerConversion. 2131 if (getLangOpts().CPlusPlus && 2132 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2133 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2134 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2135 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2137 ToPointeeType, 2138 ToType, Context); 2139 return true; 2140 } 2141 2142 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2143 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2144 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2145 ToPointeeType, 2146 ToType, Context); 2147 return true; 2148 } 2149 2150 return false; 2151 } 2152 2153 /// \brief Adopt the given qualifiers for the given type. 2154 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2155 Qualifiers TQs = T.getQualifiers(); 2156 2157 // Check whether qualifiers already match. 2158 if (TQs == Qs) 2159 return T; 2160 2161 if (Qs.compatiblyIncludes(TQs)) 2162 return Context.getQualifiedType(T, Qs); 2163 2164 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2165 } 2166 2167 /// isObjCPointerConversion - Determines whether this is an 2168 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2169 /// with the same arguments and return values. 2170 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2171 QualType& ConvertedType, 2172 bool &IncompatibleObjC) { 2173 if (!getLangOpts().ObjC1) 2174 return false; 2175 2176 // The set of qualifiers on the type we're converting from. 2177 Qualifiers FromQualifiers = FromType.getQualifiers(); 2178 2179 // First, we handle all conversions on ObjC object pointer types. 2180 const ObjCObjectPointerType* ToObjCPtr = 2181 ToType->getAs<ObjCObjectPointerType>(); 2182 const ObjCObjectPointerType *FromObjCPtr = 2183 FromType->getAs<ObjCObjectPointerType>(); 2184 2185 if (ToObjCPtr && FromObjCPtr) { 2186 // If the pointee types are the same (ignoring qualifications), 2187 // then this is not a pointer conversion. 2188 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2189 FromObjCPtr->getPointeeType())) 2190 return false; 2191 2192 // Check for compatible 2193 // Objective C++: We're able to convert between "id" or "Class" and a 2194 // pointer to any interface (in both directions). 2195 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2197 return true; 2198 } 2199 // Conversions with Objective-C's id<...>. 2200 if ((FromObjCPtr->isObjCQualifiedIdType() || 2201 ToObjCPtr->isObjCQualifiedIdType()) && 2202 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2203 /*compare=*/false)) { 2204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2205 return true; 2206 } 2207 // Objective C++: We're able to convert from a pointer to an 2208 // interface to a pointer to a different interface. 2209 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2210 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2211 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2212 if (getLangOpts().CPlusPlus && LHS && RHS && 2213 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2214 FromObjCPtr->getPointeeType())) 2215 return false; 2216 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2217 ToObjCPtr->getPointeeType(), 2218 ToType, Context); 2219 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2220 return true; 2221 } 2222 2223 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2224 // Okay: this is some kind of implicit downcast of Objective-C 2225 // interfaces, which is permitted. However, we're going to 2226 // complain about it. 2227 IncompatibleObjC = true; 2228 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2229 ToObjCPtr->getPointeeType(), 2230 ToType, Context); 2231 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2232 return true; 2233 } 2234 } 2235 // Beyond this point, both types need to be C pointers or block pointers. 2236 QualType ToPointeeType; 2237 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2238 ToPointeeType = ToCPtr->getPointeeType(); 2239 else if (const BlockPointerType *ToBlockPtr = 2240 ToType->getAs<BlockPointerType>()) { 2241 // Objective C++: We're able to convert from a pointer to any object 2242 // to a block pointer type. 2243 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2245 return true; 2246 } 2247 ToPointeeType = ToBlockPtr->getPointeeType(); 2248 } 2249 else if (FromType->getAs<BlockPointerType>() && 2250 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2251 // Objective C++: We're able to convert from a block pointer type to a 2252 // pointer to any object. 2253 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2254 return true; 2255 } 2256 else 2257 return false; 2258 2259 QualType FromPointeeType; 2260 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2261 FromPointeeType = FromCPtr->getPointeeType(); 2262 else if (const BlockPointerType *FromBlockPtr = 2263 FromType->getAs<BlockPointerType>()) 2264 FromPointeeType = FromBlockPtr->getPointeeType(); 2265 else 2266 return false; 2267 2268 // If we have pointers to pointers, recursively check whether this 2269 // is an Objective-C conversion. 2270 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2271 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2272 IncompatibleObjC)) { 2273 // We always complain about this conversion. 2274 IncompatibleObjC = true; 2275 ConvertedType = Context.getPointerType(ConvertedType); 2276 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2277 return true; 2278 } 2279 // Allow conversion of pointee being objective-c pointer to another one; 2280 // as in I* to id. 2281 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2282 ToPointeeType->getAs<ObjCObjectPointerType>() && 2283 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2284 IncompatibleObjC)) { 2285 2286 ConvertedType = Context.getPointerType(ConvertedType); 2287 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2288 return true; 2289 } 2290 2291 // If we have pointers to functions or blocks, check whether the only 2292 // differences in the argument and result types are in Objective-C 2293 // pointer conversions. If so, we permit the conversion (but 2294 // complain about it). 2295 const FunctionProtoType *FromFunctionType 2296 = FromPointeeType->getAs<FunctionProtoType>(); 2297 const FunctionProtoType *ToFunctionType 2298 = ToPointeeType->getAs<FunctionProtoType>(); 2299 if (FromFunctionType && ToFunctionType) { 2300 // If the function types are exactly the same, this isn't an 2301 // Objective-C pointer conversion. 2302 if (Context.getCanonicalType(FromPointeeType) 2303 == Context.getCanonicalType(ToPointeeType)) 2304 return false; 2305 2306 // Perform the quick checks that will tell us whether these 2307 // function types are obviously different. 2308 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2309 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2310 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2311 return false; 2312 2313 bool HasObjCConversion = false; 2314 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2315 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2316 // Okay, the types match exactly. Nothing to do. 2317 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2318 ToFunctionType->getResultType(), 2319 ConvertedType, IncompatibleObjC)) { 2320 // Okay, we have an Objective-C pointer conversion. 2321 HasObjCConversion = true; 2322 } else { 2323 // Function types are too different. Abort. 2324 return false; 2325 } 2326 2327 // Check argument types. 2328 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2329 ArgIdx != NumArgs; ++ArgIdx) { 2330 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2331 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2332 if (Context.getCanonicalType(FromArgType) 2333 == Context.getCanonicalType(ToArgType)) { 2334 // Okay, the types match exactly. Nothing to do. 2335 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2336 ConvertedType, IncompatibleObjC)) { 2337 // Okay, we have an Objective-C pointer conversion. 2338 HasObjCConversion = true; 2339 } else { 2340 // Argument types are too different. Abort. 2341 return false; 2342 } 2343 } 2344 2345 if (HasObjCConversion) { 2346 // We had an Objective-C conversion. Allow this pointer 2347 // conversion, but complain about it. 2348 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2349 IncompatibleObjC = true; 2350 return true; 2351 } 2352 } 2353 2354 return false; 2355 } 2356 2357 /// \brief Determine whether this is an Objective-C writeback conversion, 2358 /// used for parameter passing when performing automatic reference counting. 2359 /// 2360 /// \param FromType The type we're converting form. 2361 /// 2362 /// \param ToType The type we're converting to. 2363 /// 2364 /// \param ConvertedType The type that will be produced after applying 2365 /// this conversion. 2366 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2367 QualType &ConvertedType) { 2368 if (!getLangOpts().ObjCAutoRefCount || 2369 Context.hasSameUnqualifiedType(FromType, ToType)) 2370 return false; 2371 2372 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2373 QualType ToPointee; 2374 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2375 ToPointee = ToPointer->getPointeeType(); 2376 else 2377 return false; 2378 2379 Qualifiers ToQuals = ToPointee.getQualifiers(); 2380 if (!ToPointee->isObjCLifetimeType() || 2381 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2382 !ToQuals.withoutObjCLifetime().empty()) 2383 return false; 2384 2385 // Argument must be a pointer to __strong to __weak. 2386 QualType FromPointee; 2387 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2388 FromPointee = FromPointer->getPointeeType(); 2389 else 2390 return false; 2391 2392 Qualifiers FromQuals = FromPointee.getQualifiers(); 2393 if (!FromPointee->isObjCLifetimeType() || 2394 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2395 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2396 return false; 2397 2398 // Make sure that we have compatible qualifiers. 2399 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2400 if (!ToQuals.compatiblyIncludes(FromQuals)) 2401 return false; 2402 2403 // Remove qualifiers from the pointee type we're converting from; they 2404 // aren't used in the compatibility check belong, and we'll be adding back 2405 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2406 FromPointee = FromPointee.getUnqualifiedType(); 2407 2408 // The unqualified form of the pointee types must be compatible. 2409 ToPointee = ToPointee.getUnqualifiedType(); 2410 bool IncompatibleObjC; 2411 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2412 FromPointee = ToPointee; 2413 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2414 IncompatibleObjC)) 2415 return false; 2416 2417 /// \brief Construct the type we're converting to, which is a pointer to 2418 /// __autoreleasing pointee. 2419 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2420 ConvertedType = Context.getPointerType(FromPointee); 2421 return true; 2422 } 2423 2424 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2425 QualType& ConvertedType) { 2426 QualType ToPointeeType; 2427 if (const BlockPointerType *ToBlockPtr = 2428 ToType->getAs<BlockPointerType>()) 2429 ToPointeeType = ToBlockPtr->getPointeeType(); 2430 else 2431 return false; 2432 2433 QualType FromPointeeType; 2434 if (const BlockPointerType *FromBlockPtr = 2435 FromType->getAs<BlockPointerType>()) 2436 FromPointeeType = FromBlockPtr->getPointeeType(); 2437 else 2438 return false; 2439 // We have pointer to blocks, check whether the only 2440 // differences in the argument and result types are in Objective-C 2441 // pointer conversions. If so, we permit the conversion. 2442 2443 const FunctionProtoType *FromFunctionType 2444 = FromPointeeType->getAs<FunctionProtoType>(); 2445 const FunctionProtoType *ToFunctionType 2446 = ToPointeeType->getAs<FunctionProtoType>(); 2447 2448 if (!FromFunctionType || !ToFunctionType) 2449 return false; 2450 2451 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2452 return true; 2453 2454 // Perform the quick checks that will tell us whether these 2455 // function types are obviously different. 2456 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2457 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2458 return false; 2459 2460 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2461 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2462 if (FromEInfo != ToEInfo) 2463 return false; 2464 2465 bool IncompatibleObjC = false; 2466 if (Context.hasSameType(FromFunctionType->getResultType(), 2467 ToFunctionType->getResultType())) { 2468 // Okay, the types match exactly. Nothing to do. 2469 } else { 2470 QualType RHS = FromFunctionType->getResultType(); 2471 QualType LHS = ToFunctionType->getResultType(); 2472 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2473 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2474 LHS = LHS.getUnqualifiedType(); 2475 2476 if (Context.hasSameType(RHS,LHS)) { 2477 // OK exact match. 2478 } else if (isObjCPointerConversion(RHS, LHS, 2479 ConvertedType, IncompatibleObjC)) { 2480 if (IncompatibleObjC) 2481 return false; 2482 // Okay, we have an Objective-C pointer conversion. 2483 } 2484 else 2485 return false; 2486 } 2487 2488 // Check argument types. 2489 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2490 ArgIdx != NumArgs; ++ArgIdx) { 2491 IncompatibleObjC = false; 2492 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2493 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2494 if (Context.hasSameType(FromArgType, ToArgType)) { 2495 // Okay, the types match exactly. Nothing to do. 2496 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2497 ConvertedType, IncompatibleObjC)) { 2498 if (IncompatibleObjC) 2499 return false; 2500 // Okay, we have an Objective-C pointer conversion. 2501 } else 2502 // Argument types are too different. Abort. 2503 return false; 2504 } 2505 if (LangOpts.ObjCAutoRefCount && 2506 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2507 ToFunctionType)) 2508 return false; 2509 2510 ConvertedType = ToType; 2511 return true; 2512 } 2513 2514 enum { 2515 ft_default, 2516 ft_different_class, 2517 ft_parameter_arity, 2518 ft_parameter_mismatch, 2519 ft_return_type, 2520 ft_qualifer_mismatch 2521 }; 2522 2523 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2524 /// function types. Catches different number of parameter, mismatch in 2525 /// parameter types, and different return types. 2526 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2527 QualType FromType, QualType ToType) { 2528 // If either type is not valid, include no extra info. 2529 if (FromType.isNull() || ToType.isNull()) { 2530 PDiag << ft_default; 2531 return; 2532 } 2533 2534 // Get the function type from the pointers. 2535 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2536 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2537 *ToMember = ToType->getAs<MemberPointerType>(); 2538 if (FromMember->getClass() != ToMember->getClass()) { 2539 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2540 << QualType(FromMember->getClass(), 0); 2541 return; 2542 } 2543 FromType = FromMember->getPointeeType(); 2544 ToType = ToMember->getPointeeType(); 2545 } 2546 2547 if (FromType->isPointerType()) 2548 FromType = FromType->getPointeeType(); 2549 if (ToType->isPointerType()) 2550 ToType = ToType->getPointeeType(); 2551 2552 // Remove references. 2553 FromType = FromType.getNonReferenceType(); 2554 ToType = ToType.getNonReferenceType(); 2555 2556 // Don't print extra info for non-specialized template functions. 2557 if (FromType->isInstantiationDependentType() && 2558 !FromType->getAs<TemplateSpecializationType>()) { 2559 PDiag << ft_default; 2560 return; 2561 } 2562 2563 // No extra info for same types. 2564 if (Context.hasSameType(FromType, ToType)) { 2565 PDiag << ft_default; 2566 return; 2567 } 2568 2569 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2570 *ToFunction = ToType->getAs<FunctionProtoType>(); 2571 2572 // Both types need to be function types. 2573 if (!FromFunction || !ToFunction) { 2574 PDiag << ft_default; 2575 return; 2576 } 2577 2578 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2579 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2580 << FromFunction->getNumArgs(); 2581 return; 2582 } 2583 2584 // Handle different parameter types. 2585 unsigned ArgPos; 2586 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2587 PDiag << ft_parameter_mismatch << ArgPos + 1 2588 << ToFunction->getArgType(ArgPos) 2589 << FromFunction->getArgType(ArgPos); 2590 return; 2591 } 2592 2593 // Handle different return type. 2594 if (!Context.hasSameType(FromFunction->getResultType(), 2595 ToFunction->getResultType())) { 2596 PDiag << ft_return_type << ToFunction->getResultType() 2597 << FromFunction->getResultType(); 2598 return; 2599 } 2600 2601 unsigned FromQuals = FromFunction->getTypeQuals(), 2602 ToQuals = ToFunction->getTypeQuals(); 2603 if (FromQuals != ToQuals) { 2604 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2605 return; 2606 } 2607 2608 // Unable to find a difference, so add no extra info. 2609 PDiag << ft_default; 2610 } 2611 2612 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2613 /// for equality of their argument types. Caller has already checked that 2614 /// they have same number of arguments. If the parameters are different, 2615 /// ArgPos will have the parameter index of the first different parameter. 2616 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2617 const FunctionProtoType *NewType, 2618 unsigned *ArgPos) { 2619 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2620 N = NewType->arg_type_begin(), 2621 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2622 if (!Context.hasSameType(O->getUnqualifiedType(), 2623 N->getUnqualifiedType())) { 2624 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2625 return false; 2626 } 2627 } 2628 return true; 2629 } 2630 2631 /// CheckPointerConversion - Check the pointer conversion from the 2632 /// expression From to the type ToType. This routine checks for 2633 /// ambiguous or inaccessible derived-to-base pointer 2634 /// conversions for which IsPointerConversion has already returned 2635 /// true. It returns true and produces a diagnostic if there was an 2636 /// error, or returns false otherwise. 2637 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2638 CastKind &Kind, 2639 CXXCastPath& BasePath, 2640 bool IgnoreBaseAccess) { 2641 QualType FromType = From->getType(); 2642 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2643 2644 Kind = CK_BitCast; 2645 2646 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2647 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2648 Expr::NPCK_ZeroExpression) { 2649 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2650 DiagRuntimeBehavior(From->getExprLoc(), From, 2651 PDiag(diag::warn_impcast_bool_to_null_pointer) 2652 << ToType << From->getSourceRange()); 2653 else if (!isUnevaluatedContext()) 2654 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2655 << ToType << From->getSourceRange(); 2656 } 2657 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2658 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2659 QualType FromPointeeType = FromPtrType->getPointeeType(), 2660 ToPointeeType = ToPtrType->getPointeeType(); 2661 2662 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2663 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2664 // We must have a derived-to-base conversion. Check an 2665 // ambiguous or inaccessible conversion. 2666 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2667 From->getExprLoc(), 2668 From->getSourceRange(), &BasePath, 2669 IgnoreBaseAccess)) 2670 return true; 2671 2672 // The conversion was successful. 2673 Kind = CK_DerivedToBase; 2674 } 2675 } 2676 } else if (const ObjCObjectPointerType *ToPtrType = 2677 ToType->getAs<ObjCObjectPointerType>()) { 2678 if (const ObjCObjectPointerType *FromPtrType = 2679 FromType->getAs<ObjCObjectPointerType>()) { 2680 // Objective-C++ conversions are always okay. 2681 // FIXME: We should have a different class of conversions for the 2682 // Objective-C++ implicit conversions. 2683 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2684 return false; 2685 } else if (FromType->isBlockPointerType()) { 2686 Kind = CK_BlockPointerToObjCPointerCast; 2687 } else { 2688 Kind = CK_CPointerToObjCPointerCast; 2689 } 2690 } else if (ToType->isBlockPointerType()) { 2691 if (!FromType->isBlockPointerType()) 2692 Kind = CK_AnyPointerToBlockPointerCast; 2693 } 2694 2695 // We shouldn't fall into this case unless it's valid for other 2696 // reasons. 2697 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2698 Kind = CK_NullToPointer; 2699 2700 return false; 2701 } 2702 2703 /// IsMemberPointerConversion - Determines whether the conversion of the 2704 /// expression From, which has the (possibly adjusted) type FromType, can be 2705 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2706 /// If so, returns true and places the converted type (that might differ from 2707 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2708 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2709 QualType ToType, 2710 bool InOverloadResolution, 2711 QualType &ConvertedType) { 2712 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2713 if (!ToTypePtr) 2714 return false; 2715 2716 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2717 if (From->isNullPointerConstant(Context, 2718 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2719 : Expr::NPC_ValueDependentIsNull)) { 2720 ConvertedType = ToType; 2721 return true; 2722 } 2723 2724 // Otherwise, both types have to be member pointers. 2725 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2726 if (!FromTypePtr) 2727 return false; 2728 2729 // A pointer to member of B can be converted to a pointer to member of D, 2730 // where D is derived from B (C++ 4.11p2). 2731 QualType FromClass(FromTypePtr->getClass(), 0); 2732 QualType ToClass(ToTypePtr->getClass(), 0); 2733 2734 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2735 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2736 IsDerivedFrom(ToClass, FromClass)) { 2737 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2738 ToClass.getTypePtr()); 2739 return true; 2740 } 2741 2742 return false; 2743 } 2744 2745 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2746 /// expression From to the type ToType. This routine checks for ambiguous or 2747 /// virtual or inaccessible base-to-derived member pointer conversions 2748 /// for which IsMemberPointerConversion has already returned true. It returns 2749 /// true and produces a diagnostic if there was an error, or returns false 2750 /// otherwise. 2751 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2752 CastKind &Kind, 2753 CXXCastPath &BasePath, 2754 bool IgnoreBaseAccess) { 2755 QualType FromType = From->getType(); 2756 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2757 if (!FromPtrType) { 2758 // This must be a null pointer to member pointer conversion 2759 assert(From->isNullPointerConstant(Context, 2760 Expr::NPC_ValueDependentIsNull) && 2761 "Expr must be null pointer constant!"); 2762 Kind = CK_NullToMemberPointer; 2763 return false; 2764 } 2765 2766 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2767 assert(ToPtrType && "No member pointer cast has a target type " 2768 "that is not a member pointer."); 2769 2770 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2771 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2772 2773 // FIXME: What about dependent types? 2774 assert(FromClass->isRecordType() && "Pointer into non-class."); 2775 assert(ToClass->isRecordType() && "Pointer into non-class."); 2776 2777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2778 /*DetectVirtual=*/true); 2779 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2780 assert(DerivationOkay && 2781 "Should not have been called if derivation isn't OK."); 2782 (void)DerivationOkay; 2783 2784 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2785 getUnqualifiedType())) { 2786 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2787 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2788 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2789 return true; 2790 } 2791 2792 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2793 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2794 << FromClass << ToClass << QualType(VBase, 0) 2795 << From->getSourceRange(); 2796 return true; 2797 } 2798 2799 if (!IgnoreBaseAccess) 2800 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2801 Paths.front(), 2802 diag::err_downcast_from_inaccessible_base); 2803 2804 // Must be a base to derived member conversion. 2805 BuildBasePathArray(Paths, BasePath); 2806 Kind = CK_BaseToDerivedMemberPointer; 2807 return false; 2808 } 2809 2810 /// Determine whether the lifetime conversion between the two given 2811 /// qualifiers sets is nontrivial. 2812 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2813 Qualifiers ToQuals) { 2814 // Converting anything to const __unsafe_unretained is trivial. 2815 if (ToQuals.hasConst() && 2816 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2817 return false; 2818 2819 return true; 2820 } 2821 2822 /// IsQualificationConversion - Determines whether the conversion from 2823 /// an rvalue of type FromType to ToType is a qualification conversion 2824 /// (C++ 4.4). 2825 /// 2826 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2827 /// when the qualification conversion involves a change in the Objective-C 2828 /// object lifetime. 2829 bool 2830 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2831 bool CStyle, bool &ObjCLifetimeConversion) { 2832 FromType = Context.getCanonicalType(FromType); 2833 ToType = Context.getCanonicalType(ToType); 2834 ObjCLifetimeConversion = false; 2835 2836 // If FromType and ToType are the same type, this is not a 2837 // qualification conversion. 2838 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2839 return false; 2840 2841 // (C++ 4.4p4): 2842 // A conversion can add cv-qualifiers at levels other than the first 2843 // in multi-level pointers, subject to the following rules: [...] 2844 bool PreviousToQualsIncludeConst = true; 2845 bool UnwrappedAnyPointer = false; 2846 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2847 // Within each iteration of the loop, we check the qualifiers to 2848 // determine if this still looks like a qualification 2849 // conversion. Then, if all is well, we unwrap one more level of 2850 // pointers or pointers-to-members and do it all again 2851 // until there are no more pointers or pointers-to-members left to 2852 // unwrap. 2853 UnwrappedAnyPointer = true; 2854 2855 Qualifiers FromQuals = FromType.getQualifiers(); 2856 Qualifiers ToQuals = ToType.getQualifiers(); 2857 2858 // Objective-C ARC: 2859 // Check Objective-C lifetime conversions. 2860 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2861 UnwrappedAnyPointer) { 2862 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2863 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2864 ObjCLifetimeConversion = true; 2865 FromQuals.removeObjCLifetime(); 2866 ToQuals.removeObjCLifetime(); 2867 } else { 2868 // Qualification conversions cannot cast between different 2869 // Objective-C lifetime qualifiers. 2870 return false; 2871 } 2872 } 2873 2874 // Allow addition/removal of GC attributes but not changing GC attributes. 2875 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2876 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2877 FromQuals.removeObjCGCAttr(); 2878 ToQuals.removeObjCGCAttr(); 2879 } 2880 2881 // -- for every j > 0, if const is in cv 1,j then const is in cv 2882 // 2,j, and similarly for volatile. 2883 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2884 return false; 2885 2886 // -- if the cv 1,j and cv 2,j are different, then const is in 2887 // every cv for 0 < k < j. 2888 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2889 && !PreviousToQualsIncludeConst) 2890 return false; 2891 2892 // Keep track of whether all prior cv-qualifiers in the "to" type 2893 // include const. 2894 PreviousToQualsIncludeConst 2895 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2896 } 2897 2898 // We are left with FromType and ToType being the pointee types 2899 // after unwrapping the original FromType and ToType the same number 2900 // of types. If we unwrapped any pointers, and if FromType and 2901 // ToType have the same unqualified type (since we checked 2902 // qualifiers above), then this is a qualification conversion. 2903 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2904 } 2905 2906 /// \brief - Determine whether this is a conversion from a scalar type to an 2907 /// atomic type. 2908 /// 2909 /// If successful, updates \c SCS's second and third steps in the conversion 2910 /// sequence to finish the conversion. 2911 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2912 bool InOverloadResolution, 2913 StandardConversionSequence &SCS, 2914 bool CStyle) { 2915 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2916 if (!ToAtomic) 2917 return false; 2918 2919 StandardConversionSequence InnerSCS; 2920 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2921 InOverloadResolution, InnerSCS, 2922 CStyle, /*AllowObjCWritebackConversion=*/false)) 2923 return false; 2924 2925 SCS.Second = InnerSCS.Second; 2926 SCS.setToType(1, InnerSCS.getToType(1)); 2927 SCS.Third = InnerSCS.Third; 2928 SCS.QualificationIncludesObjCLifetime 2929 = InnerSCS.QualificationIncludesObjCLifetime; 2930 SCS.setToType(2, InnerSCS.getToType(2)); 2931 return true; 2932 } 2933 2934 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2935 CXXConstructorDecl *Constructor, 2936 QualType Type) { 2937 const FunctionProtoType *CtorType = 2938 Constructor->getType()->getAs<FunctionProtoType>(); 2939 if (CtorType->getNumArgs() > 0) { 2940 QualType FirstArg = CtorType->getArgType(0); 2941 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2942 return true; 2943 } 2944 return false; 2945 } 2946 2947 static OverloadingResult 2948 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2949 CXXRecordDecl *To, 2950 UserDefinedConversionSequence &User, 2951 OverloadCandidateSet &CandidateSet, 2952 bool AllowExplicit) { 2953 DeclContext::lookup_result R = S.LookupConstructors(To); 2954 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2955 Con != ConEnd; ++Con) { 2956 NamedDecl *D = *Con; 2957 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2958 2959 // Find the constructor (which may be a template). 2960 CXXConstructorDecl *Constructor = 0; 2961 FunctionTemplateDecl *ConstructorTmpl 2962 = dyn_cast<FunctionTemplateDecl>(D); 2963 if (ConstructorTmpl) 2964 Constructor 2965 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2966 else 2967 Constructor = cast<CXXConstructorDecl>(D); 2968 2969 bool Usable = !Constructor->isInvalidDecl() && 2970 S.isInitListConstructor(Constructor) && 2971 (AllowExplicit || !Constructor->isExplicit()); 2972 if (Usable) { 2973 // If the first argument is (a reference to) the target type, 2974 // suppress conversions. 2975 bool SuppressUserConversions = 2976 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2977 if (ConstructorTmpl) 2978 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2979 /*ExplicitArgs*/ 0, 2980 From, CandidateSet, 2981 SuppressUserConversions); 2982 else 2983 S.AddOverloadCandidate(Constructor, FoundDecl, 2984 From, CandidateSet, 2985 SuppressUserConversions); 2986 } 2987 } 2988 2989 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2990 2991 OverloadCandidateSet::iterator Best; 2992 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2993 case OR_Success: { 2994 // Record the standard conversion we used and the conversion function. 2995 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2996 QualType ThisType = Constructor->getThisType(S.Context); 2997 // Initializer lists don't have conversions as such. 2998 User.Before.setAsIdentityConversion(); 2999 User.HadMultipleCandidates = HadMultipleCandidates; 3000 User.ConversionFunction = Constructor; 3001 User.FoundConversionFunction = Best->FoundDecl; 3002 User.After.setAsIdentityConversion(); 3003 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3004 User.After.setAllToTypes(ToType); 3005 return OR_Success; 3006 } 3007 3008 case OR_No_Viable_Function: 3009 return OR_No_Viable_Function; 3010 case OR_Deleted: 3011 return OR_Deleted; 3012 case OR_Ambiguous: 3013 return OR_Ambiguous; 3014 } 3015 3016 llvm_unreachable("Invalid OverloadResult!"); 3017 } 3018 3019 /// Determines whether there is a user-defined conversion sequence 3020 /// (C++ [over.ics.user]) that converts expression From to the type 3021 /// ToType. If such a conversion exists, User will contain the 3022 /// user-defined conversion sequence that performs such a conversion 3023 /// and this routine will return true. Otherwise, this routine returns 3024 /// false and User is unspecified. 3025 /// 3026 /// \param AllowExplicit true if the conversion should consider C++0x 3027 /// "explicit" conversion functions as well as non-explicit conversion 3028 /// functions (C++0x [class.conv.fct]p2). 3029 /// 3030 /// \param AllowObjCConversionOnExplicit true if the conversion should 3031 /// allow an extra Objective-C pointer conversion on uses of explicit 3032 /// constructors. Requires \c AllowExplicit to also be set. 3033 static OverloadingResult 3034 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3035 UserDefinedConversionSequence &User, 3036 OverloadCandidateSet &CandidateSet, 3037 bool AllowExplicit, 3038 bool AllowObjCConversionOnExplicit) { 3039 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3040 3041 // Whether we will only visit constructors. 3042 bool ConstructorsOnly = false; 3043 3044 // If the type we are conversion to is a class type, enumerate its 3045 // constructors. 3046 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3047 // C++ [over.match.ctor]p1: 3048 // When objects of class type are direct-initialized (8.5), or 3049 // copy-initialized from an expression of the same or a 3050 // derived class type (8.5), overload resolution selects the 3051 // constructor. [...] For copy-initialization, the candidate 3052 // functions are all the converting constructors (12.3.1) of 3053 // that class. The argument list is the expression-list within 3054 // the parentheses of the initializer. 3055 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3056 (From->getType()->getAs<RecordType>() && 3057 S.IsDerivedFrom(From->getType(), ToType))) 3058 ConstructorsOnly = true; 3059 3060 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3061 // RequireCompleteType may have returned true due to some invalid decl 3062 // during template instantiation, but ToType may be complete enough now 3063 // to try to recover. 3064 if (ToType->isIncompleteType()) { 3065 // We're not going to find any constructors. 3066 } else if (CXXRecordDecl *ToRecordDecl 3067 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3068 3069 Expr **Args = &From; 3070 unsigned NumArgs = 1; 3071 bool ListInitializing = false; 3072 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3073 // But first, see if there is an init-list-constructor that will work. 3074 OverloadingResult Result = IsInitializerListConstructorConversion( 3075 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3076 if (Result != OR_No_Viable_Function) 3077 return Result; 3078 // Never mind. 3079 CandidateSet.clear(); 3080 3081 // If we're list-initializing, we pass the individual elements as 3082 // arguments, not the entire list. 3083 Args = InitList->getInits(); 3084 NumArgs = InitList->getNumInits(); 3085 ListInitializing = true; 3086 } 3087 3088 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3089 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3090 Con != ConEnd; ++Con) { 3091 NamedDecl *D = *Con; 3092 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3093 3094 // Find the constructor (which may be a template). 3095 CXXConstructorDecl *Constructor = 0; 3096 FunctionTemplateDecl *ConstructorTmpl 3097 = dyn_cast<FunctionTemplateDecl>(D); 3098 if (ConstructorTmpl) 3099 Constructor 3100 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3101 else 3102 Constructor = cast<CXXConstructorDecl>(D); 3103 3104 bool Usable = !Constructor->isInvalidDecl(); 3105 if (ListInitializing) 3106 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3107 else 3108 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3109 if (Usable) { 3110 bool SuppressUserConversions = !ConstructorsOnly; 3111 if (SuppressUserConversions && ListInitializing) { 3112 SuppressUserConversions = false; 3113 if (NumArgs == 1) { 3114 // If the first argument is (a reference to) the target type, 3115 // suppress conversions. 3116 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3117 S.Context, Constructor, ToType); 3118 } 3119 } 3120 if (ConstructorTmpl) 3121 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3122 /*ExplicitArgs*/ 0, 3123 llvm::makeArrayRef(Args, NumArgs), 3124 CandidateSet, SuppressUserConversions); 3125 else 3126 // Allow one user-defined conversion when user specifies a 3127 // From->ToType conversion via an static cast (c-style, etc). 3128 S.AddOverloadCandidate(Constructor, FoundDecl, 3129 llvm::makeArrayRef(Args, NumArgs), 3130 CandidateSet, SuppressUserConversions); 3131 } 3132 } 3133 } 3134 } 3135 3136 // Enumerate conversion functions, if we're allowed to. 3137 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3138 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3139 // No conversion functions from incomplete types. 3140 } else if (const RecordType *FromRecordType 3141 = From->getType()->getAs<RecordType>()) { 3142 if (CXXRecordDecl *FromRecordDecl 3143 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3144 // Add all of the conversion functions as candidates. 3145 std::pair<CXXRecordDecl::conversion_iterator, 3146 CXXRecordDecl::conversion_iterator> 3147 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3148 for (CXXRecordDecl::conversion_iterator 3149 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3150 DeclAccessPair FoundDecl = I.getPair(); 3151 NamedDecl *D = FoundDecl.getDecl(); 3152 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3153 if (isa<UsingShadowDecl>(D)) 3154 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3155 3156 CXXConversionDecl *Conv; 3157 FunctionTemplateDecl *ConvTemplate; 3158 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3159 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3160 else 3161 Conv = cast<CXXConversionDecl>(D); 3162 3163 if (AllowExplicit || !Conv->isExplicit()) { 3164 if (ConvTemplate) 3165 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3166 ActingContext, From, ToType, 3167 CandidateSet, 3168 AllowObjCConversionOnExplicit); 3169 else 3170 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3171 From, ToType, CandidateSet, 3172 AllowObjCConversionOnExplicit); 3173 } 3174 } 3175 } 3176 } 3177 3178 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3179 3180 OverloadCandidateSet::iterator Best; 3181 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3182 case OR_Success: 3183 // Record the standard conversion we used and the conversion function. 3184 if (CXXConstructorDecl *Constructor 3185 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3186 // C++ [over.ics.user]p1: 3187 // If the user-defined conversion is specified by a 3188 // constructor (12.3.1), the initial standard conversion 3189 // sequence converts the source type to the type required by 3190 // the argument of the constructor. 3191 // 3192 QualType ThisType = Constructor->getThisType(S.Context); 3193 if (isa<InitListExpr>(From)) { 3194 // Initializer lists don't have conversions as such. 3195 User.Before.setAsIdentityConversion(); 3196 } else { 3197 if (Best->Conversions[0].isEllipsis()) 3198 User.EllipsisConversion = true; 3199 else { 3200 User.Before = Best->Conversions[0].Standard; 3201 User.EllipsisConversion = false; 3202 } 3203 } 3204 User.HadMultipleCandidates = HadMultipleCandidates; 3205 User.ConversionFunction = Constructor; 3206 User.FoundConversionFunction = Best->FoundDecl; 3207 User.After.setAsIdentityConversion(); 3208 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3209 User.After.setAllToTypes(ToType); 3210 return OR_Success; 3211 } 3212 if (CXXConversionDecl *Conversion 3213 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3214 // C++ [over.ics.user]p1: 3215 // 3216 // [...] If the user-defined conversion is specified by a 3217 // conversion function (12.3.2), the initial standard 3218 // conversion sequence converts the source type to the 3219 // implicit object parameter of the conversion function. 3220 User.Before = Best->Conversions[0].Standard; 3221 User.HadMultipleCandidates = HadMultipleCandidates; 3222 User.ConversionFunction = Conversion; 3223 User.FoundConversionFunction = Best->FoundDecl; 3224 User.EllipsisConversion = false; 3225 3226 // C++ [over.ics.user]p2: 3227 // The second standard conversion sequence converts the 3228 // result of the user-defined conversion to the target type 3229 // for the sequence. Since an implicit conversion sequence 3230 // is an initialization, the special rules for 3231 // initialization by user-defined conversion apply when 3232 // selecting the best user-defined conversion for a 3233 // user-defined conversion sequence (see 13.3.3 and 3234 // 13.3.3.1). 3235 User.After = Best->FinalConversion; 3236 return OR_Success; 3237 } 3238 llvm_unreachable("Not a constructor or conversion function?"); 3239 3240 case OR_No_Viable_Function: 3241 return OR_No_Viable_Function; 3242 case OR_Deleted: 3243 // No conversion here! We're done. 3244 return OR_Deleted; 3245 3246 case OR_Ambiguous: 3247 return OR_Ambiguous; 3248 } 3249 3250 llvm_unreachable("Invalid OverloadResult!"); 3251 } 3252 3253 bool 3254 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3255 ImplicitConversionSequence ICS; 3256 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3257 OverloadingResult OvResult = 3258 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3259 CandidateSet, false, false); 3260 if (OvResult == OR_Ambiguous) 3261 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3262 << From->getType() << ToType << From->getSourceRange(); 3263 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3264 if (!RequireCompleteType(From->getLocStart(), ToType, 3265 diag::err_typecheck_nonviable_condition_incomplete, 3266 From->getType(), From->getSourceRange())) 3267 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3268 << From->getType() << From->getSourceRange() << ToType; 3269 } else 3270 return false; 3271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3272 return true; 3273 } 3274 3275 /// \brief Compare the user-defined conversion functions or constructors 3276 /// of two user-defined conversion sequences to determine whether any ordering 3277 /// is possible. 3278 static ImplicitConversionSequence::CompareKind 3279 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3280 FunctionDecl *Function2) { 3281 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3282 return ImplicitConversionSequence::Indistinguishable; 3283 3284 // Objective-C++: 3285 // If both conversion functions are implicitly-declared conversions from 3286 // a lambda closure type to a function pointer and a block pointer, 3287 // respectively, always prefer the conversion to a function pointer, 3288 // because the function pointer is more lightweight and is more likely 3289 // to keep code working. 3290 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3291 if (!Conv1) 3292 return ImplicitConversionSequence::Indistinguishable; 3293 3294 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3295 if (!Conv2) 3296 return ImplicitConversionSequence::Indistinguishable; 3297 3298 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3299 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3300 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3301 if (Block1 != Block2) 3302 return Block1 ? ImplicitConversionSequence::Worse 3303 : ImplicitConversionSequence::Better; 3304 } 3305 3306 return ImplicitConversionSequence::Indistinguishable; 3307 } 3308 3309 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3310 const ImplicitConversionSequence &ICS) { 3311 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3312 (ICS.isUserDefined() && 3313 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3314 } 3315 3316 /// CompareImplicitConversionSequences - Compare two implicit 3317 /// conversion sequences to determine whether one is better than the 3318 /// other or if they are indistinguishable (C++ 13.3.3.2). 3319 static ImplicitConversionSequence::CompareKind 3320 CompareImplicitConversionSequences(Sema &S, 3321 const ImplicitConversionSequence& ICS1, 3322 const ImplicitConversionSequence& ICS2) 3323 { 3324 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3325 // conversion sequences (as defined in 13.3.3.1) 3326 // -- a standard conversion sequence (13.3.3.1.1) is a better 3327 // conversion sequence than a user-defined conversion sequence or 3328 // an ellipsis conversion sequence, and 3329 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3330 // conversion sequence than an ellipsis conversion sequence 3331 // (13.3.3.1.3). 3332 // 3333 // C++0x [over.best.ics]p10: 3334 // For the purpose of ranking implicit conversion sequences as 3335 // described in 13.3.3.2, the ambiguous conversion sequence is 3336 // treated as a user-defined sequence that is indistinguishable 3337 // from any other user-defined conversion sequence. 3338 3339 // String literal to 'char *' conversion has been deprecated in C++03. It has 3340 // been removed from C++11. We still accept this conversion, if it happens at 3341 // the best viable function. Otherwise, this conversion is considered worse 3342 // than ellipsis conversion. Consider this as an extension; this is not in the 3343 // standard. For example: 3344 // 3345 // int &f(...); // #1 3346 // void f(char*); // #2 3347 // void g() { int &r = f("foo"); } 3348 // 3349 // In C++03, we pick #2 as the best viable function. 3350 // In C++11, we pick #1 as the best viable function, because ellipsis 3351 // conversion is better than string-literal to char* conversion (since there 3352 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3353 // convert arguments, #2 would be the best viable function in C++11. 3354 // If the best viable function has this conversion, a warning will be issued 3355 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3356 3357 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3358 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3359 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3360 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3361 ? ImplicitConversionSequence::Worse 3362 : ImplicitConversionSequence::Better; 3363 3364 if (ICS1.getKindRank() < ICS2.getKindRank()) 3365 return ImplicitConversionSequence::Better; 3366 if (ICS2.getKindRank() < ICS1.getKindRank()) 3367 return ImplicitConversionSequence::Worse; 3368 3369 // The following checks require both conversion sequences to be of 3370 // the same kind. 3371 if (ICS1.getKind() != ICS2.getKind()) 3372 return ImplicitConversionSequence::Indistinguishable; 3373 3374 ImplicitConversionSequence::CompareKind Result = 3375 ImplicitConversionSequence::Indistinguishable; 3376 3377 // Two implicit conversion sequences of the same form are 3378 // indistinguishable conversion sequences unless one of the 3379 // following rules apply: (C++ 13.3.3.2p3): 3380 if (ICS1.isStandard()) 3381 Result = CompareStandardConversionSequences(S, 3382 ICS1.Standard, ICS2.Standard); 3383 else if (ICS1.isUserDefined()) { 3384 // User-defined conversion sequence U1 is a better conversion 3385 // sequence than another user-defined conversion sequence U2 if 3386 // they contain the same user-defined conversion function or 3387 // constructor and if the second standard conversion sequence of 3388 // U1 is better than the second standard conversion sequence of 3389 // U2 (C++ 13.3.3.2p3). 3390 if (ICS1.UserDefined.ConversionFunction == 3391 ICS2.UserDefined.ConversionFunction) 3392 Result = CompareStandardConversionSequences(S, 3393 ICS1.UserDefined.After, 3394 ICS2.UserDefined.After); 3395 else 3396 Result = compareConversionFunctions(S, 3397 ICS1.UserDefined.ConversionFunction, 3398 ICS2.UserDefined.ConversionFunction); 3399 } 3400 3401 // List-initialization sequence L1 is a better conversion sequence than 3402 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3403 // for some X and L2 does not. 3404 if (Result == ImplicitConversionSequence::Indistinguishable && 3405 !ICS1.isBad()) { 3406 if (ICS1.isStdInitializerListElement() && 3407 !ICS2.isStdInitializerListElement()) 3408 return ImplicitConversionSequence::Better; 3409 if (!ICS1.isStdInitializerListElement() && 3410 ICS2.isStdInitializerListElement()) 3411 return ImplicitConversionSequence::Worse; 3412 } 3413 3414 return Result; 3415 } 3416 3417 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3418 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3419 Qualifiers Quals; 3420 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3421 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3422 } 3423 3424 return Context.hasSameUnqualifiedType(T1, T2); 3425 } 3426 3427 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3428 // determine if one is a proper subset of the other. 3429 static ImplicitConversionSequence::CompareKind 3430 compareStandardConversionSubsets(ASTContext &Context, 3431 const StandardConversionSequence& SCS1, 3432 const StandardConversionSequence& SCS2) { 3433 ImplicitConversionSequence::CompareKind Result 3434 = ImplicitConversionSequence::Indistinguishable; 3435 3436 // the identity conversion sequence is considered to be a subsequence of 3437 // any non-identity conversion sequence 3438 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3439 return ImplicitConversionSequence::Better; 3440 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3441 return ImplicitConversionSequence::Worse; 3442 3443 if (SCS1.Second != SCS2.Second) { 3444 if (SCS1.Second == ICK_Identity) 3445 Result = ImplicitConversionSequence::Better; 3446 else if (SCS2.Second == ICK_Identity) 3447 Result = ImplicitConversionSequence::Worse; 3448 else 3449 return ImplicitConversionSequence::Indistinguishable; 3450 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3451 return ImplicitConversionSequence::Indistinguishable; 3452 3453 if (SCS1.Third == SCS2.Third) { 3454 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3455 : ImplicitConversionSequence::Indistinguishable; 3456 } 3457 3458 if (SCS1.Third == ICK_Identity) 3459 return Result == ImplicitConversionSequence::Worse 3460 ? ImplicitConversionSequence::Indistinguishable 3461 : ImplicitConversionSequence::Better; 3462 3463 if (SCS2.Third == ICK_Identity) 3464 return Result == ImplicitConversionSequence::Better 3465 ? ImplicitConversionSequence::Indistinguishable 3466 : ImplicitConversionSequence::Worse; 3467 3468 return ImplicitConversionSequence::Indistinguishable; 3469 } 3470 3471 /// \brief Determine whether one of the given reference bindings is better 3472 /// than the other based on what kind of bindings they are. 3473 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3474 const StandardConversionSequence &SCS2) { 3475 // C++0x [over.ics.rank]p3b4: 3476 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3477 // implicit object parameter of a non-static member function declared 3478 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3479 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3480 // lvalue reference to a function lvalue and S2 binds an rvalue 3481 // reference*. 3482 // 3483 // FIXME: Rvalue references. We're going rogue with the above edits, 3484 // because the semantics in the current C++0x working paper (N3225 at the 3485 // time of this writing) break the standard definition of std::forward 3486 // and std::reference_wrapper when dealing with references to functions. 3487 // Proposed wording changes submitted to CWG for consideration. 3488 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3489 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3490 return false; 3491 3492 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3493 SCS2.IsLvalueReference) || 3494 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3495 !SCS2.IsLvalueReference); 3496 } 3497 3498 /// CompareStandardConversionSequences - Compare two standard 3499 /// conversion sequences to determine whether one is better than the 3500 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3501 static ImplicitConversionSequence::CompareKind 3502 CompareStandardConversionSequences(Sema &S, 3503 const StandardConversionSequence& SCS1, 3504 const StandardConversionSequence& SCS2) 3505 { 3506 // Standard conversion sequence S1 is a better conversion sequence 3507 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3508 3509 // -- S1 is a proper subsequence of S2 (comparing the conversion 3510 // sequences in the canonical form defined by 13.3.3.1.1, 3511 // excluding any Lvalue Transformation; the identity conversion 3512 // sequence is considered to be a subsequence of any 3513 // non-identity conversion sequence) or, if not that, 3514 if (ImplicitConversionSequence::CompareKind CK 3515 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3516 return CK; 3517 3518 // -- the rank of S1 is better than the rank of S2 (by the rules 3519 // defined below), or, if not that, 3520 ImplicitConversionRank Rank1 = SCS1.getRank(); 3521 ImplicitConversionRank Rank2 = SCS2.getRank(); 3522 if (Rank1 < Rank2) 3523 return ImplicitConversionSequence::Better; 3524 else if (Rank2 < Rank1) 3525 return ImplicitConversionSequence::Worse; 3526 3527 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3528 // are indistinguishable unless one of the following rules 3529 // applies: 3530 3531 // A conversion that is not a conversion of a pointer, or 3532 // pointer to member, to bool is better than another conversion 3533 // that is such a conversion. 3534 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3535 return SCS2.isPointerConversionToBool() 3536 ? ImplicitConversionSequence::Better 3537 : ImplicitConversionSequence::Worse; 3538 3539 // C++ [over.ics.rank]p4b2: 3540 // 3541 // If class B is derived directly or indirectly from class A, 3542 // conversion of B* to A* is better than conversion of B* to 3543 // void*, and conversion of A* to void* is better than conversion 3544 // of B* to void*. 3545 bool SCS1ConvertsToVoid 3546 = SCS1.isPointerConversionToVoidPointer(S.Context); 3547 bool SCS2ConvertsToVoid 3548 = SCS2.isPointerConversionToVoidPointer(S.Context); 3549 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3550 // Exactly one of the conversion sequences is a conversion to 3551 // a void pointer; it's the worse conversion. 3552 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3553 : ImplicitConversionSequence::Worse; 3554 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3555 // Neither conversion sequence converts to a void pointer; compare 3556 // their derived-to-base conversions. 3557 if (ImplicitConversionSequence::CompareKind DerivedCK 3558 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3559 return DerivedCK; 3560 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3561 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3562 // Both conversion sequences are conversions to void 3563 // pointers. Compare the source types to determine if there's an 3564 // inheritance relationship in their sources. 3565 QualType FromType1 = SCS1.getFromType(); 3566 QualType FromType2 = SCS2.getFromType(); 3567 3568 // Adjust the types we're converting from via the array-to-pointer 3569 // conversion, if we need to. 3570 if (SCS1.First == ICK_Array_To_Pointer) 3571 FromType1 = S.Context.getArrayDecayedType(FromType1); 3572 if (SCS2.First == ICK_Array_To_Pointer) 3573 FromType2 = S.Context.getArrayDecayedType(FromType2); 3574 3575 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3576 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3577 3578 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3579 return ImplicitConversionSequence::Better; 3580 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3581 return ImplicitConversionSequence::Worse; 3582 3583 // Objective-C++: If one interface is more specific than the 3584 // other, it is the better one. 3585 const ObjCObjectPointerType* FromObjCPtr1 3586 = FromType1->getAs<ObjCObjectPointerType>(); 3587 const ObjCObjectPointerType* FromObjCPtr2 3588 = FromType2->getAs<ObjCObjectPointerType>(); 3589 if (FromObjCPtr1 && FromObjCPtr2) { 3590 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3591 FromObjCPtr2); 3592 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3593 FromObjCPtr1); 3594 if (AssignLeft != AssignRight) { 3595 return AssignLeft? ImplicitConversionSequence::Better 3596 : ImplicitConversionSequence::Worse; 3597 } 3598 } 3599 } 3600 3601 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3602 // bullet 3). 3603 if (ImplicitConversionSequence::CompareKind QualCK 3604 = CompareQualificationConversions(S, SCS1, SCS2)) 3605 return QualCK; 3606 3607 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3608 // Check for a better reference binding based on the kind of bindings. 3609 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3610 return ImplicitConversionSequence::Better; 3611 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3612 return ImplicitConversionSequence::Worse; 3613 3614 // C++ [over.ics.rank]p3b4: 3615 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3616 // which the references refer are the same type except for 3617 // top-level cv-qualifiers, and the type to which the reference 3618 // initialized by S2 refers is more cv-qualified than the type 3619 // to which the reference initialized by S1 refers. 3620 QualType T1 = SCS1.getToType(2); 3621 QualType T2 = SCS2.getToType(2); 3622 T1 = S.Context.getCanonicalType(T1); 3623 T2 = S.Context.getCanonicalType(T2); 3624 Qualifiers T1Quals, T2Quals; 3625 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3626 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3627 if (UnqualT1 == UnqualT2) { 3628 // Objective-C++ ARC: If the references refer to objects with different 3629 // lifetimes, prefer bindings that don't change lifetime. 3630 if (SCS1.ObjCLifetimeConversionBinding != 3631 SCS2.ObjCLifetimeConversionBinding) { 3632 return SCS1.ObjCLifetimeConversionBinding 3633 ? ImplicitConversionSequence::Worse 3634 : ImplicitConversionSequence::Better; 3635 } 3636 3637 // If the type is an array type, promote the element qualifiers to the 3638 // type for comparison. 3639 if (isa<ArrayType>(T1) && T1Quals) 3640 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3641 if (isa<ArrayType>(T2) && T2Quals) 3642 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3643 if (T2.isMoreQualifiedThan(T1)) 3644 return ImplicitConversionSequence::Better; 3645 else if (T1.isMoreQualifiedThan(T2)) 3646 return ImplicitConversionSequence::Worse; 3647 } 3648 } 3649 3650 // In Microsoft mode, prefer an integral conversion to a 3651 // floating-to-integral conversion if the integral conversion 3652 // is between types of the same size. 3653 // For example: 3654 // void f(float); 3655 // void f(int); 3656 // int main { 3657 // long a; 3658 // f(a); 3659 // } 3660 // Here, MSVC will call f(int) instead of generating a compile error 3661 // as clang will do in standard mode. 3662 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3663 SCS2.Second == ICK_Floating_Integral && 3664 S.Context.getTypeSize(SCS1.getFromType()) == 3665 S.Context.getTypeSize(SCS1.getToType(2))) 3666 return ImplicitConversionSequence::Better; 3667 3668 return ImplicitConversionSequence::Indistinguishable; 3669 } 3670 3671 /// CompareQualificationConversions - Compares two standard conversion 3672 /// sequences to determine whether they can be ranked based on their 3673 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3674 ImplicitConversionSequence::CompareKind 3675 CompareQualificationConversions(Sema &S, 3676 const StandardConversionSequence& SCS1, 3677 const StandardConversionSequence& SCS2) { 3678 // C++ 13.3.3.2p3: 3679 // -- S1 and S2 differ only in their qualification conversion and 3680 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3681 // cv-qualification signature of type T1 is a proper subset of 3682 // the cv-qualification signature of type T2, and S1 is not the 3683 // deprecated string literal array-to-pointer conversion (4.2). 3684 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3685 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3686 return ImplicitConversionSequence::Indistinguishable; 3687 3688 // FIXME: the example in the standard doesn't use a qualification 3689 // conversion (!) 3690 QualType T1 = SCS1.getToType(2); 3691 QualType T2 = SCS2.getToType(2); 3692 T1 = S.Context.getCanonicalType(T1); 3693 T2 = S.Context.getCanonicalType(T2); 3694 Qualifiers T1Quals, T2Quals; 3695 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3696 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3697 3698 // If the types are the same, we won't learn anything by unwrapped 3699 // them. 3700 if (UnqualT1 == UnqualT2) 3701 return ImplicitConversionSequence::Indistinguishable; 3702 3703 // If the type is an array type, promote the element qualifiers to the type 3704 // for comparison. 3705 if (isa<ArrayType>(T1) && T1Quals) 3706 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3707 if (isa<ArrayType>(T2) && T2Quals) 3708 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3709 3710 ImplicitConversionSequence::CompareKind Result 3711 = ImplicitConversionSequence::Indistinguishable; 3712 3713 // Objective-C++ ARC: 3714 // Prefer qualification conversions not involving a change in lifetime 3715 // to qualification conversions that do not change lifetime. 3716 if (SCS1.QualificationIncludesObjCLifetime != 3717 SCS2.QualificationIncludesObjCLifetime) { 3718 Result = SCS1.QualificationIncludesObjCLifetime 3719 ? ImplicitConversionSequence::Worse 3720 : ImplicitConversionSequence::Better; 3721 } 3722 3723 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3724 // Within each iteration of the loop, we check the qualifiers to 3725 // determine if this still looks like a qualification 3726 // conversion. Then, if all is well, we unwrap one more level of 3727 // pointers or pointers-to-members and do it all again 3728 // until there are no more pointers or pointers-to-members left 3729 // to unwrap. This essentially mimics what 3730 // IsQualificationConversion does, but here we're checking for a 3731 // strict subset of qualifiers. 3732 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3733 // The qualifiers are the same, so this doesn't tell us anything 3734 // about how the sequences rank. 3735 ; 3736 else if (T2.isMoreQualifiedThan(T1)) { 3737 // T1 has fewer qualifiers, so it could be the better sequence. 3738 if (Result == ImplicitConversionSequence::Worse) 3739 // Neither has qualifiers that are a subset of the other's 3740 // qualifiers. 3741 return ImplicitConversionSequence::Indistinguishable; 3742 3743 Result = ImplicitConversionSequence::Better; 3744 } else if (T1.isMoreQualifiedThan(T2)) { 3745 // T2 has fewer qualifiers, so it could be the better sequence. 3746 if (Result == ImplicitConversionSequence::Better) 3747 // Neither has qualifiers that are a subset of the other's 3748 // qualifiers. 3749 return ImplicitConversionSequence::Indistinguishable; 3750 3751 Result = ImplicitConversionSequence::Worse; 3752 } else { 3753 // Qualifiers are disjoint. 3754 return ImplicitConversionSequence::Indistinguishable; 3755 } 3756 3757 // If the types after this point are equivalent, we're done. 3758 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3759 break; 3760 } 3761 3762 // Check that the winning standard conversion sequence isn't using 3763 // the deprecated string literal array to pointer conversion. 3764 switch (Result) { 3765 case ImplicitConversionSequence::Better: 3766 if (SCS1.DeprecatedStringLiteralToCharPtr) 3767 Result = ImplicitConversionSequence::Indistinguishable; 3768 break; 3769 3770 case ImplicitConversionSequence::Indistinguishable: 3771 break; 3772 3773 case ImplicitConversionSequence::Worse: 3774 if (SCS2.DeprecatedStringLiteralToCharPtr) 3775 Result = ImplicitConversionSequence::Indistinguishable; 3776 break; 3777 } 3778 3779 return Result; 3780 } 3781 3782 /// CompareDerivedToBaseConversions - Compares two standard conversion 3783 /// sequences to determine whether they can be ranked based on their 3784 /// various kinds of derived-to-base conversions (C++ 3785 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3786 /// conversions between Objective-C interface types. 3787 ImplicitConversionSequence::CompareKind 3788 CompareDerivedToBaseConversions(Sema &S, 3789 const StandardConversionSequence& SCS1, 3790 const StandardConversionSequence& SCS2) { 3791 QualType FromType1 = SCS1.getFromType(); 3792 QualType ToType1 = SCS1.getToType(1); 3793 QualType FromType2 = SCS2.getFromType(); 3794 QualType ToType2 = SCS2.getToType(1); 3795 3796 // Adjust the types we're converting from via the array-to-pointer 3797 // conversion, if we need to. 3798 if (SCS1.First == ICK_Array_To_Pointer) 3799 FromType1 = S.Context.getArrayDecayedType(FromType1); 3800 if (SCS2.First == ICK_Array_To_Pointer) 3801 FromType2 = S.Context.getArrayDecayedType(FromType2); 3802 3803 // Canonicalize all of the types. 3804 FromType1 = S.Context.getCanonicalType(FromType1); 3805 ToType1 = S.Context.getCanonicalType(ToType1); 3806 FromType2 = S.Context.getCanonicalType(FromType2); 3807 ToType2 = S.Context.getCanonicalType(ToType2); 3808 3809 // C++ [over.ics.rank]p4b3: 3810 // 3811 // If class B is derived directly or indirectly from class A and 3812 // class C is derived directly or indirectly from B, 3813 // 3814 // Compare based on pointer conversions. 3815 if (SCS1.Second == ICK_Pointer_Conversion && 3816 SCS2.Second == ICK_Pointer_Conversion && 3817 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3818 FromType1->isPointerType() && FromType2->isPointerType() && 3819 ToType1->isPointerType() && ToType2->isPointerType()) { 3820 QualType FromPointee1 3821 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3822 QualType ToPointee1 3823 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3824 QualType FromPointee2 3825 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3826 QualType ToPointee2 3827 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3828 3829 // -- conversion of C* to B* is better than conversion of C* to A*, 3830 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3831 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3832 return ImplicitConversionSequence::Better; 3833 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3834 return ImplicitConversionSequence::Worse; 3835 } 3836 3837 // -- conversion of B* to A* is better than conversion of C* to A*, 3838 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3839 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3840 return ImplicitConversionSequence::Better; 3841 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3842 return ImplicitConversionSequence::Worse; 3843 } 3844 } else if (SCS1.Second == ICK_Pointer_Conversion && 3845 SCS2.Second == ICK_Pointer_Conversion) { 3846 const ObjCObjectPointerType *FromPtr1 3847 = FromType1->getAs<ObjCObjectPointerType>(); 3848 const ObjCObjectPointerType *FromPtr2 3849 = FromType2->getAs<ObjCObjectPointerType>(); 3850 const ObjCObjectPointerType *ToPtr1 3851 = ToType1->getAs<ObjCObjectPointerType>(); 3852 const ObjCObjectPointerType *ToPtr2 3853 = ToType2->getAs<ObjCObjectPointerType>(); 3854 3855 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3856 // Apply the same conversion ranking rules for Objective-C pointer types 3857 // that we do for C++ pointers to class types. However, we employ the 3858 // Objective-C pseudo-subtyping relationship used for assignment of 3859 // Objective-C pointer types. 3860 bool FromAssignLeft 3861 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3862 bool FromAssignRight 3863 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3864 bool ToAssignLeft 3865 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3866 bool ToAssignRight 3867 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3868 3869 // A conversion to an a non-id object pointer type or qualified 'id' 3870 // type is better than a conversion to 'id'. 3871 if (ToPtr1->isObjCIdType() && 3872 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3873 return ImplicitConversionSequence::Worse; 3874 if (ToPtr2->isObjCIdType() && 3875 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3876 return ImplicitConversionSequence::Better; 3877 3878 // A conversion to a non-id object pointer type is better than a 3879 // conversion to a qualified 'id' type 3880 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3881 return ImplicitConversionSequence::Worse; 3882 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3883 return ImplicitConversionSequence::Better; 3884 3885 // A conversion to an a non-Class object pointer type or qualified 'Class' 3886 // type is better than a conversion to 'Class'. 3887 if (ToPtr1->isObjCClassType() && 3888 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3889 return ImplicitConversionSequence::Worse; 3890 if (ToPtr2->isObjCClassType() && 3891 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3892 return ImplicitConversionSequence::Better; 3893 3894 // A conversion to a non-Class object pointer type is better than a 3895 // conversion to a qualified 'Class' type. 3896 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3897 return ImplicitConversionSequence::Worse; 3898 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3899 return ImplicitConversionSequence::Better; 3900 3901 // -- "conversion of C* to B* is better than conversion of C* to A*," 3902 if (S.Context.hasSameType(FromType1, FromType2) && 3903 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3904 (ToAssignLeft != ToAssignRight)) 3905 return ToAssignLeft? ImplicitConversionSequence::Worse 3906 : ImplicitConversionSequence::Better; 3907 3908 // -- "conversion of B* to A* is better than conversion of C* to A*," 3909 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3910 (FromAssignLeft != FromAssignRight)) 3911 return FromAssignLeft? ImplicitConversionSequence::Better 3912 : ImplicitConversionSequence::Worse; 3913 } 3914 } 3915 3916 // Ranking of member-pointer types. 3917 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3918 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3919 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3920 const MemberPointerType * FromMemPointer1 = 3921 FromType1->getAs<MemberPointerType>(); 3922 const MemberPointerType * ToMemPointer1 = 3923 ToType1->getAs<MemberPointerType>(); 3924 const MemberPointerType * FromMemPointer2 = 3925 FromType2->getAs<MemberPointerType>(); 3926 const MemberPointerType * ToMemPointer2 = 3927 ToType2->getAs<MemberPointerType>(); 3928 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3929 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3930 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3931 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3932 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3933 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3934 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3935 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3936 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3937 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3938 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3939 return ImplicitConversionSequence::Worse; 3940 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3941 return ImplicitConversionSequence::Better; 3942 } 3943 // conversion of B::* to C::* is better than conversion of A::* to C::* 3944 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3945 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3946 return ImplicitConversionSequence::Better; 3947 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3948 return ImplicitConversionSequence::Worse; 3949 } 3950 } 3951 3952 if (SCS1.Second == ICK_Derived_To_Base) { 3953 // -- conversion of C to B is better than conversion of C to A, 3954 // -- binding of an expression of type C to a reference of type 3955 // B& is better than binding an expression of type C to a 3956 // reference of type A&, 3957 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3958 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3959 if (S.IsDerivedFrom(ToType1, ToType2)) 3960 return ImplicitConversionSequence::Better; 3961 else if (S.IsDerivedFrom(ToType2, ToType1)) 3962 return ImplicitConversionSequence::Worse; 3963 } 3964 3965 // -- conversion of B to A is better than conversion of C to A. 3966 // -- binding of an expression of type B to a reference of type 3967 // A& is better than binding an expression of type C to a 3968 // reference of type A&, 3969 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3970 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3971 if (S.IsDerivedFrom(FromType2, FromType1)) 3972 return ImplicitConversionSequence::Better; 3973 else if (S.IsDerivedFrom(FromType1, FromType2)) 3974 return ImplicitConversionSequence::Worse; 3975 } 3976 } 3977 3978 return ImplicitConversionSequence::Indistinguishable; 3979 } 3980 3981 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3982 /// C++ class. 3983 static bool isTypeValid(QualType T) { 3984 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3985 return !Record->isInvalidDecl(); 3986 3987 return true; 3988 } 3989 3990 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3991 /// determine whether they are reference-related, 3992 /// reference-compatible, reference-compatible with added 3993 /// qualification, or incompatible, for use in C++ initialization by 3994 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3995 /// type, and the first type (T1) is the pointee type of the reference 3996 /// type being initialized. 3997 Sema::ReferenceCompareResult 3998 Sema::CompareReferenceRelationship(SourceLocation Loc, 3999 QualType OrigT1, QualType OrigT2, 4000 bool &DerivedToBase, 4001 bool &ObjCConversion, 4002 bool &ObjCLifetimeConversion) { 4003 assert(!OrigT1->isReferenceType() && 4004 "T1 must be the pointee type of the reference type"); 4005 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4006 4007 QualType T1 = Context.getCanonicalType(OrigT1); 4008 QualType T2 = Context.getCanonicalType(OrigT2); 4009 Qualifiers T1Quals, T2Quals; 4010 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4011 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4012 4013 // C++ [dcl.init.ref]p4: 4014 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4015 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4016 // T1 is a base class of T2. 4017 DerivedToBase = false; 4018 ObjCConversion = false; 4019 ObjCLifetimeConversion = false; 4020 if (UnqualT1 == UnqualT2) { 4021 // Nothing to do. 4022 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4023 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4024 IsDerivedFrom(UnqualT2, UnqualT1)) 4025 DerivedToBase = true; 4026 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4027 UnqualT2->isObjCObjectOrInterfaceType() && 4028 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4029 ObjCConversion = true; 4030 else 4031 return Ref_Incompatible; 4032 4033 // At this point, we know that T1 and T2 are reference-related (at 4034 // least). 4035 4036 // If the type is an array type, promote the element qualifiers to the type 4037 // for comparison. 4038 if (isa<ArrayType>(T1) && T1Quals) 4039 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4040 if (isa<ArrayType>(T2) && T2Quals) 4041 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4042 4043 // C++ [dcl.init.ref]p4: 4044 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4045 // reference-related to T2 and cv1 is the same cv-qualification 4046 // as, or greater cv-qualification than, cv2. For purposes of 4047 // overload resolution, cases for which cv1 is greater 4048 // cv-qualification than cv2 are identified as 4049 // reference-compatible with added qualification (see 13.3.3.2). 4050 // 4051 // Note that we also require equivalence of Objective-C GC and address-space 4052 // qualifiers when performing these computations, so that e.g., an int in 4053 // address space 1 is not reference-compatible with an int in address 4054 // space 2. 4055 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4056 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4057 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4058 ObjCLifetimeConversion = true; 4059 4060 T1Quals.removeObjCLifetime(); 4061 T2Quals.removeObjCLifetime(); 4062 } 4063 4064 if (T1Quals == T2Quals) 4065 return Ref_Compatible; 4066 else if (T1Quals.compatiblyIncludes(T2Quals)) 4067 return Ref_Compatible_With_Added_Qualification; 4068 else 4069 return Ref_Related; 4070 } 4071 4072 /// \brief Look for a user-defined conversion to an value reference-compatible 4073 /// with DeclType. Return true if something definite is found. 4074 static bool 4075 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4076 QualType DeclType, SourceLocation DeclLoc, 4077 Expr *Init, QualType T2, bool AllowRvalues, 4078 bool AllowExplicit) { 4079 assert(T2->isRecordType() && "Can only find conversions of record types."); 4080 CXXRecordDecl *T2RecordDecl 4081 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4082 4083 OverloadCandidateSet CandidateSet(DeclLoc); 4084 std::pair<CXXRecordDecl::conversion_iterator, 4085 CXXRecordDecl::conversion_iterator> 4086 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4087 for (CXXRecordDecl::conversion_iterator 4088 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4089 NamedDecl *D = *I; 4090 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4091 if (isa<UsingShadowDecl>(D)) 4092 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4093 4094 FunctionTemplateDecl *ConvTemplate 4095 = dyn_cast<FunctionTemplateDecl>(D); 4096 CXXConversionDecl *Conv; 4097 if (ConvTemplate) 4098 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4099 else 4100 Conv = cast<CXXConversionDecl>(D); 4101 4102 // If this is an explicit conversion, and we're not allowed to consider 4103 // explicit conversions, skip it. 4104 if (!AllowExplicit && Conv->isExplicit()) 4105 continue; 4106 4107 if (AllowRvalues) { 4108 bool DerivedToBase = false; 4109 bool ObjCConversion = false; 4110 bool ObjCLifetimeConversion = false; 4111 4112 // If we are initializing an rvalue reference, don't permit conversion 4113 // functions that return lvalues. 4114 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4115 const ReferenceType *RefType 4116 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4117 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4118 continue; 4119 } 4120 4121 if (!ConvTemplate && 4122 S.CompareReferenceRelationship( 4123 DeclLoc, 4124 Conv->getConversionType().getNonReferenceType() 4125 .getUnqualifiedType(), 4126 DeclType.getNonReferenceType().getUnqualifiedType(), 4127 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4128 Sema::Ref_Incompatible) 4129 continue; 4130 } else { 4131 // If the conversion function doesn't return a reference type, 4132 // it can't be considered for this conversion. An rvalue reference 4133 // is only acceptable if its referencee is a function type. 4134 4135 const ReferenceType *RefType = 4136 Conv->getConversionType()->getAs<ReferenceType>(); 4137 if (!RefType || 4138 (!RefType->isLValueReferenceType() && 4139 !RefType->getPointeeType()->isFunctionType())) 4140 continue; 4141 } 4142 4143 if (ConvTemplate) 4144 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4145 Init, DeclType, CandidateSet, 4146 /*AllowObjCConversionOnExplicit=*/false); 4147 else 4148 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4149 DeclType, CandidateSet, 4150 /*AllowObjCConversionOnExplicit=*/false); 4151 } 4152 4153 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4154 4155 OverloadCandidateSet::iterator Best; 4156 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4157 case OR_Success: 4158 // C++ [over.ics.ref]p1: 4159 // 4160 // [...] If the parameter binds directly to the result of 4161 // applying a conversion function to the argument 4162 // expression, the implicit conversion sequence is a 4163 // user-defined conversion sequence (13.3.3.1.2), with the 4164 // second standard conversion sequence either an identity 4165 // conversion or, if the conversion function returns an 4166 // entity of a type that is a derived class of the parameter 4167 // type, a derived-to-base Conversion. 4168 if (!Best->FinalConversion.DirectBinding) 4169 return false; 4170 4171 ICS.setUserDefined(); 4172 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4173 ICS.UserDefined.After = Best->FinalConversion; 4174 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4175 ICS.UserDefined.ConversionFunction = Best->Function; 4176 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4177 ICS.UserDefined.EllipsisConversion = false; 4178 assert(ICS.UserDefined.After.ReferenceBinding && 4179 ICS.UserDefined.After.DirectBinding && 4180 "Expected a direct reference binding!"); 4181 return true; 4182 4183 case OR_Ambiguous: 4184 ICS.setAmbiguous(); 4185 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4186 Cand != CandidateSet.end(); ++Cand) 4187 if (Cand->Viable) 4188 ICS.Ambiguous.addConversion(Cand->Function); 4189 return true; 4190 4191 case OR_No_Viable_Function: 4192 case OR_Deleted: 4193 // There was no suitable conversion, or we found a deleted 4194 // conversion; continue with other checks. 4195 return false; 4196 } 4197 4198 llvm_unreachable("Invalid OverloadResult!"); 4199 } 4200 4201 /// \brief Compute an implicit conversion sequence for reference 4202 /// initialization. 4203 static ImplicitConversionSequence 4204 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4205 SourceLocation DeclLoc, 4206 bool SuppressUserConversions, 4207 bool AllowExplicit) { 4208 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4209 4210 // Most paths end in a failed conversion. 4211 ImplicitConversionSequence ICS; 4212 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4213 4214 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4215 QualType T2 = Init->getType(); 4216 4217 // If the initializer is the address of an overloaded function, try 4218 // to resolve the overloaded function. If all goes well, T2 is the 4219 // type of the resulting function. 4220 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4221 DeclAccessPair Found; 4222 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4223 false, Found)) 4224 T2 = Fn->getType(); 4225 } 4226 4227 // Compute some basic properties of the types and the initializer. 4228 bool isRValRef = DeclType->isRValueReferenceType(); 4229 bool DerivedToBase = false; 4230 bool ObjCConversion = false; 4231 bool ObjCLifetimeConversion = false; 4232 Expr::Classification InitCategory = Init->Classify(S.Context); 4233 Sema::ReferenceCompareResult RefRelationship 4234 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4235 ObjCConversion, ObjCLifetimeConversion); 4236 4237 4238 // C++0x [dcl.init.ref]p5: 4239 // A reference to type "cv1 T1" is initialized by an expression 4240 // of type "cv2 T2" as follows: 4241 4242 // -- If reference is an lvalue reference and the initializer expression 4243 if (!isRValRef) { 4244 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4245 // reference-compatible with "cv2 T2," or 4246 // 4247 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4248 if (InitCategory.isLValue() && 4249 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4250 // C++ [over.ics.ref]p1: 4251 // When a parameter of reference type binds directly (8.5.3) 4252 // to an argument expression, the implicit conversion sequence 4253 // is the identity conversion, unless the argument expression 4254 // has a type that is a derived class of the parameter type, 4255 // in which case the implicit conversion sequence is a 4256 // derived-to-base Conversion (13.3.3.1). 4257 ICS.setStandard(); 4258 ICS.Standard.First = ICK_Identity; 4259 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4260 : ObjCConversion? ICK_Compatible_Conversion 4261 : ICK_Identity; 4262 ICS.Standard.Third = ICK_Identity; 4263 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4264 ICS.Standard.setToType(0, T2); 4265 ICS.Standard.setToType(1, T1); 4266 ICS.Standard.setToType(2, T1); 4267 ICS.Standard.ReferenceBinding = true; 4268 ICS.Standard.DirectBinding = true; 4269 ICS.Standard.IsLvalueReference = !isRValRef; 4270 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4271 ICS.Standard.BindsToRvalue = false; 4272 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4273 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4274 ICS.Standard.CopyConstructor = 0; 4275 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4276 4277 // Nothing more to do: the inaccessibility/ambiguity check for 4278 // derived-to-base conversions is suppressed when we're 4279 // computing the implicit conversion sequence (C++ 4280 // [over.best.ics]p2). 4281 return ICS; 4282 } 4283 4284 // -- has a class type (i.e., T2 is a class type), where T1 is 4285 // not reference-related to T2, and can be implicitly 4286 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4287 // is reference-compatible with "cv3 T3" 92) (this 4288 // conversion is selected by enumerating the applicable 4289 // conversion functions (13.3.1.6) and choosing the best 4290 // one through overload resolution (13.3)), 4291 if (!SuppressUserConversions && T2->isRecordType() && 4292 !S.RequireCompleteType(DeclLoc, T2, 0) && 4293 RefRelationship == Sema::Ref_Incompatible) { 4294 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4295 Init, T2, /*AllowRvalues=*/false, 4296 AllowExplicit)) 4297 return ICS; 4298 } 4299 } 4300 4301 // -- Otherwise, the reference shall be an lvalue reference to a 4302 // non-volatile const type (i.e., cv1 shall be const), or the reference 4303 // shall be an rvalue reference. 4304 // 4305 // We actually handle one oddity of C++ [over.ics.ref] at this 4306 // point, which is that, due to p2 (which short-circuits reference 4307 // binding by only attempting a simple conversion for non-direct 4308 // bindings) and p3's strange wording, we allow a const volatile 4309 // reference to bind to an rvalue. Hence the check for the presence 4310 // of "const" rather than checking for "const" being the only 4311 // qualifier. 4312 // This is also the point where rvalue references and lvalue inits no longer 4313 // go together. 4314 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4315 return ICS; 4316 4317 // -- If the initializer expression 4318 // 4319 // -- is an xvalue, class prvalue, array prvalue or function 4320 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4321 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4322 (InitCategory.isXValue() || 4323 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4324 (InitCategory.isLValue() && T2->isFunctionType()))) { 4325 ICS.setStandard(); 4326 ICS.Standard.First = ICK_Identity; 4327 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4328 : ObjCConversion? ICK_Compatible_Conversion 4329 : ICK_Identity; 4330 ICS.Standard.Third = ICK_Identity; 4331 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4332 ICS.Standard.setToType(0, T2); 4333 ICS.Standard.setToType(1, T1); 4334 ICS.Standard.setToType(2, T1); 4335 ICS.Standard.ReferenceBinding = true; 4336 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4337 // binding unless we're binding to a class prvalue. 4338 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4339 // allow the use of rvalue references in C++98/03 for the benefit of 4340 // standard library implementors; therefore, we need the xvalue check here. 4341 ICS.Standard.DirectBinding = 4342 S.getLangOpts().CPlusPlus11 || 4343 (InitCategory.isPRValue() && !T2->isRecordType()); 4344 ICS.Standard.IsLvalueReference = !isRValRef; 4345 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4346 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4347 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4348 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4349 ICS.Standard.CopyConstructor = 0; 4350 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4351 return ICS; 4352 } 4353 4354 // -- has a class type (i.e., T2 is a class type), where T1 is not 4355 // reference-related to T2, and can be implicitly converted to 4356 // an xvalue, class prvalue, or function lvalue of type 4357 // "cv3 T3", where "cv1 T1" is reference-compatible with 4358 // "cv3 T3", 4359 // 4360 // then the reference is bound to the value of the initializer 4361 // expression in the first case and to the result of the conversion 4362 // in the second case (or, in either case, to an appropriate base 4363 // class subobject). 4364 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4365 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4366 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4367 Init, T2, /*AllowRvalues=*/true, 4368 AllowExplicit)) { 4369 // In the second case, if the reference is an rvalue reference 4370 // and the second standard conversion sequence of the 4371 // user-defined conversion sequence includes an lvalue-to-rvalue 4372 // conversion, the program is ill-formed. 4373 if (ICS.isUserDefined() && isRValRef && 4374 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4375 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4376 4377 return ICS; 4378 } 4379 4380 // -- Otherwise, a temporary of type "cv1 T1" is created and 4381 // initialized from the initializer expression using the 4382 // rules for a non-reference copy initialization (8.5). The 4383 // reference is then bound to the temporary. If T1 is 4384 // reference-related to T2, cv1 must be the same 4385 // cv-qualification as, or greater cv-qualification than, 4386 // cv2; otherwise, the program is ill-formed. 4387 if (RefRelationship == Sema::Ref_Related) { 4388 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4389 // we would be reference-compatible or reference-compatible with 4390 // added qualification. But that wasn't the case, so the reference 4391 // initialization fails. 4392 // 4393 // Note that we only want to check address spaces and cvr-qualifiers here. 4394 // ObjC GC and lifetime qualifiers aren't important. 4395 Qualifiers T1Quals = T1.getQualifiers(); 4396 Qualifiers T2Quals = T2.getQualifiers(); 4397 T1Quals.removeObjCGCAttr(); 4398 T1Quals.removeObjCLifetime(); 4399 T2Quals.removeObjCGCAttr(); 4400 T2Quals.removeObjCLifetime(); 4401 if (!T1Quals.compatiblyIncludes(T2Quals)) 4402 return ICS; 4403 } 4404 4405 // If at least one of the types is a class type, the types are not 4406 // related, and we aren't allowed any user conversions, the 4407 // reference binding fails. This case is important for breaking 4408 // recursion, since TryImplicitConversion below will attempt to 4409 // create a temporary through the use of a copy constructor. 4410 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4411 (T1->isRecordType() || T2->isRecordType())) 4412 return ICS; 4413 4414 // If T1 is reference-related to T2 and the reference is an rvalue 4415 // reference, the initializer expression shall not be an lvalue. 4416 if (RefRelationship >= Sema::Ref_Related && 4417 isRValRef && Init->Classify(S.Context).isLValue()) 4418 return ICS; 4419 4420 // C++ [over.ics.ref]p2: 4421 // When a parameter of reference type is not bound directly to 4422 // an argument expression, the conversion sequence is the one 4423 // required to convert the argument expression to the 4424 // underlying type of the reference according to 4425 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4426 // to copy-initializing a temporary of the underlying type with 4427 // the argument expression. Any difference in top-level 4428 // cv-qualification is subsumed by the initialization itself 4429 // and does not constitute a conversion. 4430 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4431 /*AllowExplicit=*/false, 4432 /*InOverloadResolution=*/false, 4433 /*CStyle=*/false, 4434 /*AllowObjCWritebackConversion=*/false, 4435 /*AllowObjCConversionOnExplicit=*/false); 4436 4437 // Of course, that's still a reference binding. 4438 if (ICS.isStandard()) { 4439 ICS.Standard.ReferenceBinding = true; 4440 ICS.Standard.IsLvalueReference = !isRValRef; 4441 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4442 ICS.Standard.BindsToRvalue = true; 4443 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4444 ICS.Standard.ObjCLifetimeConversionBinding = false; 4445 } else if (ICS.isUserDefined()) { 4446 // Don't allow rvalue references to bind to lvalues. 4447 if (DeclType->isRValueReferenceType()) { 4448 if (const ReferenceType *RefType 4449 = ICS.UserDefined.ConversionFunction->getResultType() 4450 ->getAs<LValueReferenceType>()) { 4451 if (!RefType->getPointeeType()->isFunctionType()) { 4452 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4453 DeclType); 4454 return ICS; 4455 } 4456 } 4457 } 4458 4459 ICS.UserDefined.After.ReferenceBinding = true; 4460 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4461 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4462 ICS.UserDefined.After.BindsToRvalue = true; 4463 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4464 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4465 } 4466 4467 return ICS; 4468 } 4469 4470 static ImplicitConversionSequence 4471 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4472 bool SuppressUserConversions, 4473 bool InOverloadResolution, 4474 bool AllowObjCWritebackConversion, 4475 bool AllowExplicit = false); 4476 4477 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4478 /// initializer list From. 4479 static ImplicitConversionSequence 4480 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4481 bool SuppressUserConversions, 4482 bool InOverloadResolution, 4483 bool AllowObjCWritebackConversion) { 4484 // C++11 [over.ics.list]p1: 4485 // When an argument is an initializer list, it is not an expression and 4486 // special rules apply for converting it to a parameter type. 4487 4488 ImplicitConversionSequence Result; 4489 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4490 4491 // We need a complete type for what follows. Incomplete types can never be 4492 // initialized from init lists. 4493 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4494 return Result; 4495 4496 // C++11 [over.ics.list]p2: 4497 // If the parameter type is std::initializer_list<X> or "array of X" and 4498 // all the elements can be implicitly converted to X, the implicit 4499 // conversion sequence is the worst conversion necessary to convert an 4500 // element of the list to X. 4501 bool toStdInitializerList = false; 4502 QualType X; 4503 if (ToType->isArrayType()) 4504 X = S.Context.getAsArrayType(ToType)->getElementType(); 4505 else 4506 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4507 if (!X.isNull()) { 4508 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4509 Expr *Init = From->getInit(i); 4510 ImplicitConversionSequence ICS = 4511 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4512 InOverloadResolution, 4513 AllowObjCWritebackConversion); 4514 // If a single element isn't convertible, fail. 4515 if (ICS.isBad()) { 4516 Result = ICS; 4517 break; 4518 } 4519 // Otherwise, look for the worst conversion. 4520 if (Result.isBad() || 4521 CompareImplicitConversionSequences(S, ICS, Result) == 4522 ImplicitConversionSequence::Worse) 4523 Result = ICS; 4524 } 4525 4526 // For an empty list, we won't have computed any conversion sequence. 4527 // Introduce the identity conversion sequence. 4528 if (From->getNumInits() == 0) { 4529 Result.setStandard(); 4530 Result.Standard.setAsIdentityConversion(); 4531 Result.Standard.setFromType(ToType); 4532 Result.Standard.setAllToTypes(ToType); 4533 } 4534 4535 Result.setStdInitializerListElement(toStdInitializerList); 4536 return Result; 4537 } 4538 4539 // C++11 [over.ics.list]p3: 4540 // Otherwise, if the parameter is a non-aggregate class X and overload 4541 // resolution chooses a single best constructor [...] the implicit 4542 // conversion sequence is a user-defined conversion sequence. If multiple 4543 // constructors are viable but none is better than the others, the 4544 // implicit conversion sequence is a user-defined conversion sequence. 4545 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4546 // This function can deal with initializer lists. 4547 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4548 /*AllowExplicit=*/false, 4549 InOverloadResolution, /*CStyle=*/false, 4550 AllowObjCWritebackConversion, 4551 /*AllowObjCConversionOnExplicit=*/false); 4552 } 4553 4554 // C++11 [over.ics.list]p4: 4555 // Otherwise, if the parameter has an aggregate type which can be 4556 // initialized from the initializer list [...] the implicit conversion 4557 // sequence is a user-defined conversion sequence. 4558 if (ToType->isAggregateType()) { 4559 // Type is an aggregate, argument is an init list. At this point it comes 4560 // down to checking whether the initialization works. 4561 // FIXME: Find out whether this parameter is consumed or not. 4562 InitializedEntity Entity = 4563 InitializedEntity::InitializeParameter(S.Context, ToType, 4564 /*Consumed=*/false); 4565 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4566 Result.setUserDefined(); 4567 Result.UserDefined.Before.setAsIdentityConversion(); 4568 // Initializer lists don't have a type. 4569 Result.UserDefined.Before.setFromType(QualType()); 4570 Result.UserDefined.Before.setAllToTypes(QualType()); 4571 4572 Result.UserDefined.After.setAsIdentityConversion(); 4573 Result.UserDefined.After.setFromType(ToType); 4574 Result.UserDefined.After.setAllToTypes(ToType); 4575 Result.UserDefined.ConversionFunction = 0; 4576 } 4577 return Result; 4578 } 4579 4580 // C++11 [over.ics.list]p5: 4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4582 if (ToType->isReferenceType()) { 4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4584 // mention initializer lists in any way. So we go by what list- 4585 // initialization would do and try to extrapolate from that. 4586 4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4588 4589 // If the initializer list has a single element that is reference-related 4590 // to the parameter type, we initialize the reference from that. 4591 if (From->getNumInits() == 1) { 4592 Expr *Init = From->getInit(0); 4593 4594 QualType T2 = Init->getType(); 4595 4596 // If the initializer is the address of an overloaded function, try 4597 // to resolve the overloaded function. If all goes well, T2 is the 4598 // type of the resulting function. 4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4600 DeclAccessPair Found; 4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4602 Init, ToType, false, Found)) 4603 T2 = Fn->getType(); 4604 } 4605 4606 // Compute some basic properties of the types and the initializer. 4607 bool dummy1 = false; 4608 bool dummy2 = false; 4609 bool dummy3 = false; 4610 Sema::ReferenceCompareResult RefRelationship 4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4612 dummy2, dummy3); 4613 4614 if (RefRelationship >= Sema::Ref_Related) { 4615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4616 SuppressUserConversions, 4617 /*AllowExplicit=*/false); 4618 } 4619 } 4620 4621 // Otherwise, we bind the reference to a temporary created from the 4622 // initializer list. 4623 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4624 InOverloadResolution, 4625 AllowObjCWritebackConversion); 4626 if (Result.isFailure()) 4627 return Result; 4628 assert(!Result.isEllipsis() && 4629 "Sub-initialization cannot result in ellipsis conversion."); 4630 4631 // Can we even bind to a temporary? 4632 if (ToType->isRValueReferenceType() || 4633 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4635 Result.UserDefined.After; 4636 SCS.ReferenceBinding = true; 4637 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4638 SCS.BindsToRvalue = true; 4639 SCS.BindsToFunctionLvalue = false; 4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4641 SCS.ObjCLifetimeConversionBinding = false; 4642 } else 4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4644 From, ToType); 4645 return Result; 4646 } 4647 4648 // C++11 [over.ics.list]p6: 4649 // Otherwise, if the parameter type is not a class: 4650 if (!ToType->isRecordType()) { 4651 // - if the initializer list has one element, the implicit conversion 4652 // sequence is the one required to convert the element to the 4653 // parameter type. 4654 unsigned NumInits = From->getNumInits(); 4655 if (NumInits == 1) 4656 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4657 SuppressUserConversions, 4658 InOverloadResolution, 4659 AllowObjCWritebackConversion); 4660 // - if the initializer list has no elements, the implicit conversion 4661 // sequence is the identity conversion. 4662 else if (NumInits == 0) { 4663 Result.setStandard(); 4664 Result.Standard.setAsIdentityConversion(); 4665 Result.Standard.setFromType(ToType); 4666 Result.Standard.setAllToTypes(ToType); 4667 } 4668 return Result; 4669 } 4670 4671 // C++11 [over.ics.list]p7: 4672 // In all cases other than those enumerated above, no conversion is possible 4673 return Result; 4674 } 4675 4676 /// TryCopyInitialization - Try to copy-initialize a value of type 4677 /// ToType from the expression From. Return the implicit conversion 4678 /// sequence required to pass this argument, which may be a bad 4679 /// conversion sequence (meaning that the argument cannot be passed to 4680 /// a parameter of this type). If @p SuppressUserConversions, then we 4681 /// do not permit any user-defined conversion sequences. 4682 static ImplicitConversionSequence 4683 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4684 bool SuppressUserConversions, 4685 bool InOverloadResolution, 4686 bool AllowObjCWritebackConversion, 4687 bool AllowExplicit) { 4688 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4689 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4690 InOverloadResolution,AllowObjCWritebackConversion); 4691 4692 if (ToType->isReferenceType()) 4693 return TryReferenceInit(S, From, ToType, 4694 /*FIXME:*/From->getLocStart(), 4695 SuppressUserConversions, 4696 AllowExplicit); 4697 4698 return TryImplicitConversion(S, From, ToType, 4699 SuppressUserConversions, 4700 /*AllowExplicit=*/false, 4701 InOverloadResolution, 4702 /*CStyle=*/false, 4703 AllowObjCWritebackConversion, 4704 /*AllowObjCConversionOnExplicit=*/false); 4705 } 4706 4707 static bool TryCopyInitialization(const CanQualType FromQTy, 4708 const CanQualType ToQTy, 4709 Sema &S, 4710 SourceLocation Loc, 4711 ExprValueKind FromVK) { 4712 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4713 ImplicitConversionSequence ICS = 4714 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4715 4716 return !ICS.isBad(); 4717 } 4718 4719 /// TryObjectArgumentInitialization - Try to initialize the object 4720 /// parameter of the given member function (@c Method) from the 4721 /// expression @p From. 4722 static ImplicitConversionSequence 4723 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4724 Expr::Classification FromClassification, 4725 CXXMethodDecl *Method, 4726 CXXRecordDecl *ActingContext) { 4727 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4728 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4729 // const volatile object. 4730 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4731 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4732 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4733 4734 // Set up the conversion sequence as a "bad" conversion, to allow us 4735 // to exit early. 4736 ImplicitConversionSequence ICS; 4737 4738 // We need to have an object of class type. 4739 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4740 FromType = PT->getPointeeType(); 4741 4742 // When we had a pointer, it's implicitly dereferenced, so we 4743 // better have an lvalue. 4744 assert(FromClassification.isLValue()); 4745 } 4746 4747 assert(FromType->isRecordType()); 4748 4749 // C++0x [over.match.funcs]p4: 4750 // For non-static member functions, the type of the implicit object 4751 // parameter is 4752 // 4753 // - "lvalue reference to cv X" for functions declared without a 4754 // ref-qualifier or with the & ref-qualifier 4755 // - "rvalue reference to cv X" for functions declared with the && 4756 // ref-qualifier 4757 // 4758 // where X is the class of which the function is a member and cv is the 4759 // cv-qualification on the member function declaration. 4760 // 4761 // However, when finding an implicit conversion sequence for the argument, we 4762 // are not allowed to create temporaries or perform user-defined conversions 4763 // (C++ [over.match.funcs]p5). We perform a simplified version of 4764 // reference binding here, that allows class rvalues to bind to 4765 // non-constant references. 4766 4767 // First check the qualifiers. 4768 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4769 if (ImplicitParamType.getCVRQualifiers() 4770 != FromTypeCanon.getLocalCVRQualifiers() && 4771 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4772 ICS.setBad(BadConversionSequence::bad_qualifiers, 4773 FromType, ImplicitParamType); 4774 return ICS; 4775 } 4776 4777 // Check that we have either the same type or a derived type. It 4778 // affects the conversion rank. 4779 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4780 ImplicitConversionKind SecondKind; 4781 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4782 SecondKind = ICK_Identity; 4783 } else if (S.IsDerivedFrom(FromType, ClassType)) 4784 SecondKind = ICK_Derived_To_Base; 4785 else { 4786 ICS.setBad(BadConversionSequence::unrelated_class, 4787 FromType, ImplicitParamType); 4788 return ICS; 4789 } 4790 4791 // Check the ref-qualifier. 4792 switch (Method->getRefQualifier()) { 4793 case RQ_None: 4794 // Do nothing; we don't care about lvalueness or rvalueness. 4795 break; 4796 4797 case RQ_LValue: 4798 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4799 // non-const lvalue reference cannot bind to an rvalue 4800 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4801 ImplicitParamType); 4802 return ICS; 4803 } 4804 break; 4805 4806 case RQ_RValue: 4807 if (!FromClassification.isRValue()) { 4808 // rvalue reference cannot bind to an lvalue 4809 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4810 ImplicitParamType); 4811 return ICS; 4812 } 4813 break; 4814 } 4815 4816 // Success. Mark this as a reference binding. 4817 ICS.setStandard(); 4818 ICS.Standard.setAsIdentityConversion(); 4819 ICS.Standard.Second = SecondKind; 4820 ICS.Standard.setFromType(FromType); 4821 ICS.Standard.setAllToTypes(ImplicitParamType); 4822 ICS.Standard.ReferenceBinding = true; 4823 ICS.Standard.DirectBinding = true; 4824 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4825 ICS.Standard.BindsToFunctionLvalue = false; 4826 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4827 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4828 = (Method->getRefQualifier() == RQ_None); 4829 return ICS; 4830 } 4831 4832 /// PerformObjectArgumentInitialization - Perform initialization of 4833 /// the implicit object parameter for the given Method with the given 4834 /// expression. 4835 ExprResult 4836 Sema::PerformObjectArgumentInitialization(Expr *From, 4837 NestedNameSpecifier *Qualifier, 4838 NamedDecl *FoundDecl, 4839 CXXMethodDecl *Method) { 4840 QualType FromRecordType, DestType; 4841 QualType ImplicitParamRecordType = 4842 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4843 4844 Expr::Classification FromClassification; 4845 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4846 FromRecordType = PT->getPointeeType(); 4847 DestType = Method->getThisType(Context); 4848 FromClassification = Expr::Classification::makeSimpleLValue(); 4849 } else { 4850 FromRecordType = From->getType(); 4851 DestType = ImplicitParamRecordType; 4852 FromClassification = From->Classify(Context); 4853 } 4854 4855 // Note that we always use the true parent context when performing 4856 // the actual argument initialization. 4857 ImplicitConversionSequence ICS 4858 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4859 Method, Method->getParent()); 4860 if (ICS.isBad()) { 4861 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4862 Qualifiers FromQs = FromRecordType.getQualifiers(); 4863 Qualifiers ToQs = DestType.getQualifiers(); 4864 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4865 if (CVR) { 4866 Diag(From->getLocStart(), 4867 diag::err_member_function_call_bad_cvr) 4868 << Method->getDeclName() << FromRecordType << (CVR - 1) 4869 << From->getSourceRange(); 4870 Diag(Method->getLocation(), diag::note_previous_decl) 4871 << Method->getDeclName(); 4872 return ExprError(); 4873 } 4874 } 4875 4876 return Diag(From->getLocStart(), 4877 diag::err_implicit_object_parameter_init) 4878 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4879 } 4880 4881 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4882 ExprResult FromRes = 4883 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4884 if (FromRes.isInvalid()) 4885 return ExprError(); 4886 From = FromRes.take(); 4887 } 4888 4889 if (!Context.hasSameType(From->getType(), DestType)) 4890 From = ImpCastExprToType(From, DestType, CK_NoOp, 4891 From->getValueKind()).take(); 4892 return Owned(From); 4893 } 4894 4895 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4896 /// expression From to bool (C++0x [conv]p3). 4897 static ImplicitConversionSequence 4898 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4899 return TryImplicitConversion(S, From, S.Context.BoolTy, 4900 /*SuppressUserConversions=*/false, 4901 /*AllowExplicit=*/true, 4902 /*InOverloadResolution=*/false, 4903 /*CStyle=*/false, 4904 /*AllowObjCWritebackConversion=*/false, 4905 /*AllowObjCConversionOnExplicit=*/false); 4906 } 4907 4908 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4909 /// of the expression From to bool (C++0x [conv]p3). 4910 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4911 if (checkPlaceholderForOverload(*this, From)) 4912 return ExprError(); 4913 4914 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4915 if (!ICS.isBad()) 4916 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4917 4918 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4919 return Diag(From->getLocStart(), 4920 diag::err_typecheck_bool_condition) 4921 << From->getType() << From->getSourceRange(); 4922 return ExprError(); 4923 } 4924 4925 /// Check that the specified conversion is permitted in a converted constant 4926 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4927 /// is acceptable. 4928 static bool CheckConvertedConstantConversions(Sema &S, 4929 StandardConversionSequence &SCS) { 4930 // Since we know that the target type is an integral or unscoped enumeration 4931 // type, most conversion kinds are impossible. All possible First and Third 4932 // conversions are fine. 4933 switch (SCS.Second) { 4934 case ICK_Identity: 4935 case ICK_Integral_Promotion: 4936 case ICK_Integral_Conversion: 4937 case ICK_Zero_Event_Conversion: 4938 return true; 4939 4940 case ICK_Boolean_Conversion: 4941 // Conversion from an integral or unscoped enumeration type to bool is 4942 // classified as ICK_Boolean_Conversion, but it's also an integral 4943 // conversion, so it's permitted in a converted constant expression. 4944 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4945 SCS.getToType(2)->isBooleanType(); 4946 4947 case ICK_Floating_Integral: 4948 case ICK_Complex_Real: 4949 return false; 4950 4951 case ICK_Lvalue_To_Rvalue: 4952 case ICK_Array_To_Pointer: 4953 case ICK_Function_To_Pointer: 4954 case ICK_NoReturn_Adjustment: 4955 case ICK_Qualification: 4956 case ICK_Compatible_Conversion: 4957 case ICK_Vector_Conversion: 4958 case ICK_Vector_Splat: 4959 case ICK_Derived_To_Base: 4960 case ICK_Pointer_Conversion: 4961 case ICK_Pointer_Member: 4962 case ICK_Block_Pointer_Conversion: 4963 case ICK_Writeback_Conversion: 4964 case ICK_Floating_Promotion: 4965 case ICK_Complex_Promotion: 4966 case ICK_Complex_Conversion: 4967 case ICK_Floating_Conversion: 4968 case ICK_TransparentUnionConversion: 4969 llvm_unreachable("unexpected second conversion kind"); 4970 4971 case ICK_Num_Conversion_Kinds: 4972 break; 4973 } 4974 4975 llvm_unreachable("unknown conversion kind"); 4976 } 4977 4978 /// CheckConvertedConstantExpression - Check that the expression From is a 4979 /// converted constant expression of type T, perform the conversion and produce 4980 /// the converted expression, per C++11 [expr.const]p3. 4981 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4982 llvm::APSInt &Value, 4983 CCEKind CCE) { 4984 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4985 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4986 4987 if (checkPlaceholderForOverload(*this, From)) 4988 return ExprError(); 4989 4990 // C++11 [expr.const]p3 with proposed wording fixes: 4991 // A converted constant expression of type T is a core constant expression, 4992 // implicitly converted to a prvalue of type T, where the converted 4993 // expression is a literal constant expression and the implicit conversion 4994 // sequence contains only user-defined conversions, lvalue-to-rvalue 4995 // conversions, integral promotions, and integral conversions other than 4996 // narrowing conversions. 4997 ImplicitConversionSequence ICS = 4998 TryImplicitConversion(From, T, 4999 /*SuppressUserConversions=*/false, 5000 /*AllowExplicit=*/false, 5001 /*InOverloadResolution=*/false, 5002 /*CStyle=*/false, 5003 /*AllowObjcWritebackConversion=*/false); 5004 StandardConversionSequence *SCS = 0; 5005 switch (ICS.getKind()) { 5006 case ImplicitConversionSequence::StandardConversion: 5007 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 5008 return Diag(From->getLocStart(), 5009 diag::err_typecheck_converted_constant_expression_disallowed) 5010 << From->getType() << From->getSourceRange() << T; 5011 SCS = &ICS.Standard; 5012 break; 5013 case ImplicitConversionSequence::UserDefinedConversion: 5014 // We are converting from class type to an integral or enumeration type, so 5015 // the Before sequence must be trivial. 5016 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 5017 return Diag(From->getLocStart(), 5018 diag::err_typecheck_converted_constant_expression_disallowed) 5019 << From->getType() << From->getSourceRange() << T; 5020 SCS = &ICS.UserDefined.After; 5021 break; 5022 case ImplicitConversionSequence::AmbiguousConversion: 5023 case ImplicitConversionSequence::BadConversion: 5024 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 5025 return Diag(From->getLocStart(), 5026 diag::err_typecheck_converted_constant_expression) 5027 << From->getType() << From->getSourceRange() << T; 5028 return ExprError(); 5029 5030 case ImplicitConversionSequence::EllipsisConversion: 5031 llvm_unreachable("ellipsis conversion in converted constant expression"); 5032 } 5033 5034 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 5035 if (Result.isInvalid()) 5036 return Result; 5037 5038 // Check for a narrowing implicit conversion. 5039 APValue PreNarrowingValue; 5040 QualType PreNarrowingType; 5041 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5042 PreNarrowingType)) { 5043 case NK_Variable_Narrowing: 5044 // Implicit conversion to a narrower type, and the value is not a constant 5045 // expression. We'll diagnose this in a moment. 5046 case NK_Not_Narrowing: 5047 break; 5048 5049 case NK_Constant_Narrowing: 5050 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5051 << CCE << /*Constant*/1 5052 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5053 break; 5054 5055 case NK_Type_Narrowing: 5056 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5057 << CCE << /*Constant*/0 << From->getType() << T; 5058 break; 5059 } 5060 5061 // Check the expression is a constant expression. 5062 SmallVector<PartialDiagnosticAt, 8> Notes; 5063 Expr::EvalResult Eval; 5064 Eval.Diag = &Notes; 5065 5066 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5067 // The expression can't be folded, so we can't keep it at this position in 5068 // the AST. 5069 Result = ExprError(); 5070 } else { 5071 Value = Eval.Val.getInt(); 5072 5073 if (Notes.empty()) { 5074 // It's a constant expression. 5075 return Result; 5076 } 5077 } 5078 5079 // It's not a constant expression. Produce an appropriate diagnostic. 5080 if (Notes.size() == 1 && 5081 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5082 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5083 else { 5084 Diag(From->getLocStart(), diag::err_expr_not_cce) 5085 << CCE << From->getSourceRange(); 5086 for (unsigned I = 0; I < Notes.size(); ++I) 5087 Diag(Notes[I].first, Notes[I].second); 5088 } 5089 return Result; 5090 } 5091 5092 /// dropPointerConversions - If the given standard conversion sequence 5093 /// involves any pointer conversions, remove them. This may change 5094 /// the result type of the conversion sequence. 5095 static void dropPointerConversion(StandardConversionSequence &SCS) { 5096 if (SCS.Second == ICK_Pointer_Conversion) { 5097 SCS.Second = ICK_Identity; 5098 SCS.Third = ICK_Identity; 5099 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5100 } 5101 } 5102 5103 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5104 /// convert the expression From to an Objective-C pointer type. 5105 static ImplicitConversionSequence 5106 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5107 // Do an implicit conversion to 'id'. 5108 QualType Ty = S.Context.getObjCIdType(); 5109 ImplicitConversionSequence ICS 5110 = TryImplicitConversion(S, From, Ty, 5111 // FIXME: Are these flags correct? 5112 /*SuppressUserConversions=*/false, 5113 /*AllowExplicit=*/true, 5114 /*InOverloadResolution=*/false, 5115 /*CStyle=*/false, 5116 /*AllowObjCWritebackConversion=*/false, 5117 /*AllowObjCConversionOnExplicit=*/true); 5118 5119 // Strip off any final conversions to 'id'. 5120 switch (ICS.getKind()) { 5121 case ImplicitConversionSequence::BadConversion: 5122 case ImplicitConversionSequence::AmbiguousConversion: 5123 case ImplicitConversionSequence::EllipsisConversion: 5124 break; 5125 5126 case ImplicitConversionSequence::UserDefinedConversion: 5127 dropPointerConversion(ICS.UserDefined.After); 5128 break; 5129 5130 case ImplicitConversionSequence::StandardConversion: 5131 dropPointerConversion(ICS.Standard); 5132 break; 5133 } 5134 5135 return ICS; 5136 } 5137 5138 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5139 /// conversion of the expression From to an Objective-C pointer type. 5140 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5141 if (checkPlaceholderForOverload(*this, From)) 5142 return ExprError(); 5143 5144 QualType Ty = Context.getObjCIdType(); 5145 ImplicitConversionSequence ICS = 5146 TryContextuallyConvertToObjCPointer(*this, From); 5147 if (!ICS.isBad()) 5148 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5149 return ExprError(); 5150 } 5151 5152 /// Determine whether the provided type is an integral type, or an enumeration 5153 /// type of a permitted flavor. 5154 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5155 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5156 : T->isIntegralOrUnscopedEnumerationType(); 5157 } 5158 5159 static ExprResult 5160 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5161 Sema::ContextualImplicitConverter &Converter, 5162 QualType T, UnresolvedSetImpl &ViableConversions) { 5163 5164 if (Converter.Suppress) 5165 return ExprError(); 5166 5167 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5168 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5169 CXXConversionDecl *Conv = 5170 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5171 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5172 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5173 } 5174 return SemaRef.Owned(From); 5175 } 5176 5177 static bool 5178 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5179 Sema::ContextualImplicitConverter &Converter, 5180 QualType T, bool HadMultipleCandidates, 5181 UnresolvedSetImpl &ExplicitConversions) { 5182 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5183 DeclAccessPair Found = ExplicitConversions[0]; 5184 CXXConversionDecl *Conversion = 5185 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5186 5187 // The user probably meant to invoke the given explicit 5188 // conversion; use it. 5189 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5190 std::string TypeStr; 5191 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5192 5193 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5194 << FixItHint::CreateInsertion(From->getLocStart(), 5195 "static_cast<" + TypeStr + ">(") 5196 << FixItHint::CreateInsertion( 5197 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5198 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5199 5200 // If we aren't in a SFINAE context, build a call to the 5201 // explicit conversion function. 5202 if (SemaRef.isSFINAEContext()) 5203 return true; 5204 5205 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5206 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5207 HadMultipleCandidates); 5208 if (Result.isInvalid()) 5209 return true; 5210 // Record usage of conversion in an implicit cast. 5211 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5212 CK_UserDefinedConversion, Result.get(), 0, 5213 Result.get()->getValueKind()); 5214 } 5215 return false; 5216 } 5217 5218 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5219 Sema::ContextualImplicitConverter &Converter, 5220 QualType T, bool HadMultipleCandidates, 5221 DeclAccessPair &Found) { 5222 CXXConversionDecl *Conversion = 5223 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5224 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5225 5226 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5227 if (!Converter.SuppressConversion) { 5228 if (SemaRef.isSFINAEContext()) 5229 return true; 5230 5231 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5232 << From->getSourceRange(); 5233 } 5234 5235 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5236 HadMultipleCandidates); 5237 if (Result.isInvalid()) 5238 return true; 5239 // Record usage of conversion in an implicit cast. 5240 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5241 CK_UserDefinedConversion, Result.get(), 0, 5242 Result.get()->getValueKind()); 5243 return false; 5244 } 5245 5246 static ExprResult finishContextualImplicitConversion( 5247 Sema &SemaRef, SourceLocation Loc, Expr *From, 5248 Sema::ContextualImplicitConverter &Converter) { 5249 if (!Converter.match(From->getType()) && !Converter.Suppress) 5250 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5251 << From->getSourceRange(); 5252 5253 return SemaRef.DefaultLvalueConversion(From); 5254 } 5255 5256 static void 5257 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5258 UnresolvedSetImpl &ViableConversions, 5259 OverloadCandidateSet &CandidateSet) { 5260 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5261 DeclAccessPair FoundDecl = ViableConversions[I]; 5262 NamedDecl *D = FoundDecl.getDecl(); 5263 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5264 if (isa<UsingShadowDecl>(D)) 5265 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5266 5267 CXXConversionDecl *Conv; 5268 FunctionTemplateDecl *ConvTemplate; 5269 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5270 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5271 else 5272 Conv = cast<CXXConversionDecl>(D); 5273 5274 if (ConvTemplate) 5275 SemaRef.AddTemplateConversionCandidate( 5276 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5277 /*AllowObjCConversionOnExplicit=*/false); 5278 else 5279 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5280 ToType, CandidateSet, 5281 /*AllowObjCConversionOnExplicit=*/false); 5282 } 5283 } 5284 5285 /// \brief Attempt to convert the given expression to a type which is accepted 5286 /// by the given converter. 5287 /// 5288 /// This routine will attempt to convert an expression of class type to a 5289 /// type accepted by the specified converter. In C++11 and before, the class 5290 /// must have a single non-explicit conversion function converting to a matching 5291 /// type. In C++1y, there can be multiple such conversion functions, but only 5292 /// one target type. 5293 /// 5294 /// \param Loc The source location of the construct that requires the 5295 /// conversion. 5296 /// 5297 /// \param From The expression we're converting from. 5298 /// 5299 /// \param Converter Used to control and diagnose the conversion process. 5300 /// 5301 /// \returns The expression, converted to an integral or enumeration type if 5302 /// successful. 5303 ExprResult Sema::PerformContextualImplicitConversion( 5304 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5305 // We can't perform any more checking for type-dependent expressions. 5306 if (From->isTypeDependent()) 5307 return Owned(From); 5308 5309 // Process placeholders immediately. 5310 if (From->hasPlaceholderType()) { 5311 ExprResult result = CheckPlaceholderExpr(From); 5312 if (result.isInvalid()) 5313 return result; 5314 From = result.take(); 5315 } 5316 5317 // If the expression already has a matching type, we're golden. 5318 QualType T = From->getType(); 5319 if (Converter.match(T)) 5320 return DefaultLvalueConversion(From); 5321 5322 // FIXME: Check for missing '()' if T is a function type? 5323 5324 // We can only perform contextual implicit conversions on objects of class 5325 // type. 5326 const RecordType *RecordTy = T->getAs<RecordType>(); 5327 if (!RecordTy || !getLangOpts().CPlusPlus) { 5328 if (!Converter.Suppress) 5329 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5330 return Owned(From); 5331 } 5332 5333 // We must have a complete class type. 5334 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5335 ContextualImplicitConverter &Converter; 5336 Expr *From; 5337 5338 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5339 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5340 5341 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5342 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5343 } 5344 } IncompleteDiagnoser(Converter, From); 5345 5346 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5347 return Owned(From); 5348 5349 // Look for a conversion to an integral or enumeration type. 5350 UnresolvedSet<4> 5351 ViableConversions; // These are *potentially* viable in C++1y. 5352 UnresolvedSet<4> ExplicitConversions; 5353 std::pair<CXXRecordDecl::conversion_iterator, 5354 CXXRecordDecl::conversion_iterator> Conversions = 5355 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5356 5357 bool HadMultipleCandidates = 5358 (std::distance(Conversions.first, Conversions.second) > 1); 5359 5360 // To check that there is only one target type, in C++1y: 5361 QualType ToType; 5362 bool HasUniqueTargetType = true; 5363 5364 // Collect explicit or viable (potentially in C++1y) conversions. 5365 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5366 E = Conversions.second; 5367 I != E; ++I) { 5368 NamedDecl *D = (*I)->getUnderlyingDecl(); 5369 CXXConversionDecl *Conversion; 5370 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5371 if (ConvTemplate) { 5372 if (getLangOpts().CPlusPlus1y) 5373 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5374 else 5375 continue; // C++11 does not consider conversion operator templates(?). 5376 } else 5377 Conversion = cast<CXXConversionDecl>(D); 5378 5379 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5380 "Conversion operator templates are considered potentially " 5381 "viable in C++1y"); 5382 5383 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5384 if (Converter.match(CurToType) || ConvTemplate) { 5385 5386 if (Conversion->isExplicit()) { 5387 // FIXME: For C++1y, do we need this restriction? 5388 // cf. diagnoseNoViableConversion() 5389 if (!ConvTemplate) 5390 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5391 } else { 5392 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5393 if (ToType.isNull()) 5394 ToType = CurToType.getUnqualifiedType(); 5395 else if (HasUniqueTargetType && 5396 (CurToType.getUnqualifiedType() != ToType)) 5397 HasUniqueTargetType = false; 5398 } 5399 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5400 } 5401 } 5402 } 5403 5404 if (getLangOpts().CPlusPlus1y) { 5405 // C++1y [conv]p6: 5406 // ... An expression e of class type E appearing in such a context 5407 // is said to be contextually implicitly converted to a specified 5408 // type T and is well-formed if and only if e can be implicitly 5409 // converted to a type T that is determined as follows: E is searched 5410 // for conversion functions whose return type is cv T or reference to 5411 // cv T such that T is allowed by the context. There shall be 5412 // exactly one such T. 5413 5414 // If no unique T is found: 5415 if (ToType.isNull()) { 5416 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5417 HadMultipleCandidates, 5418 ExplicitConversions)) 5419 return ExprError(); 5420 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5421 } 5422 5423 // If more than one unique Ts are found: 5424 if (!HasUniqueTargetType) 5425 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5426 ViableConversions); 5427 5428 // If one unique T is found: 5429 // First, build a candidate set from the previously recorded 5430 // potentially viable conversions. 5431 OverloadCandidateSet CandidateSet(Loc); 5432 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5433 CandidateSet); 5434 5435 // Then, perform overload resolution over the candidate set. 5436 OverloadCandidateSet::iterator Best; 5437 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5438 case OR_Success: { 5439 // Apply this conversion. 5440 DeclAccessPair Found = 5441 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5442 if (recordConversion(*this, Loc, From, Converter, T, 5443 HadMultipleCandidates, Found)) 5444 return ExprError(); 5445 break; 5446 } 5447 case OR_Ambiguous: 5448 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5449 ViableConversions); 5450 case OR_No_Viable_Function: 5451 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5452 HadMultipleCandidates, 5453 ExplicitConversions)) 5454 return ExprError(); 5455 // fall through 'OR_Deleted' case. 5456 case OR_Deleted: 5457 // We'll complain below about a non-integral condition type. 5458 break; 5459 } 5460 } else { 5461 switch (ViableConversions.size()) { 5462 case 0: { 5463 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5464 HadMultipleCandidates, 5465 ExplicitConversions)) 5466 return ExprError(); 5467 5468 // We'll complain below about a non-integral condition type. 5469 break; 5470 } 5471 case 1: { 5472 // Apply this conversion. 5473 DeclAccessPair Found = ViableConversions[0]; 5474 if (recordConversion(*this, Loc, From, Converter, T, 5475 HadMultipleCandidates, Found)) 5476 return ExprError(); 5477 break; 5478 } 5479 default: 5480 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5481 ViableConversions); 5482 } 5483 } 5484 5485 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5486 } 5487 5488 /// AddOverloadCandidate - Adds the given function to the set of 5489 /// candidate functions, using the given function call arguments. If 5490 /// @p SuppressUserConversions, then don't allow user-defined 5491 /// conversions via constructors or conversion operators. 5492 /// 5493 /// \param PartialOverloading true if we are performing "partial" overloading 5494 /// based on an incomplete set of function arguments. This feature is used by 5495 /// code completion. 5496 void 5497 Sema::AddOverloadCandidate(FunctionDecl *Function, 5498 DeclAccessPair FoundDecl, 5499 ArrayRef<Expr *> Args, 5500 OverloadCandidateSet &CandidateSet, 5501 bool SuppressUserConversions, 5502 bool PartialOverloading, 5503 bool AllowExplicit) { 5504 const FunctionProtoType *Proto 5505 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5506 assert(Proto && "Functions without a prototype cannot be overloaded"); 5507 assert(!Function->getDescribedFunctionTemplate() && 5508 "Use AddTemplateOverloadCandidate for function templates"); 5509 5510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5511 if (!isa<CXXConstructorDecl>(Method)) { 5512 // If we get here, it's because we're calling a member function 5513 // that is named without a member access expression (e.g., 5514 // "this->f") that was either written explicitly or created 5515 // implicitly. This can happen with a qualified call to a member 5516 // function, e.g., X::f(). We use an empty type for the implied 5517 // object argument (C++ [over.call.func]p3), and the acting context 5518 // is irrelevant. 5519 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5520 QualType(), Expr::Classification::makeSimpleLValue(), 5521 Args, CandidateSet, SuppressUserConversions); 5522 return; 5523 } 5524 // We treat a constructor like a non-member function, since its object 5525 // argument doesn't participate in overload resolution. 5526 } 5527 5528 if (!CandidateSet.isNewCandidate(Function)) 5529 return; 5530 5531 // C++11 [class.copy]p11: [DR1402] 5532 // A defaulted move constructor that is defined as deleted is ignored by 5533 // overload resolution. 5534 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5535 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5536 Constructor->isMoveConstructor()) 5537 return; 5538 5539 // Overload resolution is always an unevaluated context. 5540 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5541 5542 if (Constructor) { 5543 // C++ [class.copy]p3: 5544 // A member function template is never instantiated to perform the copy 5545 // of a class object to an object of its class type. 5546 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5547 if (Args.size() == 1 && 5548 Constructor->isSpecializationCopyingObject() && 5549 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5550 IsDerivedFrom(Args[0]->getType(), ClassType))) 5551 return; 5552 } 5553 5554 // Add this candidate 5555 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5556 Candidate.FoundDecl = FoundDecl; 5557 Candidate.Function = Function; 5558 Candidate.Viable = true; 5559 Candidate.IsSurrogate = false; 5560 Candidate.IgnoreObjectArgument = false; 5561 Candidate.ExplicitCallArguments = Args.size(); 5562 5563 unsigned NumArgsInProto = Proto->getNumArgs(); 5564 5565 // (C++ 13.3.2p2): A candidate function having fewer than m 5566 // parameters is viable only if it has an ellipsis in its parameter 5567 // list (8.3.5). 5568 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5569 !Proto->isVariadic()) { 5570 Candidate.Viable = false; 5571 Candidate.FailureKind = ovl_fail_too_many_arguments; 5572 return; 5573 } 5574 5575 // (C++ 13.3.2p2): A candidate function having more than m parameters 5576 // is viable only if the (m+1)st parameter has a default argument 5577 // (8.3.6). For the purposes of overload resolution, the 5578 // parameter list is truncated on the right, so that there are 5579 // exactly m parameters. 5580 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5581 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5582 // Not enough arguments. 5583 Candidate.Viable = false; 5584 Candidate.FailureKind = ovl_fail_too_few_arguments; 5585 return; 5586 } 5587 5588 // (CUDA B.1): Check for invalid calls between targets. 5589 if (getLangOpts().CUDA) 5590 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5591 if (CheckCUDATarget(Caller, Function)) { 5592 Candidate.Viable = false; 5593 Candidate.FailureKind = ovl_fail_bad_target; 5594 return; 5595 } 5596 5597 // Determine the implicit conversion sequences for each of the 5598 // arguments. 5599 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5600 if (ArgIdx < NumArgsInProto) { 5601 // (C++ 13.3.2p3): for F to be a viable function, there shall 5602 // exist for each argument an implicit conversion sequence 5603 // (13.3.3.1) that converts that argument to the corresponding 5604 // parameter of F. 5605 QualType ParamType = Proto->getArgType(ArgIdx); 5606 Candidate.Conversions[ArgIdx] 5607 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5608 SuppressUserConversions, 5609 /*InOverloadResolution=*/true, 5610 /*AllowObjCWritebackConversion=*/ 5611 getLangOpts().ObjCAutoRefCount, 5612 AllowExplicit); 5613 if (Candidate.Conversions[ArgIdx].isBad()) { 5614 Candidate.Viable = false; 5615 Candidate.FailureKind = ovl_fail_bad_conversion; 5616 return; 5617 } 5618 } else { 5619 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5620 // argument for which there is no corresponding parameter is 5621 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5622 Candidate.Conversions[ArgIdx].setEllipsis(); 5623 } 5624 } 5625 5626 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5627 Candidate.Viable = false; 5628 Candidate.FailureKind = ovl_fail_enable_if; 5629 Candidate.DeductionFailure.Data = FailedAttr; 5630 return; 5631 } 5632 } 5633 5634 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5635 5636 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5637 bool MissingImplicitThis) { 5638 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5639 // we need to find the first failing one. 5640 if (!Function->hasAttrs()) 5641 return 0; 5642 AttrVec Attrs = Function->getAttrs(); 5643 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5644 IsNotEnableIfAttr); 5645 if (Attrs.begin() == E) 5646 return 0; 5647 std::reverse(Attrs.begin(), E); 5648 5649 SFINAETrap Trap(*this); 5650 5651 // Convert the arguments. 5652 SmallVector<Expr *, 16> ConvertedArgs; 5653 bool InitializationFailed = false; 5654 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5655 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5656 !cast<CXXMethodDecl>(Function)->isStatic()) { 5657 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5658 ExprResult R = 5659 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 5660 Method, Method); 5661 if (R.isInvalid()) { 5662 InitializationFailed = true; 5663 break; 5664 } 5665 ConvertedArgs.push_back(R.take()); 5666 } else { 5667 ExprResult R = 5668 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5669 Context, 5670 Function->getParamDecl(i)), 5671 SourceLocation(), 5672 Args[i]); 5673 if (R.isInvalid()) { 5674 InitializationFailed = true; 5675 break; 5676 } 5677 ConvertedArgs.push_back(R.take()); 5678 } 5679 } 5680 5681 if (InitializationFailed || Trap.hasErrorOccurred()) 5682 return cast<EnableIfAttr>(Attrs[0]); 5683 5684 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5685 APValue Result; 5686 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5687 if (!EIA->getCond()->EvaluateWithSubstitution( 5688 Result, Context, Function, 5689 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(), 5690 ConvertedArgs.size())) || 5691 !Result.isInt() || !Result.getInt().getBoolValue()) { 5692 return EIA; 5693 } 5694 } 5695 return 0; 5696 } 5697 5698 /// \brief Add all of the function declarations in the given function set to 5699 /// the overload candidate set. 5700 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5701 ArrayRef<Expr *> Args, 5702 OverloadCandidateSet& CandidateSet, 5703 bool SuppressUserConversions, 5704 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5705 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5706 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5707 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5708 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5709 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5710 cast<CXXMethodDecl>(FD)->getParent(), 5711 Args[0]->getType(), Args[0]->Classify(Context), 5712 Args.slice(1), CandidateSet, 5713 SuppressUserConversions); 5714 else 5715 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5716 SuppressUserConversions); 5717 } else { 5718 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5719 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5720 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5721 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5722 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5723 ExplicitTemplateArgs, 5724 Args[0]->getType(), 5725 Args[0]->Classify(Context), Args.slice(1), 5726 CandidateSet, SuppressUserConversions); 5727 else 5728 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5729 ExplicitTemplateArgs, Args, 5730 CandidateSet, SuppressUserConversions); 5731 } 5732 } 5733 } 5734 5735 /// AddMethodCandidate - Adds a named decl (which is some kind of 5736 /// method) as a method candidate to the given overload set. 5737 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5738 QualType ObjectType, 5739 Expr::Classification ObjectClassification, 5740 ArrayRef<Expr *> Args, 5741 OverloadCandidateSet& CandidateSet, 5742 bool SuppressUserConversions) { 5743 NamedDecl *Decl = FoundDecl.getDecl(); 5744 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5745 5746 if (isa<UsingShadowDecl>(Decl)) 5747 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5748 5749 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5750 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5751 "Expected a member function template"); 5752 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5753 /*ExplicitArgs*/ 0, 5754 ObjectType, ObjectClassification, 5755 Args, CandidateSet, 5756 SuppressUserConversions); 5757 } else { 5758 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5759 ObjectType, ObjectClassification, 5760 Args, 5761 CandidateSet, SuppressUserConversions); 5762 } 5763 } 5764 5765 /// AddMethodCandidate - Adds the given C++ member function to the set 5766 /// of candidate functions, using the given function call arguments 5767 /// and the object argument (@c Object). For example, in a call 5768 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5769 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5770 /// allow user-defined conversions via constructors or conversion 5771 /// operators. 5772 void 5773 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5774 CXXRecordDecl *ActingContext, QualType ObjectType, 5775 Expr::Classification ObjectClassification, 5776 ArrayRef<Expr *> Args, 5777 OverloadCandidateSet &CandidateSet, 5778 bool SuppressUserConversions) { 5779 const FunctionProtoType *Proto 5780 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5781 assert(Proto && "Methods without a prototype cannot be overloaded"); 5782 assert(!isa<CXXConstructorDecl>(Method) && 5783 "Use AddOverloadCandidate for constructors"); 5784 5785 if (!CandidateSet.isNewCandidate(Method)) 5786 return; 5787 5788 // C++11 [class.copy]p23: [DR1402] 5789 // A defaulted move assignment operator that is defined as deleted is 5790 // ignored by overload resolution. 5791 if (Method->isDefaulted() && Method->isDeleted() && 5792 Method->isMoveAssignmentOperator()) 5793 return; 5794 5795 // Overload resolution is always an unevaluated context. 5796 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5797 5798 // Add this candidate 5799 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5800 Candidate.FoundDecl = FoundDecl; 5801 Candidate.Function = Method; 5802 Candidate.IsSurrogate = false; 5803 Candidate.IgnoreObjectArgument = false; 5804 Candidate.ExplicitCallArguments = Args.size(); 5805 5806 unsigned NumArgsInProto = Proto->getNumArgs(); 5807 5808 // (C++ 13.3.2p2): A candidate function having fewer than m 5809 // parameters is viable only if it has an ellipsis in its parameter 5810 // list (8.3.5). 5811 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5812 Candidate.Viable = false; 5813 Candidate.FailureKind = ovl_fail_too_many_arguments; 5814 return; 5815 } 5816 5817 // (C++ 13.3.2p2): A candidate function having more than m parameters 5818 // is viable only if the (m+1)st parameter has a default argument 5819 // (8.3.6). For the purposes of overload resolution, the 5820 // parameter list is truncated on the right, so that there are 5821 // exactly m parameters. 5822 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5823 if (Args.size() < MinRequiredArgs) { 5824 // Not enough arguments. 5825 Candidate.Viable = false; 5826 Candidate.FailureKind = ovl_fail_too_few_arguments; 5827 return; 5828 } 5829 5830 Candidate.Viable = true; 5831 5832 if (Method->isStatic() || ObjectType.isNull()) 5833 // The implicit object argument is ignored. 5834 Candidate.IgnoreObjectArgument = true; 5835 else { 5836 // Determine the implicit conversion sequence for the object 5837 // parameter. 5838 Candidate.Conversions[0] 5839 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5840 Method, ActingContext); 5841 if (Candidate.Conversions[0].isBad()) { 5842 Candidate.Viable = false; 5843 Candidate.FailureKind = ovl_fail_bad_conversion; 5844 return; 5845 } 5846 } 5847 5848 // Determine the implicit conversion sequences for each of the 5849 // arguments. 5850 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5851 if (ArgIdx < NumArgsInProto) { 5852 // (C++ 13.3.2p3): for F to be a viable function, there shall 5853 // exist for each argument an implicit conversion sequence 5854 // (13.3.3.1) that converts that argument to the corresponding 5855 // parameter of F. 5856 QualType ParamType = Proto->getArgType(ArgIdx); 5857 Candidate.Conversions[ArgIdx + 1] 5858 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5859 SuppressUserConversions, 5860 /*InOverloadResolution=*/true, 5861 /*AllowObjCWritebackConversion=*/ 5862 getLangOpts().ObjCAutoRefCount); 5863 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5864 Candidate.Viable = false; 5865 Candidate.FailureKind = ovl_fail_bad_conversion; 5866 return; 5867 } 5868 } else { 5869 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5870 // argument for which there is no corresponding parameter is 5871 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 5872 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5873 } 5874 } 5875 5876 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 5877 Candidate.Viable = false; 5878 Candidate.FailureKind = ovl_fail_enable_if; 5879 Candidate.DeductionFailure.Data = FailedAttr; 5880 return; 5881 } 5882 } 5883 5884 /// \brief Add a C++ member function template as a candidate to the candidate 5885 /// set, using template argument deduction to produce an appropriate member 5886 /// function template specialization. 5887 void 5888 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5889 DeclAccessPair FoundDecl, 5890 CXXRecordDecl *ActingContext, 5891 TemplateArgumentListInfo *ExplicitTemplateArgs, 5892 QualType ObjectType, 5893 Expr::Classification ObjectClassification, 5894 ArrayRef<Expr *> Args, 5895 OverloadCandidateSet& CandidateSet, 5896 bool SuppressUserConversions) { 5897 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5898 return; 5899 5900 // C++ [over.match.funcs]p7: 5901 // In each case where a candidate is a function template, candidate 5902 // function template specializations are generated using template argument 5903 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5904 // candidate functions in the usual way.113) A given name can refer to one 5905 // or more function templates and also to a set of overloaded non-template 5906 // functions. In such a case, the candidate functions generated from each 5907 // function template are combined with the set of non-template candidate 5908 // functions. 5909 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5910 FunctionDecl *Specialization = 0; 5911 if (TemplateDeductionResult Result 5912 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5913 Specialization, Info)) { 5914 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5915 Candidate.FoundDecl = FoundDecl; 5916 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5917 Candidate.Viable = false; 5918 Candidate.FailureKind = ovl_fail_bad_deduction; 5919 Candidate.IsSurrogate = false; 5920 Candidate.IgnoreObjectArgument = false; 5921 Candidate.ExplicitCallArguments = Args.size(); 5922 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5923 Info); 5924 return; 5925 } 5926 5927 // Add the function template specialization produced by template argument 5928 // deduction as a candidate. 5929 assert(Specialization && "Missing member function template specialization?"); 5930 assert(isa<CXXMethodDecl>(Specialization) && 5931 "Specialization is not a member function?"); 5932 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5933 ActingContext, ObjectType, ObjectClassification, Args, 5934 CandidateSet, SuppressUserConversions); 5935 } 5936 5937 /// \brief Add a C++ function template specialization as a candidate 5938 /// in the candidate set, using template argument deduction to produce 5939 /// an appropriate function template specialization. 5940 void 5941 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5942 DeclAccessPair FoundDecl, 5943 TemplateArgumentListInfo *ExplicitTemplateArgs, 5944 ArrayRef<Expr *> Args, 5945 OverloadCandidateSet& CandidateSet, 5946 bool SuppressUserConversions) { 5947 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5948 return; 5949 5950 // C++ [over.match.funcs]p7: 5951 // In each case where a candidate is a function template, candidate 5952 // function template specializations are generated using template argument 5953 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5954 // candidate functions in the usual way.113) A given name can refer to one 5955 // or more function templates and also to a set of overloaded non-template 5956 // functions. In such a case, the candidate functions generated from each 5957 // function template are combined with the set of non-template candidate 5958 // functions. 5959 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5960 FunctionDecl *Specialization = 0; 5961 if (TemplateDeductionResult Result 5962 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5963 Specialization, Info)) { 5964 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5965 Candidate.FoundDecl = FoundDecl; 5966 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5967 Candidate.Viable = false; 5968 Candidate.FailureKind = ovl_fail_bad_deduction; 5969 Candidate.IsSurrogate = false; 5970 Candidate.IgnoreObjectArgument = false; 5971 Candidate.ExplicitCallArguments = Args.size(); 5972 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5973 Info); 5974 return; 5975 } 5976 5977 // Add the function template specialization produced by template argument 5978 // deduction as a candidate. 5979 assert(Specialization && "Missing function template specialization?"); 5980 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5981 SuppressUserConversions); 5982 } 5983 5984 /// Determine whether this is an allowable conversion from the result 5985 /// of an explicit conversion operator to the expected type, per C++ 5986 /// [over.match.conv]p1 and [over.match.ref]p1. 5987 /// 5988 /// \param ConvType The return type of the conversion function. 5989 /// 5990 /// \param ToType The type we are converting to. 5991 /// 5992 /// \param AllowObjCPointerConversion Allow a conversion from one 5993 /// Objective-C pointer to another. 5994 /// 5995 /// \returns true if the conversion is allowable, false otherwise. 5996 static bool isAllowableExplicitConversion(Sema &S, 5997 QualType ConvType, QualType ToType, 5998 bool AllowObjCPointerConversion) { 5999 QualType ToNonRefType = ToType.getNonReferenceType(); 6000 6001 // Easy case: the types are the same. 6002 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6003 return true; 6004 6005 // Allow qualification conversions. 6006 bool ObjCLifetimeConversion; 6007 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6008 ObjCLifetimeConversion)) 6009 return true; 6010 6011 // If we're not allowed to consider Objective-C pointer conversions, 6012 // we're done. 6013 if (!AllowObjCPointerConversion) 6014 return false; 6015 6016 // Is this an Objective-C pointer conversion? 6017 bool IncompatibleObjC = false; 6018 QualType ConvertedType; 6019 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6020 IncompatibleObjC); 6021 } 6022 6023 /// AddConversionCandidate - Add a C++ conversion function as a 6024 /// candidate in the candidate set (C++ [over.match.conv], 6025 /// C++ [over.match.copy]). From is the expression we're converting from, 6026 /// and ToType is the type that we're eventually trying to convert to 6027 /// (which may or may not be the same type as the type that the 6028 /// conversion function produces). 6029 void 6030 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6031 DeclAccessPair FoundDecl, 6032 CXXRecordDecl *ActingContext, 6033 Expr *From, QualType ToType, 6034 OverloadCandidateSet& CandidateSet, 6035 bool AllowObjCConversionOnExplicit) { 6036 assert(!Conversion->getDescribedFunctionTemplate() && 6037 "Conversion function templates use AddTemplateConversionCandidate"); 6038 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6039 if (!CandidateSet.isNewCandidate(Conversion)) 6040 return; 6041 6042 // If the conversion function has an undeduced return type, trigger its 6043 // deduction now. 6044 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 6045 if (DeduceReturnType(Conversion, From->getExprLoc())) 6046 return; 6047 ConvType = Conversion->getConversionType().getNonReferenceType(); 6048 } 6049 6050 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6051 // operator is only a candidate if its return type is the target type or 6052 // can be converted to the target type with a qualification conversion. 6053 if (Conversion->isExplicit() && 6054 !isAllowableExplicitConversion(*this, ConvType, ToType, 6055 AllowObjCConversionOnExplicit)) 6056 return; 6057 6058 // Overload resolution is always an unevaluated context. 6059 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6060 6061 // Add this candidate 6062 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6063 Candidate.FoundDecl = FoundDecl; 6064 Candidate.Function = Conversion; 6065 Candidate.IsSurrogate = false; 6066 Candidate.IgnoreObjectArgument = false; 6067 Candidate.FinalConversion.setAsIdentityConversion(); 6068 Candidate.FinalConversion.setFromType(ConvType); 6069 Candidate.FinalConversion.setAllToTypes(ToType); 6070 Candidate.Viable = true; 6071 Candidate.ExplicitCallArguments = 1; 6072 6073 // C++ [over.match.funcs]p4: 6074 // For conversion functions, the function is considered to be a member of 6075 // the class of the implicit implied object argument for the purpose of 6076 // defining the type of the implicit object parameter. 6077 // 6078 // Determine the implicit conversion sequence for the implicit 6079 // object parameter. 6080 QualType ImplicitParamType = From->getType(); 6081 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6082 ImplicitParamType = FromPtrType->getPointeeType(); 6083 CXXRecordDecl *ConversionContext 6084 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6085 6086 Candidate.Conversions[0] 6087 = TryObjectArgumentInitialization(*this, From->getType(), 6088 From->Classify(Context), 6089 Conversion, ConversionContext); 6090 6091 if (Candidate.Conversions[0].isBad()) { 6092 Candidate.Viable = false; 6093 Candidate.FailureKind = ovl_fail_bad_conversion; 6094 return; 6095 } 6096 6097 // We won't go through a user-defined type conversion function to convert a 6098 // derived to base as such conversions are given Conversion Rank. They only 6099 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6100 QualType FromCanon 6101 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6102 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6103 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6104 Candidate.Viable = false; 6105 Candidate.FailureKind = ovl_fail_trivial_conversion; 6106 return; 6107 } 6108 6109 // To determine what the conversion from the result of calling the 6110 // conversion function to the type we're eventually trying to 6111 // convert to (ToType), we need to synthesize a call to the 6112 // conversion function and attempt copy initialization from it. This 6113 // makes sure that we get the right semantics with respect to 6114 // lvalues/rvalues and the type. Fortunately, we can allocate this 6115 // call on the stack and we don't need its arguments to be 6116 // well-formed. 6117 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6118 VK_LValue, From->getLocStart()); 6119 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6120 Context.getPointerType(Conversion->getType()), 6121 CK_FunctionToPointerDecay, 6122 &ConversionRef, VK_RValue); 6123 6124 QualType ConversionType = Conversion->getConversionType(); 6125 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6126 Candidate.Viable = false; 6127 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6128 return; 6129 } 6130 6131 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6132 6133 // Note that it is safe to allocate CallExpr on the stack here because 6134 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6135 // allocator). 6136 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6137 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6138 From->getLocStart()); 6139 ImplicitConversionSequence ICS = 6140 TryCopyInitialization(*this, &Call, ToType, 6141 /*SuppressUserConversions=*/true, 6142 /*InOverloadResolution=*/false, 6143 /*AllowObjCWritebackConversion=*/false); 6144 6145 switch (ICS.getKind()) { 6146 case ImplicitConversionSequence::StandardConversion: 6147 Candidate.FinalConversion = ICS.Standard; 6148 6149 // C++ [over.ics.user]p3: 6150 // If the user-defined conversion is specified by a specialization of a 6151 // conversion function template, the second standard conversion sequence 6152 // shall have exact match rank. 6153 if (Conversion->getPrimaryTemplate() && 6154 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6155 Candidate.Viable = false; 6156 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6157 return; 6158 } 6159 6160 // C++0x [dcl.init.ref]p5: 6161 // In the second case, if the reference is an rvalue reference and 6162 // the second standard conversion sequence of the user-defined 6163 // conversion sequence includes an lvalue-to-rvalue conversion, the 6164 // program is ill-formed. 6165 if (ToType->isRValueReferenceType() && 6166 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6167 Candidate.Viable = false; 6168 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6169 return; 6170 } 6171 break; 6172 6173 case ImplicitConversionSequence::BadConversion: 6174 Candidate.Viable = false; 6175 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6176 return; 6177 6178 default: 6179 llvm_unreachable( 6180 "Can only end up with a standard conversion sequence or failure"); 6181 } 6182 6183 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6184 Candidate.Viable = false; 6185 Candidate.FailureKind = ovl_fail_enable_if; 6186 Candidate.DeductionFailure.Data = FailedAttr; 6187 return; 6188 } 6189 } 6190 6191 /// \brief Adds a conversion function template specialization 6192 /// candidate to the overload set, using template argument deduction 6193 /// to deduce the template arguments of the conversion function 6194 /// template from the type that we are converting to (C++ 6195 /// [temp.deduct.conv]). 6196 void 6197 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6198 DeclAccessPair FoundDecl, 6199 CXXRecordDecl *ActingDC, 6200 Expr *From, QualType ToType, 6201 OverloadCandidateSet &CandidateSet, 6202 bool AllowObjCConversionOnExplicit) { 6203 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6204 "Only conversion function templates permitted here"); 6205 6206 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6207 return; 6208 6209 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6210 CXXConversionDecl *Specialization = 0; 6211 if (TemplateDeductionResult Result 6212 = DeduceTemplateArguments(FunctionTemplate, ToType, 6213 Specialization, Info)) { 6214 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6215 Candidate.FoundDecl = FoundDecl; 6216 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6217 Candidate.Viable = false; 6218 Candidate.FailureKind = ovl_fail_bad_deduction; 6219 Candidate.IsSurrogate = false; 6220 Candidate.IgnoreObjectArgument = false; 6221 Candidate.ExplicitCallArguments = 1; 6222 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6223 Info); 6224 return; 6225 } 6226 6227 // Add the conversion function template specialization produced by 6228 // template argument deduction as a candidate. 6229 assert(Specialization && "Missing function template specialization?"); 6230 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6231 CandidateSet, AllowObjCConversionOnExplicit); 6232 } 6233 6234 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6235 /// converts the given @c Object to a function pointer via the 6236 /// conversion function @c Conversion, and then attempts to call it 6237 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6238 /// the type of function that we'll eventually be calling. 6239 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6240 DeclAccessPair FoundDecl, 6241 CXXRecordDecl *ActingContext, 6242 const FunctionProtoType *Proto, 6243 Expr *Object, 6244 ArrayRef<Expr *> Args, 6245 OverloadCandidateSet& CandidateSet) { 6246 if (!CandidateSet.isNewCandidate(Conversion)) 6247 return; 6248 6249 // Overload resolution is always an unevaluated context. 6250 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6251 6252 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6253 Candidate.FoundDecl = FoundDecl; 6254 Candidate.Function = 0; 6255 Candidate.Surrogate = Conversion; 6256 Candidate.Viable = true; 6257 Candidate.IsSurrogate = true; 6258 Candidate.IgnoreObjectArgument = false; 6259 Candidate.ExplicitCallArguments = Args.size(); 6260 6261 // Determine the implicit conversion sequence for the implicit 6262 // object parameter. 6263 ImplicitConversionSequence ObjectInit 6264 = TryObjectArgumentInitialization(*this, Object->getType(), 6265 Object->Classify(Context), 6266 Conversion, ActingContext); 6267 if (ObjectInit.isBad()) { 6268 Candidate.Viable = false; 6269 Candidate.FailureKind = ovl_fail_bad_conversion; 6270 Candidate.Conversions[0] = ObjectInit; 6271 return; 6272 } 6273 6274 // The first conversion is actually a user-defined conversion whose 6275 // first conversion is ObjectInit's standard conversion (which is 6276 // effectively a reference binding). Record it as such. 6277 Candidate.Conversions[0].setUserDefined(); 6278 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6279 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6280 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6281 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6282 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6283 Candidate.Conversions[0].UserDefined.After 6284 = Candidate.Conversions[0].UserDefined.Before; 6285 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6286 6287 // Find the 6288 unsigned NumArgsInProto = Proto->getNumArgs(); 6289 6290 // (C++ 13.3.2p2): A candidate function having fewer than m 6291 // parameters is viable only if it has an ellipsis in its parameter 6292 // list (8.3.5). 6293 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6294 Candidate.Viable = false; 6295 Candidate.FailureKind = ovl_fail_too_many_arguments; 6296 return; 6297 } 6298 6299 // Function types don't have any default arguments, so just check if 6300 // we have enough arguments. 6301 if (Args.size() < NumArgsInProto) { 6302 // Not enough arguments. 6303 Candidate.Viable = false; 6304 Candidate.FailureKind = ovl_fail_too_few_arguments; 6305 return; 6306 } 6307 6308 // Determine the implicit conversion sequences for each of the 6309 // arguments. 6310 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6311 if (ArgIdx < NumArgsInProto) { 6312 // (C++ 13.3.2p3): for F to be a viable function, there shall 6313 // exist for each argument an implicit conversion sequence 6314 // (13.3.3.1) that converts that argument to the corresponding 6315 // parameter of F. 6316 QualType ParamType = Proto->getArgType(ArgIdx); 6317 Candidate.Conversions[ArgIdx + 1] 6318 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6319 /*SuppressUserConversions=*/false, 6320 /*InOverloadResolution=*/false, 6321 /*AllowObjCWritebackConversion=*/ 6322 getLangOpts().ObjCAutoRefCount); 6323 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6324 Candidate.Viable = false; 6325 Candidate.FailureKind = ovl_fail_bad_conversion; 6326 return; 6327 } 6328 } else { 6329 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6330 // argument for which there is no corresponding parameter is 6331 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6332 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6333 } 6334 } 6335 6336 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6337 Candidate.Viable = false; 6338 Candidate.FailureKind = ovl_fail_enable_if; 6339 Candidate.DeductionFailure.Data = FailedAttr; 6340 return; 6341 } 6342 } 6343 6344 /// \brief Add overload candidates for overloaded operators that are 6345 /// member functions. 6346 /// 6347 /// Add the overloaded operator candidates that are member functions 6348 /// for the operator Op that was used in an operator expression such 6349 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6350 /// CandidateSet will store the added overload candidates. (C++ 6351 /// [over.match.oper]). 6352 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6353 SourceLocation OpLoc, 6354 ArrayRef<Expr *> Args, 6355 OverloadCandidateSet& CandidateSet, 6356 SourceRange OpRange) { 6357 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6358 6359 // C++ [over.match.oper]p3: 6360 // For a unary operator @ with an operand of a type whose 6361 // cv-unqualified version is T1, and for a binary operator @ with 6362 // a left operand of a type whose cv-unqualified version is T1 and 6363 // a right operand of a type whose cv-unqualified version is T2, 6364 // three sets of candidate functions, designated member 6365 // candidates, non-member candidates and built-in candidates, are 6366 // constructed as follows: 6367 QualType T1 = Args[0]->getType(); 6368 6369 // -- If T1 is a complete class type or a class currently being 6370 // defined, the set of member candidates is the result of the 6371 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6372 // the set of member candidates is empty. 6373 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6374 // Complete the type if it can be completed. 6375 RequireCompleteType(OpLoc, T1, 0); 6376 // If the type is neither complete nor being defined, bail out now. 6377 if (!T1Rec->getDecl()->getDefinition()) 6378 return; 6379 6380 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6381 LookupQualifiedName(Operators, T1Rec->getDecl()); 6382 Operators.suppressDiagnostics(); 6383 6384 for (LookupResult::iterator Oper = Operators.begin(), 6385 OperEnd = Operators.end(); 6386 Oper != OperEnd; 6387 ++Oper) 6388 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6389 Args[0]->Classify(Context), 6390 Args.slice(1), 6391 CandidateSet, 6392 /* SuppressUserConversions = */ false); 6393 } 6394 } 6395 6396 /// AddBuiltinCandidate - Add a candidate for a built-in 6397 /// operator. ResultTy and ParamTys are the result and parameter types 6398 /// of the built-in candidate, respectively. Args and NumArgs are the 6399 /// arguments being passed to the candidate. IsAssignmentOperator 6400 /// should be true when this built-in candidate is an assignment 6401 /// operator. NumContextualBoolArguments is the number of arguments 6402 /// (at the beginning of the argument list) that will be contextually 6403 /// converted to bool. 6404 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6405 ArrayRef<Expr *> Args, 6406 OverloadCandidateSet& CandidateSet, 6407 bool IsAssignmentOperator, 6408 unsigned NumContextualBoolArguments) { 6409 // Overload resolution is always an unevaluated context. 6410 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6411 6412 // Add this candidate 6413 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6414 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6415 Candidate.Function = 0; 6416 Candidate.IsSurrogate = false; 6417 Candidate.IgnoreObjectArgument = false; 6418 Candidate.BuiltinTypes.ResultTy = ResultTy; 6419 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6420 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6421 6422 // Determine the implicit conversion sequences for each of the 6423 // arguments. 6424 Candidate.Viable = true; 6425 Candidate.ExplicitCallArguments = Args.size(); 6426 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6427 // C++ [over.match.oper]p4: 6428 // For the built-in assignment operators, conversions of the 6429 // left operand are restricted as follows: 6430 // -- no temporaries are introduced to hold the left operand, and 6431 // -- no user-defined conversions are applied to the left 6432 // operand to achieve a type match with the left-most 6433 // parameter of a built-in candidate. 6434 // 6435 // We block these conversions by turning off user-defined 6436 // conversions, since that is the only way that initialization of 6437 // a reference to a non-class type can occur from something that 6438 // is not of the same type. 6439 if (ArgIdx < NumContextualBoolArguments) { 6440 assert(ParamTys[ArgIdx] == Context.BoolTy && 6441 "Contextual conversion to bool requires bool type"); 6442 Candidate.Conversions[ArgIdx] 6443 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6444 } else { 6445 Candidate.Conversions[ArgIdx] 6446 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6447 ArgIdx == 0 && IsAssignmentOperator, 6448 /*InOverloadResolution=*/false, 6449 /*AllowObjCWritebackConversion=*/ 6450 getLangOpts().ObjCAutoRefCount); 6451 } 6452 if (Candidate.Conversions[ArgIdx].isBad()) { 6453 Candidate.Viable = false; 6454 Candidate.FailureKind = ovl_fail_bad_conversion; 6455 break; 6456 } 6457 } 6458 } 6459 6460 namespace { 6461 6462 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6463 /// candidate operator functions for built-in operators (C++ 6464 /// [over.built]). The types are separated into pointer types and 6465 /// enumeration types. 6466 class BuiltinCandidateTypeSet { 6467 /// TypeSet - A set of types. 6468 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6469 6470 /// PointerTypes - The set of pointer types that will be used in the 6471 /// built-in candidates. 6472 TypeSet PointerTypes; 6473 6474 /// MemberPointerTypes - The set of member pointer types that will be 6475 /// used in the built-in candidates. 6476 TypeSet MemberPointerTypes; 6477 6478 /// EnumerationTypes - The set of enumeration types that will be 6479 /// used in the built-in candidates. 6480 TypeSet EnumerationTypes; 6481 6482 /// \brief The set of vector types that will be used in the built-in 6483 /// candidates. 6484 TypeSet VectorTypes; 6485 6486 /// \brief A flag indicating non-record types are viable candidates 6487 bool HasNonRecordTypes; 6488 6489 /// \brief A flag indicating whether either arithmetic or enumeration types 6490 /// were present in the candidate set. 6491 bool HasArithmeticOrEnumeralTypes; 6492 6493 /// \brief A flag indicating whether the nullptr type was present in the 6494 /// candidate set. 6495 bool HasNullPtrType; 6496 6497 /// Sema - The semantic analysis instance where we are building the 6498 /// candidate type set. 6499 Sema &SemaRef; 6500 6501 /// Context - The AST context in which we will build the type sets. 6502 ASTContext &Context; 6503 6504 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6505 const Qualifiers &VisibleQuals); 6506 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6507 6508 public: 6509 /// iterator - Iterates through the types that are part of the set. 6510 typedef TypeSet::iterator iterator; 6511 6512 BuiltinCandidateTypeSet(Sema &SemaRef) 6513 : HasNonRecordTypes(false), 6514 HasArithmeticOrEnumeralTypes(false), 6515 HasNullPtrType(false), 6516 SemaRef(SemaRef), 6517 Context(SemaRef.Context) { } 6518 6519 void AddTypesConvertedFrom(QualType Ty, 6520 SourceLocation Loc, 6521 bool AllowUserConversions, 6522 bool AllowExplicitConversions, 6523 const Qualifiers &VisibleTypeConversionsQuals); 6524 6525 /// pointer_begin - First pointer type found; 6526 iterator pointer_begin() { return PointerTypes.begin(); } 6527 6528 /// pointer_end - Past the last pointer type found; 6529 iterator pointer_end() { return PointerTypes.end(); } 6530 6531 /// member_pointer_begin - First member pointer type found; 6532 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6533 6534 /// member_pointer_end - Past the last member pointer type found; 6535 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6536 6537 /// enumeration_begin - First enumeration type found; 6538 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6539 6540 /// enumeration_end - Past the last enumeration type found; 6541 iterator enumeration_end() { return EnumerationTypes.end(); } 6542 6543 iterator vector_begin() { return VectorTypes.begin(); } 6544 iterator vector_end() { return VectorTypes.end(); } 6545 6546 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6547 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6548 bool hasNullPtrType() const { return HasNullPtrType; } 6549 }; 6550 6551 } // end anonymous namespace 6552 6553 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6554 /// the set of pointer types along with any more-qualified variants of 6555 /// that type. For example, if @p Ty is "int const *", this routine 6556 /// will add "int const *", "int const volatile *", "int const 6557 /// restrict *", and "int const volatile restrict *" to the set of 6558 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6559 /// false otherwise. 6560 /// 6561 /// FIXME: what to do about extended qualifiers? 6562 bool 6563 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6564 const Qualifiers &VisibleQuals) { 6565 6566 // Insert this type. 6567 if (!PointerTypes.insert(Ty)) 6568 return false; 6569 6570 QualType PointeeTy; 6571 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6572 bool buildObjCPtr = false; 6573 if (!PointerTy) { 6574 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6575 PointeeTy = PTy->getPointeeType(); 6576 buildObjCPtr = true; 6577 } else { 6578 PointeeTy = PointerTy->getPointeeType(); 6579 } 6580 6581 // Don't add qualified variants of arrays. For one, they're not allowed 6582 // (the qualifier would sink to the element type), and for another, the 6583 // only overload situation where it matters is subscript or pointer +- int, 6584 // and those shouldn't have qualifier variants anyway. 6585 if (PointeeTy->isArrayType()) 6586 return true; 6587 6588 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6589 bool hasVolatile = VisibleQuals.hasVolatile(); 6590 bool hasRestrict = VisibleQuals.hasRestrict(); 6591 6592 // Iterate through all strict supersets of BaseCVR. 6593 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6594 if ((CVR | BaseCVR) != CVR) continue; 6595 // Skip over volatile if no volatile found anywhere in the types. 6596 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6597 6598 // Skip over restrict if no restrict found anywhere in the types, or if 6599 // the type cannot be restrict-qualified. 6600 if ((CVR & Qualifiers::Restrict) && 6601 (!hasRestrict || 6602 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6603 continue; 6604 6605 // Build qualified pointee type. 6606 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6607 6608 // Build qualified pointer type. 6609 QualType QPointerTy; 6610 if (!buildObjCPtr) 6611 QPointerTy = Context.getPointerType(QPointeeTy); 6612 else 6613 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6614 6615 // Insert qualified pointer type. 6616 PointerTypes.insert(QPointerTy); 6617 } 6618 6619 return true; 6620 } 6621 6622 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6623 /// to the set of pointer types along with any more-qualified variants of 6624 /// that type. For example, if @p Ty is "int const *", this routine 6625 /// will add "int const *", "int const volatile *", "int const 6626 /// restrict *", and "int const volatile restrict *" to the set of 6627 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6628 /// false otherwise. 6629 /// 6630 /// FIXME: what to do about extended qualifiers? 6631 bool 6632 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6633 QualType Ty) { 6634 // Insert this type. 6635 if (!MemberPointerTypes.insert(Ty)) 6636 return false; 6637 6638 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6639 assert(PointerTy && "type was not a member pointer type!"); 6640 6641 QualType PointeeTy = PointerTy->getPointeeType(); 6642 // Don't add qualified variants of arrays. For one, they're not allowed 6643 // (the qualifier would sink to the element type), and for another, the 6644 // only overload situation where it matters is subscript or pointer +- int, 6645 // and those shouldn't have qualifier variants anyway. 6646 if (PointeeTy->isArrayType()) 6647 return true; 6648 const Type *ClassTy = PointerTy->getClass(); 6649 6650 // Iterate through all strict supersets of the pointee type's CVR 6651 // qualifiers. 6652 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6653 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6654 if ((CVR | BaseCVR) != CVR) continue; 6655 6656 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6657 MemberPointerTypes.insert( 6658 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6659 } 6660 6661 return true; 6662 } 6663 6664 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6665 /// Ty can be implicit converted to the given set of @p Types. We're 6666 /// primarily interested in pointer types and enumeration types. We also 6667 /// take member pointer types, for the conditional operator. 6668 /// AllowUserConversions is true if we should look at the conversion 6669 /// functions of a class type, and AllowExplicitConversions if we 6670 /// should also include the explicit conversion functions of a class 6671 /// type. 6672 void 6673 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6674 SourceLocation Loc, 6675 bool AllowUserConversions, 6676 bool AllowExplicitConversions, 6677 const Qualifiers &VisibleQuals) { 6678 // Only deal with canonical types. 6679 Ty = Context.getCanonicalType(Ty); 6680 6681 // Look through reference types; they aren't part of the type of an 6682 // expression for the purposes of conversions. 6683 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6684 Ty = RefTy->getPointeeType(); 6685 6686 // If we're dealing with an array type, decay to the pointer. 6687 if (Ty->isArrayType()) 6688 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6689 6690 // Otherwise, we don't care about qualifiers on the type. 6691 Ty = Ty.getLocalUnqualifiedType(); 6692 6693 // Flag if we ever add a non-record type. 6694 const RecordType *TyRec = Ty->getAs<RecordType>(); 6695 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6696 6697 // Flag if we encounter an arithmetic type. 6698 HasArithmeticOrEnumeralTypes = 6699 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6700 6701 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6702 PointerTypes.insert(Ty); 6703 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6704 // Insert our type, and its more-qualified variants, into the set 6705 // of types. 6706 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6707 return; 6708 } else if (Ty->isMemberPointerType()) { 6709 // Member pointers are far easier, since the pointee can't be converted. 6710 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6711 return; 6712 } else if (Ty->isEnumeralType()) { 6713 HasArithmeticOrEnumeralTypes = true; 6714 EnumerationTypes.insert(Ty); 6715 } else if (Ty->isVectorType()) { 6716 // We treat vector types as arithmetic types in many contexts as an 6717 // extension. 6718 HasArithmeticOrEnumeralTypes = true; 6719 VectorTypes.insert(Ty); 6720 } else if (Ty->isNullPtrType()) { 6721 HasNullPtrType = true; 6722 } else if (AllowUserConversions && TyRec) { 6723 // No conversion functions in incomplete types. 6724 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6725 return; 6726 6727 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6728 std::pair<CXXRecordDecl::conversion_iterator, 6729 CXXRecordDecl::conversion_iterator> 6730 Conversions = ClassDecl->getVisibleConversionFunctions(); 6731 for (CXXRecordDecl::conversion_iterator 6732 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6733 NamedDecl *D = I.getDecl(); 6734 if (isa<UsingShadowDecl>(D)) 6735 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6736 6737 // Skip conversion function templates; they don't tell us anything 6738 // about which builtin types we can convert to. 6739 if (isa<FunctionTemplateDecl>(D)) 6740 continue; 6741 6742 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6743 if (AllowExplicitConversions || !Conv->isExplicit()) { 6744 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6745 VisibleQuals); 6746 } 6747 } 6748 } 6749 } 6750 6751 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6752 /// the volatile- and non-volatile-qualified assignment operators for the 6753 /// given type to the candidate set. 6754 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6755 QualType T, 6756 ArrayRef<Expr *> Args, 6757 OverloadCandidateSet &CandidateSet) { 6758 QualType ParamTypes[2]; 6759 6760 // T& operator=(T&, T) 6761 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6762 ParamTypes[1] = T; 6763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6764 /*IsAssignmentOperator=*/true); 6765 6766 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6767 // volatile T& operator=(volatile T&, T) 6768 ParamTypes[0] 6769 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6770 ParamTypes[1] = T; 6771 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6772 /*IsAssignmentOperator=*/true); 6773 } 6774 } 6775 6776 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6777 /// if any, found in visible type conversion functions found in ArgExpr's type. 6778 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6779 Qualifiers VRQuals; 6780 const RecordType *TyRec; 6781 if (const MemberPointerType *RHSMPType = 6782 ArgExpr->getType()->getAs<MemberPointerType>()) 6783 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6784 else 6785 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6786 if (!TyRec) { 6787 // Just to be safe, assume the worst case. 6788 VRQuals.addVolatile(); 6789 VRQuals.addRestrict(); 6790 return VRQuals; 6791 } 6792 6793 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6794 if (!ClassDecl->hasDefinition()) 6795 return VRQuals; 6796 6797 std::pair<CXXRecordDecl::conversion_iterator, 6798 CXXRecordDecl::conversion_iterator> 6799 Conversions = ClassDecl->getVisibleConversionFunctions(); 6800 6801 for (CXXRecordDecl::conversion_iterator 6802 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6803 NamedDecl *D = I.getDecl(); 6804 if (isa<UsingShadowDecl>(D)) 6805 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6806 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6807 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6808 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6809 CanTy = ResTypeRef->getPointeeType(); 6810 // Need to go down the pointer/mempointer chain and add qualifiers 6811 // as see them. 6812 bool done = false; 6813 while (!done) { 6814 if (CanTy.isRestrictQualified()) 6815 VRQuals.addRestrict(); 6816 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6817 CanTy = ResTypePtr->getPointeeType(); 6818 else if (const MemberPointerType *ResTypeMPtr = 6819 CanTy->getAs<MemberPointerType>()) 6820 CanTy = ResTypeMPtr->getPointeeType(); 6821 else 6822 done = true; 6823 if (CanTy.isVolatileQualified()) 6824 VRQuals.addVolatile(); 6825 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6826 return VRQuals; 6827 } 6828 } 6829 } 6830 return VRQuals; 6831 } 6832 6833 namespace { 6834 6835 /// \brief Helper class to manage the addition of builtin operator overload 6836 /// candidates. It provides shared state and utility methods used throughout 6837 /// the process, as well as a helper method to add each group of builtin 6838 /// operator overloads from the standard to a candidate set. 6839 class BuiltinOperatorOverloadBuilder { 6840 // Common instance state available to all overload candidate addition methods. 6841 Sema &S; 6842 ArrayRef<Expr *> Args; 6843 Qualifiers VisibleTypeConversionsQuals; 6844 bool HasArithmeticOrEnumeralCandidateType; 6845 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6846 OverloadCandidateSet &CandidateSet; 6847 6848 // Define some constants used to index and iterate over the arithemetic types 6849 // provided via the getArithmeticType() method below. 6850 // The "promoted arithmetic types" are the arithmetic 6851 // types are that preserved by promotion (C++ [over.built]p2). 6852 static const unsigned FirstIntegralType = 3; 6853 static const unsigned LastIntegralType = 20; 6854 static const unsigned FirstPromotedIntegralType = 3, 6855 LastPromotedIntegralType = 11; 6856 static const unsigned FirstPromotedArithmeticType = 0, 6857 LastPromotedArithmeticType = 11; 6858 static const unsigned NumArithmeticTypes = 20; 6859 6860 /// \brief Get the canonical type for a given arithmetic type index. 6861 CanQualType getArithmeticType(unsigned index) { 6862 assert(index < NumArithmeticTypes); 6863 static CanQualType ASTContext::* const 6864 ArithmeticTypes[NumArithmeticTypes] = { 6865 // Start of promoted types. 6866 &ASTContext::FloatTy, 6867 &ASTContext::DoubleTy, 6868 &ASTContext::LongDoubleTy, 6869 6870 // Start of integral types. 6871 &ASTContext::IntTy, 6872 &ASTContext::LongTy, 6873 &ASTContext::LongLongTy, 6874 &ASTContext::Int128Ty, 6875 &ASTContext::UnsignedIntTy, 6876 &ASTContext::UnsignedLongTy, 6877 &ASTContext::UnsignedLongLongTy, 6878 &ASTContext::UnsignedInt128Ty, 6879 // End of promoted types. 6880 6881 &ASTContext::BoolTy, 6882 &ASTContext::CharTy, 6883 &ASTContext::WCharTy, 6884 &ASTContext::Char16Ty, 6885 &ASTContext::Char32Ty, 6886 &ASTContext::SignedCharTy, 6887 &ASTContext::ShortTy, 6888 &ASTContext::UnsignedCharTy, 6889 &ASTContext::UnsignedShortTy, 6890 // End of integral types. 6891 // FIXME: What about complex? What about half? 6892 }; 6893 return S.Context.*ArithmeticTypes[index]; 6894 } 6895 6896 /// \brief Gets the canonical type resulting from the usual arithemetic 6897 /// converions for the given arithmetic types. 6898 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6899 // Accelerator table for performing the usual arithmetic conversions. 6900 // The rules are basically: 6901 // - if either is floating-point, use the wider floating-point 6902 // - if same signedness, use the higher rank 6903 // - if same size, use unsigned of the higher rank 6904 // - use the larger type 6905 // These rules, together with the axiom that higher ranks are 6906 // never smaller, are sufficient to precompute all of these results 6907 // *except* when dealing with signed types of higher rank. 6908 // (we could precompute SLL x UI for all known platforms, but it's 6909 // better not to make any assumptions). 6910 // We assume that int128 has a higher rank than long long on all platforms. 6911 enum PromotedType { 6912 Dep=-1, 6913 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6914 }; 6915 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6916 [LastPromotedArithmeticType] = { 6917 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6918 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6919 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6920 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6921 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6922 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6923 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6924 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6925 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6926 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6927 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6928 }; 6929 6930 assert(L < LastPromotedArithmeticType); 6931 assert(R < LastPromotedArithmeticType); 6932 int Idx = ConversionsTable[L][R]; 6933 6934 // Fast path: the table gives us a concrete answer. 6935 if (Idx != Dep) return getArithmeticType(Idx); 6936 6937 // Slow path: we need to compare widths. 6938 // An invariant is that the signed type has higher rank. 6939 CanQualType LT = getArithmeticType(L), 6940 RT = getArithmeticType(R); 6941 unsigned LW = S.Context.getIntWidth(LT), 6942 RW = S.Context.getIntWidth(RT); 6943 6944 // If they're different widths, use the signed type. 6945 if (LW > RW) return LT; 6946 else if (LW < RW) return RT; 6947 6948 // Otherwise, use the unsigned type of the signed type's rank. 6949 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6950 assert(L == SLL || R == SLL); 6951 return S.Context.UnsignedLongLongTy; 6952 } 6953 6954 /// \brief Helper method to factor out the common pattern of adding overloads 6955 /// for '++' and '--' builtin operators. 6956 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6957 bool HasVolatile, 6958 bool HasRestrict) { 6959 QualType ParamTypes[2] = { 6960 S.Context.getLValueReferenceType(CandidateTy), 6961 S.Context.IntTy 6962 }; 6963 6964 // Non-volatile version. 6965 if (Args.size() == 1) 6966 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6967 else 6968 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6969 6970 // Use a heuristic to reduce number of builtin candidates in the set: 6971 // add volatile version only if there are conversions to a volatile type. 6972 if (HasVolatile) { 6973 ParamTypes[0] = 6974 S.Context.getLValueReferenceType( 6975 S.Context.getVolatileType(CandidateTy)); 6976 if (Args.size() == 1) 6977 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6978 else 6979 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6980 } 6981 6982 // Add restrict version only if there are conversions to a restrict type 6983 // and our candidate type is a non-restrict-qualified pointer. 6984 if (HasRestrict && CandidateTy->isAnyPointerType() && 6985 !CandidateTy.isRestrictQualified()) { 6986 ParamTypes[0] 6987 = S.Context.getLValueReferenceType( 6988 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6989 if (Args.size() == 1) 6990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6991 else 6992 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6993 6994 if (HasVolatile) { 6995 ParamTypes[0] 6996 = S.Context.getLValueReferenceType( 6997 S.Context.getCVRQualifiedType(CandidateTy, 6998 (Qualifiers::Volatile | 6999 Qualifiers::Restrict))); 7000 if (Args.size() == 1) 7001 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7002 else 7003 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7004 } 7005 } 7006 7007 } 7008 7009 public: 7010 BuiltinOperatorOverloadBuilder( 7011 Sema &S, ArrayRef<Expr *> Args, 7012 Qualifiers VisibleTypeConversionsQuals, 7013 bool HasArithmeticOrEnumeralCandidateType, 7014 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7015 OverloadCandidateSet &CandidateSet) 7016 : S(S), Args(Args), 7017 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7018 HasArithmeticOrEnumeralCandidateType( 7019 HasArithmeticOrEnumeralCandidateType), 7020 CandidateTypes(CandidateTypes), 7021 CandidateSet(CandidateSet) { 7022 // Validate some of our static helper constants in debug builds. 7023 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7024 "Invalid first promoted integral type"); 7025 assert(getArithmeticType(LastPromotedIntegralType - 1) 7026 == S.Context.UnsignedInt128Ty && 7027 "Invalid last promoted integral type"); 7028 assert(getArithmeticType(FirstPromotedArithmeticType) 7029 == S.Context.FloatTy && 7030 "Invalid first promoted arithmetic type"); 7031 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7032 == S.Context.UnsignedInt128Ty && 7033 "Invalid last promoted arithmetic type"); 7034 } 7035 7036 // C++ [over.built]p3: 7037 // 7038 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7039 // is either volatile or empty, there exist candidate operator 7040 // functions of the form 7041 // 7042 // VQ T& operator++(VQ T&); 7043 // T operator++(VQ T&, int); 7044 // 7045 // C++ [over.built]p4: 7046 // 7047 // For every pair (T, VQ), where T is an arithmetic type other 7048 // than bool, and VQ is either volatile or empty, there exist 7049 // candidate operator functions of the form 7050 // 7051 // VQ T& operator--(VQ T&); 7052 // T operator--(VQ T&, int); 7053 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7054 if (!HasArithmeticOrEnumeralCandidateType) 7055 return; 7056 7057 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7058 Arith < NumArithmeticTypes; ++Arith) { 7059 addPlusPlusMinusMinusStyleOverloads( 7060 getArithmeticType(Arith), 7061 VisibleTypeConversionsQuals.hasVolatile(), 7062 VisibleTypeConversionsQuals.hasRestrict()); 7063 } 7064 } 7065 7066 // C++ [over.built]p5: 7067 // 7068 // For every pair (T, VQ), where T is a cv-qualified or 7069 // cv-unqualified object type, and VQ is either volatile or 7070 // empty, there exist candidate operator functions of the form 7071 // 7072 // T*VQ& operator++(T*VQ&); 7073 // T*VQ& operator--(T*VQ&); 7074 // T* operator++(T*VQ&, int); 7075 // T* operator--(T*VQ&, int); 7076 void addPlusPlusMinusMinusPointerOverloads() { 7077 for (BuiltinCandidateTypeSet::iterator 7078 Ptr = CandidateTypes[0].pointer_begin(), 7079 PtrEnd = CandidateTypes[0].pointer_end(); 7080 Ptr != PtrEnd; ++Ptr) { 7081 // Skip pointer types that aren't pointers to object types. 7082 if (!(*Ptr)->getPointeeType()->isObjectType()) 7083 continue; 7084 7085 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7086 (!(*Ptr).isVolatileQualified() && 7087 VisibleTypeConversionsQuals.hasVolatile()), 7088 (!(*Ptr).isRestrictQualified() && 7089 VisibleTypeConversionsQuals.hasRestrict())); 7090 } 7091 } 7092 7093 // C++ [over.built]p6: 7094 // For every cv-qualified or cv-unqualified object type T, there 7095 // exist candidate operator functions of the form 7096 // 7097 // T& operator*(T*); 7098 // 7099 // C++ [over.built]p7: 7100 // For every function type T that does not have cv-qualifiers or a 7101 // ref-qualifier, there exist candidate operator functions of the form 7102 // T& operator*(T*); 7103 void addUnaryStarPointerOverloads() { 7104 for (BuiltinCandidateTypeSet::iterator 7105 Ptr = CandidateTypes[0].pointer_begin(), 7106 PtrEnd = CandidateTypes[0].pointer_end(); 7107 Ptr != PtrEnd; ++Ptr) { 7108 QualType ParamTy = *Ptr; 7109 QualType PointeeTy = ParamTy->getPointeeType(); 7110 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7111 continue; 7112 7113 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7114 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7115 continue; 7116 7117 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7118 &ParamTy, Args, CandidateSet); 7119 } 7120 } 7121 7122 // C++ [over.built]p9: 7123 // For every promoted arithmetic type T, there exist candidate 7124 // operator functions of the form 7125 // 7126 // T operator+(T); 7127 // T operator-(T); 7128 void addUnaryPlusOrMinusArithmeticOverloads() { 7129 if (!HasArithmeticOrEnumeralCandidateType) 7130 return; 7131 7132 for (unsigned Arith = FirstPromotedArithmeticType; 7133 Arith < LastPromotedArithmeticType; ++Arith) { 7134 QualType ArithTy = getArithmeticType(Arith); 7135 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7136 } 7137 7138 // Extension: We also add these operators for vector types. 7139 for (BuiltinCandidateTypeSet::iterator 7140 Vec = CandidateTypes[0].vector_begin(), 7141 VecEnd = CandidateTypes[0].vector_end(); 7142 Vec != VecEnd; ++Vec) { 7143 QualType VecTy = *Vec; 7144 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7145 } 7146 } 7147 7148 // C++ [over.built]p8: 7149 // For every type T, there exist candidate operator functions of 7150 // the form 7151 // 7152 // T* operator+(T*); 7153 void addUnaryPlusPointerOverloads() { 7154 for (BuiltinCandidateTypeSet::iterator 7155 Ptr = CandidateTypes[0].pointer_begin(), 7156 PtrEnd = CandidateTypes[0].pointer_end(); 7157 Ptr != PtrEnd; ++Ptr) { 7158 QualType ParamTy = *Ptr; 7159 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7160 } 7161 } 7162 7163 // C++ [over.built]p10: 7164 // For every promoted integral type T, there exist candidate 7165 // operator functions of the form 7166 // 7167 // T operator~(T); 7168 void addUnaryTildePromotedIntegralOverloads() { 7169 if (!HasArithmeticOrEnumeralCandidateType) 7170 return; 7171 7172 for (unsigned Int = FirstPromotedIntegralType; 7173 Int < LastPromotedIntegralType; ++Int) { 7174 QualType IntTy = getArithmeticType(Int); 7175 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7176 } 7177 7178 // Extension: We also add this operator for vector types. 7179 for (BuiltinCandidateTypeSet::iterator 7180 Vec = CandidateTypes[0].vector_begin(), 7181 VecEnd = CandidateTypes[0].vector_end(); 7182 Vec != VecEnd; ++Vec) { 7183 QualType VecTy = *Vec; 7184 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7185 } 7186 } 7187 7188 // C++ [over.match.oper]p16: 7189 // For every pointer to member type T, there exist candidate operator 7190 // functions of the form 7191 // 7192 // bool operator==(T,T); 7193 // bool operator!=(T,T); 7194 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7195 /// Set of (canonical) types that we've already handled. 7196 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7197 7198 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7199 for (BuiltinCandidateTypeSet::iterator 7200 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7201 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7202 MemPtr != MemPtrEnd; 7203 ++MemPtr) { 7204 // Don't add the same builtin candidate twice. 7205 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7206 continue; 7207 7208 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7209 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7210 } 7211 } 7212 } 7213 7214 // C++ [over.built]p15: 7215 // 7216 // For every T, where T is an enumeration type, a pointer type, or 7217 // std::nullptr_t, there exist candidate operator functions of the form 7218 // 7219 // bool operator<(T, T); 7220 // bool operator>(T, T); 7221 // bool operator<=(T, T); 7222 // bool operator>=(T, T); 7223 // bool operator==(T, T); 7224 // bool operator!=(T, T); 7225 void addRelationalPointerOrEnumeralOverloads() { 7226 // C++ [over.match.oper]p3: 7227 // [...]the built-in candidates include all of the candidate operator 7228 // functions defined in 13.6 that, compared to the given operator, [...] 7229 // do not have the same parameter-type-list as any non-template non-member 7230 // candidate. 7231 // 7232 // Note that in practice, this only affects enumeration types because there 7233 // aren't any built-in candidates of record type, and a user-defined operator 7234 // must have an operand of record or enumeration type. Also, the only other 7235 // overloaded operator with enumeration arguments, operator=, 7236 // cannot be overloaded for enumeration types, so this is the only place 7237 // where we must suppress candidates like this. 7238 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7239 UserDefinedBinaryOperators; 7240 7241 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7242 if (CandidateTypes[ArgIdx].enumeration_begin() != 7243 CandidateTypes[ArgIdx].enumeration_end()) { 7244 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7245 CEnd = CandidateSet.end(); 7246 C != CEnd; ++C) { 7247 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7248 continue; 7249 7250 if (C->Function->isFunctionTemplateSpecialization()) 7251 continue; 7252 7253 QualType FirstParamType = 7254 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7255 QualType SecondParamType = 7256 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7257 7258 // Skip if either parameter isn't of enumeral type. 7259 if (!FirstParamType->isEnumeralType() || 7260 !SecondParamType->isEnumeralType()) 7261 continue; 7262 7263 // Add this operator to the set of known user-defined operators. 7264 UserDefinedBinaryOperators.insert( 7265 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7266 S.Context.getCanonicalType(SecondParamType))); 7267 } 7268 } 7269 } 7270 7271 /// Set of (canonical) types that we've already handled. 7272 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7273 7274 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7275 for (BuiltinCandidateTypeSet::iterator 7276 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7277 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7278 Ptr != PtrEnd; ++Ptr) { 7279 // Don't add the same builtin candidate twice. 7280 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7281 continue; 7282 7283 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7284 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7285 } 7286 for (BuiltinCandidateTypeSet::iterator 7287 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7288 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7289 Enum != EnumEnd; ++Enum) { 7290 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7291 7292 // Don't add the same builtin candidate twice, or if a user defined 7293 // candidate exists. 7294 if (!AddedTypes.insert(CanonType) || 7295 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7296 CanonType))) 7297 continue; 7298 7299 QualType ParamTypes[2] = { *Enum, *Enum }; 7300 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7301 } 7302 7303 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7304 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7305 if (AddedTypes.insert(NullPtrTy) && 7306 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7307 NullPtrTy))) { 7308 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7309 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7310 CandidateSet); 7311 } 7312 } 7313 } 7314 } 7315 7316 // C++ [over.built]p13: 7317 // 7318 // For every cv-qualified or cv-unqualified object type T 7319 // there exist candidate operator functions of the form 7320 // 7321 // T* operator+(T*, ptrdiff_t); 7322 // T& operator[](T*, ptrdiff_t); [BELOW] 7323 // T* operator-(T*, ptrdiff_t); 7324 // T* operator+(ptrdiff_t, T*); 7325 // T& operator[](ptrdiff_t, T*); [BELOW] 7326 // 7327 // C++ [over.built]p14: 7328 // 7329 // For every T, where T is a pointer to object type, there 7330 // exist candidate operator functions of the form 7331 // 7332 // ptrdiff_t operator-(T, T); 7333 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7334 /// Set of (canonical) types that we've already handled. 7335 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7336 7337 for (int Arg = 0; Arg < 2; ++Arg) { 7338 QualType AsymetricParamTypes[2] = { 7339 S.Context.getPointerDiffType(), 7340 S.Context.getPointerDiffType(), 7341 }; 7342 for (BuiltinCandidateTypeSet::iterator 7343 Ptr = CandidateTypes[Arg].pointer_begin(), 7344 PtrEnd = CandidateTypes[Arg].pointer_end(); 7345 Ptr != PtrEnd; ++Ptr) { 7346 QualType PointeeTy = (*Ptr)->getPointeeType(); 7347 if (!PointeeTy->isObjectType()) 7348 continue; 7349 7350 AsymetricParamTypes[Arg] = *Ptr; 7351 if (Arg == 0 || Op == OO_Plus) { 7352 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7353 // T* operator+(ptrdiff_t, T*); 7354 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7355 } 7356 if (Op == OO_Minus) { 7357 // ptrdiff_t operator-(T, T); 7358 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7359 continue; 7360 7361 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7362 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7363 Args, CandidateSet); 7364 } 7365 } 7366 } 7367 } 7368 7369 // C++ [over.built]p12: 7370 // 7371 // For every pair of promoted arithmetic types L and R, there 7372 // exist candidate operator functions of the form 7373 // 7374 // LR operator*(L, R); 7375 // LR operator/(L, R); 7376 // LR operator+(L, R); 7377 // LR operator-(L, R); 7378 // bool operator<(L, R); 7379 // bool operator>(L, R); 7380 // bool operator<=(L, R); 7381 // bool operator>=(L, R); 7382 // bool operator==(L, R); 7383 // bool operator!=(L, R); 7384 // 7385 // where LR is the result of the usual arithmetic conversions 7386 // between types L and R. 7387 // 7388 // C++ [over.built]p24: 7389 // 7390 // For every pair of promoted arithmetic types L and R, there exist 7391 // candidate operator functions of the form 7392 // 7393 // LR operator?(bool, L, R); 7394 // 7395 // where LR is the result of the usual arithmetic conversions 7396 // between types L and R. 7397 // Our candidates ignore the first parameter. 7398 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7399 if (!HasArithmeticOrEnumeralCandidateType) 7400 return; 7401 7402 for (unsigned Left = FirstPromotedArithmeticType; 7403 Left < LastPromotedArithmeticType; ++Left) { 7404 for (unsigned Right = FirstPromotedArithmeticType; 7405 Right < LastPromotedArithmeticType; ++Right) { 7406 QualType LandR[2] = { getArithmeticType(Left), 7407 getArithmeticType(Right) }; 7408 QualType Result = 7409 isComparison ? S.Context.BoolTy 7410 : getUsualArithmeticConversions(Left, Right); 7411 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7412 } 7413 } 7414 7415 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7416 // conditional operator for vector types. 7417 for (BuiltinCandidateTypeSet::iterator 7418 Vec1 = CandidateTypes[0].vector_begin(), 7419 Vec1End = CandidateTypes[0].vector_end(); 7420 Vec1 != Vec1End; ++Vec1) { 7421 for (BuiltinCandidateTypeSet::iterator 7422 Vec2 = CandidateTypes[1].vector_begin(), 7423 Vec2End = CandidateTypes[1].vector_end(); 7424 Vec2 != Vec2End; ++Vec2) { 7425 QualType LandR[2] = { *Vec1, *Vec2 }; 7426 QualType Result = S.Context.BoolTy; 7427 if (!isComparison) { 7428 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7429 Result = *Vec1; 7430 else 7431 Result = *Vec2; 7432 } 7433 7434 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7435 } 7436 } 7437 } 7438 7439 // C++ [over.built]p17: 7440 // 7441 // For every pair of promoted integral types L and R, there 7442 // exist candidate operator functions of the form 7443 // 7444 // LR operator%(L, R); 7445 // LR operator&(L, R); 7446 // LR operator^(L, R); 7447 // LR operator|(L, R); 7448 // L operator<<(L, R); 7449 // L operator>>(L, R); 7450 // 7451 // where LR is the result of the usual arithmetic conversions 7452 // between types L and R. 7453 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7454 if (!HasArithmeticOrEnumeralCandidateType) 7455 return; 7456 7457 for (unsigned Left = FirstPromotedIntegralType; 7458 Left < LastPromotedIntegralType; ++Left) { 7459 for (unsigned Right = FirstPromotedIntegralType; 7460 Right < LastPromotedIntegralType; ++Right) { 7461 QualType LandR[2] = { getArithmeticType(Left), 7462 getArithmeticType(Right) }; 7463 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7464 ? LandR[0] 7465 : getUsualArithmeticConversions(Left, Right); 7466 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7467 } 7468 } 7469 } 7470 7471 // C++ [over.built]p20: 7472 // 7473 // For every pair (T, VQ), where T is an enumeration or 7474 // pointer to member type and VQ is either volatile or 7475 // empty, there exist candidate operator functions of the form 7476 // 7477 // VQ T& operator=(VQ T&, T); 7478 void addAssignmentMemberPointerOrEnumeralOverloads() { 7479 /// Set of (canonical) types that we've already handled. 7480 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7481 7482 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7483 for (BuiltinCandidateTypeSet::iterator 7484 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7485 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7486 Enum != EnumEnd; ++Enum) { 7487 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7488 continue; 7489 7490 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7491 } 7492 7493 for (BuiltinCandidateTypeSet::iterator 7494 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7495 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7496 MemPtr != MemPtrEnd; ++MemPtr) { 7497 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7498 continue; 7499 7500 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7501 } 7502 } 7503 } 7504 7505 // C++ [over.built]p19: 7506 // 7507 // For every pair (T, VQ), where T is any type and VQ is either 7508 // volatile or empty, there exist candidate operator functions 7509 // of the form 7510 // 7511 // T*VQ& operator=(T*VQ&, T*); 7512 // 7513 // C++ [over.built]p21: 7514 // 7515 // For every pair (T, VQ), where T is a cv-qualified or 7516 // cv-unqualified object type and VQ is either volatile or 7517 // empty, there exist candidate operator functions of the form 7518 // 7519 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7520 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7521 void addAssignmentPointerOverloads(bool isEqualOp) { 7522 /// Set of (canonical) types that we've already handled. 7523 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7524 7525 for (BuiltinCandidateTypeSet::iterator 7526 Ptr = CandidateTypes[0].pointer_begin(), 7527 PtrEnd = CandidateTypes[0].pointer_end(); 7528 Ptr != PtrEnd; ++Ptr) { 7529 // If this is operator=, keep track of the builtin candidates we added. 7530 if (isEqualOp) 7531 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7532 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7533 continue; 7534 7535 // non-volatile version 7536 QualType ParamTypes[2] = { 7537 S.Context.getLValueReferenceType(*Ptr), 7538 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7539 }; 7540 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7541 /*IsAssigmentOperator=*/ isEqualOp); 7542 7543 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7544 VisibleTypeConversionsQuals.hasVolatile(); 7545 if (NeedVolatile) { 7546 // volatile version 7547 ParamTypes[0] = 7548 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7549 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7550 /*IsAssigmentOperator=*/isEqualOp); 7551 } 7552 7553 if (!(*Ptr).isRestrictQualified() && 7554 VisibleTypeConversionsQuals.hasRestrict()) { 7555 // restrict version 7556 ParamTypes[0] 7557 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7558 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7559 /*IsAssigmentOperator=*/isEqualOp); 7560 7561 if (NeedVolatile) { 7562 // volatile restrict version 7563 ParamTypes[0] 7564 = S.Context.getLValueReferenceType( 7565 S.Context.getCVRQualifiedType(*Ptr, 7566 (Qualifiers::Volatile | 7567 Qualifiers::Restrict))); 7568 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7569 /*IsAssigmentOperator=*/isEqualOp); 7570 } 7571 } 7572 } 7573 7574 if (isEqualOp) { 7575 for (BuiltinCandidateTypeSet::iterator 7576 Ptr = CandidateTypes[1].pointer_begin(), 7577 PtrEnd = CandidateTypes[1].pointer_end(); 7578 Ptr != PtrEnd; ++Ptr) { 7579 // Make sure we don't add the same candidate twice. 7580 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7581 continue; 7582 7583 QualType ParamTypes[2] = { 7584 S.Context.getLValueReferenceType(*Ptr), 7585 *Ptr, 7586 }; 7587 7588 // non-volatile version 7589 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7590 /*IsAssigmentOperator=*/true); 7591 7592 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7593 VisibleTypeConversionsQuals.hasVolatile(); 7594 if (NeedVolatile) { 7595 // volatile version 7596 ParamTypes[0] = 7597 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7598 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7599 /*IsAssigmentOperator=*/true); 7600 } 7601 7602 if (!(*Ptr).isRestrictQualified() && 7603 VisibleTypeConversionsQuals.hasRestrict()) { 7604 // restrict version 7605 ParamTypes[0] 7606 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7607 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7608 /*IsAssigmentOperator=*/true); 7609 7610 if (NeedVolatile) { 7611 // volatile restrict version 7612 ParamTypes[0] 7613 = S.Context.getLValueReferenceType( 7614 S.Context.getCVRQualifiedType(*Ptr, 7615 (Qualifiers::Volatile | 7616 Qualifiers::Restrict))); 7617 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7618 /*IsAssigmentOperator=*/true); 7619 } 7620 } 7621 } 7622 } 7623 } 7624 7625 // C++ [over.built]p18: 7626 // 7627 // For every triple (L, VQ, R), where L is an arithmetic type, 7628 // VQ is either volatile or empty, and R is a promoted 7629 // arithmetic type, there exist candidate operator functions of 7630 // the form 7631 // 7632 // VQ L& operator=(VQ L&, R); 7633 // VQ L& operator*=(VQ L&, R); 7634 // VQ L& operator/=(VQ L&, R); 7635 // VQ L& operator+=(VQ L&, R); 7636 // VQ L& operator-=(VQ L&, R); 7637 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7638 if (!HasArithmeticOrEnumeralCandidateType) 7639 return; 7640 7641 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7642 for (unsigned Right = FirstPromotedArithmeticType; 7643 Right < LastPromotedArithmeticType; ++Right) { 7644 QualType ParamTypes[2]; 7645 ParamTypes[1] = getArithmeticType(Right); 7646 7647 // Add this built-in operator as a candidate (VQ is empty). 7648 ParamTypes[0] = 7649 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7650 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7651 /*IsAssigmentOperator=*/isEqualOp); 7652 7653 // Add this built-in operator as a candidate (VQ is 'volatile'). 7654 if (VisibleTypeConversionsQuals.hasVolatile()) { 7655 ParamTypes[0] = 7656 S.Context.getVolatileType(getArithmeticType(Left)); 7657 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7658 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7659 /*IsAssigmentOperator=*/isEqualOp); 7660 } 7661 } 7662 } 7663 7664 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7665 for (BuiltinCandidateTypeSet::iterator 7666 Vec1 = CandidateTypes[0].vector_begin(), 7667 Vec1End = CandidateTypes[0].vector_end(); 7668 Vec1 != Vec1End; ++Vec1) { 7669 for (BuiltinCandidateTypeSet::iterator 7670 Vec2 = CandidateTypes[1].vector_begin(), 7671 Vec2End = CandidateTypes[1].vector_end(); 7672 Vec2 != Vec2End; ++Vec2) { 7673 QualType ParamTypes[2]; 7674 ParamTypes[1] = *Vec2; 7675 // Add this built-in operator as a candidate (VQ is empty). 7676 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7677 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7678 /*IsAssigmentOperator=*/isEqualOp); 7679 7680 // Add this built-in operator as a candidate (VQ is 'volatile'). 7681 if (VisibleTypeConversionsQuals.hasVolatile()) { 7682 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7683 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7684 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7685 /*IsAssigmentOperator=*/isEqualOp); 7686 } 7687 } 7688 } 7689 } 7690 7691 // C++ [over.built]p22: 7692 // 7693 // For every triple (L, VQ, R), where L is an integral type, VQ 7694 // is either volatile or empty, and R is a promoted integral 7695 // type, there exist candidate operator functions of the form 7696 // 7697 // VQ L& operator%=(VQ L&, R); 7698 // VQ L& operator<<=(VQ L&, R); 7699 // VQ L& operator>>=(VQ L&, R); 7700 // VQ L& operator&=(VQ L&, R); 7701 // VQ L& operator^=(VQ L&, R); 7702 // VQ L& operator|=(VQ L&, R); 7703 void addAssignmentIntegralOverloads() { 7704 if (!HasArithmeticOrEnumeralCandidateType) 7705 return; 7706 7707 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7708 for (unsigned Right = FirstPromotedIntegralType; 7709 Right < LastPromotedIntegralType; ++Right) { 7710 QualType ParamTypes[2]; 7711 ParamTypes[1] = getArithmeticType(Right); 7712 7713 // Add this built-in operator as a candidate (VQ is empty). 7714 ParamTypes[0] = 7715 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7716 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7717 if (VisibleTypeConversionsQuals.hasVolatile()) { 7718 // Add this built-in operator as a candidate (VQ is 'volatile'). 7719 ParamTypes[0] = getArithmeticType(Left); 7720 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7721 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7722 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7723 } 7724 } 7725 } 7726 } 7727 7728 // C++ [over.operator]p23: 7729 // 7730 // There also exist candidate operator functions of the form 7731 // 7732 // bool operator!(bool); 7733 // bool operator&&(bool, bool); 7734 // bool operator||(bool, bool); 7735 void addExclaimOverload() { 7736 QualType ParamTy = S.Context.BoolTy; 7737 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7738 /*IsAssignmentOperator=*/false, 7739 /*NumContextualBoolArguments=*/1); 7740 } 7741 void addAmpAmpOrPipePipeOverload() { 7742 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7743 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7744 /*IsAssignmentOperator=*/false, 7745 /*NumContextualBoolArguments=*/2); 7746 } 7747 7748 // C++ [over.built]p13: 7749 // 7750 // For every cv-qualified or cv-unqualified object type T there 7751 // exist candidate operator functions of the form 7752 // 7753 // T* operator+(T*, ptrdiff_t); [ABOVE] 7754 // T& operator[](T*, ptrdiff_t); 7755 // T* operator-(T*, ptrdiff_t); [ABOVE] 7756 // T* operator+(ptrdiff_t, T*); [ABOVE] 7757 // T& operator[](ptrdiff_t, T*); 7758 void addSubscriptOverloads() { 7759 for (BuiltinCandidateTypeSet::iterator 7760 Ptr = CandidateTypes[0].pointer_begin(), 7761 PtrEnd = CandidateTypes[0].pointer_end(); 7762 Ptr != PtrEnd; ++Ptr) { 7763 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7764 QualType PointeeType = (*Ptr)->getPointeeType(); 7765 if (!PointeeType->isObjectType()) 7766 continue; 7767 7768 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7769 7770 // T& operator[](T*, ptrdiff_t) 7771 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7772 } 7773 7774 for (BuiltinCandidateTypeSet::iterator 7775 Ptr = CandidateTypes[1].pointer_begin(), 7776 PtrEnd = CandidateTypes[1].pointer_end(); 7777 Ptr != PtrEnd; ++Ptr) { 7778 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7779 QualType PointeeType = (*Ptr)->getPointeeType(); 7780 if (!PointeeType->isObjectType()) 7781 continue; 7782 7783 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7784 7785 // T& operator[](ptrdiff_t, T*) 7786 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7787 } 7788 } 7789 7790 // C++ [over.built]p11: 7791 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7792 // C1 is the same type as C2 or is a derived class of C2, T is an object 7793 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7794 // there exist candidate operator functions of the form 7795 // 7796 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7797 // 7798 // where CV12 is the union of CV1 and CV2. 7799 void addArrowStarOverloads() { 7800 for (BuiltinCandidateTypeSet::iterator 7801 Ptr = CandidateTypes[0].pointer_begin(), 7802 PtrEnd = CandidateTypes[0].pointer_end(); 7803 Ptr != PtrEnd; ++Ptr) { 7804 QualType C1Ty = (*Ptr); 7805 QualType C1; 7806 QualifierCollector Q1; 7807 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7808 if (!isa<RecordType>(C1)) 7809 continue; 7810 // heuristic to reduce number of builtin candidates in the set. 7811 // Add volatile/restrict version only if there are conversions to a 7812 // volatile/restrict type. 7813 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7814 continue; 7815 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7816 continue; 7817 for (BuiltinCandidateTypeSet::iterator 7818 MemPtr = CandidateTypes[1].member_pointer_begin(), 7819 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7820 MemPtr != MemPtrEnd; ++MemPtr) { 7821 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7822 QualType C2 = QualType(mptr->getClass(), 0); 7823 C2 = C2.getUnqualifiedType(); 7824 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7825 break; 7826 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7827 // build CV12 T& 7828 QualType T = mptr->getPointeeType(); 7829 if (!VisibleTypeConversionsQuals.hasVolatile() && 7830 T.isVolatileQualified()) 7831 continue; 7832 if (!VisibleTypeConversionsQuals.hasRestrict() && 7833 T.isRestrictQualified()) 7834 continue; 7835 T = Q1.apply(S.Context, T); 7836 QualType ResultTy = S.Context.getLValueReferenceType(T); 7837 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7838 } 7839 } 7840 } 7841 7842 // Note that we don't consider the first argument, since it has been 7843 // contextually converted to bool long ago. The candidates below are 7844 // therefore added as binary. 7845 // 7846 // C++ [over.built]p25: 7847 // For every type T, where T is a pointer, pointer-to-member, or scoped 7848 // enumeration type, there exist candidate operator functions of the form 7849 // 7850 // T operator?(bool, T, T); 7851 // 7852 void addConditionalOperatorOverloads() { 7853 /// Set of (canonical) types that we've already handled. 7854 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7855 7856 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7857 for (BuiltinCandidateTypeSet::iterator 7858 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7859 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7860 Ptr != PtrEnd; ++Ptr) { 7861 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7862 continue; 7863 7864 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7865 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7866 } 7867 7868 for (BuiltinCandidateTypeSet::iterator 7869 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7870 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7871 MemPtr != MemPtrEnd; ++MemPtr) { 7872 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7873 continue; 7874 7875 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7876 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7877 } 7878 7879 if (S.getLangOpts().CPlusPlus11) { 7880 for (BuiltinCandidateTypeSet::iterator 7881 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7882 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7883 Enum != EnumEnd; ++Enum) { 7884 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7885 continue; 7886 7887 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7888 continue; 7889 7890 QualType ParamTypes[2] = { *Enum, *Enum }; 7891 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7892 } 7893 } 7894 } 7895 } 7896 }; 7897 7898 } // end anonymous namespace 7899 7900 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7901 /// operator overloads to the candidate set (C++ [over.built]), based 7902 /// on the operator @p Op and the arguments given. For example, if the 7903 /// operator is a binary '+', this routine might add "int 7904 /// operator+(int, int)" to cover integer addition. 7905 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7906 SourceLocation OpLoc, 7907 ArrayRef<Expr *> Args, 7908 OverloadCandidateSet &CandidateSet) { 7909 // Find all of the types that the arguments can convert to, but only 7910 // if the operator we're looking at has built-in operator candidates 7911 // that make use of these types. Also record whether we encounter non-record 7912 // candidate types or either arithmetic or enumeral candidate types. 7913 Qualifiers VisibleTypeConversionsQuals; 7914 VisibleTypeConversionsQuals.addConst(); 7915 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7916 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7917 7918 bool HasNonRecordCandidateType = false; 7919 bool HasArithmeticOrEnumeralCandidateType = false; 7920 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7921 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7922 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7923 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7924 OpLoc, 7925 true, 7926 (Op == OO_Exclaim || 7927 Op == OO_AmpAmp || 7928 Op == OO_PipePipe), 7929 VisibleTypeConversionsQuals); 7930 HasNonRecordCandidateType = HasNonRecordCandidateType || 7931 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7932 HasArithmeticOrEnumeralCandidateType = 7933 HasArithmeticOrEnumeralCandidateType || 7934 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7935 } 7936 7937 // Exit early when no non-record types have been added to the candidate set 7938 // for any of the arguments to the operator. 7939 // 7940 // We can't exit early for !, ||, or &&, since there we have always have 7941 // 'bool' overloads. 7942 if (!HasNonRecordCandidateType && 7943 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7944 return; 7945 7946 // Setup an object to manage the common state for building overloads. 7947 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7948 VisibleTypeConversionsQuals, 7949 HasArithmeticOrEnumeralCandidateType, 7950 CandidateTypes, CandidateSet); 7951 7952 // Dispatch over the operation to add in only those overloads which apply. 7953 switch (Op) { 7954 case OO_None: 7955 case NUM_OVERLOADED_OPERATORS: 7956 llvm_unreachable("Expected an overloaded operator"); 7957 7958 case OO_New: 7959 case OO_Delete: 7960 case OO_Array_New: 7961 case OO_Array_Delete: 7962 case OO_Call: 7963 llvm_unreachable( 7964 "Special operators don't use AddBuiltinOperatorCandidates"); 7965 7966 case OO_Comma: 7967 case OO_Arrow: 7968 // C++ [over.match.oper]p3: 7969 // -- For the operator ',', the unary operator '&', or the 7970 // operator '->', the built-in candidates set is empty. 7971 break; 7972 7973 case OO_Plus: // '+' is either unary or binary 7974 if (Args.size() == 1) 7975 OpBuilder.addUnaryPlusPointerOverloads(); 7976 // Fall through. 7977 7978 case OO_Minus: // '-' is either unary or binary 7979 if (Args.size() == 1) { 7980 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7981 } else { 7982 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7983 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7984 } 7985 break; 7986 7987 case OO_Star: // '*' is either unary or binary 7988 if (Args.size() == 1) 7989 OpBuilder.addUnaryStarPointerOverloads(); 7990 else 7991 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7992 break; 7993 7994 case OO_Slash: 7995 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7996 break; 7997 7998 case OO_PlusPlus: 7999 case OO_MinusMinus: 8000 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8001 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8002 break; 8003 8004 case OO_EqualEqual: 8005 case OO_ExclaimEqual: 8006 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8007 // Fall through. 8008 8009 case OO_Less: 8010 case OO_Greater: 8011 case OO_LessEqual: 8012 case OO_GreaterEqual: 8013 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8014 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8015 break; 8016 8017 case OO_Percent: 8018 case OO_Caret: 8019 case OO_Pipe: 8020 case OO_LessLess: 8021 case OO_GreaterGreater: 8022 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8023 break; 8024 8025 case OO_Amp: // '&' is either unary or binary 8026 if (Args.size() == 1) 8027 // C++ [over.match.oper]p3: 8028 // -- For the operator ',', the unary operator '&', or the 8029 // operator '->', the built-in candidates set is empty. 8030 break; 8031 8032 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8033 break; 8034 8035 case OO_Tilde: 8036 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8037 break; 8038 8039 case OO_Equal: 8040 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8041 // Fall through. 8042 8043 case OO_PlusEqual: 8044 case OO_MinusEqual: 8045 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8046 // Fall through. 8047 8048 case OO_StarEqual: 8049 case OO_SlashEqual: 8050 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8051 break; 8052 8053 case OO_PercentEqual: 8054 case OO_LessLessEqual: 8055 case OO_GreaterGreaterEqual: 8056 case OO_AmpEqual: 8057 case OO_CaretEqual: 8058 case OO_PipeEqual: 8059 OpBuilder.addAssignmentIntegralOverloads(); 8060 break; 8061 8062 case OO_Exclaim: 8063 OpBuilder.addExclaimOverload(); 8064 break; 8065 8066 case OO_AmpAmp: 8067 case OO_PipePipe: 8068 OpBuilder.addAmpAmpOrPipePipeOverload(); 8069 break; 8070 8071 case OO_Subscript: 8072 OpBuilder.addSubscriptOverloads(); 8073 break; 8074 8075 case OO_ArrowStar: 8076 OpBuilder.addArrowStarOverloads(); 8077 break; 8078 8079 case OO_Conditional: 8080 OpBuilder.addConditionalOperatorOverloads(); 8081 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8082 break; 8083 } 8084 } 8085 8086 /// \brief Add function candidates found via argument-dependent lookup 8087 /// to the set of overloading candidates. 8088 /// 8089 /// This routine performs argument-dependent name lookup based on the 8090 /// given function name (which may also be an operator name) and adds 8091 /// all of the overload candidates found by ADL to the overload 8092 /// candidate set (C++ [basic.lookup.argdep]). 8093 void 8094 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8095 bool Operator, SourceLocation Loc, 8096 ArrayRef<Expr *> Args, 8097 TemplateArgumentListInfo *ExplicitTemplateArgs, 8098 OverloadCandidateSet& CandidateSet, 8099 bool PartialOverloading) { 8100 ADLResult Fns; 8101 8102 // FIXME: This approach for uniquing ADL results (and removing 8103 // redundant candidates from the set) relies on pointer-equality, 8104 // which means we need to key off the canonical decl. However, 8105 // always going back to the canonical decl might not get us the 8106 // right set of default arguments. What default arguments are 8107 // we supposed to consider on ADL candidates, anyway? 8108 8109 // FIXME: Pass in the explicit template arguments? 8110 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 8111 8112 // Erase all of the candidates we already knew about. 8113 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8114 CandEnd = CandidateSet.end(); 8115 Cand != CandEnd; ++Cand) 8116 if (Cand->Function) { 8117 Fns.erase(Cand->Function); 8118 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8119 Fns.erase(FunTmpl); 8120 } 8121 8122 // For each of the ADL candidates we found, add it to the overload 8123 // set. 8124 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8125 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8126 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8127 if (ExplicitTemplateArgs) 8128 continue; 8129 8130 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8131 PartialOverloading); 8132 } else 8133 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8134 FoundDecl, ExplicitTemplateArgs, 8135 Args, CandidateSet); 8136 } 8137 } 8138 8139 /// isBetterOverloadCandidate - Determines whether the first overload 8140 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8141 bool 8142 isBetterOverloadCandidate(Sema &S, 8143 const OverloadCandidate &Cand1, 8144 const OverloadCandidate &Cand2, 8145 SourceLocation Loc, 8146 bool UserDefinedConversion) { 8147 // Define viable functions to be better candidates than non-viable 8148 // functions. 8149 if (!Cand2.Viable) 8150 return Cand1.Viable; 8151 else if (!Cand1.Viable) 8152 return false; 8153 8154 // C++ [over.match.best]p1: 8155 // 8156 // -- if F is a static member function, ICS1(F) is defined such 8157 // that ICS1(F) is neither better nor worse than ICS1(G) for 8158 // any function G, and, symmetrically, ICS1(G) is neither 8159 // better nor worse than ICS1(F). 8160 unsigned StartArg = 0; 8161 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8162 StartArg = 1; 8163 8164 // C++ [over.match.best]p1: 8165 // A viable function F1 is defined to be a better function than another 8166 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8167 // conversion sequence than ICSi(F2), and then... 8168 unsigned NumArgs = Cand1.NumConversions; 8169 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8170 bool HasBetterConversion = false; 8171 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8172 switch (CompareImplicitConversionSequences(S, 8173 Cand1.Conversions[ArgIdx], 8174 Cand2.Conversions[ArgIdx])) { 8175 case ImplicitConversionSequence::Better: 8176 // Cand1 has a better conversion sequence. 8177 HasBetterConversion = true; 8178 break; 8179 8180 case ImplicitConversionSequence::Worse: 8181 // Cand1 can't be better than Cand2. 8182 return false; 8183 8184 case ImplicitConversionSequence::Indistinguishable: 8185 // Do nothing. 8186 break; 8187 } 8188 } 8189 8190 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8191 // ICSj(F2), or, if not that, 8192 if (HasBetterConversion) 8193 return true; 8194 8195 // - F1 is a non-template function and F2 is a function template 8196 // specialization, or, if not that, 8197 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 8198 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 8199 return true; 8200 8201 // -- F1 and F2 are function template specializations, and the function 8202 // template for F1 is more specialized than the template for F2 8203 // according to the partial ordering rules described in 14.5.5.2, or, 8204 // if not that, 8205 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 8206 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 8207 if (FunctionTemplateDecl *BetterTemplate 8208 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8209 Cand2.Function->getPrimaryTemplate(), 8210 Loc, 8211 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8212 : TPOC_Call, 8213 Cand1.ExplicitCallArguments, 8214 Cand2.ExplicitCallArguments)) 8215 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8216 } 8217 8218 // -- the context is an initialization by user-defined conversion 8219 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8220 // from the return type of F1 to the destination type (i.e., 8221 // the type of the entity being initialized) is a better 8222 // conversion sequence than the standard conversion sequence 8223 // from the return type of F2 to the destination type. 8224 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8225 isa<CXXConversionDecl>(Cand1.Function) && 8226 isa<CXXConversionDecl>(Cand2.Function)) { 8227 // First check whether we prefer one of the conversion functions over the 8228 // other. This only distinguishes the results in non-standard, extension 8229 // cases such as the conversion from a lambda closure type to a function 8230 // pointer or block. 8231 ImplicitConversionSequence::CompareKind FuncResult 8232 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8233 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8234 return FuncResult; 8235 8236 switch (CompareStandardConversionSequences(S, 8237 Cand1.FinalConversion, 8238 Cand2.FinalConversion)) { 8239 case ImplicitConversionSequence::Better: 8240 // Cand1 has a better conversion sequence. 8241 return true; 8242 8243 case ImplicitConversionSequence::Worse: 8244 // Cand1 can't be better than Cand2. 8245 return false; 8246 8247 case ImplicitConversionSequence::Indistinguishable: 8248 // Do nothing 8249 break; 8250 } 8251 } 8252 8253 // Check for enable_if value-based overload resolution. 8254 if (Cand1.Function && Cand2.Function && 8255 (Cand1.Function->hasAttr<EnableIfAttr>() || 8256 Cand2.Function->hasAttr<EnableIfAttr>())) { 8257 // FIXME: The next several lines are just 8258 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8259 // instead of reverse order which is how they're stored in the AST. 8260 AttrVec Cand1Attrs; 8261 AttrVec::iterator Cand1E = Cand1Attrs.end(); 8262 if (Cand1.Function->hasAttrs()) { 8263 Cand1Attrs = Cand1.Function->getAttrs(); 8264 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8265 IsNotEnableIfAttr); 8266 std::reverse(Cand1Attrs.begin(), Cand1E); 8267 } 8268 8269 AttrVec Cand2Attrs; 8270 AttrVec::iterator Cand2E = Cand2Attrs.end(); 8271 if (Cand2.Function->hasAttrs()) { 8272 Cand2Attrs = Cand2.Function->getAttrs(); 8273 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8274 IsNotEnableIfAttr); 8275 std::reverse(Cand2Attrs.begin(), Cand2E); 8276 } 8277 for (AttrVec::iterator 8278 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin(); 8279 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) { 8280 if (Cand1I == Cand1E) 8281 return false; 8282 if (Cand2I == Cand2E) 8283 return true; 8284 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8285 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID, 8286 S.getASTContext(), true); 8287 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID, 8288 S.getASTContext(), true); 8289 if (!(Cand1ID == Cand2ID)) 8290 return false; 8291 } 8292 } 8293 8294 return false; 8295 } 8296 8297 /// \brief Computes the best viable function (C++ 13.3.3) 8298 /// within an overload candidate set. 8299 /// 8300 /// \param Loc The location of the function name (or operator symbol) for 8301 /// which overload resolution occurs. 8302 /// 8303 /// \param Best If overload resolution was successful or found a deleted 8304 /// function, \p Best points to the candidate function found. 8305 /// 8306 /// \returns The result of overload resolution. 8307 OverloadingResult 8308 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8309 iterator &Best, 8310 bool UserDefinedConversion) { 8311 // Find the best viable function. 8312 Best = end(); 8313 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8314 if (Cand->Viable) 8315 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8316 UserDefinedConversion)) 8317 Best = Cand; 8318 } 8319 8320 // If we didn't find any viable functions, abort. 8321 if (Best == end()) 8322 return OR_No_Viable_Function; 8323 8324 // Make sure that this function is better than every other viable 8325 // function. If not, we have an ambiguity. 8326 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8327 if (Cand->Viable && 8328 Cand != Best && 8329 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8330 UserDefinedConversion)) { 8331 Best = end(); 8332 return OR_Ambiguous; 8333 } 8334 } 8335 8336 // Best is the best viable function. 8337 if (Best->Function && 8338 (Best->Function->isDeleted() || 8339 S.isFunctionConsideredUnavailable(Best->Function))) 8340 return OR_Deleted; 8341 8342 return OR_Success; 8343 } 8344 8345 namespace { 8346 8347 enum OverloadCandidateKind { 8348 oc_function, 8349 oc_method, 8350 oc_constructor, 8351 oc_function_template, 8352 oc_method_template, 8353 oc_constructor_template, 8354 oc_implicit_default_constructor, 8355 oc_implicit_copy_constructor, 8356 oc_implicit_move_constructor, 8357 oc_implicit_copy_assignment, 8358 oc_implicit_move_assignment, 8359 oc_implicit_inherited_constructor 8360 }; 8361 8362 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8363 FunctionDecl *Fn, 8364 std::string &Description) { 8365 bool isTemplate = false; 8366 8367 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8368 isTemplate = true; 8369 Description = S.getTemplateArgumentBindingsText( 8370 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8371 } 8372 8373 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8374 if (!Ctor->isImplicit()) 8375 return isTemplate ? oc_constructor_template : oc_constructor; 8376 8377 if (Ctor->getInheritedConstructor()) 8378 return oc_implicit_inherited_constructor; 8379 8380 if (Ctor->isDefaultConstructor()) 8381 return oc_implicit_default_constructor; 8382 8383 if (Ctor->isMoveConstructor()) 8384 return oc_implicit_move_constructor; 8385 8386 assert(Ctor->isCopyConstructor() && 8387 "unexpected sort of implicit constructor"); 8388 return oc_implicit_copy_constructor; 8389 } 8390 8391 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8392 // This actually gets spelled 'candidate function' for now, but 8393 // it doesn't hurt to split it out. 8394 if (!Meth->isImplicit()) 8395 return isTemplate ? oc_method_template : oc_method; 8396 8397 if (Meth->isMoveAssignmentOperator()) 8398 return oc_implicit_move_assignment; 8399 8400 if (Meth->isCopyAssignmentOperator()) 8401 return oc_implicit_copy_assignment; 8402 8403 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8404 return oc_method; 8405 } 8406 8407 return isTemplate ? oc_function_template : oc_function; 8408 } 8409 8410 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8411 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8412 if (!Ctor) return; 8413 8414 Ctor = Ctor->getInheritedConstructor(); 8415 if (!Ctor) return; 8416 8417 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8418 } 8419 8420 } // end anonymous namespace 8421 8422 // Notes the location of an overload candidate. 8423 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8424 std::string FnDesc; 8425 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8426 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8427 << (unsigned) K << FnDesc; 8428 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8429 Diag(Fn->getLocation(), PD); 8430 MaybeEmitInheritedConstructorNote(*this, Fn); 8431 } 8432 8433 // Notes the location of all overload candidates designated through 8434 // OverloadedExpr 8435 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8436 assert(OverloadedExpr->getType() == Context.OverloadTy); 8437 8438 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8439 OverloadExpr *OvlExpr = Ovl.Expression; 8440 8441 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8442 IEnd = OvlExpr->decls_end(); 8443 I != IEnd; ++I) { 8444 if (FunctionTemplateDecl *FunTmpl = 8445 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8446 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8447 } else if (FunctionDecl *Fun 8448 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8449 NoteOverloadCandidate(Fun, DestType); 8450 } 8451 } 8452 } 8453 8454 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8455 /// "lead" diagnostic; it will be given two arguments, the source and 8456 /// target types of the conversion. 8457 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8458 Sema &S, 8459 SourceLocation CaretLoc, 8460 const PartialDiagnostic &PDiag) const { 8461 S.Diag(CaretLoc, PDiag) 8462 << Ambiguous.getFromType() << Ambiguous.getToType(); 8463 // FIXME: The note limiting machinery is borrowed from 8464 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8465 // refactoring here. 8466 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8467 unsigned CandsShown = 0; 8468 AmbiguousConversionSequence::const_iterator I, E; 8469 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8470 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8471 break; 8472 ++CandsShown; 8473 S.NoteOverloadCandidate(*I); 8474 } 8475 if (I != E) 8476 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8477 } 8478 8479 namespace { 8480 8481 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8482 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8483 assert(Conv.isBad()); 8484 assert(Cand->Function && "for now, candidate must be a function"); 8485 FunctionDecl *Fn = Cand->Function; 8486 8487 // There's a conversion slot for the object argument if this is a 8488 // non-constructor method. Note that 'I' corresponds the 8489 // conversion-slot index. 8490 bool isObjectArgument = false; 8491 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8492 if (I == 0) 8493 isObjectArgument = true; 8494 else 8495 I--; 8496 } 8497 8498 std::string FnDesc; 8499 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8500 8501 Expr *FromExpr = Conv.Bad.FromExpr; 8502 QualType FromTy = Conv.Bad.getFromType(); 8503 QualType ToTy = Conv.Bad.getToType(); 8504 8505 if (FromTy == S.Context.OverloadTy) { 8506 assert(FromExpr && "overload set argument came from implicit argument?"); 8507 Expr *E = FromExpr->IgnoreParens(); 8508 if (isa<UnaryOperator>(E)) 8509 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8510 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8511 8512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8513 << (unsigned) FnKind << FnDesc 8514 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8515 << ToTy << Name << I+1; 8516 MaybeEmitInheritedConstructorNote(S, Fn); 8517 return; 8518 } 8519 8520 // Do some hand-waving analysis to see if the non-viability is due 8521 // to a qualifier mismatch. 8522 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8523 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8524 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8525 CToTy = RT->getPointeeType(); 8526 else { 8527 // TODO: detect and diagnose the full richness of const mismatches. 8528 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8529 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8530 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8531 } 8532 8533 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8534 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8535 Qualifiers FromQs = CFromTy.getQualifiers(); 8536 Qualifiers ToQs = CToTy.getQualifiers(); 8537 8538 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8540 << (unsigned) FnKind << FnDesc 8541 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8542 << FromTy 8543 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8544 << (unsigned) isObjectArgument << I+1; 8545 MaybeEmitInheritedConstructorNote(S, Fn); 8546 return; 8547 } 8548 8549 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8550 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8551 << (unsigned) FnKind << FnDesc 8552 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8553 << FromTy 8554 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8555 << (unsigned) isObjectArgument << I+1; 8556 MaybeEmitInheritedConstructorNote(S, Fn); 8557 return; 8558 } 8559 8560 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8561 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8562 << (unsigned) FnKind << FnDesc 8563 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8564 << FromTy 8565 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8566 << (unsigned) isObjectArgument << I+1; 8567 MaybeEmitInheritedConstructorNote(S, Fn); 8568 return; 8569 } 8570 8571 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8572 assert(CVR && "unexpected qualifiers mismatch"); 8573 8574 if (isObjectArgument) { 8575 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8576 << (unsigned) FnKind << FnDesc 8577 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8578 << FromTy << (CVR - 1); 8579 } else { 8580 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8581 << (unsigned) FnKind << FnDesc 8582 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8583 << FromTy << (CVR - 1) << I+1; 8584 } 8585 MaybeEmitInheritedConstructorNote(S, Fn); 8586 return; 8587 } 8588 8589 // Special diagnostic for failure to convert an initializer list, since 8590 // telling the user that it has type void is not useful. 8591 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8592 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8593 << (unsigned) FnKind << FnDesc 8594 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8595 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8596 MaybeEmitInheritedConstructorNote(S, Fn); 8597 return; 8598 } 8599 8600 // Diagnose references or pointers to incomplete types differently, 8601 // since it's far from impossible that the incompleteness triggered 8602 // the failure. 8603 QualType TempFromTy = FromTy.getNonReferenceType(); 8604 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8605 TempFromTy = PTy->getPointeeType(); 8606 if (TempFromTy->isIncompleteType()) { 8607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8608 << (unsigned) FnKind << FnDesc 8609 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8610 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8611 MaybeEmitInheritedConstructorNote(S, Fn); 8612 return; 8613 } 8614 8615 // Diagnose base -> derived pointer conversions. 8616 unsigned BaseToDerivedConversion = 0; 8617 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8618 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8619 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8620 FromPtrTy->getPointeeType()) && 8621 !FromPtrTy->getPointeeType()->isIncompleteType() && 8622 !ToPtrTy->getPointeeType()->isIncompleteType() && 8623 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8624 FromPtrTy->getPointeeType())) 8625 BaseToDerivedConversion = 1; 8626 } 8627 } else if (const ObjCObjectPointerType *FromPtrTy 8628 = FromTy->getAs<ObjCObjectPointerType>()) { 8629 if (const ObjCObjectPointerType *ToPtrTy 8630 = ToTy->getAs<ObjCObjectPointerType>()) 8631 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8632 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8633 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8634 FromPtrTy->getPointeeType()) && 8635 FromIface->isSuperClassOf(ToIface)) 8636 BaseToDerivedConversion = 2; 8637 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8638 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8639 !FromTy->isIncompleteType() && 8640 !ToRefTy->getPointeeType()->isIncompleteType() && 8641 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8642 BaseToDerivedConversion = 3; 8643 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8644 ToTy.getNonReferenceType().getCanonicalType() == 8645 FromTy.getNonReferenceType().getCanonicalType()) { 8646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8647 << (unsigned) FnKind << FnDesc 8648 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8649 << (unsigned) isObjectArgument << I + 1; 8650 MaybeEmitInheritedConstructorNote(S, Fn); 8651 return; 8652 } 8653 } 8654 8655 if (BaseToDerivedConversion) { 8656 S.Diag(Fn->getLocation(), 8657 diag::note_ovl_candidate_bad_base_to_derived_conv) 8658 << (unsigned) FnKind << FnDesc 8659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8660 << (BaseToDerivedConversion - 1) 8661 << FromTy << ToTy << I+1; 8662 MaybeEmitInheritedConstructorNote(S, Fn); 8663 return; 8664 } 8665 8666 if (isa<ObjCObjectPointerType>(CFromTy) && 8667 isa<PointerType>(CToTy)) { 8668 Qualifiers FromQs = CFromTy.getQualifiers(); 8669 Qualifiers ToQs = CToTy.getQualifiers(); 8670 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8672 << (unsigned) FnKind << FnDesc 8673 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8674 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8675 MaybeEmitInheritedConstructorNote(S, Fn); 8676 return; 8677 } 8678 } 8679 8680 // Emit the generic diagnostic and, optionally, add the hints to it. 8681 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8682 FDiag << (unsigned) FnKind << FnDesc 8683 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8684 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8685 << (unsigned) (Cand->Fix.Kind); 8686 8687 // If we can fix the conversion, suggest the FixIts. 8688 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8689 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8690 FDiag << *HI; 8691 S.Diag(Fn->getLocation(), FDiag); 8692 8693 MaybeEmitInheritedConstructorNote(S, Fn); 8694 } 8695 8696 /// Additional arity mismatch diagnosis specific to a function overload 8697 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8698 /// over a candidate in any candidate set. 8699 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8700 unsigned NumArgs) { 8701 FunctionDecl *Fn = Cand->Function; 8702 unsigned MinParams = Fn->getMinRequiredArguments(); 8703 8704 // With invalid overloaded operators, it's possible that we think we 8705 // have an arity mismatch when in fact it looks like we have the 8706 // right number of arguments, because only overloaded operators have 8707 // the weird behavior of overloading member and non-member functions. 8708 // Just don't report anything. 8709 if (Fn->isInvalidDecl() && 8710 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8711 return true; 8712 8713 if (NumArgs < MinParams) { 8714 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8715 (Cand->FailureKind == ovl_fail_bad_deduction && 8716 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8717 } else { 8718 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8719 (Cand->FailureKind == ovl_fail_bad_deduction && 8720 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8721 } 8722 8723 return false; 8724 } 8725 8726 /// General arity mismatch diagnosis over a candidate in a candidate set. 8727 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8728 assert(isa<FunctionDecl>(D) && 8729 "The templated declaration should at least be a function" 8730 " when diagnosing bad template argument deduction due to too many" 8731 " or too few arguments"); 8732 8733 FunctionDecl *Fn = cast<FunctionDecl>(D); 8734 8735 // TODO: treat calls to a missing default constructor as a special case 8736 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8737 unsigned MinParams = Fn->getMinRequiredArguments(); 8738 8739 // at least / at most / exactly 8740 unsigned mode, modeCount; 8741 if (NumFormalArgs < MinParams) { 8742 if (MinParams != FnTy->getNumArgs() || 8743 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8744 mode = 0; // "at least" 8745 else 8746 mode = 2; // "exactly" 8747 modeCount = MinParams; 8748 } else { 8749 if (MinParams != FnTy->getNumArgs()) 8750 mode = 1; // "at most" 8751 else 8752 mode = 2; // "exactly" 8753 modeCount = FnTy->getNumArgs(); 8754 } 8755 8756 std::string Description; 8757 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8758 8759 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8761 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8762 << Fn->getParamDecl(0) << NumFormalArgs; 8763 else 8764 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8765 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8766 << modeCount << NumFormalArgs; 8767 MaybeEmitInheritedConstructorNote(S, Fn); 8768 } 8769 8770 /// Arity mismatch diagnosis specific to a function overload candidate. 8771 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8772 unsigned NumFormalArgs) { 8773 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8774 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8775 } 8776 8777 TemplateDecl *getDescribedTemplate(Decl *Templated) { 8778 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8779 return FD->getDescribedFunctionTemplate(); 8780 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8781 return RD->getDescribedClassTemplate(); 8782 8783 llvm_unreachable("Unsupported: Getting the described template declaration" 8784 " for bad deduction diagnosis"); 8785 } 8786 8787 /// Diagnose a failed template-argument deduction. 8788 void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8789 DeductionFailureInfo &DeductionFailure, 8790 unsigned NumArgs) { 8791 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8792 NamedDecl *ParamD; 8793 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8794 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8795 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8796 switch (DeductionFailure.Result) { 8797 case Sema::TDK_Success: 8798 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8799 8800 case Sema::TDK_Incomplete: { 8801 assert(ParamD && "no parameter found for incomplete deduction result"); 8802 S.Diag(Templated->getLocation(), 8803 diag::note_ovl_candidate_incomplete_deduction) 8804 << ParamD->getDeclName(); 8805 MaybeEmitInheritedConstructorNote(S, Templated); 8806 return; 8807 } 8808 8809 case Sema::TDK_Underqualified: { 8810 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8811 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8812 8813 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8814 8815 // Param will have been canonicalized, but it should just be a 8816 // qualified version of ParamD, so move the qualifiers to that. 8817 QualifierCollector Qs; 8818 Qs.strip(Param); 8819 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8820 assert(S.Context.hasSameType(Param, NonCanonParam)); 8821 8822 // Arg has also been canonicalized, but there's nothing we can do 8823 // about that. It also doesn't matter as much, because it won't 8824 // have any template parameters in it (because deduction isn't 8825 // done on dependent types). 8826 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8827 8828 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8829 << ParamD->getDeclName() << Arg << NonCanonParam; 8830 MaybeEmitInheritedConstructorNote(S, Templated); 8831 return; 8832 } 8833 8834 case Sema::TDK_Inconsistent: { 8835 assert(ParamD && "no parameter found for inconsistent deduction result"); 8836 int which = 0; 8837 if (isa<TemplateTypeParmDecl>(ParamD)) 8838 which = 0; 8839 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8840 which = 1; 8841 else { 8842 which = 2; 8843 } 8844 8845 S.Diag(Templated->getLocation(), 8846 diag::note_ovl_candidate_inconsistent_deduction) 8847 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8848 << *DeductionFailure.getSecondArg(); 8849 MaybeEmitInheritedConstructorNote(S, Templated); 8850 return; 8851 } 8852 8853 case Sema::TDK_InvalidExplicitArguments: 8854 assert(ParamD && "no parameter found for invalid explicit arguments"); 8855 if (ParamD->getDeclName()) 8856 S.Diag(Templated->getLocation(), 8857 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8858 << ParamD->getDeclName(); 8859 else { 8860 int index = 0; 8861 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8862 index = TTP->getIndex(); 8863 else if (NonTypeTemplateParmDecl *NTTP 8864 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8865 index = NTTP->getIndex(); 8866 else 8867 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8868 S.Diag(Templated->getLocation(), 8869 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8870 << (index + 1); 8871 } 8872 MaybeEmitInheritedConstructorNote(S, Templated); 8873 return; 8874 8875 case Sema::TDK_TooManyArguments: 8876 case Sema::TDK_TooFewArguments: 8877 DiagnoseArityMismatch(S, Templated, NumArgs); 8878 return; 8879 8880 case Sema::TDK_InstantiationDepth: 8881 S.Diag(Templated->getLocation(), 8882 diag::note_ovl_candidate_instantiation_depth); 8883 MaybeEmitInheritedConstructorNote(S, Templated); 8884 return; 8885 8886 case Sema::TDK_SubstitutionFailure: { 8887 // Format the template argument list into the argument string. 8888 SmallString<128> TemplateArgString; 8889 if (TemplateArgumentList *Args = 8890 DeductionFailure.getTemplateArgumentList()) { 8891 TemplateArgString = " "; 8892 TemplateArgString += S.getTemplateArgumentBindingsText( 8893 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8894 } 8895 8896 // If this candidate was disabled by enable_if, say so. 8897 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8898 if (PDiag && PDiag->second.getDiagID() == 8899 diag::err_typename_nested_not_found_enable_if) { 8900 // FIXME: Use the source range of the condition, and the fully-qualified 8901 // name of the enable_if template. These are both present in PDiag. 8902 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8903 << "'enable_if'" << TemplateArgString; 8904 return; 8905 } 8906 8907 // Format the SFINAE diagnostic into the argument string. 8908 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8909 // formatted message in another diagnostic. 8910 SmallString<128> SFINAEArgString; 8911 SourceRange R; 8912 if (PDiag) { 8913 SFINAEArgString = ": "; 8914 R = SourceRange(PDiag->first, PDiag->first); 8915 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8916 } 8917 8918 S.Diag(Templated->getLocation(), 8919 diag::note_ovl_candidate_substitution_failure) 8920 << TemplateArgString << SFINAEArgString << R; 8921 MaybeEmitInheritedConstructorNote(S, Templated); 8922 return; 8923 } 8924 8925 case Sema::TDK_FailedOverloadResolution: { 8926 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8927 S.Diag(Templated->getLocation(), 8928 diag::note_ovl_candidate_failed_overload_resolution) 8929 << R.Expression->getName(); 8930 return; 8931 } 8932 8933 case Sema::TDK_NonDeducedMismatch: { 8934 // FIXME: Provide a source location to indicate what we couldn't match. 8935 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8936 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8937 if (FirstTA.getKind() == TemplateArgument::Template && 8938 SecondTA.getKind() == TemplateArgument::Template) { 8939 TemplateName FirstTN = FirstTA.getAsTemplate(); 8940 TemplateName SecondTN = SecondTA.getAsTemplate(); 8941 if (FirstTN.getKind() == TemplateName::Template && 8942 SecondTN.getKind() == TemplateName::Template) { 8943 if (FirstTN.getAsTemplateDecl()->getName() == 8944 SecondTN.getAsTemplateDecl()->getName()) { 8945 // FIXME: This fixes a bad diagnostic where both templates are named 8946 // the same. This particular case is a bit difficult since: 8947 // 1) It is passed as a string to the diagnostic printer. 8948 // 2) The diagnostic printer only attempts to find a better 8949 // name for types, not decls. 8950 // Ideally, this should folded into the diagnostic printer. 8951 S.Diag(Templated->getLocation(), 8952 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8953 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8954 return; 8955 } 8956 } 8957 } 8958 // FIXME: For generic lambda parameters, check if the function is a lambda 8959 // call operator, and if so, emit a prettier and more informative 8960 // diagnostic that mentions 'auto' and lambda in addition to 8961 // (or instead of?) the canonical template type parameters. 8962 S.Diag(Templated->getLocation(), 8963 diag::note_ovl_candidate_non_deduced_mismatch) 8964 << FirstTA << SecondTA; 8965 return; 8966 } 8967 // TODO: diagnose these individually, then kill off 8968 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8969 case Sema::TDK_MiscellaneousDeductionFailure: 8970 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 8971 MaybeEmitInheritedConstructorNote(S, Templated); 8972 return; 8973 } 8974 } 8975 8976 /// Diagnose a failed template-argument deduction, for function calls. 8977 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 8978 unsigned TDK = Cand->DeductionFailure.Result; 8979 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 8980 if (CheckArityMismatch(S, Cand, NumArgs)) 8981 return; 8982 } 8983 DiagnoseBadDeduction(S, Cand->Function, // pattern 8984 Cand->DeductionFailure, NumArgs); 8985 } 8986 8987 /// CUDA: diagnose an invalid call across targets. 8988 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8989 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8990 FunctionDecl *Callee = Cand->Function; 8991 8992 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8993 CalleeTarget = S.IdentifyCUDATarget(Callee); 8994 8995 std::string FnDesc; 8996 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8997 8998 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8999 << (unsigned) FnKind << CalleeTarget << CallerTarget; 9000 } 9001 9002 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9003 FunctionDecl *Callee = Cand->Function; 9004 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9005 9006 S.Diag(Callee->getLocation(), 9007 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9008 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9009 } 9010 9011 /// Generates a 'note' diagnostic for an overload candidate. We've 9012 /// already generated a primary error at the call site. 9013 /// 9014 /// It really does need to be a single diagnostic with its caret 9015 /// pointed at the candidate declaration. Yes, this creates some 9016 /// major challenges of technical writing. Yes, this makes pointing 9017 /// out problems with specific arguments quite awkward. It's still 9018 /// better than generating twenty screens of text for every failed 9019 /// overload. 9020 /// 9021 /// It would be great to be able to express per-candidate problems 9022 /// more richly for those diagnostic clients that cared, but we'd 9023 /// still have to be just as careful with the default diagnostics. 9024 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9025 unsigned NumArgs) { 9026 FunctionDecl *Fn = Cand->Function; 9027 9028 // Note deleted candidates, but only if they're viable. 9029 if (Cand->Viable && (Fn->isDeleted() || 9030 S.isFunctionConsideredUnavailable(Fn))) { 9031 std::string FnDesc; 9032 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9033 9034 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9035 << FnKind << FnDesc 9036 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9037 MaybeEmitInheritedConstructorNote(S, Fn); 9038 return; 9039 } 9040 9041 // We don't really have anything else to say about viable candidates. 9042 if (Cand->Viable) { 9043 S.NoteOverloadCandidate(Fn); 9044 return; 9045 } 9046 9047 switch (Cand->FailureKind) { 9048 case ovl_fail_too_many_arguments: 9049 case ovl_fail_too_few_arguments: 9050 return DiagnoseArityMismatch(S, Cand, NumArgs); 9051 9052 case ovl_fail_bad_deduction: 9053 return DiagnoseBadDeduction(S, Cand, NumArgs); 9054 9055 case ovl_fail_trivial_conversion: 9056 case ovl_fail_bad_final_conversion: 9057 case ovl_fail_final_conversion_not_exact: 9058 return S.NoteOverloadCandidate(Fn); 9059 9060 case ovl_fail_bad_conversion: { 9061 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9062 for (unsigned N = Cand->NumConversions; I != N; ++I) 9063 if (Cand->Conversions[I].isBad()) 9064 return DiagnoseBadConversion(S, Cand, I); 9065 9066 // FIXME: this currently happens when we're called from SemaInit 9067 // when user-conversion overload fails. Figure out how to handle 9068 // those conditions and diagnose them well. 9069 return S.NoteOverloadCandidate(Fn); 9070 } 9071 9072 case ovl_fail_bad_target: 9073 return DiagnoseBadTarget(S, Cand); 9074 9075 case ovl_fail_enable_if: 9076 return DiagnoseFailedEnableIfAttr(S, Cand); 9077 } 9078 } 9079 9080 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9081 // Desugar the type of the surrogate down to a function type, 9082 // retaining as many typedefs as possible while still showing 9083 // the function type (and, therefore, its parameter types). 9084 QualType FnType = Cand->Surrogate->getConversionType(); 9085 bool isLValueReference = false; 9086 bool isRValueReference = false; 9087 bool isPointer = false; 9088 if (const LValueReferenceType *FnTypeRef = 9089 FnType->getAs<LValueReferenceType>()) { 9090 FnType = FnTypeRef->getPointeeType(); 9091 isLValueReference = true; 9092 } else if (const RValueReferenceType *FnTypeRef = 9093 FnType->getAs<RValueReferenceType>()) { 9094 FnType = FnTypeRef->getPointeeType(); 9095 isRValueReference = true; 9096 } 9097 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9098 FnType = FnTypePtr->getPointeeType(); 9099 isPointer = true; 9100 } 9101 // Desugar down to a function type. 9102 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9103 // Reconstruct the pointer/reference as appropriate. 9104 if (isPointer) FnType = S.Context.getPointerType(FnType); 9105 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9106 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9107 9108 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9109 << FnType; 9110 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9111 } 9112 9113 void NoteBuiltinOperatorCandidate(Sema &S, 9114 StringRef Opc, 9115 SourceLocation OpLoc, 9116 OverloadCandidate *Cand) { 9117 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9118 std::string TypeStr("operator"); 9119 TypeStr += Opc; 9120 TypeStr += "("; 9121 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9122 if (Cand->NumConversions == 1) { 9123 TypeStr += ")"; 9124 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9125 } else { 9126 TypeStr += ", "; 9127 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9128 TypeStr += ")"; 9129 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9130 } 9131 } 9132 9133 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9134 OverloadCandidate *Cand) { 9135 unsigned NoOperands = Cand->NumConversions; 9136 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9137 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9138 if (ICS.isBad()) break; // all meaningless after first invalid 9139 if (!ICS.isAmbiguous()) continue; 9140 9141 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9142 S.PDiag(diag::note_ambiguous_type_conversion)); 9143 } 9144 } 9145 9146 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9147 if (Cand->Function) 9148 return Cand->Function->getLocation(); 9149 if (Cand->IsSurrogate) 9150 return Cand->Surrogate->getLocation(); 9151 return SourceLocation(); 9152 } 9153 9154 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9155 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9156 case Sema::TDK_Success: 9157 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9158 9159 case Sema::TDK_Invalid: 9160 case Sema::TDK_Incomplete: 9161 return 1; 9162 9163 case Sema::TDK_Underqualified: 9164 case Sema::TDK_Inconsistent: 9165 return 2; 9166 9167 case Sema::TDK_SubstitutionFailure: 9168 case Sema::TDK_NonDeducedMismatch: 9169 case Sema::TDK_MiscellaneousDeductionFailure: 9170 return 3; 9171 9172 case Sema::TDK_InstantiationDepth: 9173 case Sema::TDK_FailedOverloadResolution: 9174 return 4; 9175 9176 case Sema::TDK_InvalidExplicitArguments: 9177 return 5; 9178 9179 case Sema::TDK_TooManyArguments: 9180 case Sema::TDK_TooFewArguments: 9181 return 6; 9182 } 9183 llvm_unreachable("Unhandled deduction result"); 9184 } 9185 9186 struct CompareOverloadCandidatesForDisplay { 9187 Sema &S; 9188 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 9189 9190 bool operator()(const OverloadCandidate *L, 9191 const OverloadCandidate *R) { 9192 // Fast-path this check. 9193 if (L == R) return false; 9194 9195 // Order first by viability. 9196 if (L->Viable) { 9197 if (!R->Viable) return true; 9198 9199 // TODO: introduce a tri-valued comparison for overload 9200 // candidates. Would be more worthwhile if we had a sort 9201 // that could exploit it. 9202 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9203 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9204 } else if (R->Viable) 9205 return false; 9206 9207 assert(L->Viable == R->Viable); 9208 9209 // Criteria by which we can sort non-viable candidates: 9210 if (!L->Viable) { 9211 // 1. Arity mismatches come after other candidates. 9212 if (L->FailureKind == ovl_fail_too_many_arguments || 9213 L->FailureKind == ovl_fail_too_few_arguments) 9214 return false; 9215 if (R->FailureKind == ovl_fail_too_many_arguments || 9216 R->FailureKind == ovl_fail_too_few_arguments) 9217 return true; 9218 9219 // 2. Bad conversions come first and are ordered by the number 9220 // of bad conversions and quality of good conversions. 9221 if (L->FailureKind == ovl_fail_bad_conversion) { 9222 if (R->FailureKind != ovl_fail_bad_conversion) 9223 return true; 9224 9225 // The conversion that can be fixed with a smaller number of changes, 9226 // comes first. 9227 unsigned numLFixes = L->Fix.NumConversionsFixed; 9228 unsigned numRFixes = R->Fix.NumConversionsFixed; 9229 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9230 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9231 if (numLFixes != numRFixes) { 9232 if (numLFixes < numRFixes) 9233 return true; 9234 else 9235 return false; 9236 } 9237 9238 // If there's any ordering between the defined conversions... 9239 // FIXME: this might not be transitive. 9240 assert(L->NumConversions == R->NumConversions); 9241 9242 int leftBetter = 0; 9243 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9244 for (unsigned E = L->NumConversions; I != E; ++I) { 9245 switch (CompareImplicitConversionSequences(S, 9246 L->Conversions[I], 9247 R->Conversions[I])) { 9248 case ImplicitConversionSequence::Better: 9249 leftBetter++; 9250 break; 9251 9252 case ImplicitConversionSequence::Worse: 9253 leftBetter--; 9254 break; 9255 9256 case ImplicitConversionSequence::Indistinguishable: 9257 break; 9258 } 9259 } 9260 if (leftBetter > 0) return true; 9261 if (leftBetter < 0) return false; 9262 9263 } else if (R->FailureKind == ovl_fail_bad_conversion) 9264 return false; 9265 9266 if (L->FailureKind == ovl_fail_bad_deduction) { 9267 if (R->FailureKind != ovl_fail_bad_deduction) 9268 return true; 9269 9270 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9271 return RankDeductionFailure(L->DeductionFailure) 9272 < RankDeductionFailure(R->DeductionFailure); 9273 } else if (R->FailureKind == ovl_fail_bad_deduction) 9274 return false; 9275 9276 // TODO: others? 9277 } 9278 9279 // Sort everything else by location. 9280 SourceLocation LLoc = GetLocationForCandidate(L); 9281 SourceLocation RLoc = GetLocationForCandidate(R); 9282 9283 // Put candidates without locations (e.g. builtins) at the end. 9284 if (LLoc.isInvalid()) return false; 9285 if (RLoc.isInvalid()) return true; 9286 9287 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9288 } 9289 }; 9290 9291 /// CompleteNonViableCandidate - Normally, overload resolution only 9292 /// computes up to the first. Produces the FixIt set if possible. 9293 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9294 ArrayRef<Expr *> Args) { 9295 assert(!Cand->Viable); 9296 9297 // Don't do anything on failures other than bad conversion. 9298 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9299 9300 // We only want the FixIts if all the arguments can be corrected. 9301 bool Unfixable = false; 9302 // Use a implicit copy initialization to check conversion fixes. 9303 Cand->Fix.setConversionChecker(TryCopyInitialization); 9304 9305 // Skip forward to the first bad conversion. 9306 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9307 unsigned ConvCount = Cand->NumConversions; 9308 while (true) { 9309 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9310 ConvIdx++; 9311 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9312 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9313 break; 9314 } 9315 } 9316 9317 if (ConvIdx == ConvCount) 9318 return; 9319 9320 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9321 "remaining conversion is initialized?"); 9322 9323 // FIXME: this should probably be preserved from the overload 9324 // operation somehow. 9325 bool SuppressUserConversions = false; 9326 9327 const FunctionProtoType* Proto; 9328 unsigned ArgIdx = ConvIdx; 9329 9330 if (Cand->IsSurrogate) { 9331 QualType ConvType 9332 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9333 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9334 ConvType = ConvPtrType->getPointeeType(); 9335 Proto = ConvType->getAs<FunctionProtoType>(); 9336 ArgIdx--; 9337 } else if (Cand->Function) { 9338 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9339 if (isa<CXXMethodDecl>(Cand->Function) && 9340 !isa<CXXConstructorDecl>(Cand->Function)) 9341 ArgIdx--; 9342 } else { 9343 // Builtin binary operator with a bad first conversion. 9344 assert(ConvCount <= 3); 9345 for (; ConvIdx != ConvCount; ++ConvIdx) 9346 Cand->Conversions[ConvIdx] 9347 = TryCopyInitialization(S, Args[ConvIdx], 9348 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9349 SuppressUserConversions, 9350 /*InOverloadResolution*/ true, 9351 /*AllowObjCWritebackConversion=*/ 9352 S.getLangOpts().ObjCAutoRefCount); 9353 return; 9354 } 9355 9356 // Fill in the rest of the conversions. 9357 unsigned NumArgsInProto = Proto->getNumArgs(); 9358 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9359 if (ArgIdx < NumArgsInProto) { 9360 Cand->Conversions[ConvIdx] 9361 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9362 SuppressUserConversions, 9363 /*InOverloadResolution=*/true, 9364 /*AllowObjCWritebackConversion=*/ 9365 S.getLangOpts().ObjCAutoRefCount); 9366 // Store the FixIt in the candidate if it exists. 9367 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9368 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9369 } 9370 else 9371 Cand->Conversions[ConvIdx].setEllipsis(); 9372 } 9373 } 9374 9375 } // end anonymous namespace 9376 9377 /// PrintOverloadCandidates - When overload resolution fails, prints 9378 /// diagnostic messages containing the candidates in the candidate 9379 /// set. 9380 void OverloadCandidateSet::NoteCandidates(Sema &S, 9381 OverloadCandidateDisplayKind OCD, 9382 ArrayRef<Expr *> Args, 9383 StringRef Opc, 9384 SourceLocation OpLoc) { 9385 // Sort the candidates by viability and position. Sorting directly would 9386 // be prohibitive, so we make a set of pointers and sort those. 9387 SmallVector<OverloadCandidate*, 32> Cands; 9388 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9389 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9390 if (Cand->Viable) 9391 Cands.push_back(Cand); 9392 else if (OCD == OCD_AllCandidates) { 9393 CompleteNonViableCandidate(S, Cand, Args); 9394 if (Cand->Function || Cand->IsSurrogate) 9395 Cands.push_back(Cand); 9396 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9397 // want to list every possible builtin candidate. 9398 } 9399 } 9400 9401 std::sort(Cands.begin(), Cands.end(), 9402 CompareOverloadCandidatesForDisplay(S)); 9403 9404 bool ReportedAmbiguousConversions = false; 9405 9406 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9407 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9408 unsigned CandsShown = 0; 9409 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9410 OverloadCandidate *Cand = *I; 9411 9412 // Set an arbitrary limit on the number of candidate functions we'll spam 9413 // the user with. FIXME: This limit should depend on details of the 9414 // candidate list. 9415 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9416 break; 9417 } 9418 ++CandsShown; 9419 9420 if (Cand->Function) 9421 NoteFunctionCandidate(S, Cand, Args.size()); 9422 else if (Cand->IsSurrogate) 9423 NoteSurrogateCandidate(S, Cand); 9424 else { 9425 assert(Cand->Viable && 9426 "Non-viable built-in candidates are not added to Cands."); 9427 // Generally we only see ambiguities including viable builtin 9428 // operators if overload resolution got screwed up by an 9429 // ambiguous user-defined conversion. 9430 // 9431 // FIXME: It's quite possible for different conversions to see 9432 // different ambiguities, though. 9433 if (!ReportedAmbiguousConversions) { 9434 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9435 ReportedAmbiguousConversions = true; 9436 } 9437 9438 // If this is a viable builtin, print it. 9439 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9440 } 9441 } 9442 9443 if (I != E) 9444 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9445 } 9446 9447 static SourceLocation 9448 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9449 return Cand->Specialization ? Cand->Specialization->getLocation() 9450 : SourceLocation(); 9451 } 9452 9453 struct CompareTemplateSpecCandidatesForDisplay { 9454 Sema &S; 9455 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9456 9457 bool operator()(const TemplateSpecCandidate *L, 9458 const TemplateSpecCandidate *R) { 9459 // Fast-path this check. 9460 if (L == R) 9461 return false; 9462 9463 // Assuming that both candidates are not matches... 9464 9465 // Sort by the ranking of deduction failures. 9466 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9467 return RankDeductionFailure(L->DeductionFailure) < 9468 RankDeductionFailure(R->DeductionFailure); 9469 9470 // Sort everything else by location. 9471 SourceLocation LLoc = GetLocationForCandidate(L); 9472 SourceLocation RLoc = GetLocationForCandidate(R); 9473 9474 // Put candidates without locations (e.g. builtins) at the end. 9475 if (LLoc.isInvalid()) 9476 return false; 9477 if (RLoc.isInvalid()) 9478 return true; 9479 9480 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9481 } 9482 }; 9483 9484 /// Diagnose a template argument deduction failure. 9485 /// We are treating these failures as overload failures due to bad 9486 /// deductions. 9487 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9488 DiagnoseBadDeduction(S, Specialization, // pattern 9489 DeductionFailure, /*NumArgs=*/0); 9490 } 9491 9492 void TemplateSpecCandidateSet::destroyCandidates() { 9493 for (iterator i = begin(), e = end(); i != e; ++i) { 9494 i->DeductionFailure.Destroy(); 9495 } 9496 } 9497 9498 void TemplateSpecCandidateSet::clear() { 9499 destroyCandidates(); 9500 Candidates.clear(); 9501 } 9502 9503 /// NoteCandidates - When no template specialization match is found, prints 9504 /// diagnostic messages containing the non-matching specializations that form 9505 /// the candidate set. 9506 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9507 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9508 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9509 // Sort the candidates by position (assuming no candidate is a match). 9510 // Sorting directly would be prohibitive, so we make a set of pointers 9511 // and sort those. 9512 SmallVector<TemplateSpecCandidate *, 32> Cands; 9513 Cands.reserve(size()); 9514 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9515 if (Cand->Specialization) 9516 Cands.push_back(Cand); 9517 // Otherwise, this is a non-matching builtin candidate. We do not, 9518 // in general, want to list every possible builtin candidate. 9519 } 9520 9521 std::sort(Cands.begin(), Cands.end(), 9522 CompareTemplateSpecCandidatesForDisplay(S)); 9523 9524 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9525 // for generalization purposes (?). 9526 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9527 9528 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9529 unsigned CandsShown = 0; 9530 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9531 TemplateSpecCandidate *Cand = *I; 9532 9533 // Set an arbitrary limit on the number of candidates we'll spam 9534 // the user with. FIXME: This limit should depend on details of the 9535 // candidate list. 9536 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9537 break; 9538 ++CandsShown; 9539 9540 assert(Cand->Specialization && 9541 "Non-matching built-in candidates are not added to Cands."); 9542 Cand->NoteDeductionFailure(S); 9543 } 9544 9545 if (I != E) 9546 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9547 } 9548 9549 // [PossiblyAFunctionType] --> [Return] 9550 // NonFunctionType --> NonFunctionType 9551 // R (A) --> R(A) 9552 // R (*)(A) --> R (A) 9553 // R (&)(A) --> R (A) 9554 // R (S::*)(A) --> R (A) 9555 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9556 QualType Ret = PossiblyAFunctionType; 9557 if (const PointerType *ToTypePtr = 9558 PossiblyAFunctionType->getAs<PointerType>()) 9559 Ret = ToTypePtr->getPointeeType(); 9560 else if (const ReferenceType *ToTypeRef = 9561 PossiblyAFunctionType->getAs<ReferenceType>()) 9562 Ret = ToTypeRef->getPointeeType(); 9563 else if (const MemberPointerType *MemTypePtr = 9564 PossiblyAFunctionType->getAs<MemberPointerType>()) 9565 Ret = MemTypePtr->getPointeeType(); 9566 Ret = 9567 Context.getCanonicalType(Ret).getUnqualifiedType(); 9568 return Ret; 9569 } 9570 9571 // A helper class to help with address of function resolution 9572 // - allows us to avoid passing around all those ugly parameters 9573 class AddressOfFunctionResolver 9574 { 9575 Sema& S; 9576 Expr* SourceExpr; 9577 const QualType& TargetType; 9578 QualType TargetFunctionType; // Extracted function type from target type 9579 9580 bool Complain; 9581 //DeclAccessPair& ResultFunctionAccessPair; 9582 ASTContext& Context; 9583 9584 bool TargetTypeIsNonStaticMemberFunction; 9585 bool FoundNonTemplateFunction; 9586 bool StaticMemberFunctionFromBoundPointer; 9587 9588 OverloadExpr::FindResult OvlExprInfo; 9589 OverloadExpr *OvlExpr; 9590 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9591 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9592 TemplateSpecCandidateSet FailedCandidates; 9593 9594 public: 9595 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9596 const QualType &TargetType, bool Complain) 9597 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9598 Complain(Complain), Context(S.getASTContext()), 9599 TargetTypeIsNonStaticMemberFunction( 9600 !!TargetType->getAs<MemberPointerType>()), 9601 FoundNonTemplateFunction(false), 9602 StaticMemberFunctionFromBoundPointer(false), 9603 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9604 OvlExpr(OvlExprInfo.Expression), 9605 FailedCandidates(OvlExpr->getNameLoc()) { 9606 ExtractUnqualifiedFunctionTypeFromTargetType(); 9607 9608 if (TargetFunctionType->isFunctionType()) { 9609 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9610 if (!UME->isImplicitAccess() && 9611 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9612 StaticMemberFunctionFromBoundPointer = true; 9613 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9614 DeclAccessPair dap; 9615 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9616 OvlExpr, false, &dap)) { 9617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9618 if (!Method->isStatic()) { 9619 // If the target type is a non-function type and the function found 9620 // is a non-static member function, pretend as if that was the 9621 // target, it's the only possible type to end up with. 9622 TargetTypeIsNonStaticMemberFunction = true; 9623 9624 // And skip adding the function if its not in the proper form. 9625 // We'll diagnose this due to an empty set of functions. 9626 if (!OvlExprInfo.HasFormOfMemberPointer) 9627 return; 9628 } 9629 9630 Matches.push_back(std::make_pair(dap, Fn)); 9631 } 9632 return; 9633 } 9634 9635 if (OvlExpr->hasExplicitTemplateArgs()) 9636 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9637 9638 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9639 // C++ [over.over]p4: 9640 // If more than one function is selected, [...] 9641 if (Matches.size() > 1) { 9642 if (FoundNonTemplateFunction) 9643 EliminateAllTemplateMatches(); 9644 else 9645 EliminateAllExceptMostSpecializedTemplate(); 9646 } 9647 } 9648 } 9649 9650 private: 9651 bool isTargetTypeAFunction() const { 9652 return TargetFunctionType->isFunctionType(); 9653 } 9654 9655 // [ToType] [Return] 9656 9657 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9658 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9659 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9660 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9661 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9662 } 9663 9664 // return true if any matching specializations were found 9665 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9666 const DeclAccessPair& CurAccessFunPair) { 9667 if (CXXMethodDecl *Method 9668 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9669 // Skip non-static function templates when converting to pointer, and 9670 // static when converting to member pointer. 9671 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9672 return false; 9673 } 9674 else if (TargetTypeIsNonStaticMemberFunction) 9675 return false; 9676 9677 // C++ [over.over]p2: 9678 // If the name is a function template, template argument deduction is 9679 // done (14.8.2.2), and if the argument deduction succeeds, the 9680 // resulting template argument list is used to generate a single 9681 // function template specialization, which is added to the set of 9682 // overloaded functions considered. 9683 FunctionDecl *Specialization = 0; 9684 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9685 if (Sema::TemplateDeductionResult Result 9686 = S.DeduceTemplateArguments(FunctionTemplate, 9687 &OvlExplicitTemplateArgs, 9688 TargetFunctionType, Specialization, 9689 Info, /*InOverloadResolution=*/true)) { 9690 // Make a note of the failed deduction for diagnostics. 9691 FailedCandidates.addCandidate() 9692 .set(FunctionTemplate->getTemplatedDecl(), 9693 MakeDeductionFailureInfo(Context, Result, Info)); 9694 return false; 9695 } 9696 9697 // Template argument deduction ensures that we have an exact match or 9698 // compatible pointer-to-function arguments that would be adjusted by ICS. 9699 // This function template specicalization works. 9700 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9701 assert(S.isSameOrCompatibleFunctionType( 9702 Context.getCanonicalType(Specialization->getType()), 9703 Context.getCanonicalType(TargetFunctionType))); 9704 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9705 return true; 9706 } 9707 9708 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9709 const DeclAccessPair& CurAccessFunPair) { 9710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9711 // Skip non-static functions when converting to pointer, and static 9712 // when converting to member pointer. 9713 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9714 return false; 9715 } 9716 else if (TargetTypeIsNonStaticMemberFunction) 9717 return false; 9718 9719 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9720 if (S.getLangOpts().CUDA) 9721 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9722 if (S.CheckCUDATarget(Caller, FunDecl)) 9723 return false; 9724 9725 // If any candidate has a placeholder return type, trigger its deduction 9726 // now. 9727 if (S.getLangOpts().CPlusPlus1y && 9728 FunDecl->getResultType()->isUndeducedType() && 9729 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9730 return false; 9731 9732 QualType ResultTy; 9733 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9734 FunDecl->getType()) || 9735 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9736 ResultTy)) { 9737 Matches.push_back(std::make_pair(CurAccessFunPair, 9738 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9739 FoundNonTemplateFunction = true; 9740 return true; 9741 } 9742 } 9743 9744 return false; 9745 } 9746 9747 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9748 bool Ret = false; 9749 9750 // If the overload expression doesn't have the form of a pointer to 9751 // member, don't try to convert it to a pointer-to-member type. 9752 if (IsInvalidFormOfPointerToMemberFunction()) 9753 return false; 9754 9755 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9756 E = OvlExpr->decls_end(); 9757 I != E; ++I) { 9758 // Look through any using declarations to find the underlying function. 9759 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9760 9761 // C++ [over.over]p3: 9762 // Non-member functions and static member functions match 9763 // targets of type "pointer-to-function" or "reference-to-function." 9764 // Nonstatic member functions match targets of 9765 // type "pointer-to-member-function." 9766 // Note that according to DR 247, the containing class does not matter. 9767 if (FunctionTemplateDecl *FunctionTemplate 9768 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9769 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9770 Ret = true; 9771 } 9772 // If we have explicit template arguments supplied, skip non-templates. 9773 else if (!OvlExpr->hasExplicitTemplateArgs() && 9774 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9775 Ret = true; 9776 } 9777 assert(Ret || Matches.empty()); 9778 return Ret; 9779 } 9780 9781 void EliminateAllExceptMostSpecializedTemplate() { 9782 // [...] and any given function template specialization F1 is 9783 // eliminated if the set contains a second function template 9784 // specialization whose function template is more specialized 9785 // than the function template of F1 according to the partial 9786 // ordering rules of 14.5.5.2. 9787 9788 // The algorithm specified above is quadratic. We instead use a 9789 // two-pass algorithm (similar to the one used to identify the 9790 // best viable function in an overload set) that identifies the 9791 // best function template (if it exists). 9792 9793 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9794 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9795 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9796 9797 // TODO: It looks like FailedCandidates does not serve much purpose 9798 // here, since the no_viable diagnostic has index 0. 9799 UnresolvedSetIterator Result = S.getMostSpecialized( 9800 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9801 SourceExpr->getLocStart(), S.PDiag(), 9802 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9803 .second->getDeclName(), 9804 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9805 Complain, TargetFunctionType); 9806 9807 if (Result != MatchesCopy.end()) { 9808 // Make it the first and only element 9809 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9810 Matches[0].second = cast<FunctionDecl>(*Result); 9811 Matches.resize(1); 9812 } 9813 } 9814 9815 void EliminateAllTemplateMatches() { 9816 // [...] any function template specializations in the set are 9817 // eliminated if the set also contains a non-template function, [...] 9818 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9819 if (Matches[I].second->getPrimaryTemplate() == 0) 9820 ++I; 9821 else { 9822 Matches[I] = Matches[--N]; 9823 Matches.set_size(N); 9824 } 9825 } 9826 } 9827 9828 public: 9829 void ComplainNoMatchesFound() const { 9830 assert(Matches.empty()); 9831 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9832 << OvlExpr->getName() << TargetFunctionType 9833 << OvlExpr->getSourceRange(); 9834 if (FailedCandidates.empty()) 9835 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9836 else { 9837 // We have some deduction failure messages. Use them to diagnose 9838 // the function templates, and diagnose the non-template candidates 9839 // normally. 9840 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9841 IEnd = OvlExpr->decls_end(); 9842 I != IEnd; ++I) 9843 if (FunctionDecl *Fun = 9844 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9845 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9846 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9847 } 9848 } 9849 9850 bool IsInvalidFormOfPointerToMemberFunction() const { 9851 return TargetTypeIsNonStaticMemberFunction && 9852 !OvlExprInfo.HasFormOfMemberPointer; 9853 } 9854 9855 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9856 // TODO: Should we condition this on whether any functions might 9857 // have matched, or is it more appropriate to do that in callers? 9858 // TODO: a fixit wouldn't hurt. 9859 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9860 << TargetType << OvlExpr->getSourceRange(); 9861 } 9862 9863 bool IsStaticMemberFunctionFromBoundPointer() const { 9864 return StaticMemberFunctionFromBoundPointer; 9865 } 9866 9867 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9868 S.Diag(OvlExpr->getLocStart(), 9869 diag::err_invalid_form_pointer_member_function) 9870 << OvlExpr->getSourceRange(); 9871 } 9872 9873 void ComplainOfInvalidConversion() const { 9874 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9875 << OvlExpr->getName() << TargetType; 9876 } 9877 9878 void ComplainMultipleMatchesFound() const { 9879 assert(Matches.size() > 1); 9880 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9881 << OvlExpr->getName() 9882 << OvlExpr->getSourceRange(); 9883 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9884 } 9885 9886 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9887 9888 int getNumMatches() const { return Matches.size(); } 9889 9890 FunctionDecl* getMatchingFunctionDecl() const { 9891 if (Matches.size() != 1) return 0; 9892 return Matches[0].second; 9893 } 9894 9895 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9896 if (Matches.size() != 1) return 0; 9897 return &Matches[0].first; 9898 } 9899 }; 9900 9901 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9902 /// an overloaded function (C++ [over.over]), where @p From is an 9903 /// expression with overloaded function type and @p ToType is the type 9904 /// we're trying to resolve to. For example: 9905 /// 9906 /// @code 9907 /// int f(double); 9908 /// int f(int); 9909 /// 9910 /// int (*pfd)(double) = f; // selects f(double) 9911 /// @endcode 9912 /// 9913 /// This routine returns the resulting FunctionDecl if it could be 9914 /// resolved, and NULL otherwise. When @p Complain is true, this 9915 /// routine will emit diagnostics if there is an error. 9916 FunctionDecl * 9917 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9918 QualType TargetType, 9919 bool Complain, 9920 DeclAccessPair &FoundResult, 9921 bool *pHadMultipleCandidates) { 9922 assert(AddressOfExpr->getType() == Context.OverloadTy); 9923 9924 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9925 Complain); 9926 int NumMatches = Resolver.getNumMatches(); 9927 FunctionDecl* Fn = 0; 9928 if (NumMatches == 0 && Complain) { 9929 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9930 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9931 else 9932 Resolver.ComplainNoMatchesFound(); 9933 } 9934 else if (NumMatches > 1 && Complain) 9935 Resolver.ComplainMultipleMatchesFound(); 9936 else if (NumMatches == 1) { 9937 Fn = Resolver.getMatchingFunctionDecl(); 9938 assert(Fn); 9939 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9940 if (Complain) { 9941 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9942 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9943 else 9944 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9945 } 9946 } 9947 9948 if (pHadMultipleCandidates) 9949 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9950 return Fn; 9951 } 9952 9953 /// \brief Given an expression that refers to an overloaded function, try to 9954 /// resolve that overloaded function expression down to a single function. 9955 /// 9956 /// This routine can only resolve template-ids that refer to a single function 9957 /// template, where that template-id refers to a single template whose template 9958 /// arguments are either provided by the template-id or have defaults, 9959 /// as described in C++0x [temp.arg.explicit]p3. 9960 /// 9961 /// If no template-ids are found, no diagnostics are emitted and NULL is 9962 /// returned. 9963 FunctionDecl * 9964 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9965 bool Complain, 9966 DeclAccessPair *FoundResult) { 9967 // C++ [over.over]p1: 9968 // [...] [Note: any redundant set of parentheses surrounding the 9969 // overloaded function name is ignored (5.1). ] 9970 // C++ [over.over]p1: 9971 // [...] The overloaded function name can be preceded by the & 9972 // operator. 9973 9974 // If we didn't actually find any template-ids, we're done. 9975 if (!ovl->hasExplicitTemplateArgs()) 9976 return 0; 9977 9978 TemplateArgumentListInfo ExplicitTemplateArgs; 9979 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9980 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 9981 9982 // Look through all of the overloaded functions, searching for one 9983 // whose type matches exactly. 9984 FunctionDecl *Matched = 0; 9985 for (UnresolvedSetIterator I = ovl->decls_begin(), 9986 E = ovl->decls_end(); I != E; ++I) { 9987 // C++0x [temp.arg.explicit]p3: 9988 // [...] In contexts where deduction is done and fails, or in contexts 9989 // where deduction is not done, if a template argument list is 9990 // specified and it, along with any default template arguments, 9991 // identifies a single function template specialization, then the 9992 // template-id is an lvalue for the function template specialization. 9993 FunctionTemplateDecl *FunctionTemplate 9994 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9995 9996 // C++ [over.over]p2: 9997 // If the name is a function template, template argument deduction is 9998 // done (14.8.2.2), and if the argument deduction succeeds, the 9999 // resulting template argument list is used to generate a single 10000 // function template specialization, which is added to the set of 10001 // overloaded functions considered. 10002 FunctionDecl *Specialization = 0; 10003 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10004 if (TemplateDeductionResult Result 10005 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10006 Specialization, Info, 10007 /*InOverloadResolution=*/true)) { 10008 // Make a note of the failed deduction for diagnostics. 10009 // TODO: Actually use the failed-deduction info? 10010 FailedCandidates.addCandidate() 10011 .set(FunctionTemplate->getTemplatedDecl(), 10012 MakeDeductionFailureInfo(Context, Result, Info)); 10013 continue; 10014 } 10015 10016 assert(Specialization && "no specialization and no error?"); 10017 10018 // Multiple matches; we can't resolve to a single declaration. 10019 if (Matched) { 10020 if (Complain) { 10021 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10022 << ovl->getName(); 10023 NoteAllOverloadCandidates(ovl); 10024 } 10025 return 0; 10026 } 10027 10028 Matched = Specialization; 10029 if (FoundResult) *FoundResult = I.getPair(); 10030 } 10031 10032 if (Matched && getLangOpts().CPlusPlus1y && 10033 Matched->getResultType()->isUndeducedType() && 10034 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10035 return 0; 10036 10037 return Matched; 10038 } 10039 10040 10041 10042 10043 // Resolve and fix an overloaded expression that can be resolved 10044 // because it identifies a single function template specialization. 10045 // 10046 // Last three arguments should only be supplied if Complain = true 10047 // 10048 // Return true if it was logically possible to so resolve the 10049 // expression, regardless of whether or not it succeeded. Always 10050 // returns true if 'complain' is set. 10051 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10052 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10053 bool complain, const SourceRange& OpRangeForComplaining, 10054 QualType DestTypeForComplaining, 10055 unsigned DiagIDForComplaining) { 10056 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10057 10058 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10059 10060 DeclAccessPair found; 10061 ExprResult SingleFunctionExpression; 10062 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10063 ovl.Expression, /*complain*/ false, &found)) { 10064 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10065 SrcExpr = ExprError(); 10066 return true; 10067 } 10068 10069 // It is only correct to resolve to an instance method if we're 10070 // resolving a form that's permitted to be a pointer to member. 10071 // Otherwise we'll end up making a bound member expression, which 10072 // is illegal in all the contexts we resolve like this. 10073 if (!ovl.HasFormOfMemberPointer && 10074 isa<CXXMethodDecl>(fn) && 10075 cast<CXXMethodDecl>(fn)->isInstance()) { 10076 if (!complain) return false; 10077 10078 Diag(ovl.Expression->getExprLoc(), 10079 diag::err_bound_member_function) 10080 << 0 << ovl.Expression->getSourceRange(); 10081 10082 // TODO: I believe we only end up here if there's a mix of 10083 // static and non-static candidates (otherwise the expression 10084 // would have 'bound member' type, not 'overload' type). 10085 // Ideally we would note which candidate was chosen and why 10086 // the static candidates were rejected. 10087 SrcExpr = ExprError(); 10088 return true; 10089 } 10090 10091 // Fix the expression to refer to 'fn'. 10092 SingleFunctionExpression = 10093 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 10094 10095 // If desired, do function-to-pointer decay. 10096 if (doFunctionPointerConverion) { 10097 SingleFunctionExpression = 10098 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 10099 if (SingleFunctionExpression.isInvalid()) { 10100 SrcExpr = ExprError(); 10101 return true; 10102 } 10103 } 10104 } 10105 10106 if (!SingleFunctionExpression.isUsable()) { 10107 if (complain) { 10108 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10109 << ovl.Expression->getName() 10110 << DestTypeForComplaining 10111 << OpRangeForComplaining 10112 << ovl.Expression->getQualifierLoc().getSourceRange(); 10113 NoteAllOverloadCandidates(SrcExpr.get()); 10114 10115 SrcExpr = ExprError(); 10116 return true; 10117 } 10118 10119 return false; 10120 } 10121 10122 SrcExpr = SingleFunctionExpression; 10123 return true; 10124 } 10125 10126 /// \brief Add a single candidate to the overload set. 10127 static void AddOverloadedCallCandidate(Sema &S, 10128 DeclAccessPair FoundDecl, 10129 TemplateArgumentListInfo *ExplicitTemplateArgs, 10130 ArrayRef<Expr *> Args, 10131 OverloadCandidateSet &CandidateSet, 10132 bool PartialOverloading, 10133 bool KnownValid) { 10134 NamedDecl *Callee = FoundDecl.getDecl(); 10135 if (isa<UsingShadowDecl>(Callee)) 10136 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10137 10138 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10139 if (ExplicitTemplateArgs) { 10140 assert(!KnownValid && "Explicit template arguments?"); 10141 return; 10142 } 10143 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 10144 PartialOverloading); 10145 return; 10146 } 10147 10148 if (FunctionTemplateDecl *FuncTemplate 10149 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10150 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10151 ExplicitTemplateArgs, Args, CandidateSet); 10152 return; 10153 } 10154 10155 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10156 } 10157 10158 /// \brief Add the overload candidates named by callee and/or found by argument 10159 /// dependent lookup to the given overload set. 10160 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10161 ArrayRef<Expr *> Args, 10162 OverloadCandidateSet &CandidateSet, 10163 bool PartialOverloading) { 10164 10165 #ifndef NDEBUG 10166 // Verify that ArgumentDependentLookup is consistent with the rules 10167 // in C++0x [basic.lookup.argdep]p3: 10168 // 10169 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10170 // and let Y be the lookup set produced by argument dependent 10171 // lookup (defined as follows). If X contains 10172 // 10173 // -- a declaration of a class member, or 10174 // 10175 // -- a block-scope function declaration that is not a 10176 // using-declaration, or 10177 // 10178 // -- a declaration that is neither a function or a function 10179 // template 10180 // 10181 // then Y is empty. 10182 10183 if (ULE->requiresADL()) { 10184 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10185 E = ULE->decls_end(); I != E; ++I) { 10186 assert(!(*I)->getDeclContext()->isRecord()); 10187 assert(isa<UsingShadowDecl>(*I) || 10188 !(*I)->getDeclContext()->isFunctionOrMethod()); 10189 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10190 } 10191 } 10192 #endif 10193 10194 // It would be nice to avoid this copy. 10195 TemplateArgumentListInfo TABuffer; 10196 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10197 if (ULE->hasExplicitTemplateArgs()) { 10198 ULE->copyTemplateArgumentsInto(TABuffer); 10199 ExplicitTemplateArgs = &TABuffer; 10200 } 10201 10202 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10203 E = ULE->decls_end(); I != E; ++I) 10204 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10205 CandidateSet, PartialOverloading, 10206 /*KnownValid*/ true); 10207 10208 if (ULE->requiresADL()) 10209 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 10210 ULE->getExprLoc(), 10211 Args, ExplicitTemplateArgs, 10212 CandidateSet, PartialOverloading); 10213 } 10214 10215 /// Determine whether a declaration with the specified name could be moved into 10216 /// a different namespace. 10217 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10218 switch (Name.getCXXOverloadedOperator()) { 10219 case OO_New: case OO_Array_New: 10220 case OO_Delete: case OO_Array_Delete: 10221 return false; 10222 10223 default: 10224 return true; 10225 } 10226 } 10227 10228 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10229 /// template, where the non-dependent name was declared after the template 10230 /// was defined. This is common in code written for a compilers which do not 10231 /// correctly implement two-stage name lookup. 10232 /// 10233 /// Returns true if a viable candidate was found and a diagnostic was issued. 10234 static bool 10235 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10236 const CXXScopeSpec &SS, LookupResult &R, 10237 TemplateArgumentListInfo *ExplicitTemplateArgs, 10238 ArrayRef<Expr *> Args) { 10239 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10240 return false; 10241 10242 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10243 if (DC->isTransparentContext()) 10244 continue; 10245 10246 SemaRef.LookupQualifiedName(R, DC); 10247 10248 if (!R.empty()) { 10249 R.suppressDiagnostics(); 10250 10251 if (isa<CXXRecordDecl>(DC)) { 10252 // Don't diagnose names we find in classes; we get much better 10253 // diagnostics for these from DiagnoseEmptyLookup. 10254 R.clear(); 10255 return false; 10256 } 10257 10258 OverloadCandidateSet Candidates(FnLoc); 10259 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10260 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10261 ExplicitTemplateArgs, Args, 10262 Candidates, false, /*KnownValid*/ false); 10263 10264 OverloadCandidateSet::iterator Best; 10265 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10266 // No viable functions. Don't bother the user with notes for functions 10267 // which don't work and shouldn't be found anyway. 10268 R.clear(); 10269 return false; 10270 } 10271 10272 // Find the namespaces where ADL would have looked, and suggest 10273 // declaring the function there instead. 10274 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10275 Sema::AssociatedClassSet AssociatedClasses; 10276 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10277 AssociatedNamespaces, 10278 AssociatedClasses); 10279 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10280 if (canBeDeclaredInNamespace(R.getLookupName())) { 10281 DeclContext *Std = SemaRef.getStdNamespace(); 10282 for (Sema::AssociatedNamespaceSet::iterator 10283 it = AssociatedNamespaces.begin(), 10284 end = AssociatedNamespaces.end(); it != end; ++it) { 10285 // Never suggest declaring a function within namespace 'std'. 10286 if (Std && Std->Encloses(*it)) 10287 continue; 10288 10289 // Never suggest declaring a function within a namespace with a 10290 // reserved name, like __gnu_cxx. 10291 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10292 if (NS && 10293 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10294 continue; 10295 10296 SuggestedNamespaces.insert(*it); 10297 } 10298 } 10299 10300 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10301 << R.getLookupName(); 10302 if (SuggestedNamespaces.empty()) { 10303 SemaRef.Diag(Best->Function->getLocation(), 10304 diag::note_not_found_by_two_phase_lookup) 10305 << R.getLookupName() << 0; 10306 } else if (SuggestedNamespaces.size() == 1) { 10307 SemaRef.Diag(Best->Function->getLocation(), 10308 diag::note_not_found_by_two_phase_lookup) 10309 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10310 } else { 10311 // FIXME: It would be useful to list the associated namespaces here, 10312 // but the diagnostics infrastructure doesn't provide a way to produce 10313 // a localized representation of a list of items. 10314 SemaRef.Diag(Best->Function->getLocation(), 10315 diag::note_not_found_by_two_phase_lookup) 10316 << R.getLookupName() << 2; 10317 } 10318 10319 // Try to recover by calling this function. 10320 return true; 10321 } 10322 10323 R.clear(); 10324 } 10325 10326 return false; 10327 } 10328 10329 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10330 /// template, where the non-dependent operator was declared after the template 10331 /// was defined. 10332 /// 10333 /// Returns true if a viable candidate was found and a diagnostic was issued. 10334 static bool 10335 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10336 SourceLocation OpLoc, 10337 ArrayRef<Expr *> Args) { 10338 DeclarationName OpName = 10339 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10340 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10341 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10342 /*ExplicitTemplateArgs=*/0, Args); 10343 } 10344 10345 namespace { 10346 class BuildRecoveryCallExprRAII { 10347 Sema &SemaRef; 10348 public: 10349 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10350 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10351 SemaRef.IsBuildingRecoveryCallExpr = true; 10352 } 10353 10354 ~BuildRecoveryCallExprRAII() { 10355 SemaRef.IsBuildingRecoveryCallExpr = false; 10356 } 10357 }; 10358 10359 } 10360 10361 /// Attempts to recover from a call where no functions were found. 10362 /// 10363 /// Returns true if new candidates were found. 10364 static ExprResult 10365 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10366 UnresolvedLookupExpr *ULE, 10367 SourceLocation LParenLoc, 10368 llvm::MutableArrayRef<Expr *> Args, 10369 SourceLocation RParenLoc, 10370 bool EmptyLookup, bool AllowTypoCorrection) { 10371 // Do not try to recover if it is already building a recovery call. 10372 // This stops infinite loops for template instantiations like 10373 // 10374 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10375 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10376 // 10377 if (SemaRef.IsBuildingRecoveryCallExpr) 10378 return ExprError(); 10379 BuildRecoveryCallExprRAII RCE(SemaRef); 10380 10381 CXXScopeSpec SS; 10382 SS.Adopt(ULE->getQualifierLoc()); 10383 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10384 10385 TemplateArgumentListInfo TABuffer; 10386 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10387 if (ULE->hasExplicitTemplateArgs()) { 10388 ULE->copyTemplateArgumentsInto(TABuffer); 10389 ExplicitTemplateArgs = &TABuffer; 10390 } 10391 10392 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10393 Sema::LookupOrdinaryName); 10394 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10395 ExplicitTemplateArgs != 0); 10396 NoTypoCorrectionCCC RejectAll; 10397 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10398 (CorrectionCandidateCallback*)&Validator : 10399 (CorrectionCandidateCallback*)&RejectAll; 10400 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10401 ExplicitTemplateArgs, Args) && 10402 (!EmptyLookup || 10403 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10404 ExplicitTemplateArgs, Args))) 10405 return ExprError(); 10406 10407 assert(!R.empty() && "lookup results empty despite recovery"); 10408 10409 // Build an implicit member call if appropriate. Just drop the 10410 // casts and such from the call, we don't really care. 10411 ExprResult NewFn = ExprError(); 10412 if ((*R.begin())->isCXXClassMember()) 10413 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10414 R, ExplicitTemplateArgs); 10415 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10416 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10417 ExplicitTemplateArgs); 10418 else 10419 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10420 10421 if (NewFn.isInvalid()) 10422 return ExprError(); 10423 10424 // This shouldn't cause an infinite loop because we're giving it 10425 // an expression with viable lookup results, which should never 10426 // end up here. 10427 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10428 MultiExprArg(Args.data(), Args.size()), 10429 RParenLoc); 10430 } 10431 10432 /// \brief Constructs and populates an OverloadedCandidateSet from 10433 /// the given function. 10434 /// \returns true when an the ExprResult output parameter has been set. 10435 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10436 UnresolvedLookupExpr *ULE, 10437 MultiExprArg Args, 10438 SourceLocation RParenLoc, 10439 OverloadCandidateSet *CandidateSet, 10440 ExprResult *Result) { 10441 #ifndef NDEBUG 10442 if (ULE->requiresADL()) { 10443 // To do ADL, we must have found an unqualified name. 10444 assert(!ULE->getQualifier() && "qualified name with ADL"); 10445 10446 // We don't perform ADL for implicit declarations of builtins. 10447 // Verify that this was correctly set up. 10448 FunctionDecl *F; 10449 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10450 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10451 F->getBuiltinID() && F->isImplicit()) 10452 llvm_unreachable("performing ADL for builtin"); 10453 10454 // We don't perform ADL in C. 10455 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10456 } 10457 #endif 10458 10459 UnbridgedCastsSet UnbridgedCasts; 10460 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10461 *Result = ExprError(); 10462 return true; 10463 } 10464 10465 // Add the functions denoted by the callee to the set of candidate 10466 // functions, including those from argument-dependent lookup. 10467 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10468 10469 // If we found nothing, try to recover. 10470 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10471 // out if it fails. 10472 if (CandidateSet->empty()) { 10473 // In Microsoft mode, if we are inside a template class member function then 10474 // create a type dependent CallExpr. The goal is to postpone name lookup 10475 // to instantiation time to be able to search into type dependent base 10476 // classes. 10477 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10478 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10479 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10480 Context.DependentTy, VK_RValue, 10481 RParenLoc); 10482 CE->setTypeDependent(true); 10483 *Result = Owned(CE); 10484 return true; 10485 } 10486 return false; 10487 } 10488 10489 UnbridgedCasts.restore(); 10490 return false; 10491 } 10492 10493 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10494 /// the completed call expression. If overload resolution fails, emits 10495 /// diagnostics and returns ExprError() 10496 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10497 UnresolvedLookupExpr *ULE, 10498 SourceLocation LParenLoc, 10499 MultiExprArg Args, 10500 SourceLocation RParenLoc, 10501 Expr *ExecConfig, 10502 OverloadCandidateSet *CandidateSet, 10503 OverloadCandidateSet::iterator *Best, 10504 OverloadingResult OverloadResult, 10505 bool AllowTypoCorrection) { 10506 if (CandidateSet->empty()) 10507 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10508 RParenLoc, /*EmptyLookup=*/true, 10509 AllowTypoCorrection); 10510 10511 switch (OverloadResult) { 10512 case OR_Success: { 10513 FunctionDecl *FDecl = (*Best)->Function; 10514 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10515 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10516 return ExprError(); 10517 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10518 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10519 ExecConfig); 10520 } 10521 10522 case OR_No_Viable_Function: { 10523 // Try to recover by looking for viable functions which the user might 10524 // have meant to call. 10525 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10526 Args, RParenLoc, 10527 /*EmptyLookup=*/false, 10528 AllowTypoCorrection); 10529 if (!Recovery.isInvalid()) 10530 return Recovery; 10531 10532 SemaRef.Diag(Fn->getLocStart(), 10533 diag::err_ovl_no_viable_function_in_call) 10534 << ULE->getName() << Fn->getSourceRange(); 10535 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10536 break; 10537 } 10538 10539 case OR_Ambiguous: 10540 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10541 << ULE->getName() << Fn->getSourceRange(); 10542 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10543 break; 10544 10545 case OR_Deleted: { 10546 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10547 << (*Best)->Function->isDeleted() 10548 << ULE->getName() 10549 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10550 << Fn->getSourceRange(); 10551 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10552 10553 // We emitted an error for the unvailable/deleted function call but keep 10554 // the call in the AST. 10555 FunctionDecl *FDecl = (*Best)->Function; 10556 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10557 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10558 ExecConfig); 10559 } 10560 } 10561 10562 // Overload resolution failed. 10563 return ExprError(); 10564 } 10565 10566 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10567 /// (which eventually refers to the declaration Func) and the call 10568 /// arguments Args/NumArgs, attempt to resolve the function call down 10569 /// to a specific function. If overload resolution succeeds, returns 10570 /// the call expression produced by overload resolution. 10571 /// Otherwise, emits diagnostics and returns ExprError. 10572 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10573 UnresolvedLookupExpr *ULE, 10574 SourceLocation LParenLoc, 10575 MultiExprArg Args, 10576 SourceLocation RParenLoc, 10577 Expr *ExecConfig, 10578 bool AllowTypoCorrection) { 10579 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10580 ExprResult result; 10581 10582 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10583 &result)) 10584 return result; 10585 10586 OverloadCandidateSet::iterator Best; 10587 OverloadingResult OverloadResult = 10588 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10589 10590 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10591 RParenLoc, ExecConfig, &CandidateSet, 10592 &Best, OverloadResult, 10593 AllowTypoCorrection); 10594 } 10595 10596 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10597 return Functions.size() > 1 || 10598 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10599 } 10600 10601 /// \brief Create a unary operation that may resolve to an overloaded 10602 /// operator. 10603 /// 10604 /// \param OpLoc The location of the operator itself (e.g., '*'). 10605 /// 10606 /// \param OpcIn The UnaryOperator::Opcode that describes this 10607 /// operator. 10608 /// 10609 /// \param Fns The set of non-member functions that will be 10610 /// considered by overload resolution. The caller needs to build this 10611 /// set based on the context using, e.g., 10612 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10613 /// set should not contain any member functions; those will be added 10614 /// by CreateOverloadedUnaryOp(). 10615 /// 10616 /// \param Input The input argument. 10617 ExprResult 10618 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10619 const UnresolvedSetImpl &Fns, 10620 Expr *Input) { 10621 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10622 10623 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10624 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10625 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10626 // TODO: provide better source location info. 10627 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10628 10629 if (checkPlaceholderForOverload(*this, Input)) 10630 return ExprError(); 10631 10632 Expr *Args[2] = { Input, 0 }; 10633 unsigned NumArgs = 1; 10634 10635 // For post-increment and post-decrement, add the implicit '0' as 10636 // the second argument, so that we know this is a post-increment or 10637 // post-decrement. 10638 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10639 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10640 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10641 SourceLocation()); 10642 NumArgs = 2; 10643 } 10644 10645 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10646 10647 if (Input->isTypeDependent()) { 10648 if (Fns.empty()) 10649 return Owned(new (Context) UnaryOperator(Input, 10650 Opc, 10651 Context.DependentTy, 10652 VK_RValue, OK_Ordinary, 10653 OpLoc)); 10654 10655 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10656 UnresolvedLookupExpr *Fn 10657 = UnresolvedLookupExpr::Create(Context, NamingClass, 10658 NestedNameSpecifierLoc(), OpNameInfo, 10659 /*ADL*/ true, IsOverloaded(Fns), 10660 Fns.begin(), Fns.end()); 10661 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10662 Context.DependentTy, 10663 VK_RValue, 10664 OpLoc, false)); 10665 } 10666 10667 // Build an empty overload set. 10668 OverloadCandidateSet CandidateSet(OpLoc); 10669 10670 // Add the candidates from the given function set. 10671 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10672 10673 // Add operator candidates that are member functions. 10674 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10675 10676 // Add candidates from ADL. 10677 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10678 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10679 CandidateSet); 10680 10681 // Add builtin operator candidates. 10682 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10683 10684 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10685 10686 // Perform overload resolution. 10687 OverloadCandidateSet::iterator Best; 10688 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10689 case OR_Success: { 10690 // We found a built-in operator or an overloaded operator. 10691 FunctionDecl *FnDecl = Best->Function; 10692 10693 if (FnDecl) { 10694 // We matched an overloaded operator. Build a call to that 10695 // operator. 10696 10697 // Convert the arguments. 10698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10699 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10700 10701 ExprResult InputRes = 10702 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10703 Best->FoundDecl, Method); 10704 if (InputRes.isInvalid()) 10705 return ExprError(); 10706 Input = InputRes.take(); 10707 } else { 10708 // Convert the arguments. 10709 ExprResult InputInit 10710 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10711 Context, 10712 FnDecl->getParamDecl(0)), 10713 SourceLocation(), 10714 Input); 10715 if (InputInit.isInvalid()) 10716 return ExprError(); 10717 Input = InputInit.take(); 10718 } 10719 10720 // Build the actual expression node. 10721 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10722 HadMultipleCandidates, OpLoc); 10723 if (FnExpr.isInvalid()) 10724 return ExprError(); 10725 10726 // Determine the result type. 10727 QualType ResultTy = FnDecl->getResultType(); 10728 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10729 ResultTy = ResultTy.getNonLValueExprType(Context); 10730 10731 Args[0] = Input; 10732 CallExpr *TheCall = 10733 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10734 ResultTy, VK, OpLoc, false); 10735 10736 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10737 FnDecl)) 10738 return ExprError(); 10739 10740 return MaybeBindToTemporary(TheCall); 10741 } else { 10742 // We matched a built-in operator. Convert the arguments, then 10743 // break out so that we will build the appropriate built-in 10744 // operator node. 10745 ExprResult InputRes = 10746 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10747 Best->Conversions[0], AA_Passing); 10748 if (InputRes.isInvalid()) 10749 return ExprError(); 10750 Input = InputRes.take(); 10751 break; 10752 } 10753 } 10754 10755 case OR_No_Viable_Function: 10756 // This is an erroneous use of an operator which can be overloaded by 10757 // a non-member function. Check for non-member operators which were 10758 // defined too late to be candidates. 10759 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10760 // FIXME: Recover by calling the found function. 10761 return ExprError(); 10762 10763 // No viable function; fall through to handling this as a 10764 // built-in operator, which will produce an error message for us. 10765 break; 10766 10767 case OR_Ambiguous: 10768 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10769 << UnaryOperator::getOpcodeStr(Opc) 10770 << Input->getType() 10771 << Input->getSourceRange(); 10772 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10773 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10774 return ExprError(); 10775 10776 case OR_Deleted: 10777 Diag(OpLoc, diag::err_ovl_deleted_oper) 10778 << Best->Function->isDeleted() 10779 << UnaryOperator::getOpcodeStr(Opc) 10780 << getDeletedOrUnavailableSuffix(Best->Function) 10781 << Input->getSourceRange(); 10782 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10783 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10784 return ExprError(); 10785 } 10786 10787 // Either we found no viable overloaded operator or we matched a 10788 // built-in operator. In either case, fall through to trying to 10789 // build a built-in operation. 10790 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10791 } 10792 10793 /// \brief Create a binary operation that may resolve to an overloaded 10794 /// operator. 10795 /// 10796 /// \param OpLoc The location of the operator itself (e.g., '+'). 10797 /// 10798 /// \param OpcIn The BinaryOperator::Opcode that describes this 10799 /// operator. 10800 /// 10801 /// \param Fns The set of non-member functions that will be 10802 /// considered by overload resolution. The caller needs to build this 10803 /// set based on the context using, e.g., 10804 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10805 /// set should not contain any member functions; those will be added 10806 /// by CreateOverloadedBinOp(). 10807 /// 10808 /// \param LHS Left-hand argument. 10809 /// \param RHS Right-hand argument. 10810 ExprResult 10811 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10812 unsigned OpcIn, 10813 const UnresolvedSetImpl &Fns, 10814 Expr *LHS, Expr *RHS) { 10815 Expr *Args[2] = { LHS, RHS }; 10816 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10817 10818 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10819 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10820 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10821 10822 // If either side is type-dependent, create an appropriate dependent 10823 // expression. 10824 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10825 if (Fns.empty()) { 10826 // If there are no functions to store, just build a dependent 10827 // BinaryOperator or CompoundAssignment. 10828 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10829 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10830 Context.DependentTy, 10831 VK_RValue, OK_Ordinary, 10832 OpLoc, 10833 FPFeatures.fp_contract)); 10834 10835 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10836 Context.DependentTy, 10837 VK_LValue, 10838 OK_Ordinary, 10839 Context.DependentTy, 10840 Context.DependentTy, 10841 OpLoc, 10842 FPFeatures.fp_contract)); 10843 } 10844 10845 // FIXME: save results of ADL from here? 10846 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10847 // TODO: provide better source location info in DNLoc component. 10848 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10849 UnresolvedLookupExpr *Fn 10850 = UnresolvedLookupExpr::Create(Context, NamingClass, 10851 NestedNameSpecifierLoc(), OpNameInfo, 10852 /*ADL*/ true, IsOverloaded(Fns), 10853 Fns.begin(), Fns.end()); 10854 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10855 Context.DependentTy, VK_RValue, 10856 OpLoc, FPFeatures.fp_contract)); 10857 } 10858 10859 // Always do placeholder-like conversions on the RHS. 10860 if (checkPlaceholderForOverload(*this, Args[1])) 10861 return ExprError(); 10862 10863 // Do placeholder-like conversion on the LHS; note that we should 10864 // not get here with a PseudoObject LHS. 10865 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10866 if (checkPlaceholderForOverload(*this, Args[0])) 10867 return ExprError(); 10868 10869 // If this is the assignment operator, we only perform overload resolution 10870 // if the left-hand side is a class or enumeration type. This is actually 10871 // a hack. The standard requires that we do overload resolution between the 10872 // various built-in candidates, but as DR507 points out, this can lead to 10873 // problems. So we do it this way, which pretty much follows what GCC does. 10874 // Note that we go the traditional code path for compound assignment forms. 10875 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10876 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10877 10878 // If this is the .* operator, which is not overloadable, just 10879 // create a built-in binary operator. 10880 if (Opc == BO_PtrMemD) 10881 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10882 10883 // Build an empty overload set. 10884 OverloadCandidateSet CandidateSet(OpLoc); 10885 10886 // Add the candidates from the given function set. 10887 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10888 10889 // Add operator candidates that are member functions. 10890 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10891 10892 // Add candidates from ADL. 10893 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10894 OpLoc, Args, 10895 /*ExplicitTemplateArgs*/ 0, 10896 CandidateSet); 10897 10898 // Add builtin operator candidates. 10899 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10900 10901 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10902 10903 // Perform overload resolution. 10904 OverloadCandidateSet::iterator Best; 10905 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10906 case OR_Success: { 10907 // We found a built-in operator or an overloaded operator. 10908 FunctionDecl *FnDecl = Best->Function; 10909 10910 if (FnDecl) { 10911 // We matched an overloaded operator. Build a call to that 10912 // operator. 10913 10914 // Convert the arguments. 10915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10916 // Best->Access is only meaningful for class members. 10917 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10918 10919 ExprResult Arg1 = 10920 PerformCopyInitialization( 10921 InitializedEntity::InitializeParameter(Context, 10922 FnDecl->getParamDecl(0)), 10923 SourceLocation(), Owned(Args[1])); 10924 if (Arg1.isInvalid()) 10925 return ExprError(); 10926 10927 ExprResult Arg0 = 10928 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10929 Best->FoundDecl, Method); 10930 if (Arg0.isInvalid()) 10931 return ExprError(); 10932 Args[0] = Arg0.takeAs<Expr>(); 10933 Args[1] = RHS = Arg1.takeAs<Expr>(); 10934 } else { 10935 // Convert the arguments. 10936 ExprResult Arg0 = PerformCopyInitialization( 10937 InitializedEntity::InitializeParameter(Context, 10938 FnDecl->getParamDecl(0)), 10939 SourceLocation(), Owned(Args[0])); 10940 if (Arg0.isInvalid()) 10941 return ExprError(); 10942 10943 ExprResult Arg1 = 10944 PerformCopyInitialization( 10945 InitializedEntity::InitializeParameter(Context, 10946 FnDecl->getParamDecl(1)), 10947 SourceLocation(), Owned(Args[1])); 10948 if (Arg1.isInvalid()) 10949 return ExprError(); 10950 Args[0] = LHS = Arg0.takeAs<Expr>(); 10951 Args[1] = RHS = Arg1.takeAs<Expr>(); 10952 } 10953 10954 // Build the actual expression node. 10955 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10956 Best->FoundDecl, 10957 HadMultipleCandidates, OpLoc); 10958 if (FnExpr.isInvalid()) 10959 return ExprError(); 10960 10961 // Determine the result type. 10962 QualType ResultTy = FnDecl->getResultType(); 10963 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10964 ResultTy = ResultTy.getNonLValueExprType(Context); 10965 10966 CXXOperatorCallExpr *TheCall = 10967 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10968 Args, ResultTy, VK, OpLoc, 10969 FPFeatures.fp_contract); 10970 10971 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10972 FnDecl)) 10973 return ExprError(); 10974 10975 ArrayRef<const Expr *> ArgsArray(Args, 2); 10976 // Cut off the implicit 'this'. 10977 if (isa<CXXMethodDecl>(FnDecl)) 10978 ArgsArray = ArgsArray.slice(1); 10979 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10980 TheCall->getSourceRange(), VariadicDoesNotApply); 10981 10982 return MaybeBindToTemporary(TheCall); 10983 } else { 10984 // We matched a built-in operator. Convert the arguments, then 10985 // break out so that we will build the appropriate built-in 10986 // operator node. 10987 ExprResult ArgsRes0 = 10988 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10989 Best->Conversions[0], AA_Passing); 10990 if (ArgsRes0.isInvalid()) 10991 return ExprError(); 10992 Args[0] = ArgsRes0.take(); 10993 10994 ExprResult ArgsRes1 = 10995 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10996 Best->Conversions[1], AA_Passing); 10997 if (ArgsRes1.isInvalid()) 10998 return ExprError(); 10999 Args[1] = ArgsRes1.take(); 11000 break; 11001 } 11002 } 11003 11004 case OR_No_Viable_Function: { 11005 // C++ [over.match.oper]p9: 11006 // If the operator is the operator , [...] and there are no 11007 // viable functions, then the operator is assumed to be the 11008 // built-in operator and interpreted according to clause 5. 11009 if (Opc == BO_Comma) 11010 break; 11011 11012 // For class as left operand for assignment or compound assigment 11013 // operator do not fall through to handling in built-in, but report that 11014 // no overloaded assignment operator found 11015 ExprResult Result = ExprError(); 11016 if (Args[0]->getType()->isRecordType() && 11017 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11018 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11019 << BinaryOperator::getOpcodeStr(Opc) 11020 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11021 if (Args[0]->getType()->isIncompleteType()) { 11022 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11023 << Args[0]->getType() 11024 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11025 } 11026 } else { 11027 // This is an erroneous use of an operator which can be overloaded by 11028 // a non-member function. Check for non-member operators which were 11029 // defined too late to be candidates. 11030 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11031 // FIXME: Recover by calling the found function. 11032 return ExprError(); 11033 11034 // No viable function; try to create a built-in operation, which will 11035 // produce an error. Then, show the non-viable candidates. 11036 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11037 } 11038 assert(Result.isInvalid() && 11039 "C++ binary operator overloading is missing candidates!"); 11040 if (Result.isInvalid()) 11041 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11042 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11043 return Result; 11044 } 11045 11046 case OR_Ambiguous: 11047 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11048 << BinaryOperator::getOpcodeStr(Opc) 11049 << Args[0]->getType() << Args[1]->getType() 11050 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11051 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11052 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11053 return ExprError(); 11054 11055 case OR_Deleted: 11056 if (isImplicitlyDeleted(Best->Function)) { 11057 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11058 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11059 << Context.getRecordType(Method->getParent()) 11060 << getSpecialMember(Method); 11061 11062 // The user probably meant to call this special member. Just 11063 // explain why it's deleted. 11064 NoteDeletedFunction(Method); 11065 return ExprError(); 11066 } else { 11067 Diag(OpLoc, diag::err_ovl_deleted_oper) 11068 << Best->Function->isDeleted() 11069 << BinaryOperator::getOpcodeStr(Opc) 11070 << getDeletedOrUnavailableSuffix(Best->Function) 11071 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11072 } 11073 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11074 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11075 return ExprError(); 11076 } 11077 11078 // We matched a built-in operator; build it. 11079 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11080 } 11081 11082 ExprResult 11083 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11084 SourceLocation RLoc, 11085 Expr *Base, Expr *Idx) { 11086 Expr *Args[2] = { Base, Idx }; 11087 DeclarationName OpName = 11088 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11089 11090 // If either side is type-dependent, create an appropriate dependent 11091 // expression. 11092 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11093 11094 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 11095 // CHECKME: no 'operator' keyword? 11096 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11097 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11098 UnresolvedLookupExpr *Fn 11099 = UnresolvedLookupExpr::Create(Context, NamingClass, 11100 NestedNameSpecifierLoc(), OpNameInfo, 11101 /*ADL*/ true, /*Overloaded*/ false, 11102 UnresolvedSetIterator(), 11103 UnresolvedSetIterator()); 11104 // Can't add any actual overloads yet 11105 11106 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 11107 Args, 11108 Context.DependentTy, 11109 VK_RValue, 11110 RLoc, false)); 11111 } 11112 11113 // Handle placeholders on both operands. 11114 if (checkPlaceholderForOverload(*this, Args[0])) 11115 return ExprError(); 11116 if (checkPlaceholderForOverload(*this, Args[1])) 11117 return ExprError(); 11118 11119 // Build an empty overload set. 11120 OverloadCandidateSet CandidateSet(LLoc); 11121 11122 // Subscript can only be overloaded as a member function. 11123 11124 // Add operator candidates that are member functions. 11125 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11126 11127 // Add builtin operator candidates. 11128 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11129 11130 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11131 11132 // Perform overload resolution. 11133 OverloadCandidateSet::iterator Best; 11134 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11135 case OR_Success: { 11136 // We found a built-in operator or an overloaded operator. 11137 FunctionDecl *FnDecl = Best->Function; 11138 11139 if (FnDecl) { 11140 // We matched an overloaded operator. Build a call to that 11141 // operator. 11142 11143 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11144 11145 // Convert the arguments. 11146 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11147 ExprResult Arg0 = 11148 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 11149 Best->FoundDecl, Method); 11150 if (Arg0.isInvalid()) 11151 return ExprError(); 11152 Args[0] = Arg0.take(); 11153 11154 // Convert the arguments. 11155 ExprResult InputInit 11156 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11157 Context, 11158 FnDecl->getParamDecl(0)), 11159 SourceLocation(), 11160 Owned(Args[1])); 11161 if (InputInit.isInvalid()) 11162 return ExprError(); 11163 11164 Args[1] = InputInit.takeAs<Expr>(); 11165 11166 // Build the actual expression node. 11167 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11168 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11169 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11170 Best->FoundDecl, 11171 HadMultipleCandidates, 11172 OpLocInfo.getLoc(), 11173 OpLocInfo.getInfo()); 11174 if (FnExpr.isInvalid()) 11175 return ExprError(); 11176 11177 // Determine the result type 11178 QualType ResultTy = FnDecl->getResultType(); 11179 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11180 ResultTy = ResultTy.getNonLValueExprType(Context); 11181 11182 CXXOperatorCallExpr *TheCall = 11183 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11184 FnExpr.take(), Args, 11185 ResultTy, VK, RLoc, 11186 false); 11187 11188 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 11189 FnDecl)) 11190 return ExprError(); 11191 11192 return MaybeBindToTemporary(TheCall); 11193 } else { 11194 // We matched a built-in operator. Convert the arguments, then 11195 // break out so that we will build the appropriate built-in 11196 // operator node. 11197 ExprResult ArgsRes0 = 11198 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11199 Best->Conversions[0], AA_Passing); 11200 if (ArgsRes0.isInvalid()) 11201 return ExprError(); 11202 Args[0] = ArgsRes0.take(); 11203 11204 ExprResult ArgsRes1 = 11205 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11206 Best->Conversions[1], AA_Passing); 11207 if (ArgsRes1.isInvalid()) 11208 return ExprError(); 11209 Args[1] = ArgsRes1.take(); 11210 11211 break; 11212 } 11213 } 11214 11215 case OR_No_Viable_Function: { 11216 if (CandidateSet.empty()) 11217 Diag(LLoc, diag::err_ovl_no_oper) 11218 << Args[0]->getType() << /*subscript*/ 0 11219 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11220 else 11221 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11222 << Args[0]->getType() 11223 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11225 "[]", LLoc); 11226 return ExprError(); 11227 } 11228 11229 case OR_Ambiguous: 11230 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11231 << "[]" 11232 << Args[0]->getType() << Args[1]->getType() 11233 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11234 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11235 "[]", LLoc); 11236 return ExprError(); 11237 11238 case OR_Deleted: 11239 Diag(LLoc, diag::err_ovl_deleted_oper) 11240 << Best->Function->isDeleted() << "[]" 11241 << getDeletedOrUnavailableSuffix(Best->Function) 11242 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11243 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11244 "[]", LLoc); 11245 return ExprError(); 11246 } 11247 11248 // We matched a built-in operator; build it. 11249 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11250 } 11251 11252 /// BuildCallToMemberFunction - Build a call to a member 11253 /// function. MemExpr is the expression that refers to the member 11254 /// function (and includes the object parameter), Args/NumArgs are the 11255 /// arguments to the function call (not including the object 11256 /// parameter). The caller needs to validate that the member 11257 /// expression refers to a non-static member function or an overloaded 11258 /// member function. 11259 ExprResult 11260 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11261 SourceLocation LParenLoc, 11262 MultiExprArg Args, 11263 SourceLocation RParenLoc) { 11264 assert(MemExprE->getType() == Context.BoundMemberTy || 11265 MemExprE->getType() == Context.OverloadTy); 11266 11267 // Dig out the member expression. This holds both the object 11268 // argument and the member function we're referring to. 11269 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11270 11271 // Determine whether this is a call to a pointer-to-member function. 11272 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11273 assert(op->getType() == Context.BoundMemberTy); 11274 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11275 11276 QualType fnType = 11277 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11278 11279 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11280 QualType resultType = proto->getCallResultType(Context); 11281 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 11282 11283 // Check that the object type isn't more qualified than the 11284 // member function we're calling. 11285 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11286 11287 QualType objectType = op->getLHS()->getType(); 11288 if (op->getOpcode() == BO_PtrMemI) 11289 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11290 Qualifiers objectQuals = objectType.getQualifiers(); 11291 11292 Qualifiers difference = objectQuals - funcQuals; 11293 difference.removeObjCGCAttr(); 11294 difference.removeAddressSpace(); 11295 if (difference) { 11296 std::string qualsString = difference.getAsString(); 11297 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11298 << fnType.getUnqualifiedType() 11299 << qualsString 11300 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11301 } 11302 11303 CXXMemberCallExpr *call 11304 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11305 resultType, valueKind, RParenLoc); 11306 11307 if (CheckCallReturnType(proto->getResultType(), 11308 op->getRHS()->getLocStart(), 11309 call, 0)) 11310 return ExprError(); 11311 11312 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11313 return ExprError(); 11314 11315 if (CheckOtherCall(call, proto)) 11316 return ExprError(); 11317 11318 return MaybeBindToTemporary(call); 11319 } 11320 11321 UnbridgedCastsSet UnbridgedCasts; 11322 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11323 return ExprError(); 11324 11325 MemberExpr *MemExpr; 11326 CXXMethodDecl *Method = 0; 11327 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11328 NestedNameSpecifier *Qualifier = 0; 11329 if (isa<MemberExpr>(NakedMemExpr)) { 11330 MemExpr = cast<MemberExpr>(NakedMemExpr); 11331 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11332 FoundDecl = MemExpr->getFoundDecl(); 11333 Qualifier = MemExpr->getQualifier(); 11334 UnbridgedCasts.restore(); 11335 } else { 11336 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11337 Qualifier = UnresExpr->getQualifier(); 11338 11339 QualType ObjectType = UnresExpr->getBaseType(); 11340 Expr::Classification ObjectClassification 11341 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11342 : UnresExpr->getBase()->Classify(Context); 11343 11344 // Add overload candidates 11345 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 11346 11347 // FIXME: avoid copy. 11348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11349 if (UnresExpr->hasExplicitTemplateArgs()) { 11350 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11351 TemplateArgs = &TemplateArgsBuffer; 11352 } 11353 11354 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11355 E = UnresExpr->decls_end(); I != E; ++I) { 11356 11357 NamedDecl *Func = *I; 11358 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11359 if (isa<UsingShadowDecl>(Func)) 11360 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11361 11362 11363 // Microsoft supports direct constructor calls. 11364 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11365 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11366 Args, CandidateSet); 11367 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11368 // If explicit template arguments were provided, we can't call a 11369 // non-template member function. 11370 if (TemplateArgs) 11371 continue; 11372 11373 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11374 ObjectClassification, Args, CandidateSet, 11375 /*SuppressUserConversions=*/false); 11376 } else { 11377 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11378 I.getPair(), ActingDC, TemplateArgs, 11379 ObjectType, ObjectClassification, 11380 Args, CandidateSet, 11381 /*SuppressUsedConversions=*/false); 11382 } 11383 } 11384 11385 DeclarationName DeclName = UnresExpr->getMemberName(); 11386 11387 UnbridgedCasts.restore(); 11388 11389 OverloadCandidateSet::iterator Best; 11390 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11391 Best)) { 11392 case OR_Success: 11393 Method = cast<CXXMethodDecl>(Best->Function); 11394 FoundDecl = Best->FoundDecl; 11395 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11396 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11397 return ExprError(); 11398 // If FoundDecl is different from Method (such as if one is a template 11399 // and the other a specialization), make sure DiagnoseUseOfDecl is 11400 // called on both. 11401 // FIXME: This would be more comprehensively addressed by modifying 11402 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11403 // being used. 11404 if (Method != FoundDecl.getDecl() && 11405 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11406 return ExprError(); 11407 break; 11408 11409 case OR_No_Viable_Function: 11410 Diag(UnresExpr->getMemberLoc(), 11411 diag::err_ovl_no_viable_member_function_in_call) 11412 << DeclName << MemExprE->getSourceRange(); 11413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11414 // FIXME: Leaking incoming expressions! 11415 return ExprError(); 11416 11417 case OR_Ambiguous: 11418 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11419 << DeclName << MemExprE->getSourceRange(); 11420 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11421 // FIXME: Leaking incoming expressions! 11422 return ExprError(); 11423 11424 case OR_Deleted: 11425 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11426 << Best->Function->isDeleted() 11427 << DeclName 11428 << getDeletedOrUnavailableSuffix(Best->Function) 11429 << MemExprE->getSourceRange(); 11430 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11431 // FIXME: Leaking incoming expressions! 11432 return ExprError(); 11433 } 11434 11435 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11436 11437 // If overload resolution picked a static member, build a 11438 // non-member call based on that function. 11439 if (Method->isStatic()) { 11440 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11441 RParenLoc); 11442 } 11443 11444 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11445 } 11446 11447 QualType ResultType = Method->getResultType(); 11448 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11449 ResultType = ResultType.getNonLValueExprType(Context); 11450 11451 assert(Method && "Member call to something that isn't a method?"); 11452 CXXMemberCallExpr *TheCall = 11453 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11454 ResultType, VK, RParenLoc); 11455 11456 // Check for a valid return type. 11457 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11458 TheCall, Method)) 11459 return ExprError(); 11460 11461 // Convert the object argument (for a non-static member function call). 11462 // We only need to do this if there was actually an overload; otherwise 11463 // it was done at lookup. 11464 if (!Method->isStatic()) { 11465 ExprResult ObjectArg = 11466 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11467 FoundDecl, Method); 11468 if (ObjectArg.isInvalid()) 11469 return ExprError(); 11470 MemExpr->setBase(ObjectArg.take()); 11471 } 11472 11473 // Convert the rest of the arguments 11474 const FunctionProtoType *Proto = 11475 Method->getType()->getAs<FunctionProtoType>(); 11476 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11477 RParenLoc)) 11478 return ExprError(); 11479 11480 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11481 11482 if (CheckFunctionCall(Method, TheCall, Proto)) 11483 return ExprError(); 11484 11485 if ((isa<CXXConstructorDecl>(CurContext) || 11486 isa<CXXDestructorDecl>(CurContext)) && 11487 TheCall->getMethodDecl()->isPure()) { 11488 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11489 11490 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11491 Diag(MemExpr->getLocStart(), 11492 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11493 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11494 << MD->getParent()->getDeclName(); 11495 11496 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11497 } 11498 } 11499 return MaybeBindToTemporary(TheCall); 11500 } 11501 11502 /// BuildCallToObjectOfClassType - Build a call to an object of class 11503 /// type (C++ [over.call.object]), which can end up invoking an 11504 /// overloaded function call operator (@c operator()) or performing a 11505 /// user-defined conversion on the object argument. 11506 ExprResult 11507 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11508 SourceLocation LParenLoc, 11509 MultiExprArg Args, 11510 SourceLocation RParenLoc) { 11511 if (checkPlaceholderForOverload(*this, Obj)) 11512 return ExprError(); 11513 ExprResult Object = Owned(Obj); 11514 11515 UnbridgedCastsSet UnbridgedCasts; 11516 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11517 return ExprError(); 11518 11519 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11520 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11521 11522 // C++ [over.call.object]p1: 11523 // If the primary-expression E in the function call syntax 11524 // evaluates to a class object of type "cv T", then the set of 11525 // candidate functions includes at least the function call 11526 // operators of T. The function call operators of T are obtained by 11527 // ordinary lookup of the name operator() in the context of 11528 // (E).operator(). 11529 OverloadCandidateSet CandidateSet(LParenLoc); 11530 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11531 11532 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11533 diag::err_incomplete_object_call, Object.get())) 11534 return true; 11535 11536 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11537 LookupQualifiedName(R, Record->getDecl()); 11538 R.suppressDiagnostics(); 11539 11540 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11541 Oper != OperEnd; ++Oper) { 11542 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11543 Object.get()->Classify(Context), 11544 Args, CandidateSet, 11545 /*SuppressUserConversions=*/ false); 11546 } 11547 11548 // C++ [over.call.object]p2: 11549 // In addition, for each (non-explicit in C++0x) conversion function 11550 // declared in T of the form 11551 // 11552 // operator conversion-type-id () cv-qualifier; 11553 // 11554 // where cv-qualifier is the same cv-qualification as, or a 11555 // greater cv-qualification than, cv, and where conversion-type-id 11556 // denotes the type "pointer to function of (P1,...,Pn) returning 11557 // R", or the type "reference to pointer to function of 11558 // (P1,...,Pn) returning R", or the type "reference to function 11559 // of (P1,...,Pn) returning R", a surrogate call function [...] 11560 // is also considered as a candidate function. Similarly, 11561 // surrogate call functions are added to the set of candidate 11562 // functions for each conversion function declared in an 11563 // accessible base class provided the function is not hidden 11564 // within T by another intervening declaration. 11565 std::pair<CXXRecordDecl::conversion_iterator, 11566 CXXRecordDecl::conversion_iterator> Conversions 11567 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11568 for (CXXRecordDecl::conversion_iterator 11569 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11570 NamedDecl *D = *I; 11571 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11572 if (isa<UsingShadowDecl>(D)) 11573 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11574 11575 // Skip over templated conversion functions; they aren't 11576 // surrogates. 11577 if (isa<FunctionTemplateDecl>(D)) 11578 continue; 11579 11580 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11581 if (!Conv->isExplicit()) { 11582 // Strip the reference type (if any) and then the pointer type (if 11583 // any) to get down to what might be a function type. 11584 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11585 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11586 ConvType = ConvPtrType->getPointeeType(); 11587 11588 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11589 { 11590 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11591 Object.get(), Args, CandidateSet); 11592 } 11593 } 11594 } 11595 11596 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11597 11598 // Perform overload resolution. 11599 OverloadCandidateSet::iterator Best; 11600 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11601 Best)) { 11602 case OR_Success: 11603 // Overload resolution succeeded; we'll build the appropriate call 11604 // below. 11605 break; 11606 11607 case OR_No_Viable_Function: 11608 if (CandidateSet.empty()) 11609 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11610 << Object.get()->getType() << /*call*/ 1 11611 << Object.get()->getSourceRange(); 11612 else 11613 Diag(Object.get()->getLocStart(), 11614 diag::err_ovl_no_viable_object_call) 11615 << Object.get()->getType() << Object.get()->getSourceRange(); 11616 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11617 break; 11618 11619 case OR_Ambiguous: 11620 Diag(Object.get()->getLocStart(), 11621 diag::err_ovl_ambiguous_object_call) 11622 << Object.get()->getType() << Object.get()->getSourceRange(); 11623 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11624 break; 11625 11626 case OR_Deleted: 11627 Diag(Object.get()->getLocStart(), 11628 diag::err_ovl_deleted_object_call) 11629 << Best->Function->isDeleted() 11630 << Object.get()->getType() 11631 << getDeletedOrUnavailableSuffix(Best->Function) 11632 << Object.get()->getSourceRange(); 11633 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11634 break; 11635 } 11636 11637 if (Best == CandidateSet.end()) 11638 return true; 11639 11640 UnbridgedCasts.restore(); 11641 11642 if (Best->Function == 0) { 11643 // Since there is no function declaration, this is one of the 11644 // surrogate candidates. Dig out the conversion function. 11645 CXXConversionDecl *Conv 11646 = cast<CXXConversionDecl>( 11647 Best->Conversions[0].UserDefined.ConversionFunction); 11648 11649 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11650 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11651 return ExprError(); 11652 assert(Conv == Best->FoundDecl.getDecl() && 11653 "Found Decl & conversion-to-functionptr should be same, right?!"); 11654 // We selected one of the surrogate functions that converts the 11655 // object parameter to a function pointer. Perform the conversion 11656 // on the object argument, then let ActOnCallExpr finish the job. 11657 11658 // Create an implicit member expr to refer to the conversion operator. 11659 // and then call it. 11660 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11661 Conv, HadMultipleCandidates); 11662 if (Call.isInvalid()) 11663 return ExprError(); 11664 // Record usage of conversion in an implicit cast. 11665 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11666 CK_UserDefinedConversion, 11667 Call.get(), 0, VK_RValue)); 11668 11669 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11670 } 11671 11672 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11673 11674 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11675 // that calls this method, using Object for the implicit object 11676 // parameter and passing along the remaining arguments. 11677 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11678 11679 // An error diagnostic has already been printed when parsing the declaration. 11680 if (Method->isInvalidDecl()) 11681 return ExprError(); 11682 11683 const FunctionProtoType *Proto = 11684 Method->getType()->getAs<FunctionProtoType>(); 11685 11686 unsigned NumArgsInProto = Proto->getNumArgs(); 11687 11688 DeclarationNameInfo OpLocInfo( 11689 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11690 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11691 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11692 HadMultipleCandidates, 11693 OpLocInfo.getLoc(), 11694 OpLocInfo.getInfo()); 11695 if (NewFn.isInvalid()) 11696 return true; 11697 11698 // Build the full argument list for the method call (the implicit object 11699 // parameter is placed at the beginning of the list). 11700 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]); 11701 MethodArgs[0] = Object.get(); 11702 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11703 11704 // Once we've built TheCall, all of the expressions are properly 11705 // owned. 11706 QualType ResultTy = Method->getResultType(); 11707 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11708 ResultTy = ResultTy.getNonLValueExprType(Context); 11709 11710 CXXOperatorCallExpr *TheCall = new (Context) 11711 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11712 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11713 ResultTy, VK, RParenLoc, false); 11714 MethodArgs.reset(); 11715 11716 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11717 Method)) 11718 return true; 11719 11720 // We may have default arguments. If so, we need to allocate more 11721 // slots in the call for them. 11722 if (Args.size() < NumArgsInProto) 11723 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11724 11725 bool IsError = false; 11726 11727 // Initialize the implicit object parameter. 11728 ExprResult ObjRes = 11729 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11730 Best->FoundDecl, Method); 11731 if (ObjRes.isInvalid()) 11732 IsError = true; 11733 else 11734 Object = ObjRes; 11735 TheCall->setArg(0, Object.take()); 11736 11737 // Check the argument types. 11738 for (unsigned i = 0; i != NumArgsInProto; i++) { 11739 Expr *Arg; 11740 if (i < Args.size()) { 11741 Arg = Args[i]; 11742 11743 // Pass the argument. 11744 11745 ExprResult InputInit 11746 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11747 Context, 11748 Method->getParamDecl(i)), 11749 SourceLocation(), Arg); 11750 11751 IsError |= InputInit.isInvalid(); 11752 Arg = InputInit.takeAs<Expr>(); 11753 } else { 11754 ExprResult DefArg 11755 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11756 if (DefArg.isInvalid()) { 11757 IsError = true; 11758 break; 11759 } 11760 11761 Arg = DefArg.takeAs<Expr>(); 11762 } 11763 11764 TheCall->setArg(i + 1, Arg); 11765 } 11766 11767 // If this is a variadic call, handle args passed through "...". 11768 if (Proto->isVariadic()) { 11769 // Promote the arguments (C99 6.5.2.2p7). 11770 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11771 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11772 IsError |= Arg.isInvalid(); 11773 TheCall->setArg(i + 1, Arg.take()); 11774 } 11775 } 11776 11777 if (IsError) return true; 11778 11779 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11780 11781 if (CheckFunctionCall(Method, TheCall, Proto)) 11782 return true; 11783 11784 return MaybeBindToTemporary(TheCall); 11785 } 11786 11787 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11788 /// (if one exists), where @c Base is an expression of class type and 11789 /// @c Member is the name of the member we're trying to find. 11790 ExprResult 11791 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11792 bool *NoArrowOperatorFound) { 11793 assert(Base->getType()->isRecordType() && 11794 "left-hand side must have class type"); 11795 11796 if (checkPlaceholderForOverload(*this, Base)) 11797 return ExprError(); 11798 11799 SourceLocation Loc = Base->getExprLoc(); 11800 11801 // C++ [over.ref]p1: 11802 // 11803 // [...] An expression x->m is interpreted as (x.operator->())->m 11804 // for a class object x of type T if T::operator->() exists and if 11805 // the operator is selected as the best match function by the 11806 // overload resolution mechanism (13.3). 11807 DeclarationName OpName = 11808 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11809 OverloadCandidateSet CandidateSet(Loc); 11810 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11811 11812 if (RequireCompleteType(Loc, Base->getType(), 11813 diag::err_typecheck_incomplete_tag, Base)) 11814 return ExprError(); 11815 11816 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11817 LookupQualifiedName(R, BaseRecord->getDecl()); 11818 R.suppressDiagnostics(); 11819 11820 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11821 Oper != OperEnd; ++Oper) { 11822 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11823 None, CandidateSet, /*SuppressUserConversions=*/false); 11824 } 11825 11826 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11827 11828 // Perform overload resolution. 11829 OverloadCandidateSet::iterator Best; 11830 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11831 case OR_Success: 11832 // Overload resolution succeeded; we'll build the call below. 11833 break; 11834 11835 case OR_No_Viable_Function: 11836 if (CandidateSet.empty()) { 11837 QualType BaseType = Base->getType(); 11838 if (NoArrowOperatorFound) { 11839 // Report this specific error to the caller instead of emitting a 11840 // diagnostic, as requested. 11841 *NoArrowOperatorFound = true; 11842 return ExprError(); 11843 } 11844 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11845 << BaseType << Base->getSourceRange(); 11846 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11847 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11848 << FixItHint::CreateReplacement(OpLoc, "."); 11849 } 11850 } else 11851 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11852 << "operator->" << Base->getSourceRange(); 11853 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11854 return ExprError(); 11855 11856 case OR_Ambiguous: 11857 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11858 << "->" << Base->getType() << Base->getSourceRange(); 11859 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11860 return ExprError(); 11861 11862 case OR_Deleted: 11863 Diag(OpLoc, diag::err_ovl_deleted_oper) 11864 << Best->Function->isDeleted() 11865 << "->" 11866 << getDeletedOrUnavailableSuffix(Best->Function) 11867 << Base->getSourceRange(); 11868 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11869 return ExprError(); 11870 } 11871 11872 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11873 11874 // Convert the object parameter. 11875 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11876 ExprResult BaseResult = 11877 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11878 Best->FoundDecl, Method); 11879 if (BaseResult.isInvalid()) 11880 return ExprError(); 11881 Base = BaseResult.take(); 11882 11883 // Build the operator call. 11884 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11885 HadMultipleCandidates, OpLoc); 11886 if (FnExpr.isInvalid()) 11887 return ExprError(); 11888 11889 QualType ResultTy = Method->getResultType(); 11890 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11891 ResultTy = ResultTy.getNonLValueExprType(Context); 11892 CXXOperatorCallExpr *TheCall = 11893 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11894 Base, ResultTy, VK, OpLoc, false); 11895 11896 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11897 Method)) 11898 return ExprError(); 11899 11900 return MaybeBindToTemporary(TheCall); 11901 } 11902 11903 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11904 /// a literal operator described by the provided lookup results. 11905 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11906 DeclarationNameInfo &SuffixInfo, 11907 ArrayRef<Expr*> Args, 11908 SourceLocation LitEndLoc, 11909 TemplateArgumentListInfo *TemplateArgs) { 11910 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11911 11912 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11913 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11914 TemplateArgs); 11915 11916 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11917 11918 // Perform overload resolution. This will usually be trivial, but might need 11919 // to perform substitutions for a literal operator template. 11920 OverloadCandidateSet::iterator Best; 11921 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11922 case OR_Success: 11923 case OR_Deleted: 11924 break; 11925 11926 case OR_No_Viable_Function: 11927 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11928 << R.getLookupName(); 11929 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11930 return ExprError(); 11931 11932 case OR_Ambiguous: 11933 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11934 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11935 return ExprError(); 11936 } 11937 11938 FunctionDecl *FD = Best->Function; 11939 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11940 HadMultipleCandidates, 11941 SuffixInfo.getLoc(), 11942 SuffixInfo.getInfo()); 11943 if (Fn.isInvalid()) 11944 return true; 11945 11946 // Check the argument types. This should almost always be a no-op, except 11947 // that array-to-pointer decay is applied to string literals. 11948 Expr *ConvArgs[2]; 11949 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11950 ExprResult InputInit = PerformCopyInitialization( 11951 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11952 SourceLocation(), Args[ArgIdx]); 11953 if (InputInit.isInvalid()) 11954 return true; 11955 ConvArgs[ArgIdx] = InputInit.take(); 11956 } 11957 11958 QualType ResultTy = FD->getResultType(); 11959 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11960 ResultTy = ResultTy.getNonLValueExprType(Context); 11961 11962 UserDefinedLiteral *UDL = 11963 new (Context) UserDefinedLiteral(Context, Fn.take(), 11964 llvm::makeArrayRef(ConvArgs, Args.size()), 11965 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11966 11967 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11968 return ExprError(); 11969 11970 if (CheckFunctionCall(FD, UDL, NULL)) 11971 return ExprError(); 11972 11973 return MaybeBindToTemporary(UDL); 11974 } 11975 11976 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11977 /// given LookupResult is non-empty, it is assumed to describe a member which 11978 /// will be invoked. Otherwise, the function will be found via argument 11979 /// dependent lookup. 11980 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11981 /// otherwise CallExpr is set to ExprError() and some non-success value 11982 /// is returned. 11983 Sema::ForRangeStatus 11984 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11985 SourceLocation RangeLoc, VarDecl *Decl, 11986 BeginEndFunction BEF, 11987 const DeclarationNameInfo &NameInfo, 11988 LookupResult &MemberLookup, 11989 OverloadCandidateSet *CandidateSet, 11990 Expr *Range, ExprResult *CallExpr) { 11991 CandidateSet->clear(); 11992 if (!MemberLookup.empty()) { 11993 ExprResult MemberRef = 11994 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11995 /*IsPtr=*/false, CXXScopeSpec(), 11996 /*TemplateKWLoc=*/SourceLocation(), 11997 /*FirstQualifierInScope=*/0, 11998 MemberLookup, 11999 /*TemplateArgs=*/0); 12000 if (MemberRef.isInvalid()) { 12001 *CallExpr = ExprError(); 12002 Diag(Range->getLocStart(), diag::note_in_for_range) 12003 << RangeLoc << BEF << Range->getType(); 12004 return FRS_DiagnosticIssued; 12005 } 12006 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 12007 if (CallExpr->isInvalid()) { 12008 *CallExpr = ExprError(); 12009 Diag(Range->getLocStart(), diag::note_in_for_range) 12010 << RangeLoc << BEF << Range->getType(); 12011 return FRS_DiagnosticIssued; 12012 } 12013 } else { 12014 UnresolvedSet<0> FoundNames; 12015 UnresolvedLookupExpr *Fn = 12016 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 12017 NestedNameSpecifierLoc(), NameInfo, 12018 /*NeedsADL=*/true, /*Overloaded=*/false, 12019 FoundNames.begin(), FoundNames.end()); 12020 12021 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12022 CandidateSet, CallExpr); 12023 if (CandidateSet->empty() || CandidateSetError) { 12024 *CallExpr = ExprError(); 12025 return FRS_NoViableFunction; 12026 } 12027 OverloadCandidateSet::iterator Best; 12028 OverloadingResult OverloadResult = 12029 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12030 12031 if (OverloadResult == OR_No_Viable_Function) { 12032 *CallExpr = ExprError(); 12033 return FRS_NoViableFunction; 12034 } 12035 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12036 Loc, 0, CandidateSet, &Best, 12037 OverloadResult, 12038 /*AllowTypoCorrection=*/false); 12039 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12040 *CallExpr = ExprError(); 12041 Diag(Range->getLocStart(), diag::note_in_for_range) 12042 << RangeLoc << BEF << Range->getType(); 12043 return FRS_DiagnosticIssued; 12044 } 12045 } 12046 return FRS_Success; 12047 } 12048 12049 12050 /// FixOverloadedFunctionReference - E is an expression that refers to 12051 /// a C++ overloaded function (possibly with some parentheses and 12052 /// perhaps a '&' around it). We have resolved the overloaded function 12053 /// to the function declaration Fn, so patch up the expression E to 12054 /// refer (possibly indirectly) to Fn. Returns the new expr. 12055 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12056 FunctionDecl *Fn) { 12057 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12058 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12059 Found, Fn); 12060 if (SubExpr == PE->getSubExpr()) 12061 return PE; 12062 12063 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12064 } 12065 12066 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12067 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12068 Found, Fn); 12069 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12070 SubExpr->getType()) && 12071 "Implicit cast type cannot be determined from overload"); 12072 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12073 if (SubExpr == ICE->getSubExpr()) 12074 return ICE; 12075 12076 return ImplicitCastExpr::Create(Context, ICE->getType(), 12077 ICE->getCastKind(), 12078 SubExpr, 0, 12079 ICE->getValueKind()); 12080 } 12081 12082 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12083 assert(UnOp->getOpcode() == UO_AddrOf && 12084 "Can only take the address of an overloaded function"); 12085 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12086 if (Method->isStatic()) { 12087 // Do nothing: static member functions aren't any different 12088 // from non-member functions. 12089 } else { 12090 // Fix the subexpression, which really has to be an 12091 // UnresolvedLookupExpr holding an overloaded member function 12092 // or template. 12093 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12094 Found, Fn); 12095 if (SubExpr == UnOp->getSubExpr()) 12096 return UnOp; 12097 12098 assert(isa<DeclRefExpr>(SubExpr) 12099 && "fixed to something other than a decl ref"); 12100 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12101 && "fixed to a member ref with no nested name qualifier"); 12102 12103 // We have taken the address of a pointer to member 12104 // function. Perform the computation here so that we get the 12105 // appropriate pointer to member type. 12106 QualType ClassType 12107 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12108 QualType MemPtrType 12109 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12110 12111 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12112 VK_RValue, OK_Ordinary, 12113 UnOp->getOperatorLoc()); 12114 } 12115 } 12116 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12117 Found, Fn); 12118 if (SubExpr == UnOp->getSubExpr()) 12119 return UnOp; 12120 12121 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12122 Context.getPointerType(SubExpr->getType()), 12123 VK_RValue, OK_Ordinary, 12124 UnOp->getOperatorLoc()); 12125 } 12126 12127 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12128 // FIXME: avoid copy. 12129 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12130 if (ULE->hasExplicitTemplateArgs()) { 12131 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12132 TemplateArgs = &TemplateArgsBuffer; 12133 } 12134 12135 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12136 ULE->getQualifierLoc(), 12137 ULE->getTemplateKeywordLoc(), 12138 Fn, 12139 /*enclosing*/ false, // FIXME? 12140 ULE->getNameLoc(), 12141 Fn->getType(), 12142 VK_LValue, 12143 Found.getDecl(), 12144 TemplateArgs); 12145 MarkDeclRefReferenced(DRE); 12146 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12147 return DRE; 12148 } 12149 12150 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12151 // FIXME: avoid copy. 12152 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12153 if (MemExpr->hasExplicitTemplateArgs()) { 12154 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12155 TemplateArgs = &TemplateArgsBuffer; 12156 } 12157 12158 Expr *Base; 12159 12160 // If we're filling in a static method where we used to have an 12161 // implicit member access, rewrite to a simple decl ref. 12162 if (MemExpr->isImplicitAccess()) { 12163 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12164 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12165 MemExpr->getQualifierLoc(), 12166 MemExpr->getTemplateKeywordLoc(), 12167 Fn, 12168 /*enclosing*/ false, 12169 MemExpr->getMemberLoc(), 12170 Fn->getType(), 12171 VK_LValue, 12172 Found.getDecl(), 12173 TemplateArgs); 12174 MarkDeclRefReferenced(DRE); 12175 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12176 return DRE; 12177 } else { 12178 SourceLocation Loc = MemExpr->getMemberLoc(); 12179 if (MemExpr->getQualifier()) 12180 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12181 CheckCXXThisCapture(Loc); 12182 Base = new (Context) CXXThisExpr(Loc, 12183 MemExpr->getBaseType(), 12184 /*isImplicit=*/true); 12185 } 12186 } else 12187 Base = MemExpr->getBase(); 12188 12189 ExprValueKind valueKind; 12190 QualType type; 12191 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12192 valueKind = VK_LValue; 12193 type = Fn->getType(); 12194 } else { 12195 valueKind = VK_RValue; 12196 type = Context.BoundMemberTy; 12197 } 12198 12199 MemberExpr *ME = MemberExpr::Create(Context, Base, 12200 MemExpr->isArrow(), 12201 MemExpr->getQualifierLoc(), 12202 MemExpr->getTemplateKeywordLoc(), 12203 Fn, 12204 Found, 12205 MemExpr->getMemberNameInfo(), 12206 TemplateArgs, 12207 type, valueKind, OK_Ordinary); 12208 ME->setHadMultipleCandidates(true); 12209 MarkMemberReferenced(ME); 12210 return ME; 12211 } 12212 12213 llvm_unreachable("Invalid reference to overloaded function"); 12214 } 12215 12216 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12217 DeclAccessPair Found, 12218 FunctionDecl *Fn) { 12219 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 12220 } 12221 12222 } // end namespace clang 12223