1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Lex/Preprocessor.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallString.h" 34 #include <algorithm> 35 36 namespace clang { 37 using namespace sema; 38 39 /// A convenience routine for creating a decayed reference to a 40 /// function. 41 static ExprResult 42 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 46 VK_LValue, Loc, LocInfo); 47 if (HadMultipleCandidates) 48 DRE->setHadMultipleCandidates(true); 49 ExprResult E = S.Owned(DRE); 50 E = S.DefaultFunctionArrayConversion(E.take()); 51 if (E.isInvalid()) 52 return ExprError(); 53 return E; 54 } 55 56 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 57 bool InOverloadResolution, 58 StandardConversionSequence &SCS, 59 bool CStyle, 60 bool AllowObjCWritebackConversion); 61 62 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 63 QualType &ToType, 64 bool InOverloadResolution, 65 StandardConversionSequence &SCS, 66 bool CStyle); 67 static OverloadingResult 68 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 69 UserDefinedConversionSequence& User, 70 OverloadCandidateSet& Conversions, 71 bool AllowExplicit); 72 73 74 static ImplicitConversionSequence::CompareKind 75 CompareStandardConversionSequences(Sema &S, 76 const StandardConversionSequence& SCS1, 77 const StandardConversionSequence& SCS2); 78 79 static ImplicitConversionSequence::CompareKind 80 CompareQualificationConversions(Sema &S, 81 const StandardConversionSequence& SCS1, 82 const StandardConversionSequence& SCS2); 83 84 static ImplicitConversionSequence::CompareKind 85 CompareDerivedToBaseConversions(Sema &S, 86 const StandardConversionSequence& SCS1, 87 const StandardConversionSequence& SCS2); 88 89 90 91 /// GetConversionCategory - Retrieve the implicit conversion 92 /// category corresponding to the given implicit conversion kind. 93 ImplicitConversionCategory 94 GetConversionCategory(ImplicitConversionKind Kind) { 95 static const ImplicitConversionCategory 96 Category[(int)ICK_Num_Conversion_Kinds] = { 97 ICC_Identity, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Lvalue_Transformation, 101 ICC_Identity, 102 ICC_Qualification_Adjustment, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Promotion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion, 118 ICC_Conversion 119 }; 120 return Category[(int)Kind]; 121 } 122 123 /// GetConversionRank - Retrieve the implicit conversion rank 124 /// corresponding to the given implicit conversion kind. 125 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 126 static const ImplicitConversionRank 127 Rank[(int)ICK_Num_Conversion_Kinds] = { 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Promotion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Conversion, 148 ICR_Complex_Real_Conversion, 149 ICR_Conversion, 150 ICR_Conversion, 151 ICR_Writeback_Conversion 152 }; 153 return Rank[(int)Kind]; 154 } 155 156 /// GetImplicitConversionName - Return the name of this kind of 157 /// implicit conversion. 158 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 160 "No conversion", 161 "Lvalue-to-rvalue", 162 "Array-to-pointer", 163 "Function-to-pointer", 164 "Noreturn adjustment", 165 "Qualification", 166 "Integral promotion", 167 "Floating point promotion", 168 "Complex promotion", 169 "Integral conversion", 170 "Floating conversion", 171 "Complex conversion", 172 "Floating-integral conversion", 173 "Pointer conversion", 174 "Pointer-to-member conversion", 175 "Boolean conversion", 176 "Compatible-types conversion", 177 "Derived-to-base conversion", 178 "Vector conversion", 179 "Vector splat", 180 "Complex-real conversion", 181 "Block Pointer conversion", 182 "Transparent Union Conversion" 183 "Writeback conversion" 184 }; 185 return Name[Kind]; 186 } 187 188 /// StandardConversionSequence - Set the standard conversion 189 /// sequence to the identity conversion. 190 void StandardConversionSequence::setAsIdentityConversion() { 191 First = ICK_Identity; 192 Second = ICK_Identity; 193 Third = ICK_Identity; 194 DeprecatedStringLiteralToCharPtr = false; 195 QualificationIncludesObjCLifetime = false; 196 ReferenceBinding = false; 197 DirectBinding = false; 198 IsLvalueReference = true; 199 BindsToFunctionLvalue = false; 200 BindsToRvalue = false; 201 BindsImplicitObjectArgumentWithoutRefQualifier = false; 202 ObjCLifetimeConversionBinding = false; 203 CopyConstructor = 0; 204 } 205 206 /// getRank - Retrieve the rank of this standard conversion sequence 207 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 208 /// implicit conversions. 209 ImplicitConversionRank StandardConversionSequence::getRank() const { 210 ImplicitConversionRank Rank = ICR_Exact_Match; 211 if (GetConversionRank(First) > Rank) 212 Rank = GetConversionRank(First); 213 if (GetConversionRank(Second) > Rank) 214 Rank = GetConversionRank(Second); 215 if (GetConversionRank(Third) > Rank) 216 Rank = GetConversionRank(Third); 217 return Rank; 218 } 219 220 /// isPointerConversionToBool - Determines whether this conversion is 221 /// a conversion of a pointer or pointer-to-member to bool. This is 222 /// used as part of the ranking of standard conversion sequences 223 /// (C++ 13.3.3.2p4). 224 bool StandardConversionSequence::isPointerConversionToBool() const { 225 // Note that FromType has not necessarily been transformed by the 226 // array-to-pointer or function-to-pointer implicit conversions, so 227 // check for their presence as well as checking whether FromType is 228 // a pointer. 229 if (getToType(1)->isBooleanType() && 230 (getFromType()->isPointerType() || 231 getFromType()->isObjCObjectPointerType() || 232 getFromType()->isBlockPointerType() || 233 getFromType()->isNullPtrType() || 234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 235 return true; 236 237 return false; 238 } 239 240 /// isPointerConversionToVoidPointer - Determines whether this 241 /// conversion is a conversion of a pointer to a void pointer. This is 242 /// used as part of the ranking of standard conversion sequences (C++ 243 /// 13.3.3.2p4). 244 bool 245 StandardConversionSequence:: 246 isPointerConversionToVoidPointer(ASTContext& Context) const { 247 QualType FromType = getFromType(); 248 QualType ToType = getToType(1); 249 250 // Note that FromType has not necessarily been transformed by the 251 // array-to-pointer implicit conversion, so check for its presence 252 // and redo the conversion to get a pointer. 253 if (First == ICK_Array_To_Pointer) 254 FromType = Context.getArrayDecayedType(FromType); 255 256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 258 return ToPtrType->getPointeeType()->isVoidType(); 259 260 return false; 261 } 262 263 /// Skip any implicit casts which could be either part of a narrowing conversion 264 /// or after one in an implicit conversion. 265 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 267 switch (ICE->getCastKind()) { 268 case CK_NoOp: 269 case CK_IntegralCast: 270 case CK_IntegralToBoolean: 271 case CK_IntegralToFloating: 272 case CK_FloatingToIntegral: 273 case CK_FloatingToBoolean: 274 case CK_FloatingCast: 275 Converted = ICE->getSubExpr(); 276 continue; 277 278 default: 279 return Converted; 280 } 281 } 282 283 return Converted; 284 } 285 286 /// Check if this standard conversion sequence represents a narrowing 287 /// conversion, according to C++11 [dcl.init.list]p7. 288 /// 289 /// \param Ctx The AST context. 290 /// \param Converted The result of applying this standard conversion sequence. 291 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 292 /// value of the expression prior to the narrowing conversion. 293 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 294 /// type of the expression prior to the narrowing conversion. 295 NarrowingKind 296 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 297 const Expr *Converted, 298 APValue &ConstantValue, 299 QualType &ConstantType) const { 300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 301 302 // C++11 [dcl.init.list]p7: 303 // A narrowing conversion is an implicit conversion ... 304 QualType FromType = getToType(0); 305 QualType ToType = getToType(1); 306 switch (Second) { 307 // -- from a floating-point type to an integer type, or 308 // 309 // -- from an integer type or unscoped enumeration type to a floating-point 310 // type, except where the source is a constant expression and the actual 311 // value after conversion will fit into the target type and will produce 312 // the original value when converted back to the original type, or 313 case ICK_Floating_Integral: 314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 315 return NK_Type_Narrowing; 316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 317 llvm::APSInt IntConstantValue; 318 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 319 if (Initializer && 320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 321 // Convert the integer to the floating type. 322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 324 llvm::APFloat::rmNearestTiesToEven); 325 // And back. 326 llvm::APSInt ConvertedValue = IntConstantValue; 327 bool ignored; 328 Result.convertToInteger(ConvertedValue, 329 llvm::APFloat::rmTowardZero, &ignored); 330 // If the resulting value is different, this was a narrowing conversion. 331 if (IntConstantValue != ConvertedValue) { 332 ConstantValue = APValue(IntConstantValue); 333 ConstantType = Initializer->getType(); 334 return NK_Constant_Narrowing; 335 } 336 } else { 337 // Variables are always narrowings. 338 return NK_Variable_Narrowing; 339 } 340 } 341 return NK_Not_Narrowing; 342 343 // -- from long double to double or float, or from double to float, except 344 // where the source is a constant expression and the actual value after 345 // conversion is within the range of values that can be represented (even 346 // if it cannot be represented exactly), or 347 case ICK_Floating_Conversion: 348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 350 // FromType is larger than ToType. 351 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 353 // Constant! 354 assert(ConstantValue.isFloat()); 355 llvm::APFloat FloatVal = ConstantValue.getFloat(); 356 // Convert the source value into the target type. 357 bool ignored; 358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 359 Ctx.getFloatTypeSemantics(ToType), 360 llvm::APFloat::rmNearestTiesToEven, &ignored); 361 // If there was no overflow, the source value is within the range of 362 // values that can be represented. 363 if (ConvertStatus & llvm::APFloat::opOverflow) { 364 ConstantType = Initializer->getType(); 365 return NK_Constant_Narrowing; 366 } 367 } else { 368 return NK_Variable_Narrowing; 369 } 370 } 371 return NK_Not_Narrowing; 372 373 // -- from an integer type or unscoped enumeration type to an integer type 374 // that cannot represent all the values of the original type, except where 375 // the source is a constant expression and the actual value after 376 // conversion will fit into the target type and will produce the original 377 // value when converted back to the original type. 378 case ICK_Boolean_Conversion: // Bools are integers too. 379 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 380 // Boolean conversions can be from pointers and pointers to members 381 // [conv.bool], and those aren't considered narrowing conversions. 382 return NK_Not_Narrowing; 383 } // Otherwise, fall through to the integral case. 384 case ICK_Integral_Conversion: { 385 assert(FromType->isIntegralOrUnscopedEnumerationType()); 386 assert(ToType->isIntegralOrUnscopedEnumerationType()); 387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 388 const unsigned FromWidth = Ctx.getIntWidth(FromType); 389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 390 const unsigned ToWidth = Ctx.getIntWidth(ToType); 391 392 if (FromWidth > ToWidth || 393 (FromWidth == ToWidth && FromSigned != ToSigned) || 394 (FromSigned && !ToSigned)) { 395 // Not all values of FromType can be represented in ToType. 396 llvm::APSInt InitializerValue; 397 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 399 // Such conversions on variables are always narrowing. 400 return NK_Variable_Narrowing; 401 } 402 bool Narrowing = false; 403 if (FromWidth < ToWidth) { 404 // Negative -> unsigned is narrowing. Otherwise, more bits is never 405 // narrowing. 406 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 407 Narrowing = true; 408 } else { 409 // Add a bit to the InitializerValue so we don't have to worry about 410 // signed vs. unsigned comparisons. 411 InitializerValue = InitializerValue.extend( 412 InitializerValue.getBitWidth() + 1); 413 // Convert the initializer to and from the target width and signed-ness. 414 llvm::APSInt ConvertedValue = InitializerValue; 415 ConvertedValue = ConvertedValue.trunc(ToWidth); 416 ConvertedValue.setIsSigned(ToSigned); 417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 418 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 419 // If the result is different, this was a narrowing conversion. 420 if (ConvertedValue != InitializerValue) 421 Narrowing = true; 422 } 423 if (Narrowing) { 424 ConstantType = Initializer->getType(); 425 ConstantValue = APValue(InitializerValue); 426 return NK_Constant_Narrowing; 427 } 428 } 429 return NK_Not_Narrowing; 430 } 431 432 default: 433 // Other kinds of conversions are not narrowings. 434 return NK_Not_Narrowing; 435 } 436 } 437 438 /// DebugPrint - Print this standard conversion sequence to standard 439 /// error. Useful for debugging overloading issues. 440 void StandardConversionSequence::DebugPrint() const { 441 raw_ostream &OS = llvm::errs(); 442 bool PrintedSomething = false; 443 if (First != ICK_Identity) { 444 OS << GetImplicitConversionName(First); 445 PrintedSomething = true; 446 } 447 448 if (Second != ICK_Identity) { 449 if (PrintedSomething) { 450 OS << " -> "; 451 } 452 OS << GetImplicitConversionName(Second); 453 454 if (CopyConstructor) { 455 OS << " (by copy constructor)"; 456 } else if (DirectBinding) { 457 OS << " (direct reference binding)"; 458 } else if (ReferenceBinding) { 459 OS << " (reference binding)"; 460 } 461 PrintedSomething = true; 462 } 463 464 if (Third != ICK_Identity) { 465 if (PrintedSomething) { 466 OS << " -> "; 467 } 468 OS << GetImplicitConversionName(Third); 469 PrintedSomething = true; 470 } 471 472 if (!PrintedSomething) { 473 OS << "No conversions required"; 474 } 475 } 476 477 /// DebugPrint - Print this user-defined conversion sequence to standard 478 /// error. Useful for debugging overloading issues. 479 void UserDefinedConversionSequence::DebugPrint() const { 480 raw_ostream &OS = llvm::errs(); 481 if (Before.First || Before.Second || Before.Third) { 482 Before.DebugPrint(); 483 OS << " -> "; 484 } 485 if (ConversionFunction) 486 OS << '\'' << *ConversionFunction << '\''; 487 else 488 OS << "aggregate initialization"; 489 if (After.First || After.Second || After.Third) { 490 OS << " -> "; 491 After.DebugPrint(); 492 } 493 } 494 495 /// DebugPrint - Print this implicit conversion sequence to standard 496 /// error. Useful for debugging overloading issues. 497 void ImplicitConversionSequence::DebugPrint() const { 498 raw_ostream &OS = llvm::errs(); 499 switch (ConversionKind) { 500 case StandardConversion: 501 OS << "Standard conversion: "; 502 Standard.DebugPrint(); 503 break; 504 case UserDefinedConversion: 505 OS << "User-defined conversion: "; 506 UserDefined.DebugPrint(); 507 break; 508 case EllipsisConversion: 509 OS << "Ellipsis conversion"; 510 break; 511 case AmbiguousConversion: 512 OS << "Ambiguous conversion"; 513 break; 514 case BadConversion: 515 OS << "Bad conversion"; 516 break; 517 } 518 519 OS << "\n"; 520 } 521 522 void AmbiguousConversionSequence::construct() { 523 new (&conversions()) ConversionSet(); 524 } 525 526 void AmbiguousConversionSequence::destruct() { 527 conversions().~ConversionSet(); 528 } 529 530 void 531 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 532 FromTypePtr = O.FromTypePtr; 533 ToTypePtr = O.ToTypePtr; 534 new (&conversions()) ConversionSet(O.conversions()); 535 } 536 537 namespace { 538 // Structure used by OverloadCandidate::DeductionFailureInfo to store 539 // template parameter and template argument information. 540 struct DFIParamWithArguments { 541 TemplateParameter Param; 542 TemplateArgument FirstArg; 543 TemplateArgument SecondArg; 544 }; 545 } 546 547 /// \brief Convert from Sema's representation of template deduction information 548 /// to the form used in overload-candidate information. 549 OverloadCandidate::DeductionFailureInfo 550 static MakeDeductionFailureInfo(ASTContext &Context, 551 Sema::TemplateDeductionResult TDK, 552 TemplateDeductionInfo &Info) { 553 OverloadCandidate::DeductionFailureInfo Result; 554 Result.Result = static_cast<unsigned>(TDK); 555 Result.HasDiagnostic = false; 556 Result.Data = 0; 557 switch (TDK) { 558 case Sema::TDK_Success: 559 case Sema::TDK_Invalid: 560 case Sema::TDK_InstantiationDepth: 561 case Sema::TDK_TooManyArguments: 562 case Sema::TDK_TooFewArguments: 563 break; 564 565 case Sema::TDK_Incomplete: 566 case Sema::TDK_InvalidExplicitArguments: 567 Result.Data = Info.Param.getOpaqueValue(); 568 break; 569 570 case Sema::TDK_Inconsistent: 571 case Sema::TDK_Underqualified: { 572 // FIXME: Should allocate from normal heap so that we can free this later. 573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 574 Saved->Param = Info.Param; 575 Saved->FirstArg = Info.FirstArg; 576 Saved->SecondArg = Info.SecondArg; 577 Result.Data = Saved; 578 break; 579 } 580 581 case Sema::TDK_SubstitutionFailure: 582 Result.Data = Info.take(); 583 if (Info.hasSFINAEDiagnostic()) { 584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 585 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 586 Info.takeSFINAEDiagnostic(*Diag); 587 Result.HasDiagnostic = true; 588 } 589 break; 590 591 case Sema::TDK_NonDeducedMismatch: 592 case Sema::TDK_FailedOverloadResolution: 593 break; 594 } 595 596 return Result; 597 } 598 599 void OverloadCandidate::DeductionFailureInfo::Destroy() { 600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 601 case Sema::TDK_Success: 602 case Sema::TDK_Invalid: 603 case Sema::TDK_InstantiationDepth: 604 case Sema::TDK_Incomplete: 605 case Sema::TDK_TooManyArguments: 606 case Sema::TDK_TooFewArguments: 607 case Sema::TDK_InvalidExplicitArguments: 608 break; 609 610 case Sema::TDK_Inconsistent: 611 case Sema::TDK_Underqualified: 612 // FIXME: Destroy the data? 613 Data = 0; 614 break; 615 616 case Sema::TDK_SubstitutionFailure: 617 // FIXME: Destroy the template argument list? 618 Data = 0; 619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 620 Diag->~PartialDiagnosticAt(); 621 HasDiagnostic = false; 622 } 623 break; 624 625 // Unhandled 626 case Sema::TDK_NonDeducedMismatch: 627 case Sema::TDK_FailedOverloadResolution: 628 break; 629 } 630 } 631 632 PartialDiagnosticAt * 633 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 634 if (HasDiagnostic) 635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 636 return 0; 637 } 638 639 TemplateParameter 640 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 642 case Sema::TDK_Success: 643 case Sema::TDK_Invalid: 644 case Sema::TDK_InstantiationDepth: 645 case Sema::TDK_TooManyArguments: 646 case Sema::TDK_TooFewArguments: 647 case Sema::TDK_SubstitutionFailure: 648 return TemplateParameter(); 649 650 case Sema::TDK_Incomplete: 651 case Sema::TDK_InvalidExplicitArguments: 652 return TemplateParameter::getFromOpaqueValue(Data); 653 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: 656 return static_cast<DFIParamWithArguments*>(Data)->Param; 657 658 // Unhandled 659 case Sema::TDK_NonDeducedMismatch: 660 case Sema::TDK_FailedOverloadResolution: 661 break; 662 } 663 664 return TemplateParameter(); 665 } 666 667 TemplateArgumentList * 668 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 670 case Sema::TDK_Success: 671 case Sema::TDK_Invalid: 672 case Sema::TDK_InstantiationDepth: 673 case Sema::TDK_TooManyArguments: 674 case Sema::TDK_TooFewArguments: 675 case Sema::TDK_Incomplete: 676 case Sema::TDK_InvalidExplicitArguments: 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 return 0; 680 681 case Sema::TDK_SubstitutionFailure: 682 return static_cast<TemplateArgumentList*>(Data); 683 684 // Unhandled 685 case Sema::TDK_NonDeducedMismatch: 686 case Sema::TDK_FailedOverloadResolution: 687 break; 688 } 689 690 return 0; 691 } 692 693 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_SubstitutionFailure: 703 return 0; 704 705 case Sema::TDK_Inconsistent: 706 case Sema::TDK_Underqualified: 707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 708 709 // Unhandled 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 break; 713 } 714 715 return 0; 716 } 717 718 const TemplateArgument * 719 OverloadCandidate::DeductionFailureInfo::getSecondArg() { 720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 721 case Sema::TDK_Success: 722 case Sema::TDK_Invalid: 723 case Sema::TDK_InstantiationDepth: 724 case Sema::TDK_Incomplete: 725 case Sema::TDK_TooManyArguments: 726 case Sema::TDK_TooFewArguments: 727 case Sema::TDK_InvalidExplicitArguments: 728 case Sema::TDK_SubstitutionFailure: 729 return 0; 730 731 case Sema::TDK_Inconsistent: 732 case Sema::TDK_Underqualified: 733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 734 735 // Unhandled 736 case Sema::TDK_NonDeducedMismatch: 737 case Sema::TDK_FailedOverloadResolution: 738 break; 739 } 740 741 return 0; 742 } 743 744 void OverloadCandidateSet::destroyCandidates() { 745 for (iterator i = begin(), e = end(); i != e; ++i) { 746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 747 i->Conversions[ii].~ImplicitConversionSequence(); 748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 749 i->DeductionFailure.Destroy(); 750 } 751 } 752 753 void OverloadCandidateSet::clear() { 754 destroyCandidates(); 755 NumInlineSequences = 0; 756 Candidates.clear(); 757 Functions.clear(); 758 } 759 760 namespace { 761 class UnbridgedCastsSet { 762 struct Entry { 763 Expr **Addr; 764 Expr *Saved; 765 }; 766 SmallVector<Entry, 2> Entries; 767 768 public: 769 void save(Sema &S, Expr *&E) { 770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 771 Entry entry = { &E, E }; 772 Entries.push_back(entry); 773 E = S.stripARCUnbridgedCast(E); 774 } 775 776 void restore() { 777 for (SmallVectorImpl<Entry>::iterator 778 i = Entries.begin(), e = Entries.end(); i != e; ++i) 779 *i->Addr = i->Saved; 780 } 781 }; 782 } 783 784 /// checkPlaceholderForOverload - Do any interesting placeholder-like 785 /// preprocessing on the given expression. 786 /// 787 /// \param unbridgedCasts a collection to which to add unbridged casts; 788 /// without this, they will be immediately diagnosed as errors 789 /// 790 /// Return true on unrecoverable error. 791 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 792 UnbridgedCastsSet *unbridgedCasts = 0) { 793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 794 // We can't handle overloaded expressions here because overload 795 // resolution might reasonably tweak them. 796 if (placeholder->getKind() == BuiltinType::Overload) return false; 797 798 // If the context potentially accepts unbridged ARC casts, strip 799 // the unbridged cast and add it to the collection for later restoration. 800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 801 unbridgedCasts) { 802 unbridgedCasts->save(S, E); 803 return false; 804 } 805 806 // Go ahead and check everything else. 807 ExprResult result = S.CheckPlaceholderExpr(E); 808 if (result.isInvalid()) 809 return true; 810 811 E = result.take(); 812 return false; 813 } 814 815 // Nothing to do. 816 return false; 817 } 818 819 /// checkArgPlaceholdersForOverload - Check a set of call operands for 820 /// placeholders. 821 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 822 unsigned numArgs, 823 UnbridgedCastsSet &unbridged) { 824 for (unsigned i = 0; i != numArgs; ++i) 825 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 826 return true; 827 828 return false; 829 } 830 831 // IsOverload - Determine whether the given New declaration is an 832 // overload of the declarations in Old. This routine returns false if 833 // New and Old cannot be overloaded, e.g., if New has the same 834 // signature as some function in Old (C++ 1.3.10) or if the Old 835 // declarations aren't functions (or function templates) at all. When 836 // it does return false, MatchedDecl will point to the decl that New 837 // cannot be overloaded with. This decl may be a UsingShadowDecl on 838 // top of the underlying declaration. 839 // 840 // Example: Given the following input: 841 // 842 // void f(int, float); // #1 843 // void f(int, int); // #2 844 // int f(int, int); // #3 845 // 846 // When we process #1, there is no previous declaration of "f", 847 // so IsOverload will not be used. 848 // 849 // When we process #2, Old contains only the FunctionDecl for #1. By 850 // comparing the parameter types, we see that #1 and #2 are overloaded 851 // (since they have different signatures), so this routine returns 852 // false; MatchedDecl is unchanged. 853 // 854 // When we process #3, Old is an overload set containing #1 and #2. We 855 // compare the signatures of #3 to #1 (they're overloaded, so we do 856 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 857 // identical (return types of functions are not part of the 858 // signature), IsOverload returns false and MatchedDecl will be set to 859 // point to the FunctionDecl for #2. 860 // 861 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 862 // into a class by a using declaration. The rules for whether to hide 863 // shadow declarations ignore some properties which otherwise figure 864 // into a function template's signature. 865 Sema::OverloadKind 866 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 867 NamedDecl *&Match, bool NewIsUsingDecl) { 868 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 869 I != E; ++I) { 870 NamedDecl *OldD = *I; 871 872 bool OldIsUsingDecl = false; 873 if (isa<UsingShadowDecl>(OldD)) { 874 OldIsUsingDecl = true; 875 876 // We can always introduce two using declarations into the same 877 // context, even if they have identical signatures. 878 if (NewIsUsingDecl) continue; 879 880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 881 } 882 883 // If either declaration was introduced by a using declaration, 884 // we'll need to use slightly different rules for matching. 885 // Essentially, these rules are the normal rules, except that 886 // function templates hide function templates with different 887 // return types or template parameter lists. 888 bool UseMemberUsingDeclRules = 889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 890 891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 893 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 895 continue; 896 } 897 898 Match = *I; 899 return Ovl_Match; 900 } 901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 903 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 905 continue; 906 } 907 908 Match = *I; 909 return Ovl_Match; 910 } 911 } else if (isa<UsingDecl>(OldD)) { 912 // We can overload with these, which can show up when doing 913 // redeclaration checks for UsingDecls. 914 assert(Old.getLookupKind() == LookupUsingDeclName); 915 } else if (isa<TagDecl>(OldD)) { 916 // We can always overload with tags by hiding them. 917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 918 // Optimistically assume that an unresolved using decl will 919 // overload; if it doesn't, we'll have to diagnose during 920 // template instantiation. 921 } else { 922 // (C++ 13p1): 923 // Only function declarations can be overloaded; object and type 924 // declarations cannot be overloaded. 925 Match = *I; 926 return Ovl_NonFunction; 927 } 928 } 929 930 return Ovl_Overload; 931 } 932 933 static bool canBeOverloaded(const FunctionDecl &D) { 934 if (D.getAttr<OverloadableAttr>()) 935 return true; 936 if (D.hasCLanguageLinkage()) 937 return false; 938 939 // Main cannot be overloaded (basic.start.main). 940 if (D.isMain()) 941 return false; 942 943 return true; 944 } 945 946 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 947 bool UseUsingDeclRules) { 948 // If both of the functions are extern "C", then they are not 949 // overloads. 950 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 951 return false; 952 953 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 954 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 955 956 // C++ [temp.fct]p2: 957 // A function template can be overloaded with other function templates 958 // and with normal (non-template) functions. 959 if ((OldTemplate == 0) != (NewTemplate == 0)) 960 return true; 961 962 // Is the function New an overload of the function Old? 963 QualType OldQType = Context.getCanonicalType(Old->getType()); 964 QualType NewQType = Context.getCanonicalType(New->getType()); 965 966 // Compare the signatures (C++ 1.3.10) of the two functions to 967 // determine whether they are overloads. If we find any mismatch 968 // in the signature, they are overloads. 969 970 // If either of these functions is a K&R-style function (no 971 // prototype), then we consider them to have matching signatures. 972 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 973 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 974 return false; 975 976 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 977 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 978 979 // The signature of a function includes the types of its 980 // parameters (C++ 1.3.10), which includes the presence or absence 981 // of the ellipsis; see C++ DR 357). 982 if (OldQType != NewQType && 983 (OldType->getNumArgs() != NewType->getNumArgs() || 984 OldType->isVariadic() != NewType->isVariadic() || 985 !FunctionArgTypesAreEqual(OldType, NewType))) 986 return true; 987 988 // C++ [temp.over.link]p4: 989 // The signature of a function template consists of its function 990 // signature, its return type and its template parameter list. The names 991 // of the template parameters are significant only for establishing the 992 // relationship between the template parameters and the rest of the 993 // signature. 994 // 995 // We check the return type and template parameter lists for function 996 // templates first; the remaining checks follow. 997 // 998 // However, we don't consider either of these when deciding whether 999 // a member introduced by a shadow declaration is hidden. 1000 if (!UseUsingDeclRules && NewTemplate && 1001 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1002 OldTemplate->getTemplateParameters(), 1003 false, TPL_TemplateMatch) || 1004 OldType->getResultType() != NewType->getResultType())) 1005 return true; 1006 1007 // If the function is a class member, its signature includes the 1008 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1009 // 1010 // As part of this, also check whether one of the member functions 1011 // is static, in which case they are not overloads (C++ 1012 // 13.1p2). While not part of the definition of the signature, 1013 // this check is important to determine whether these functions 1014 // can be overloaded. 1015 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1016 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1017 if (OldMethod && NewMethod && 1018 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1019 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1020 if (!UseUsingDeclRules && 1021 (OldMethod->getRefQualifier() == RQ_None || 1022 NewMethod->getRefQualifier() == RQ_None)) { 1023 // C++0x [over.load]p2: 1024 // - Member function declarations with the same name and the same 1025 // parameter-type-list as well as member function template 1026 // declarations with the same name, the same parameter-type-list, and 1027 // the same template parameter lists cannot be overloaded if any of 1028 // them, but not all, have a ref-qualifier (8.3.5). 1029 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1030 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1031 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1032 } 1033 return true; 1034 } 1035 1036 // We may not have applied the implicit const for a constexpr member 1037 // function yet (because we haven't yet resolved whether this is a static 1038 // or non-static member function). Add it now, on the assumption that this 1039 // is a redeclaration of OldMethod. 1040 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1041 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod)) 1042 NewQuals |= Qualifiers::Const; 1043 if (OldMethod->getTypeQualifiers() != NewQuals) 1044 return true; 1045 } 1046 1047 // The signatures match; this is not an overload. 1048 return false; 1049 } 1050 1051 /// \brief Checks availability of the function depending on the current 1052 /// function context. Inside an unavailable function, unavailability is ignored. 1053 /// 1054 /// \returns true if \arg FD is unavailable and current context is inside 1055 /// an available function, false otherwise. 1056 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1057 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1058 } 1059 1060 /// \brief Tries a user-defined conversion from From to ToType. 1061 /// 1062 /// Produces an implicit conversion sequence for when a standard conversion 1063 /// is not an option. See TryImplicitConversion for more information. 1064 static ImplicitConversionSequence 1065 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1066 bool SuppressUserConversions, 1067 bool AllowExplicit, 1068 bool InOverloadResolution, 1069 bool CStyle, 1070 bool AllowObjCWritebackConversion) { 1071 ImplicitConversionSequence ICS; 1072 1073 if (SuppressUserConversions) { 1074 // We're not in the case above, so there is no conversion that 1075 // we can perform. 1076 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1077 return ICS; 1078 } 1079 1080 // Attempt user-defined conversion. 1081 OverloadCandidateSet Conversions(From->getExprLoc()); 1082 OverloadingResult UserDefResult 1083 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1084 AllowExplicit); 1085 1086 if (UserDefResult == OR_Success) { 1087 ICS.setUserDefined(); 1088 // C++ [over.ics.user]p4: 1089 // A conversion of an expression of class type to the same class 1090 // type is given Exact Match rank, and a conversion of an 1091 // expression of class type to a base class of that type is 1092 // given Conversion rank, in spite of the fact that a copy 1093 // constructor (i.e., a user-defined conversion function) is 1094 // called for those cases. 1095 if (CXXConstructorDecl *Constructor 1096 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1097 QualType FromCanon 1098 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1099 QualType ToCanon 1100 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1101 if (Constructor->isCopyConstructor() && 1102 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1103 // Turn this into a "standard" conversion sequence, so that it 1104 // gets ranked with standard conversion sequences. 1105 ICS.setStandard(); 1106 ICS.Standard.setAsIdentityConversion(); 1107 ICS.Standard.setFromType(From->getType()); 1108 ICS.Standard.setAllToTypes(ToType); 1109 ICS.Standard.CopyConstructor = Constructor; 1110 if (ToCanon != FromCanon) 1111 ICS.Standard.Second = ICK_Derived_To_Base; 1112 } 1113 } 1114 1115 // C++ [over.best.ics]p4: 1116 // However, when considering the argument of a user-defined 1117 // conversion function that is a candidate by 13.3.1.3 when 1118 // invoked for the copying of the temporary in the second step 1119 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1120 // 13.3.1.6 in all cases, only standard conversion sequences and 1121 // ellipsis conversion sequences are allowed. 1122 if (SuppressUserConversions && ICS.isUserDefined()) { 1123 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1124 } 1125 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1126 ICS.setAmbiguous(); 1127 ICS.Ambiguous.setFromType(From->getType()); 1128 ICS.Ambiguous.setToType(ToType); 1129 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1130 Cand != Conversions.end(); ++Cand) 1131 if (Cand->Viable) 1132 ICS.Ambiguous.addConversion(Cand->Function); 1133 } else { 1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1135 } 1136 1137 return ICS; 1138 } 1139 1140 /// TryImplicitConversion - Attempt to perform an implicit conversion 1141 /// from the given expression (Expr) to the given type (ToType). This 1142 /// function returns an implicit conversion sequence that can be used 1143 /// to perform the initialization. Given 1144 /// 1145 /// void f(float f); 1146 /// void g(int i) { f(i); } 1147 /// 1148 /// this routine would produce an implicit conversion sequence to 1149 /// describe the initialization of f from i, which will be a standard 1150 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1151 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1152 // 1153 /// Note that this routine only determines how the conversion can be 1154 /// performed; it does not actually perform the conversion. As such, 1155 /// it will not produce any diagnostics if no conversion is available, 1156 /// but will instead return an implicit conversion sequence of kind 1157 /// "BadConversion". 1158 /// 1159 /// If @p SuppressUserConversions, then user-defined conversions are 1160 /// not permitted. 1161 /// If @p AllowExplicit, then explicit user-defined conversions are 1162 /// permitted. 1163 /// 1164 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1165 /// writeback conversion, which allows __autoreleasing id* parameters to 1166 /// be initialized with __strong id* or __weak id* arguments. 1167 static ImplicitConversionSequence 1168 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1169 bool SuppressUserConversions, 1170 bool AllowExplicit, 1171 bool InOverloadResolution, 1172 bool CStyle, 1173 bool AllowObjCWritebackConversion) { 1174 ImplicitConversionSequence ICS; 1175 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1176 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1177 ICS.setStandard(); 1178 return ICS; 1179 } 1180 1181 if (!S.getLangOpts().CPlusPlus) { 1182 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1183 return ICS; 1184 } 1185 1186 // C++ [over.ics.user]p4: 1187 // A conversion of an expression of class type to the same class 1188 // type is given Exact Match rank, and a conversion of an 1189 // expression of class type to a base class of that type is 1190 // given Conversion rank, in spite of the fact that a copy/move 1191 // constructor (i.e., a user-defined conversion function) is 1192 // called for those cases. 1193 QualType FromType = From->getType(); 1194 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1195 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1196 S.IsDerivedFrom(FromType, ToType))) { 1197 ICS.setStandard(); 1198 ICS.Standard.setAsIdentityConversion(); 1199 ICS.Standard.setFromType(FromType); 1200 ICS.Standard.setAllToTypes(ToType); 1201 1202 // We don't actually check at this point whether there is a valid 1203 // copy/move constructor, since overloading just assumes that it 1204 // exists. When we actually perform initialization, we'll find the 1205 // appropriate constructor to copy the returned object, if needed. 1206 ICS.Standard.CopyConstructor = 0; 1207 1208 // Determine whether this is considered a derived-to-base conversion. 1209 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1210 ICS.Standard.Second = ICK_Derived_To_Base; 1211 1212 return ICS; 1213 } 1214 1215 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1216 AllowExplicit, InOverloadResolution, CStyle, 1217 AllowObjCWritebackConversion); 1218 } 1219 1220 ImplicitConversionSequence 1221 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1222 bool SuppressUserConversions, 1223 bool AllowExplicit, 1224 bool InOverloadResolution, 1225 bool CStyle, 1226 bool AllowObjCWritebackConversion) { 1227 return clang::TryImplicitConversion(*this, From, ToType, 1228 SuppressUserConversions, AllowExplicit, 1229 InOverloadResolution, CStyle, 1230 AllowObjCWritebackConversion); 1231 } 1232 1233 /// PerformImplicitConversion - Perform an implicit conversion of the 1234 /// expression From to the type ToType. Returns the 1235 /// converted expression. Flavor is the kind of conversion we're 1236 /// performing, used in the error message. If @p AllowExplicit, 1237 /// explicit user-defined conversions are permitted. 1238 ExprResult 1239 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1240 AssignmentAction Action, bool AllowExplicit) { 1241 ImplicitConversionSequence ICS; 1242 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1243 } 1244 1245 ExprResult 1246 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1247 AssignmentAction Action, bool AllowExplicit, 1248 ImplicitConversionSequence& ICS) { 1249 if (checkPlaceholderForOverload(*this, From)) 1250 return ExprError(); 1251 1252 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1253 bool AllowObjCWritebackConversion 1254 = getLangOpts().ObjCAutoRefCount && 1255 (Action == AA_Passing || Action == AA_Sending); 1256 1257 ICS = clang::TryImplicitConversion(*this, From, ToType, 1258 /*SuppressUserConversions=*/false, 1259 AllowExplicit, 1260 /*InOverloadResolution=*/false, 1261 /*CStyle=*/false, 1262 AllowObjCWritebackConversion); 1263 return PerformImplicitConversion(From, ToType, ICS, Action); 1264 } 1265 1266 /// \brief Determine whether the conversion from FromType to ToType is a valid 1267 /// conversion that strips "noreturn" off the nested function type. 1268 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1269 QualType &ResultTy) { 1270 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1271 return false; 1272 1273 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1274 // where F adds one of the following at most once: 1275 // - a pointer 1276 // - a member pointer 1277 // - a block pointer 1278 CanQualType CanTo = Context.getCanonicalType(ToType); 1279 CanQualType CanFrom = Context.getCanonicalType(FromType); 1280 Type::TypeClass TyClass = CanTo->getTypeClass(); 1281 if (TyClass != CanFrom->getTypeClass()) return false; 1282 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1283 if (TyClass == Type::Pointer) { 1284 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1285 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1286 } else if (TyClass == Type::BlockPointer) { 1287 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1288 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1289 } else if (TyClass == Type::MemberPointer) { 1290 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1291 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1292 } else { 1293 return false; 1294 } 1295 1296 TyClass = CanTo->getTypeClass(); 1297 if (TyClass != CanFrom->getTypeClass()) return false; 1298 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1299 return false; 1300 } 1301 1302 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1303 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1304 if (!EInfo.getNoReturn()) return false; 1305 1306 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1307 assert(QualType(FromFn, 0).isCanonical()); 1308 if (QualType(FromFn, 0) != CanTo) return false; 1309 1310 ResultTy = ToType; 1311 return true; 1312 } 1313 1314 /// \brief Determine whether the conversion from FromType to ToType is a valid 1315 /// vector conversion. 1316 /// 1317 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1318 /// conversion. 1319 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1320 QualType ToType, ImplicitConversionKind &ICK) { 1321 // We need at least one of these types to be a vector type to have a vector 1322 // conversion. 1323 if (!ToType->isVectorType() && !FromType->isVectorType()) 1324 return false; 1325 1326 // Identical types require no conversions. 1327 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1328 return false; 1329 1330 // There are no conversions between extended vector types, only identity. 1331 if (ToType->isExtVectorType()) { 1332 // There are no conversions between extended vector types other than the 1333 // identity conversion. 1334 if (FromType->isExtVectorType()) 1335 return false; 1336 1337 // Vector splat from any arithmetic type to a vector. 1338 if (FromType->isArithmeticType()) { 1339 ICK = ICK_Vector_Splat; 1340 return true; 1341 } 1342 } 1343 1344 // We can perform the conversion between vector types in the following cases: 1345 // 1)vector types are equivalent AltiVec and GCC vector types 1346 // 2)lax vector conversions are permitted and the vector types are of the 1347 // same size 1348 if (ToType->isVectorType() && FromType->isVectorType()) { 1349 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1350 (Context.getLangOpts().LaxVectorConversions && 1351 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1352 ICK = ICK_Vector_Conversion; 1353 return true; 1354 } 1355 } 1356 1357 return false; 1358 } 1359 1360 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1361 bool InOverloadResolution, 1362 StandardConversionSequence &SCS, 1363 bool CStyle); 1364 1365 /// IsStandardConversion - Determines whether there is a standard 1366 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1367 /// expression From to the type ToType. Standard conversion sequences 1368 /// only consider non-class types; for conversions that involve class 1369 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1370 /// contain the standard conversion sequence required to perform this 1371 /// conversion and this routine will return true. Otherwise, this 1372 /// routine will return false and the value of SCS is unspecified. 1373 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1374 bool InOverloadResolution, 1375 StandardConversionSequence &SCS, 1376 bool CStyle, 1377 bool AllowObjCWritebackConversion) { 1378 QualType FromType = From->getType(); 1379 1380 // Standard conversions (C++ [conv]) 1381 SCS.setAsIdentityConversion(); 1382 SCS.DeprecatedStringLiteralToCharPtr = false; 1383 SCS.IncompatibleObjC = false; 1384 SCS.setFromType(FromType); 1385 SCS.CopyConstructor = 0; 1386 1387 // There are no standard conversions for class types in C++, so 1388 // abort early. When overloading in C, however, we do permit 1389 if (FromType->isRecordType() || ToType->isRecordType()) { 1390 if (S.getLangOpts().CPlusPlus) 1391 return false; 1392 1393 // When we're overloading in C, we allow, as standard conversions, 1394 } 1395 1396 // The first conversion can be an lvalue-to-rvalue conversion, 1397 // array-to-pointer conversion, or function-to-pointer conversion 1398 // (C++ 4p1). 1399 1400 if (FromType == S.Context.OverloadTy) { 1401 DeclAccessPair AccessPair; 1402 if (FunctionDecl *Fn 1403 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1404 AccessPair)) { 1405 // We were able to resolve the address of the overloaded function, 1406 // so we can convert to the type of that function. 1407 FromType = Fn->getType(); 1408 1409 // we can sometimes resolve &foo<int> regardless of ToType, so check 1410 // if the type matches (identity) or we are converting to bool 1411 if (!S.Context.hasSameUnqualifiedType( 1412 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1413 QualType resultTy; 1414 // if the function type matches except for [[noreturn]], it's ok 1415 if (!S.IsNoReturnConversion(FromType, 1416 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1417 // otherwise, only a boolean conversion is standard 1418 if (!ToType->isBooleanType()) 1419 return false; 1420 } 1421 1422 // Check if the "from" expression is taking the address of an overloaded 1423 // function and recompute the FromType accordingly. Take advantage of the 1424 // fact that non-static member functions *must* have such an address-of 1425 // expression. 1426 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1427 if (Method && !Method->isStatic()) { 1428 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1429 "Non-unary operator on non-static member address"); 1430 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1431 == UO_AddrOf && 1432 "Non-address-of operator on non-static member address"); 1433 const Type *ClassType 1434 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1435 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1436 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1437 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1438 UO_AddrOf && 1439 "Non-address-of operator for overloaded function expression"); 1440 FromType = S.Context.getPointerType(FromType); 1441 } 1442 1443 // Check that we've computed the proper type after overload resolution. 1444 assert(S.Context.hasSameType( 1445 FromType, 1446 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1447 } else { 1448 return false; 1449 } 1450 } 1451 // Lvalue-to-rvalue conversion (C++11 4.1): 1452 // A glvalue (3.10) of a non-function, non-array type T can 1453 // be converted to a prvalue. 1454 bool argIsLValue = From->isGLValue(); 1455 if (argIsLValue && 1456 !FromType->isFunctionType() && !FromType->isArrayType() && 1457 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1458 SCS.First = ICK_Lvalue_To_Rvalue; 1459 1460 // C11 6.3.2.1p2: 1461 // ... if the lvalue has atomic type, the value has the non-atomic version 1462 // of the type of the lvalue ... 1463 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1464 FromType = Atomic->getValueType(); 1465 1466 // If T is a non-class type, the type of the rvalue is the 1467 // cv-unqualified version of T. Otherwise, the type of the rvalue 1468 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1469 // just strip the qualifiers because they don't matter. 1470 FromType = FromType.getUnqualifiedType(); 1471 } else if (FromType->isArrayType()) { 1472 // Array-to-pointer conversion (C++ 4.2) 1473 SCS.First = ICK_Array_To_Pointer; 1474 1475 // An lvalue or rvalue of type "array of N T" or "array of unknown 1476 // bound of T" can be converted to an rvalue of type "pointer to 1477 // T" (C++ 4.2p1). 1478 FromType = S.Context.getArrayDecayedType(FromType); 1479 1480 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1481 // This conversion is deprecated. (C++ D.4). 1482 SCS.DeprecatedStringLiteralToCharPtr = true; 1483 1484 // For the purpose of ranking in overload resolution 1485 // (13.3.3.1.1), this conversion is considered an 1486 // array-to-pointer conversion followed by a qualification 1487 // conversion (4.4). (C++ 4.2p2) 1488 SCS.Second = ICK_Identity; 1489 SCS.Third = ICK_Qualification; 1490 SCS.QualificationIncludesObjCLifetime = false; 1491 SCS.setAllToTypes(FromType); 1492 return true; 1493 } 1494 } else if (FromType->isFunctionType() && argIsLValue) { 1495 // Function-to-pointer conversion (C++ 4.3). 1496 SCS.First = ICK_Function_To_Pointer; 1497 1498 // An lvalue of function type T can be converted to an rvalue of 1499 // type "pointer to T." The result is a pointer to the 1500 // function. (C++ 4.3p1). 1501 FromType = S.Context.getPointerType(FromType); 1502 } else { 1503 // We don't require any conversions for the first step. 1504 SCS.First = ICK_Identity; 1505 } 1506 SCS.setToType(0, FromType); 1507 1508 // The second conversion can be an integral promotion, floating 1509 // point promotion, integral conversion, floating point conversion, 1510 // floating-integral conversion, pointer conversion, 1511 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1512 // For overloading in C, this can also be a "compatible-type" 1513 // conversion. 1514 bool IncompatibleObjC = false; 1515 ImplicitConversionKind SecondICK = ICK_Identity; 1516 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1517 // The unqualified versions of the types are the same: there's no 1518 // conversion to do. 1519 SCS.Second = ICK_Identity; 1520 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1521 // Integral promotion (C++ 4.5). 1522 SCS.Second = ICK_Integral_Promotion; 1523 FromType = ToType.getUnqualifiedType(); 1524 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1525 // Floating point promotion (C++ 4.6). 1526 SCS.Second = ICK_Floating_Promotion; 1527 FromType = ToType.getUnqualifiedType(); 1528 } else if (S.IsComplexPromotion(FromType, ToType)) { 1529 // Complex promotion (Clang extension) 1530 SCS.Second = ICK_Complex_Promotion; 1531 FromType = ToType.getUnqualifiedType(); 1532 } else if (ToType->isBooleanType() && 1533 (FromType->isArithmeticType() || 1534 FromType->isAnyPointerType() || 1535 FromType->isBlockPointerType() || 1536 FromType->isMemberPointerType() || 1537 FromType->isNullPtrType())) { 1538 // Boolean conversions (C++ 4.12). 1539 SCS.Second = ICK_Boolean_Conversion; 1540 FromType = S.Context.BoolTy; 1541 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1542 ToType->isIntegralType(S.Context)) { 1543 // Integral conversions (C++ 4.7). 1544 SCS.Second = ICK_Integral_Conversion; 1545 FromType = ToType.getUnqualifiedType(); 1546 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1547 // Complex conversions (C99 6.3.1.6) 1548 SCS.Second = ICK_Complex_Conversion; 1549 FromType = ToType.getUnqualifiedType(); 1550 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1551 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1552 // Complex-real conversions (C99 6.3.1.7) 1553 SCS.Second = ICK_Complex_Real; 1554 FromType = ToType.getUnqualifiedType(); 1555 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1556 // Floating point conversions (C++ 4.8). 1557 SCS.Second = ICK_Floating_Conversion; 1558 FromType = ToType.getUnqualifiedType(); 1559 } else if ((FromType->isRealFloatingType() && 1560 ToType->isIntegralType(S.Context)) || 1561 (FromType->isIntegralOrUnscopedEnumerationType() && 1562 ToType->isRealFloatingType())) { 1563 // Floating-integral conversions (C++ 4.9). 1564 SCS.Second = ICK_Floating_Integral; 1565 FromType = ToType.getUnqualifiedType(); 1566 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1567 SCS.Second = ICK_Block_Pointer_Conversion; 1568 } else if (AllowObjCWritebackConversion && 1569 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1570 SCS.Second = ICK_Writeback_Conversion; 1571 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1572 FromType, IncompatibleObjC)) { 1573 // Pointer conversions (C++ 4.10). 1574 SCS.Second = ICK_Pointer_Conversion; 1575 SCS.IncompatibleObjC = IncompatibleObjC; 1576 FromType = FromType.getUnqualifiedType(); 1577 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1578 InOverloadResolution, FromType)) { 1579 // Pointer to member conversions (4.11). 1580 SCS.Second = ICK_Pointer_Member; 1581 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1582 SCS.Second = SecondICK; 1583 FromType = ToType.getUnqualifiedType(); 1584 } else if (!S.getLangOpts().CPlusPlus && 1585 S.Context.typesAreCompatible(ToType, FromType)) { 1586 // Compatible conversions (Clang extension for C function overloading) 1587 SCS.Second = ICK_Compatible_Conversion; 1588 FromType = ToType.getUnqualifiedType(); 1589 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1590 // Treat a conversion that strips "noreturn" as an identity conversion. 1591 SCS.Second = ICK_NoReturn_Adjustment; 1592 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1593 InOverloadResolution, 1594 SCS, CStyle)) { 1595 SCS.Second = ICK_TransparentUnionConversion; 1596 FromType = ToType; 1597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1598 CStyle)) { 1599 // tryAtomicConversion has updated the standard conversion sequence 1600 // appropriately. 1601 return true; 1602 } else { 1603 // No second conversion required. 1604 SCS.Second = ICK_Identity; 1605 } 1606 SCS.setToType(1, FromType); 1607 1608 QualType CanonFrom; 1609 QualType CanonTo; 1610 // The third conversion can be a qualification conversion (C++ 4p1). 1611 bool ObjCLifetimeConversion; 1612 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1613 ObjCLifetimeConversion)) { 1614 SCS.Third = ICK_Qualification; 1615 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1616 FromType = ToType; 1617 CanonFrom = S.Context.getCanonicalType(FromType); 1618 CanonTo = S.Context.getCanonicalType(ToType); 1619 } else { 1620 // No conversion required 1621 SCS.Third = ICK_Identity; 1622 1623 // C++ [over.best.ics]p6: 1624 // [...] Any difference in top-level cv-qualification is 1625 // subsumed by the initialization itself and does not constitute 1626 // a conversion. [...] 1627 CanonFrom = S.Context.getCanonicalType(FromType); 1628 CanonTo = S.Context.getCanonicalType(ToType); 1629 if (CanonFrom.getLocalUnqualifiedType() 1630 == CanonTo.getLocalUnqualifiedType() && 1631 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1632 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1633 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1634 FromType = ToType; 1635 CanonFrom = CanonTo; 1636 } 1637 } 1638 SCS.setToType(2, FromType); 1639 1640 // If we have not converted the argument type to the parameter type, 1641 // this is a bad conversion sequence. 1642 if (CanonFrom != CanonTo) 1643 return false; 1644 1645 return true; 1646 } 1647 1648 static bool 1649 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1650 QualType &ToType, 1651 bool InOverloadResolution, 1652 StandardConversionSequence &SCS, 1653 bool CStyle) { 1654 1655 const RecordType *UT = ToType->getAsUnionType(); 1656 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1657 return false; 1658 // The field to initialize within the transparent union. 1659 RecordDecl *UD = UT->getDecl(); 1660 // It's compatible if the expression matches any of the fields. 1661 for (RecordDecl::field_iterator it = UD->field_begin(), 1662 itend = UD->field_end(); 1663 it != itend; ++it) { 1664 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1665 CStyle, /*ObjCWritebackConversion=*/false)) { 1666 ToType = it->getType(); 1667 return true; 1668 } 1669 } 1670 return false; 1671 } 1672 1673 /// IsIntegralPromotion - Determines whether the conversion from the 1674 /// expression From (whose potentially-adjusted type is FromType) to 1675 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1676 /// sets PromotedType to the promoted type. 1677 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1678 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1679 // All integers are built-in. 1680 if (!To) { 1681 return false; 1682 } 1683 1684 // An rvalue of type char, signed char, unsigned char, short int, or 1685 // unsigned short int can be converted to an rvalue of type int if 1686 // int can represent all the values of the source type; otherwise, 1687 // the source rvalue can be converted to an rvalue of type unsigned 1688 // int (C++ 4.5p1). 1689 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1690 !FromType->isEnumeralType()) { 1691 if (// We can promote any signed, promotable integer type to an int 1692 (FromType->isSignedIntegerType() || 1693 // We can promote any unsigned integer type whose size is 1694 // less than int to an int. 1695 (!FromType->isSignedIntegerType() && 1696 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1697 return To->getKind() == BuiltinType::Int; 1698 } 1699 1700 return To->getKind() == BuiltinType::UInt; 1701 } 1702 1703 // C++11 [conv.prom]p3: 1704 // A prvalue of an unscoped enumeration type whose underlying type is not 1705 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1706 // following types that can represent all the values of the enumeration 1707 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1708 // unsigned int, long int, unsigned long int, long long int, or unsigned 1709 // long long int. If none of the types in that list can represent all the 1710 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1711 // type can be converted to an rvalue a prvalue of the extended integer type 1712 // with lowest integer conversion rank (4.13) greater than the rank of long 1713 // long in which all the values of the enumeration can be represented. If 1714 // there are two such extended types, the signed one is chosen. 1715 // C++11 [conv.prom]p4: 1716 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1717 // can be converted to a prvalue of its underlying type. Moreover, if 1718 // integral promotion can be applied to its underlying type, a prvalue of an 1719 // unscoped enumeration type whose underlying type is fixed can also be 1720 // converted to a prvalue of the promoted underlying type. 1721 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1722 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1723 // provided for a scoped enumeration. 1724 if (FromEnumType->getDecl()->isScoped()) 1725 return false; 1726 1727 // We can perform an integral promotion to the underlying type of the enum, 1728 // even if that's not the promoted type. 1729 if (FromEnumType->getDecl()->isFixed()) { 1730 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1731 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1732 IsIntegralPromotion(From, Underlying, ToType); 1733 } 1734 1735 // We have already pre-calculated the promotion type, so this is trivial. 1736 if (ToType->isIntegerType() && 1737 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1738 return Context.hasSameUnqualifiedType(ToType, 1739 FromEnumType->getDecl()->getPromotionType()); 1740 } 1741 1742 // C++0x [conv.prom]p2: 1743 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1744 // to an rvalue a prvalue of the first of the following types that can 1745 // represent all the values of its underlying type: int, unsigned int, 1746 // long int, unsigned long int, long long int, or unsigned long long int. 1747 // If none of the types in that list can represent all the values of its 1748 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1749 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1750 // type. 1751 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1752 ToType->isIntegerType()) { 1753 // Determine whether the type we're converting from is signed or 1754 // unsigned. 1755 bool FromIsSigned = FromType->isSignedIntegerType(); 1756 uint64_t FromSize = Context.getTypeSize(FromType); 1757 1758 // The types we'll try to promote to, in the appropriate 1759 // order. Try each of these types. 1760 QualType PromoteTypes[6] = { 1761 Context.IntTy, Context.UnsignedIntTy, 1762 Context.LongTy, Context.UnsignedLongTy , 1763 Context.LongLongTy, Context.UnsignedLongLongTy 1764 }; 1765 for (int Idx = 0; Idx < 6; ++Idx) { 1766 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1767 if (FromSize < ToSize || 1768 (FromSize == ToSize && 1769 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1770 // We found the type that we can promote to. If this is the 1771 // type we wanted, we have a promotion. Otherwise, no 1772 // promotion. 1773 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1774 } 1775 } 1776 } 1777 1778 // An rvalue for an integral bit-field (9.6) can be converted to an 1779 // rvalue of type int if int can represent all the values of the 1780 // bit-field; otherwise, it can be converted to unsigned int if 1781 // unsigned int can represent all the values of the bit-field. If 1782 // the bit-field is larger yet, no integral promotion applies to 1783 // it. If the bit-field has an enumerated type, it is treated as any 1784 // other value of that type for promotion purposes (C++ 4.5p3). 1785 // FIXME: We should delay checking of bit-fields until we actually perform the 1786 // conversion. 1787 using llvm::APSInt; 1788 if (From) 1789 if (FieldDecl *MemberDecl = From->getBitField()) { 1790 APSInt BitWidth; 1791 if (FromType->isIntegralType(Context) && 1792 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1793 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1794 ToSize = Context.getTypeSize(ToType); 1795 1796 // Are we promoting to an int from a bitfield that fits in an int? 1797 if (BitWidth < ToSize || 1798 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1799 return To->getKind() == BuiltinType::Int; 1800 } 1801 1802 // Are we promoting to an unsigned int from an unsigned bitfield 1803 // that fits into an unsigned int? 1804 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1805 return To->getKind() == BuiltinType::UInt; 1806 } 1807 1808 return false; 1809 } 1810 } 1811 1812 // An rvalue of type bool can be converted to an rvalue of type int, 1813 // with false becoming zero and true becoming one (C++ 4.5p4). 1814 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1815 return true; 1816 } 1817 1818 return false; 1819 } 1820 1821 /// IsFloatingPointPromotion - Determines whether the conversion from 1822 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1823 /// returns true and sets PromotedType to the promoted type. 1824 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1825 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1826 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1827 /// An rvalue of type float can be converted to an rvalue of type 1828 /// double. (C++ 4.6p1). 1829 if (FromBuiltin->getKind() == BuiltinType::Float && 1830 ToBuiltin->getKind() == BuiltinType::Double) 1831 return true; 1832 1833 // C99 6.3.1.5p1: 1834 // When a float is promoted to double or long double, or a 1835 // double is promoted to long double [...]. 1836 if (!getLangOpts().CPlusPlus && 1837 (FromBuiltin->getKind() == BuiltinType::Float || 1838 FromBuiltin->getKind() == BuiltinType::Double) && 1839 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1840 return true; 1841 1842 // Half can be promoted to float. 1843 if (FromBuiltin->getKind() == BuiltinType::Half && 1844 ToBuiltin->getKind() == BuiltinType::Float) 1845 return true; 1846 } 1847 1848 return false; 1849 } 1850 1851 /// \brief Determine if a conversion is a complex promotion. 1852 /// 1853 /// A complex promotion is defined as a complex -> complex conversion 1854 /// where the conversion between the underlying real types is a 1855 /// floating-point or integral promotion. 1856 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1857 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1858 if (!FromComplex) 1859 return false; 1860 1861 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1862 if (!ToComplex) 1863 return false; 1864 1865 return IsFloatingPointPromotion(FromComplex->getElementType(), 1866 ToComplex->getElementType()) || 1867 IsIntegralPromotion(0, FromComplex->getElementType(), 1868 ToComplex->getElementType()); 1869 } 1870 1871 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1872 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1873 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1874 /// if non-empty, will be a pointer to ToType that may or may not have 1875 /// the right set of qualifiers on its pointee. 1876 /// 1877 static QualType 1878 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1879 QualType ToPointee, QualType ToType, 1880 ASTContext &Context, 1881 bool StripObjCLifetime = false) { 1882 assert((FromPtr->getTypeClass() == Type::Pointer || 1883 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1884 "Invalid similarly-qualified pointer type"); 1885 1886 /// Conversions to 'id' subsume cv-qualifier conversions. 1887 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1888 return ToType.getUnqualifiedType(); 1889 1890 QualType CanonFromPointee 1891 = Context.getCanonicalType(FromPtr->getPointeeType()); 1892 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1893 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1894 1895 if (StripObjCLifetime) 1896 Quals.removeObjCLifetime(); 1897 1898 // Exact qualifier match -> return the pointer type we're converting to. 1899 if (CanonToPointee.getLocalQualifiers() == Quals) { 1900 // ToType is exactly what we need. Return it. 1901 if (!ToType.isNull()) 1902 return ToType.getUnqualifiedType(); 1903 1904 // Build a pointer to ToPointee. It has the right qualifiers 1905 // already. 1906 if (isa<ObjCObjectPointerType>(ToType)) 1907 return Context.getObjCObjectPointerType(ToPointee); 1908 return Context.getPointerType(ToPointee); 1909 } 1910 1911 // Just build a canonical type that has the right qualifiers. 1912 QualType QualifiedCanonToPointee 1913 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1914 1915 if (isa<ObjCObjectPointerType>(ToType)) 1916 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1917 return Context.getPointerType(QualifiedCanonToPointee); 1918 } 1919 1920 static bool isNullPointerConstantForConversion(Expr *Expr, 1921 bool InOverloadResolution, 1922 ASTContext &Context) { 1923 // Handle value-dependent integral null pointer constants correctly. 1924 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1925 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1926 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1927 return !InOverloadResolution; 1928 1929 return Expr->isNullPointerConstant(Context, 1930 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1931 : Expr::NPC_ValueDependentIsNull); 1932 } 1933 1934 /// IsPointerConversion - Determines whether the conversion of the 1935 /// expression From, which has the (possibly adjusted) type FromType, 1936 /// can be converted to the type ToType via a pointer conversion (C++ 1937 /// 4.10). If so, returns true and places the converted type (that 1938 /// might differ from ToType in its cv-qualifiers at some level) into 1939 /// ConvertedType. 1940 /// 1941 /// This routine also supports conversions to and from block pointers 1942 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1943 /// pointers to interfaces. FIXME: Once we've determined the 1944 /// appropriate overloading rules for Objective-C, we may want to 1945 /// split the Objective-C checks into a different routine; however, 1946 /// GCC seems to consider all of these conversions to be pointer 1947 /// conversions, so for now they live here. IncompatibleObjC will be 1948 /// set if the conversion is an allowed Objective-C conversion that 1949 /// should result in a warning. 1950 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1951 bool InOverloadResolution, 1952 QualType& ConvertedType, 1953 bool &IncompatibleObjC) { 1954 IncompatibleObjC = false; 1955 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1956 IncompatibleObjC)) 1957 return true; 1958 1959 // Conversion from a null pointer constant to any Objective-C pointer type. 1960 if (ToType->isObjCObjectPointerType() && 1961 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1962 ConvertedType = ToType; 1963 return true; 1964 } 1965 1966 // Blocks: Block pointers can be converted to void*. 1967 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1968 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1969 ConvertedType = ToType; 1970 return true; 1971 } 1972 // Blocks: A null pointer constant can be converted to a block 1973 // pointer type. 1974 if (ToType->isBlockPointerType() && 1975 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1976 ConvertedType = ToType; 1977 return true; 1978 } 1979 1980 // If the left-hand-side is nullptr_t, the right side can be a null 1981 // pointer constant. 1982 if (ToType->isNullPtrType() && 1983 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1984 ConvertedType = ToType; 1985 return true; 1986 } 1987 1988 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1989 if (!ToTypePtr) 1990 return false; 1991 1992 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1993 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1994 ConvertedType = ToType; 1995 return true; 1996 } 1997 1998 // Beyond this point, both types need to be pointers 1999 // , including objective-c pointers. 2000 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2001 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2002 !getLangOpts().ObjCAutoRefCount) { 2003 ConvertedType = BuildSimilarlyQualifiedPointerType( 2004 FromType->getAs<ObjCObjectPointerType>(), 2005 ToPointeeType, 2006 ToType, Context); 2007 return true; 2008 } 2009 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2010 if (!FromTypePtr) 2011 return false; 2012 2013 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2014 2015 // If the unqualified pointee types are the same, this can't be a 2016 // pointer conversion, so don't do all of the work below. 2017 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2018 return false; 2019 2020 // An rvalue of type "pointer to cv T," where T is an object type, 2021 // can be converted to an rvalue of type "pointer to cv void" (C++ 2022 // 4.10p2). 2023 if (FromPointeeType->isIncompleteOrObjectType() && 2024 ToPointeeType->isVoidType()) { 2025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2026 ToPointeeType, 2027 ToType, Context, 2028 /*StripObjCLifetime=*/true); 2029 return true; 2030 } 2031 2032 // MSVC allows implicit function to void* type conversion. 2033 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2034 ToPointeeType->isVoidType()) { 2035 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2036 ToPointeeType, 2037 ToType, Context); 2038 return true; 2039 } 2040 2041 // When we're overloading in C, we allow a special kind of pointer 2042 // conversion for compatible-but-not-identical pointee types. 2043 if (!getLangOpts().CPlusPlus && 2044 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2045 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2046 ToPointeeType, 2047 ToType, Context); 2048 return true; 2049 } 2050 2051 // C++ [conv.ptr]p3: 2052 // 2053 // An rvalue of type "pointer to cv D," where D is a class type, 2054 // can be converted to an rvalue of type "pointer to cv B," where 2055 // B is a base class (clause 10) of D. If B is an inaccessible 2056 // (clause 11) or ambiguous (10.2) base class of D, a program that 2057 // necessitates this conversion is ill-formed. The result of the 2058 // conversion is a pointer to the base class sub-object of the 2059 // derived class object. The null pointer value is converted to 2060 // the null pointer value of the destination type. 2061 // 2062 // Note that we do not check for ambiguity or inaccessibility 2063 // here. That is handled by CheckPointerConversion. 2064 if (getLangOpts().CPlusPlus && 2065 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2066 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2067 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2068 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2070 ToPointeeType, 2071 ToType, Context); 2072 return true; 2073 } 2074 2075 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2076 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2078 ToPointeeType, 2079 ToType, Context); 2080 return true; 2081 } 2082 2083 return false; 2084 } 2085 2086 /// \brief Adopt the given qualifiers for the given type. 2087 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2088 Qualifiers TQs = T.getQualifiers(); 2089 2090 // Check whether qualifiers already match. 2091 if (TQs == Qs) 2092 return T; 2093 2094 if (Qs.compatiblyIncludes(TQs)) 2095 return Context.getQualifiedType(T, Qs); 2096 2097 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2098 } 2099 2100 /// isObjCPointerConversion - Determines whether this is an 2101 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2102 /// with the same arguments and return values. 2103 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2104 QualType& ConvertedType, 2105 bool &IncompatibleObjC) { 2106 if (!getLangOpts().ObjC1) 2107 return false; 2108 2109 // The set of qualifiers on the type we're converting from. 2110 Qualifiers FromQualifiers = FromType.getQualifiers(); 2111 2112 // First, we handle all conversions on ObjC object pointer types. 2113 const ObjCObjectPointerType* ToObjCPtr = 2114 ToType->getAs<ObjCObjectPointerType>(); 2115 const ObjCObjectPointerType *FromObjCPtr = 2116 FromType->getAs<ObjCObjectPointerType>(); 2117 2118 if (ToObjCPtr && FromObjCPtr) { 2119 // If the pointee types are the same (ignoring qualifications), 2120 // then this is not a pointer conversion. 2121 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2122 FromObjCPtr->getPointeeType())) 2123 return false; 2124 2125 // Check for compatible 2126 // Objective C++: We're able to convert between "id" or "Class" and a 2127 // pointer to any interface (in both directions). 2128 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2129 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2130 return true; 2131 } 2132 // Conversions with Objective-C's id<...>. 2133 if ((FromObjCPtr->isObjCQualifiedIdType() || 2134 ToObjCPtr->isObjCQualifiedIdType()) && 2135 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2136 /*compare=*/false)) { 2137 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2138 return true; 2139 } 2140 // Objective C++: We're able to convert from a pointer to an 2141 // interface to a pointer to a different interface. 2142 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2143 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2144 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2145 if (getLangOpts().CPlusPlus && LHS && RHS && 2146 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2147 FromObjCPtr->getPointeeType())) 2148 return false; 2149 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2150 ToObjCPtr->getPointeeType(), 2151 ToType, Context); 2152 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2153 return true; 2154 } 2155 2156 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2157 // Okay: this is some kind of implicit downcast of Objective-C 2158 // interfaces, which is permitted. However, we're going to 2159 // complain about it. 2160 IncompatibleObjC = true; 2161 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2162 ToObjCPtr->getPointeeType(), 2163 ToType, Context); 2164 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2165 return true; 2166 } 2167 } 2168 // Beyond this point, both types need to be C pointers or block pointers. 2169 QualType ToPointeeType; 2170 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2171 ToPointeeType = ToCPtr->getPointeeType(); 2172 else if (const BlockPointerType *ToBlockPtr = 2173 ToType->getAs<BlockPointerType>()) { 2174 // Objective C++: We're able to convert from a pointer to any object 2175 // to a block pointer type. 2176 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2177 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2178 return true; 2179 } 2180 ToPointeeType = ToBlockPtr->getPointeeType(); 2181 } 2182 else if (FromType->getAs<BlockPointerType>() && 2183 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2184 // Objective C++: We're able to convert from a block pointer type to a 2185 // pointer to any object. 2186 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2187 return true; 2188 } 2189 else 2190 return false; 2191 2192 QualType FromPointeeType; 2193 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2194 FromPointeeType = FromCPtr->getPointeeType(); 2195 else if (const BlockPointerType *FromBlockPtr = 2196 FromType->getAs<BlockPointerType>()) 2197 FromPointeeType = FromBlockPtr->getPointeeType(); 2198 else 2199 return false; 2200 2201 // If we have pointers to pointers, recursively check whether this 2202 // is an Objective-C conversion. 2203 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2204 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2205 IncompatibleObjC)) { 2206 // We always complain about this conversion. 2207 IncompatibleObjC = true; 2208 ConvertedType = Context.getPointerType(ConvertedType); 2209 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2210 return true; 2211 } 2212 // Allow conversion of pointee being objective-c pointer to another one; 2213 // as in I* to id. 2214 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2215 ToPointeeType->getAs<ObjCObjectPointerType>() && 2216 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2217 IncompatibleObjC)) { 2218 2219 ConvertedType = Context.getPointerType(ConvertedType); 2220 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2221 return true; 2222 } 2223 2224 // If we have pointers to functions or blocks, check whether the only 2225 // differences in the argument and result types are in Objective-C 2226 // pointer conversions. If so, we permit the conversion (but 2227 // complain about it). 2228 const FunctionProtoType *FromFunctionType 2229 = FromPointeeType->getAs<FunctionProtoType>(); 2230 const FunctionProtoType *ToFunctionType 2231 = ToPointeeType->getAs<FunctionProtoType>(); 2232 if (FromFunctionType && ToFunctionType) { 2233 // If the function types are exactly the same, this isn't an 2234 // Objective-C pointer conversion. 2235 if (Context.getCanonicalType(FromPointeeType) 2236 == Context.getCanonicalType(ToPointeeType)) 2237 return false; 2238 2239 // Perform the quick checks that will tell us whether these 2240 // function types are obviously different. 2241 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2242 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2243 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2244 return false; 2245 2246 bool HasObjCConversion = false; 2247 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2248 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2249 // Okay, the types match exactly. Nothing to do. 2250 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2251 ToFunctionType->getResultType(), 2252 ConvertedType, IncompatibleObjC)) { 2253 // Okay, we have an Objective-C pointer conversion. 2254 HasObjCConversion = true; 2255 } else { 2256 // Function types are too different. Abort. 2257 return false; 2258 } 2259 2260 // Check argument types. 2261 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2262 ArgIdx != NumArgs; ++ArgIdx) { 2263 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2264 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2265 if (Context.getCanonicalType(FromArgType) 2266 == Context.getCanonicalType(ToArgType)) { 2267 // Okay, the types match exactly. Nothing to do. 2268 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2269 ConvertedType, IncompatibleObjC)) { 2270 // Okay, we have an Objective-C pointer conversion. 2271 HasObjCConversion = true; 2272 } else { 2273 // Argument types are too different. Abort. 2274 return false; 2275 } 2276 } 2277 2278 if (HasObjCConversion) { 2279 // We had an Objective-C conversion. Allow this pointer 2280 // conversion, but complain about it. 2281 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2282 IncompatibleObjC = true; 2283 return true; 2284 } 2285 } 2286 2287 return false; 2288 } 2289 2290 /// \brief Determine whether this is an Objective-C writeback conversion, 2291 /// used for parameter passing when performing automatic reference counting. 2292 /// 2293 /// \param FromType The type we're converting form. 2294 /// 2295 /// \param ToType The type we're converting to. 2296 /// 2297 /// \param ConvertedType The type that will be produced after applying 2298 /// this conversion. 2299 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2300 QualType &ConvertedType) { 2301 if (!getLangOpts().ObjCAutoRefCount || 2302 Context.hasSameUnqualifiedType(FromType, ToType)) 2303 return false; 2304 2305 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2306 QualType ToPointee; 2307 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2308 ToPointee = ToPointer->getPointeeType(); 2309 else 2310 return false; 2311 2312 Qualifiers ToQuals = ToPointee.getQualifiers(); 2313 if (!ToPointee->isObjCLifetimeType() || 2314 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2315 !ToQuals.withoutObjCLifetime().empty()) 2316 return false; 2317 2318 // Argument must be a pointer to __strong to __weak. 2319 QualType FromPointee; 2320 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2321 FromPointee = FromPointer->getPointeeType(); 2322 else 2323 return false; 2324 2325 Qualifiers FromQuals = FromPointee.getQualifiers(); 2326 if (!FromPointee->isObjCLifetimeType() || 2327 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2328 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2329 return false; 2330 2331 // Make sure that we have compatible qualifiers. 2332 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2333 if (!ToQuals.compatiblyIncludes(FromQuals)) 2334 return false; 2335 2336 // Remove qualifiers from the pointee type we're converting from; they 2337 // aren't used in the compatibility check belong, and we'll be adding back 2338 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2339 FromPointee = FromPointee.getUnqualifiedType(); 2340 2341 // The unqualified form of the pointee types must be compatible. 2342 ToPointee = ToPointee.getUnqualifiedType(); 2343 bool IncompatibleObjC; 2344 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2345 FromPointee = ToPointee; 2346 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2347 IncompatibleObjC)) 2348 return false; 2349 2350 /// \brief Construct the type we're converting to, which is a pointer to 2351 /// __autoreleasing pointee. 2352 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2353 ConvertedType = Context.getPointerType(FromPointee); 2354 return true; 2355 } 2356 2357 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2358 QualType& ConvertedType) { 2359 QualType ToPointeeType; 2360 if (const BlockPointerType *ToBlockPtr = 2361 ToType->getAs<BlockPointerType>()) 2362 ToPointeeType = ToBlockPtr->getPointeeType(); 2363 else 2364 return false; 2365 2366 QualType FromPointeeType; 2367 if (const BlockPointerType *FromBlockPtr = 2368 FromType->getAs<BlockPointerType>()) 2369 FromPointeeType = FromBlockPtr->getPointeeType(); 2370 else 2371 return false; 2372 // We have pointer to blocks, check whether the only 2373 // differences in the argument and result types are in Objective-C 2374 // pointer conversions. If so, we permit the conversion. 2375 2376 const FunctionProtoType *FromFunctionType 2377 = FromPointeeType->getAs<FunctionProtoType>(); 2378 const FunctionProtoType *ToFunctionType 2379 = ToPointeeType->getAs<FunctionProtoType>(); 2380 2381 if (!FromFunctionType || !ToFunctionType) 2382 return false; 2383 2384 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2385 return true; 2386 2387 // Perform the quick checks that will tell us whether these 2388 // function types are obviously different. 2389 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2390 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2391 return false; 2392 2393 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2394 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2395 if (FromEInfo != ToEInfo) 2396 return false; 2397 2398 bool IncompatibleObjC = false; 2399 if (Context.hasSameType(FromFunctionType->getResultType(), 2400 ToFunctionType->getResultType())) { 2401 // Okay, the types match exactly. Nothing to do. 2402 } else { 2403 QualType RHS = FromFunctionType->getResultType(); 2404 QualType LHS = ToFunctionType->getResultType(); 2405 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2406 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2407 LHS = LHS.getUnqualifiedType(); 2408 2409 if (Context.hasSameType(RHS,LHS)) { 2410 // OK exact match. 2411 } else if (isObjCPointerConversion(RHS, LHS, 2412 ConvertedType, IncompatibleObjC)) { 2413 if (IncompatibleObjC) 2414 return false; 2415 // Okay, we have an Objective-C pointer conversion. 2416 } 2417 else 2418 return false; 2419 } 2420 2421 // Check argument types. 2422 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2423 ArgIdx != NumArgs; ++ArgIdx) { 2424 IncompatibleObjC = false; 2425 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2426 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2427 if (Context.hasSameType(FromArgType, ToArgType)) { 2428 // Okay, the types match exactly. Nothing to do. 2429 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2430 ConvertedType, IncompatibleObjC)) { 2431 if (IncompatibleObjC) 2432 return false; 2433 // Okay, we have an Objective-C pointer conversion. 2434 } else 2435 // Argument types are too different. Abort. 2436 return false; 2437 } 2438 if (LangOpts.ObjCAutoRefCount && 2439 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2440 ToFunctionType)) 2441 return false; 2442 2443 ConvertedType = ToType; 2444 return true; 2445 } 2446 2447 enum { 2448 ft_default, 2449 ft_different_class, 2450 ft_parameter_arity, 2451 ft_parameter_mismatch, 2452 ft_return_type, 2453 ft_qualifer_mismatch 2454 }; 2455 2456 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2457 /// function types. Catches different number of parameter, mismatch in 2458 /// parameter types, and different return types. 2459 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2460 QualType FromType, QualType ToType) { 2461 // If either type is not valid, include no extra info. 2462 if (FromType.isNull() || ToType.isNull()) { 2463 PDiag << ft_default; 2464 return; 2465 } 2466 2467 // Get the function type from the pointers. 2468 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2469 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2470 *ToMember = ToType->getAs<MemberPointerType>(); 2471 if (FromMember->getClass() != ToMember->getClass()) { 2472 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2473 << QualType(FromMember->getClass(), 0); 2474 return; 2475 } 2476 FromType = FromMember->getPointeeType(); 2477 ToType = ToMember->getPointeeType(); 2478 } 2479 2480 if (FromType->isPointerType()) 2481 FromType = FromType->getPointeeType(); 2482 if (ToType->isPointerType()) 2483 ToType = ToType->getPointeeType(); 2484 2485 // Remove references. 2486 FromType = FromType.getNonReferenceType(); 2487 ToType = ToType.getNonReferenceType(); 2488 2489 // Don't print extra info for non-specialized template functions. 2490 if (FromType->isInstantiationDependentType() && 2491 !FromType->getAs<TemplateSpecializationType>()) { 2492 PDiag << ft_default; 2493 return; 2494 } 2495 2496 // No extra info for same types. 2497 if (Context.hasSameType(FromType, ToType)) { 2498 PDiag << ft_default; 2499 return; 2500 } 2501 2502 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2503 *ToFunction = ToType->getAs<FunctionProtoType>(); 2504 2505 // Both types need to be function types. 2506 if (!FromFunction || !ToFunction) { 2507 PDiag << ft_default; 2508 return; 2509 } 2510 2511 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2512 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2513 << FromFunction->getNumArgs(); 2514 return; 2515 } 2516 2517 // Handle different parameter types. 2518 unsigned ArgPos; 2519 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2520 PDiag << ft_parameter_mismatch << ArgPos + 1 2521 << ToFunction->getArgType(ArgPos) 2522 << FromFunction->getArgType(ArgPos); 2523 return; 2524 } 2525 2526 // Handle different return type. 2527 if (!Context.hasSameType(FromFunction->getResultType(), 2528 ToFunction->getResultType())) { 2529 PDiag << ft_return_type << ToFunction->getResultType() 2530 << FromFunction->getResultType(); 2531 return; 2532 } 2533 2534 unsigned FromQuals = FromFunction->getTypeQuals(), 2535 ToQuals = ToFunction->getTypeQuals(); 2536 if (FromQuals != ToQuals) { 2537 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2538 return; 2539 } 2540 2541 // Unable to find a difference, so add no extra info. 2542 PDiag << ft_default; 2543 } 2544 2545 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2546 /// for equality of their argument types. Caller has already checked that 2547 /// they have same number of arguments. This routine assumes that Objective-C 2548 /// pointer types which only differ in their protocol qualifiers are equal. 2549 /// If the parameters are different, ArgPos will have the parameter index 2550 /// of the first different parameter. 2551 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2552 const FunctionProtoType *NewType, 2553 unsigned *ArgPos) { 2554 if (!getLangOpts().ObjC1) { 2555 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2556 N = NewType->arg_type_begin(), 2557 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2558 if (!Context.hasSameType(*O, *N)) { 2559 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2560 return false; 2561 } 2562 } 2563 return true; 2564 } 2565 2566 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2567 N = NewType->arg_type_begin(), 2568 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2569 QualType ToType = (*O); 2570 QualType FromType = (*N); 2571 if (!Context.hasSameType(ToType, FromType)) { 2572 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2573 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2574 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2575 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2576 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2577 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2578 continue; 2579 } 2580 else if (const ObjCObjectPointerType *PTTo = 2581 ToType->getAs<ObjCObjectPointerType>()) { 2582 if (const ObjCObjectPointerType *PTFr = 2583 FromType->getAs<ObjCObjectPointerType>()) 2584 if (Context.hasSameUnqualifiedType( 2585 PTTo->getObjectType()->getBaseType(), 2586 PTFr->getObjectType()->getBaseType())) 2587 continue; 2588 } 2589 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2590 return false; 2591 } 2592 } 2593 return true; 2594 } 2595 2596 /// CheckPointerConversion - Check the pointer conversion from the 2597 /// expression From to the type ToType. This routine checks for 2598 /// ambiguous or inaccessible derived-to-base pointer 2599 /// conversions for which IsPointerConversion has already returned 2600 /// true. It returns true and produces a diagnostic if there was an 2601 /// error, or returns false otherwise. 2602 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2603 CastKind &Kind, 2604 CXXCastPath& BasePath, 2605 bool IgnoreBaseAccess) { 2606 QualType FromType = From->getType(); 2607 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2608 2609 Kind = CK_BitCast; 2610 2611 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2612 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2613 Expr::NPCK_ZeroExpression) { 2614 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2615 DiagRuntimeBehavior(From->getExprLoc(), From, 2616 PDiag(diag::warn_impcast_bool_to_null_pointer) 2617 << ToType << From->getSourceRange()); 2618 else if (!isUnevaluatedContext()) 2619 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2620 << ToType << From->getSourceRange(); 2621 } 2622 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2623 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2624 QualType FromPointeeType = FromPtrType->getPointeeType(), 2625 ToPointeeType = ToPtrType->getPointeeType(); 2626 2627 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2628 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2629 // We must have a derived-to-base conversion. Check an 2630 // ambiguous or inaccessible conversion. 2631 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2632 From->getExprLoc(), 2633 From->getSourceRange(), &BasePath, 2634 IgnoreBaseAccess)) 2635 return true; 2636 2637 // The conversion was successful. 2638 Kind = CK_DerivedToBase; 2639 } 2640 } 2641 } else if (const ObjCObjectPointerType *ToPtrType = 2642 ToType->getAs<ObjCObjectPointerType>()) { 2643 if (const ObjCObjectPointerType *FromPtrType = 2644 FromType->getAs<ObjCObjectPointerType>()) { 2645 // Objective-C++ conversions are always okay. 2646 // FIXME: We should have a different class of conversions for the 2647 // Objective-C++ implicit conversions. 2648 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2649 return false; 2650 } else if (FromType->isBlockPointerType()) { 2651 Kind = CK_BlockPointerToObjCPointerCast; 2652 } else { 2653 Kind = CK_CPointerToObjCPointerCast; 2654 } 2655 } else if (ToType->isBlockPointerType()) { 2656 if (!FromType->isBlockPointerType()) 2657 Kind = CK_AnyPointerToBlockPointerCast; 2658 } 2659 2660 // We shouldn't fall into this case unless it's valid for other 2661 // reasons. 2662 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2663 Kind = CK_NullToPointer; 2664 2665 return false; 2666 } 2667 2668 /// IsMemberPointerConversion - Determines whether the conversion of the 2669 /// expression From, which has the (possibly adjusted) type FromType, can be 2670 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2671 /// If so, returns true and places the converted type (that might differ from 2672 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2673 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2674 QualType ToType, 2675 bool InOverloadResolution, 2676 QualType &ConvertedType) { 2677 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2678 if (!ToTypePtr) 2679 return false; 2680 2681 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2682 if (From->isNullPointerConstant(Context, 2683 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2684 : Expr::NPC_ValueDependentIsNull)) { 2685 ConvertedType = ToType; 2686 return true; 2687 } 2688 2689 // Otherwise, both types have to be member pointers. 2690 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2691 if (!FromTypePtr) 2692 return false; 2693 2694 // A pointer to member of B can be converted to a pointer to member of D, 2695 // where D is derived from B (C++ 4.11p2). 2696 QualType FromClass(FromTypePtr->getClass(), 0); 2697 QualType ToClass(ToTypePtr->getClass(), 0); 2698 2699 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2700 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2701 IsDerivedFrom(ToClass, FromClass)) { 2702 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2703 ToClass.getTypePtr()); 2704 return true; 2705 } 2706 2707 return false; 2708 } 2709 2710 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2711 /// expression From to the type ToType. This routine checks for ambiguous or 2712 /// virtual or inaccessible base-to-derived member pointer conversions 2713 /// for which IsMemberPointerConversion has already returned true. It returns 2714 /// true and produces a diagnostic if there was an error, or returns false 2715 /// otherwise. 2716 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2717 CastKind &Kind, 2718 CXXCastPath &BasePath, 2719 bool IgnoreBaseAccess) { 2720 QualType FromType = From->getType(); 2721 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2722 if (!FromPtrType) { 2723 // This must be a null pointer to member pointer conversion 2724 assert(From->isNullPointerConstant(Context, 2725 Expr::NPC_ValueDependentIsNull) && 2726 "Expr must be null pointer constant!"); 2727 Kind = CK_NullToMemberPointer; 2728 return false; 2729 } 2730 2731 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2732 assert(ToPtrType && "No member pointer cast has a target type " 2733 "that is not a member pointer."); 2734 2735 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2736 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2737 2738 // FIXME: What about dependent types? 2739 assert(FromClass->isRecordType() && "Pointer into non-class."); 2740 assert(ToClass->isRecordType() && "Pointer into non-class."); 2741 2742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2743 /*DetectVirtual=*/true); 2744 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2745 assert(DerivationOkay && 2746 "Should not have been called if derivation isn't OK."); 2747 (void)DerivationOkay; 2748 2749 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2750 getUnqualifiedType())) { 2751 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2752 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2753 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2754 return true; 2755 } 2756 2757 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2758 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2759 << FromClass << ToClass << QualType(VBase, 0) 2760 << From->getSourceRange(); 2761 return true; 2762 } 2763 2764 if (!IgnoreBaseAccess) 2765 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2766 Paths.front(), 2767 diag::err_downcast_from_inaccessible_base); 2768 2769 // Must be a base to derived member conversion. 2770 BuildBasePathArray(Paths, BasePath); 2771 Kind = CK_BaseToDerivedMemberPointer; 2772 return false; 2773 } 2774 2775 /// IsQualificationConversion - Determines whether the conversion from 2776 /// an rvalue of type FromType to ToType is a qualification conversion 2777 /// (C++ 4.4). 2778 /// 2779 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2780 /// when the qualification conversion involves a change in the Objective-C 2781 /// object lifetime. 2782 bool 2783 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2784 bool CStyle, bool &ObjCLifetimeConversion) { 2785 FromType = Context.getCanonicalType(FromType); 2786 ToType = Context.getCanonicalType(ToType); 2787 ObjCLifetimeConversion = false; 2788 2789 // If FromType and ToType are the same type, this is not a 2790 // qualification conversion. 2791 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2792 return false; 2793 2794 // (C++ 4.4p4): 2795 // A conversion can add cv-qualifiers at levels other than the first 2796 // in multi-level pointers, subject to the following rules: [...] 2797 bool PreviousToQualsIncludeConst = true; 2798 bool UnwrappedAnyPointer = false; 2799 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2800 // Within each iteration of the loop, we check the qualifiers to 2801 // determine if this still looks like a qualification 2802 // conversion. Then, if all is well, we unwrap one more level of 2803 // pointers or pointers-to-members and do it all again 2804 // until there are no more pointers or pointers-to-members left to 2805 // unwrap. 2806 UnwrappedAnyPointer = true; 2807 2808 Qualifiers FromQuals = FromType.getQualifiers(); 2809 Qualifiers ToQuals = ToType.getQualifiers(); 2810 2811 // Objective-C ARC: 2812 // Check Objective-C lifetime conversions. 2813 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2814 UnwrappedAnyPointer) { 2815 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2816 ObjCLifetimeConversion = true; 2817 FromQuals.removeObjCLifetime(); 2818 ToQuals.removeObjCLifetime(); 2819 } else { 2820 // Qualification conversions cannot cast between different 2821 // Objective-C lifetime qualifiers. 2822 return false; 2823 } 2824 } 2825 2826 // Allow addition/removal of GC attributes but not changing GC attributes. 2827 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2828 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2829 FromQuals.removeObjCGCAttr(); 2830 ToQuals.removeObjCGCAttr(); 2831 } 2832 2833 // -- for every j > 0, if const is in cv 1,j then const is in cv 2834 // 2,j, and similarly for volatile. 2835 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2836 return false; 2837 2838 // -- if the cv 1,j and cv 2,j are different, then const is in 2839 // every cv for 0 < k < j. 2840 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2841 && !PreviousToQualsIncludeConst) 2842 return false; 2843 2844 // Keep track of whether all prior cv-qualifiers in the "to" type 2845 // include const. 2846 PreviousToQualsIncludeConst 2847 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2848 } 2849 2850 // We are left with FromType and ToType being the pointee types 2851 // after unwrapping the original FromType and ToType the same number 2852 // of types. If we unwrapped any pointers, and if FromType and 2853 // ToType have the same unqualified type (since we checked 2854 // qualifiers above), then this is a qualification conversion. 2855 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2856 } 2857 2858 /// \brief - Determine whether this is a conversion from a scalar type to an 2859 /// atomic type. 2860 /// 2861 /// If successful, updates \c SCS's second and third steps in the conversion 2862 /// sequence to finish the conversion. 2863 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2864 bool InOverloadResolution, 2865 StandardConversionSequence &SCS, 2866 bool CStyle) { 2867 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2868 if (!ToAtomic) 2869 return false; 2870 2871 StandardConversionSequence InnerSCS; 2872 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2873 InOverloadResolution, InnerSCS, 2874 CStyle, /*AllowObjCWritebackConversion=*/false)) 2875 return false; 2876 2877 SCS.Second = InnerSCS.Second; 2878 SCS.setToType(1, InnerSCS.getToType(1)); 2879 SCS.Third = InnerSCS.Third; 2880 SCS.QualificationIncludesObjCLifetime 2881 = InnerSCS.QualificationIncludesObjCLifetime; 2882 SCS.setToType(2, InnerSCS.getToType(2)); 2883 return true; 2884 } 2885 2886 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2887 CXXConstructorDecl *Constructor, 2888 QualType Type) { 2889 const FunctionProtoType *CtorType = 2890 Constructor->getType()->getAs<FunctionProtoType>(); 2891 if (CtorType->getNumArgs() > 0) { 2892 QualType FirstArg = CtorType->getArgType(0); 2893 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2894 return true; 2895 } 2896 return false; 2897 } 2898 2899 static OverloadingResult 2900 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2901 CXXRecordDecl *To, 2902 UserDefinedConversionSequence &User, 2903 OverloadCandidateSet &CandidateSet, 2904 bool AllowExplicit) { 2905 DeclContext::lookup_result R = S.LookupConstructors(To); 2906 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2907 Con != ConEnd; ++Con) { 2908 NamedDecl *D = *Con; 2909 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2910 2911 // Find the constructor (which may be a template). 2912 CXXConstructorDecl *Constructor = 0; 2913 FunctionTemplateDecl *ConstructorTmpl 2914 = dyn_cast<FunctionTemplateDecl>(D); 2915 if (ConstructorTmpl) 2916 Constructor 2917 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2918 else 2919 Constructor = cast<CXXConstructorDecl>(D); 2920 2921 bool Usable = !Constructor->isInvalidDecl() && 2922 S.isInitListConstructor(Constructor) && 2923 (AllowExplicit || !Constructor->isExplicit()); 2924 if (Usable) { 2925 // If the first argument is (a reference to) the target type, 2926 // suppress conversions. 2927 bool SuppressUserConversions = 2928 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2929 if (ConstructorTmpl) 2930 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2931 /*ExplicitArgs*/ 0, 2932 From, CandidateSet, 2933 SuppressUserConversions); 2934 else 2935 S.AddOverloadCandidate(Constructor, FoundDecl, 2936 From, CandidateSet, 2937 SuppressUserConversions); 2938 } 2939 } 2940 2941 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2942 2943 OverloadCandidateSet::iterator Best; 2944 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2945 case OR_Success: { 2946 // Record the standard conversion we used and the conversion function. 2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2948 QualType ThisType = Constructor->getThisType(S.Context); 2949 // Initializer lists don't have conversions as such. 2950 User.Before.setAsIdentityConversion(); 2951 User.HadMultipleCandidates = HadMultipleCandidates; 2952 User.ConversionFunction = Constructor; 2953 User.FoundConversionFunction = Best->FoundDecl; 2954 User.After.setAsIdentityConversion(); 2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2956 User.After.setAllToTypes(ToType); 2957 return OR_Success; 2958 } 2959 2960 case OR_No_Viable_Function: 2961 return OR_No_Viable_Function; 2962 case OR_Deleted: 2963 return OR_Deleted; 2964 case OR_Ambiguous: 2965 return OR_Ambiguous; 2966 } 2967 2968 llvm_unreachable("Invalid OverloadResult!"); 2969 } 2970 2971 /// Determines whether there is a user-defined conversion sequence 2972 /// (C++ [over.ics.user]) that converts expression From to the type 2973 /// ToType. If such a conversion exists, User will contain the 2974 /// user-defined conversion sequence that performs such a conversion 2975 /// and this routine will return true. Otherwise, this routine returns 2976 /// false and User is unspecified. 2977 /// 2978 /// \param AllowExplicit true if the conversion should consider C++0x 2979 /// "explicit" conversion functions as well as non-explicit conversion 2980 /// functions (C++0x [class.conv.fct]p2). 2981 static OverloadingResult 2982 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2983 UserDefinedConversionSequence &User, 2984 OverloadCandidateSet &CandidateSet, 2985 bool AllowExplicit) { 2986 // Whether we will only visit constructors. 2987 bool ConstructorsOnly = false; 2988 2989 // If the type we are conversion to is a class type, enumerate its 2990 // constructors. 2991 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2992 // C++ [over.match.ctor]p1: 2993 // When objects of class type are direct-initialized (8.5), or 2994 // copy-initialized from an expression of the same or a 2995 // derived class type (8.5), overload resolution selects the 2996 // constructor. [...] For copy-initialization, the candidate 2997 // functions are all the converting constructors (12.3.1) of 2998 // that class. The argument list is the expression-list within 2999 // the parentheses of the initializer. 3000 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3001 (From->getType()->getAs<RecordType>() && 3002 S.IsDerivedFrom(From->getType(), ToType))) 3003 ConstructorsOnly = true; 3004 3005 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3006 // RequireCompleteType may have returned true due to some invalid decl 3007 // during template instantiation, but ToType may be complete enough now 3008 // to try to recover. 3009 if (ToType->isIncompleteType()) { 3010 // We're not going to find any constructors. 3011 } else if (CXXRecordDecl *ToRecordDecl 3012 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3013 3014 Expr **Args = &From; 3015 unsigned NumArgs = 1; 3016 bool ListInitializing = false; 3017 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3018 // But first, see if there is an init-list-contructor that will work. 3019 OverloadingResult Result = IsInitializerListConstructorConversion( 3020 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3021 if (Result != OR_No_Viable_Function) 3022 return Result; 3023 // Never mind. 3024 CandidateSet.clear(); 3025 3026 // If we're list-initializing, we pass the individual elements as 3027 // arguments, not the entire list. 3028 Args = InitList->getInits(); 3029 NumArgs = InitList->getNumInits(); 3030 ListInitializing = true; 3031 } 3032 3033 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3034 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3035 Con != ConEnd; ++Con) { 3036 NamedDecl *D = *Con; 3037 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3038 3039 // Find the constructor (which may be a template). 3040 CXXConstructorDecl *Constructor = 0; 3041 FunctionTemplateDecl *ConstructorTmpl 3042 = dyn_cast<FunctionTemplateDecl>(D); 3043 if (ConstructorTmpl) 3044 Constructor 3045 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3046 else 3047 Constructor = cast<CXXConstructorDecl>(D); 3048 3049 bool Usable = !Constructor->isInvalidDecl(); 3050 if (ListInitializing) 3051 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3052 else 3053 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3054 if (Usable) { 3055 bool SuppressUserConversions = !ConstructorsOnly; 3056 if (SuppressUserConversions && ListInitializing) { 3057 SuppressUserConversions = false; 3058 if (NumArgs == 1) { 3059 // If the first argument is (a reference to) the target type, 3060 // suppress conversions. 3061 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3062 S.Context, Constructor, ToType); 3063 } 3064 } 3065 if (ConstructorTmpl) 3066 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3067 /*ExplicitArgs*/ 0, 3068 llvm::makeArrayRef(Args, NumArgs), 3069 CandidateSet, SuppressUserConversions); 3070 else 3071 // Allow one user-defined conversion when user specifies a 3072 // From->ToType conversion via an static cast (c-style, etc). 3073 S.AddOverloadCandidate(Constructor, FoundDecl, 3074 llvm::makeArrayRef(Args, NumArgs), 3075 CandidateSet, SuppressUserConversions); 3076 } 3077 } 3078 } 3079 } 3080 3081 // Enumerate conversion functions, if we're allowed to. 3082 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3083 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3084 // No conversion functions from incomplete types. 3085 } else if (const RecordType *FromRecordType 3086 = From->getType()->getAs<RecordType>()) { 3087 if (CXXRecordDecl *FromRecordDecl 3088 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3089 // Add all of the conversion functions as candidates. 3090 std::pair<CXXRecordDecl::conversion_iterator, 3091 CXXRecordDecl::conversion_iterator> 3092 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3093 for (CXXRecordDecl::conversion_iterator 3094 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3095 DeclAccessPair FoundDecl = I.getPair(); 3096 NamedDecl *D = FoundDecl.getDecl(); 3097 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3098 if (isa<UsingShadowDecl>(D)) 3099 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3100 3101 CXXConversionDecl *Conv; 3102 FunctionTemplateDecl *ConvTemplate; 3103 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3104 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3105 else 3106 Conv = cast<CXXConversionDecl>(D); 3107 3108 if (AllowExplicit || !Conv->isExplicit()) { 3109 if (ConvTemplate) 3110 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3111 ActingContext, From, ToType, 3112 CandidateSet); 3113 else 3114 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3115 From, ToType, CandidateSet); 3116 } 3117 } 3118 } 3119 } 3120 3121 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3122 3123 OverloadCandidateSet::iterator Best; 3124 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3125 case OR_Success: 3126 // Record the standard conversion we used and the conversion function. 3127 if (CXXConstructorDecl *Constructor 3128 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3129 // C++ [over.ics.user]p1: 3130 // If the user-defined conversion is specified by a 3131 // constructor (12.3.1), the initial standard conversion 3132 // sequence converts the source type to the type required by 3133 // the argument of the constructor. 3134 // 3135 QualType ThisType = Constructor->getThisType(S.Context); 3136 if (isa<InitListExpr>(From)) { 3137 // Initializer lists don't have conversions as such. 3138 User.Before.setAsIdentityConversion(); 3139 } else { 3140 if (Best->Conversions[0].isEllipsis()) 3141 User.EllipsisConversion = true; 3142 else { 3143 User.Before = Best->Conversions[0].Standard; 3144 User.EllipsisConversion = false; 3145 } 3146 } 3147 User.HadMultipleCandidates = HadMultipleCandidates; 3148 User.ConversionFunction = Constructor; 3149 User.FoundConversionFunction = Best->FoundDecl; 3150 User.After.setAsIdentityConversion(); 3151 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3152 User.After.setAllToTypes(ToType); 3153 return OR_Success; 3154 } 3155 if (CXXConversionDecl *Conversion 3156 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3157 // C++ [over.ics.user]p1: 3158 // 3159 // [...] If the user-defined conversion is specified by a 3160 // conversion function (12.3.2), the initial standard 3161 // conversion sequence converts the source type to the 3162 // implicit object parameter of the conversion function. 3163 User.Before = Best->Conversions[0].Standard; 3164 User.HadMultipleCandidates = HadMultipleCandidates; 3165 User.ConversionFunction = Conversion; 3166 User.FoundConversionFunction = Best->FoundDecl; 3167 User.EllipsisConversion = false; 3168 3169 // C++ [over.ics.user]p2: 3170 // The second standard conversion sequence converts the 3171 // result of the user-defined conversion to the target type 3172 // for the sequence. Since an implicit conversion sequence 3173 // is an initialization, the special rules for 3174 // initialization by user-defined conversion apply when 3175 // selecting the best user-defined conversion for a 3176 // user-defined conversion sequence (see 13.3.3 and 3177 // 13.3.3.1). 3178 User.After = Best->FinalConversion; 3179 return OR_Success; 3180 } 3181 llvm_unreachable("Not a constructor or conversion function?"); 3182 3183 case OR_No_Viable_Function: 3184 return OR_No_Viable_Function; 3185 case OR_Deleted: 3186 // No conversion here! We're done. 3187 return OR_Deleted; 3188 3189 case OR_Ambiguous: 3190 return OR_Ambiguous; 3191 } 3192 3193 llvm_unreachable("Invalid OverloadResult!"); 3194 } 3195 3196 bool 3197 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3198 ImplicitConversionSequence ICS; 3199 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3200 OverloadingResult OvResult = 3201 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3202 CandidateSet, false); 3203 if (OvResult == OR_Ambiguous) 3204 Diag(From->getLocStart(), 3205 diag::err_typecheck_ambiguous_condition) 3206 << From->getType() << ToType << From->getSourceRange(); 3207 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3208 Diag(From->getLocStart(), 3209 diag::err_typecheck_nonviable_condition) 3210 << From->getType() << ToType << From->getSourceRange(); 3211 else 3212 return false; 3213 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3214 return true; 3215 } 3216 3217 /// \brief Compare the user-defined conversion functions or constructors 3218 /// of two user-defined conversion sequences to determine whether any ordering 3219 /// is possible. 3220 static ImplicitConversionSequence::CompareKind 3221 compareConversionFunctions(Sema &S, 3222 FunctionDecl *Function1, 3223 FunctionDecl *Function2) { 3224 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3225 return ImplicitConversionSequence::Indistinguishable; 3226 3227 // Objective-C++: 3228 // If both conversion functions are implicitly-declared conversions from 3229 // a lambda closure type to a function pointer and a block pointer, 3230 // respectively, always prefer the conversion to a function pointer, 3231 // because the function pointer is more lightweight and is more likely 3232 // to keep code working. 3233 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3234 if (!Conv1) 3235 return ImplicitConversionSequence::Indistinguishable; 3236 3237 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3238 if (!Conv2) 3239 return ImplicitConversionSequence::Indistinguishable; 3240 3241 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3242 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3243 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3244 if (Block1 != Block2) 3245 return Block1? ImplicitConversionSequence::Worse 3246 : ImplicitConversionSequence::Better; 3247 } 3248 3249 return ImplicitConversionSequence::Indistinguishable; 3250 } 3251 3252 /// CompareImplicitConversionSequences - Compare two implicit 3253 /// conversion sequences to determine whether one is better than the 3254 /// other or if they are indistinguishable (C++ 13.3.3.2). 3255 static ImplicitConversionSequence::CompareKind 3256 CompareImplicitConversionSequences(Sema &S, 3257 const ImplicitConversionSequence& ICS1, 3258 const ImplicitConversionSequence& ICS2) 3259 { 3260 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3261 // conversion sequences (as defined in 13.3.3.1) 3262 // -- a standard conversion sequence (13.3.3.1.1) is a better 3263 // conversion sequence than a user-defined conversion sequence or 3264 // an ellipsis conversion sequence, and 3265 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3266 // conversion sequence than an ellipsis conversion sequence 3267 // (13.3.3.1.3). 3268 // 3269 // C++0x [over.best.ics]p10: 3270 // For the purpose of ranking implicit conversion sequences as 3271 // described in 13.3.3.2, the ambiguous conversion sequence is 3272 // treated as a user-defined sequence that is indistinguishable 3273 // from any other user-defined conversion sequence. 3274 if (ICS1.getKindRank() < ICS2.getKindRank()) 3275 return ImplicitConversionSequence::Better; 3276 if (ICS2.getKindRank() < ICS1.getKindRank()) 3277 return ImplicitConversionSequence::Worse; 3278 3279 // The following checks require both conversion sequences to be of 3280 // the same kind. 3281 if (ICS1.getKind() != ICS2.getKind()) 3282 return ImplicitConversionSequence::Indistinguishable; 3283 3284 ImplicitConversionSequence::CompareKind Result = 3285 ImplicitConversionSequence::Indistinguishable; 3286 3287 // Two implicit conversion sequences of the same form are 3288 // indistinguishable conversion sequences unless one of the 3289 // following rules apply: (C++ 13.3.3.2p3): 3290 if (ICS1.isStandard()) 3291 Result = CompareStandardConversionSequences(S, 3292 ICS1.Standard, ICS2.Standard); 3293 else if (ICS1.isUserDefined()) { 3294 // User-defined conversion sequence U1 is a better conversion 3295 // sequence than another user-defined conversion sequence U2 if 3296 // they contain the same user-defined conversion function or 3297 // constructor and if the second standard conversion sequence of 3298 // U1 is better than the second standard conversion sequence of 3299 // U2 (C++ 13.3.3.2p3). 3300 if (ICS1.UserDefined.ConversionFunction == 3301 ICS2.UserDefined.ConversionFunction) 3302 Result = CompareStandardConversionSequences(S, 3303 ICS1.UserDefined.After, 3304 ICS2.UserDefined.After); 3305 else 3306 Result = compareConversionFunctions(S, 3307 ICS1.UserDefined.ConversionFunction, 3308 ICS2.UserDefined.ConversionFunction); 3309 } 3310 3311 // List-initialization sequence L1 is a better conversion sequence than 3312 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3313 // for some X and L2 does not. 3314 if (Result == ImplicitConversionSequence::Indistinguishable && 3315 !ICS1.isBad() && 3316 ICS1.isListInitializationSequence() && 3317 ICS2.isListInitializationSequence()) { 3318 if (ICS1.isStdInitializerListElement() && 3319 !ICS2.isStdInitializerListElement()) 3320 return ImplicitConversionSequence::Better; 3321 if (!ICS1.isStdInitializerListElement() && 3322 ICS2.isStdInitializerListElement()) 3323 return ImplicitConversionSequence::Worse; 3324 } 3325 3326 return Result; 3327 } 3328 3329 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3330 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3331 Qualifiers Quals; 3332 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3333 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3334 } 3335 3336 return Context.hasSameUnqualifiedType(T1, T2); 3337 } 3338 3339 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3340 // determine if one is a proper subset of the other. 3341 static ImplicitConversionSequence::CompareKind 3342 compareStandardConversionSubsets(ASTContext &Context, 3343 const StandardConversionSequence& SCS1, 3344 const StandardConversionSequence& SCS2) { 3345 ImplicitConversionSequence::CompareKind Result 3346 = ImplicitConversionSequence::Indistinguishable; 3347 3348 // the identity conversion sequence is considered to be a subsequence of 3349 // any non-identity conversion sequence 3350 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3351 return ImplicitConversionSequence::Better; 3352 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3353 return ImplicitConversionSequence::Worse; 3354 3355 if (SCS1.Second != SCS2.Second) { 3356 if (SCS1.Second == ICK_Identity) 3357 Result = ImplicitConversionSequence::Better; 3358 else if (SCS2.Second == ICK_Identity) 3359 Result = ImplicitConversionSequence::Worse; 3360 else 3361 return ImplicitConversionSequence::Indistinguishable; 3362 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3363 return ImplicitConversionSequence::Indistinguishable; 3364 3365 if (SCS1.Third == SCS2.Third) { 3366 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3367 : ImplicitConversionSequence::Indistinguishable; 3368 } 3369 3370 if (SCS1.Third == ICK_Identity) 3371 return Result == ImplicitConversionSequence::Worse 3372 ? ImplicitConversionSequence::Indistinguishable 3373 : ImplicitConversionSequence::Better; 3374 3375 if (SCS2.Third == ICK_Identity) 3376 return Result == ImplicitConversionSequence::Better 3377 ? ImplicitConversionSequence::Indistinguishable 3378 : ImplicitConversionSequence::Worse; 3379 3380 return ImplicitConversionSequence::Indistinguishable; 3381 } 3382 3383 /// \brief Determine whether one of the given reference bindings is better 3384 /// than the other based on what kind of bindings they are. 3385 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3386 const StandardConversionSequence &SCS2) { 3387 // C++0x [over.ics.rank]p3b4: 3388 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3389 // implicit object parameter of a non-static member function declared 3390 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3391 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3392 // lvalue reference to a function lvalue and S2 binds an rvalue 3393 // reference*. 3394 // 3395 // FIXME: Rvalue references. We're going rogue with the above edits, 3396 // because the semantics in the current C++0x working paper (N3225 at the 3397 // time of this writing) break the standard definition of std::forward 3398 // and std::reference_wrapper when dealing with references to functions. 3399 // Proposed wording changes submitted to CWG for consideration. 3400 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3401 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3402 return false; 3403 3404 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3405 SCS2.IsLvalueReference) || 3406 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3407 !SCS2.IsLvalueReference); 3408 } 3409 3410 /// CompareStandardConversionSequences - Compare two standard 3411 /// conversion sequences to determine whether one is better than the 3412 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3413 static ImplicitConversionSequence::CompareKind 3414 CompareStandardConversionSequences(Sema &S, 3415 const StandardConversionSequence& SCS1, 3416 const StandardConversionSequence& SCS2) 3417 { 3418 // Standard conversion sequence S1 is a better conversion sequence 3419 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3420 3421 // -- S1 is a proper subsequence of S2 (comparing the conversion 3422 // sequences in the canonical form defined by 13.3.3.1.1, 3423 // excluding any Lvalue Transformation; the identity conversion 3424 // sequence is considered to be a subsequence of any 3425 // non-identity conversion sequence) or, if not that, 3426 if (ImplicitConversionSequence::CompareKind CK 3427 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3428 return CK; 3429 3430 // -- the rank of S1 is better than the rank of S2 (by the rules 3431 // defined below), or, if not that, 3432 ImplicitConversionRank Rank1 = SCS1.getRank(); 3433 ImplicitConversionRank Rank2 = SCS2.getRank(); 3434 if (Rank1 < Rank2) 3435 return ImplicitConversionSequence::Better; 3436 else if (Rank2 < Rank1) 3437 return ImplicitConversionSequence::Worse; 3438 3439 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3440 // are indistinguishable unless one of the following rules 3441 // applies: 3442 3443 // A conversion that is not a conversion of a pointer, or 3444 // pointer to member, to bool is better than another conversion 3445 // that is such a conversion. 3446 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3447 return SCS2.isPointerConversionToBool() 3448 ? ImplicitConversionSequence::Better 3449 : ImplicitConversionSequence::Worse; 3450 3451 // C++ [over.ics.rank]p4b2: 3452 // 3453 // If class B is derived directly or indirectly from class A, 3454 // conversion of B* to A* is better than conversion of B* to 3455 // void*, and conversion of A* to void* is better than conversion 3456 // of B* to void*. 3457 bool SCS1ConvertsToVoid 3458 = SCS1.isPointerConversionToVoidPointer(S.Context); 3459 bool SCS2ConvertsToVoid 3460 = SCS2.isPointerConversionToVoidPointer(S.Context); 3461 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3462 // Exactly one of the conversion sequences is a conversion to 3463 // a void pointer; it's the worse conversion. 3464 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3465 : ImplicitConversionSequence::Worse; 3466 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3467 // Neither conversion sequence converts to a void pointer; compare 3468 // their derived-to-base conversions. 3469 if (ImplicitConversionSequence::CompareKind DerivedCK 3470 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3471 return DerivedCK; 3472 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3473 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3474 // Both conversion sequences are conversions to void 3475 // pointers. Compare the source types to determine if there's an 3476 // inheritance relationship in their sources. 3477 QualType FromType1 = SCS1.getFromType(); 3478 QualType FromType2 = SCS2.getFromType(); 3479 3480 // Adjust the types we're converting from via the array-to-pointer 3481 // conversion, if we need to. 3482 if (SCS1.First == ICK_Array_To_Pointer) 3483 FromType1 = S.Context.getArrayDecayedType(FromType1); 3484 if (SCS2.First == ICK_Array_To_Pointer) 3485 FromType2 = S.Context.getArrayDecayedType(FromType2); 3486 3487 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3488 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3489 3490 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3491 return ImplicitConversionSequence::Better; 3492 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3493 return ImplicitConversionSequence::Worse; 3494 3495 // Objective-C++: If one interface is more specific than the 3496 // other, it is the better one. 3497 const ObjCObjectPointerType* FromObjCPtr1 3498 = FromType1->getAs<ObjCObjectPointerType>(); 3499 const ObjCObjectPointerType* FromObjCPtr2 3500 = FromType2->getAs<ObjCObjectPointerType>(); 3501 if (FromObjCPtr1 && FromObjCPtr2) { 3502 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3503 FromObjCPtr2); 3504 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3505 FromObjCPtr1); 3506 if (AssignLeft != AssignRight) { 3507 return AssignLeft? ImplicitConversionSequence::Better 3508 : ImplicitConversionSequence::Worse; 3509 } 3510 } 3511 } 3512 3513 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3514 // bullet 3). 3515 if (ImplicitConversionSequence::CompareKind QualCK 3516 = CompareQualificationConversions(S, SCS1, SCS2)) 3517 return QualCK; 3518 3519 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3520 // Check for a better reference binding based on the kind of bindings. 3521 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3522 return ImplicitConversionSequence::Better; 3523 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3524 return ImplicitConversionSequence::Worse; 3525 3526 // C++ [over.ics.rank]p3b4: 3527 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3528 // which the references refer are the same type except for 3529 // top-level cv-qualifiers, and the type to which the reference 3530 // initialized by S2 refers is more cv-qualified than the type 3531 // to which the reference initialized by S1 refers. 3532 QualType T1 = SCS1.getToType(2); 3533 QualType T2 = SCS2.getToType(2); 3534 T1 = S.Context.getCanonicalType(T1); 3535 T2 = S.Context.getCanonicalType(T2); 3536 Qualifiers T1Quals, T2Quals; 3537 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3538 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3539 if (UnqualT1 == UnqualT2) { 3540 // Objective-C++ ARC: If the references refer to objects with different 3541 // lifetimes, prefer bindings that don't change lifetime. 3542 if (SCS1.ObjCLifetimeConversionBinding != 3543 SCS2.ObjCLifetimeConversionBinding) { 3544 return SCS1.ObjCLifetimeConversionBinding 3545 ? ImplicitConversionSequence::Worse 3546 : ImplicitConversionSequence::Better; 3547 } 3548 3549 // If the type is an array type, promote the element qualifiers to the 3550 // type for comparison. 3551 if (isa<ArrayType>(T1) && T1Quals) 3552 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3553 if (isa<ArrayType>(T2) && T2Quals) 3554 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3555 if (T2.isMoreQualifiedThan(T1)) 3556 return ImplicitConversionSequence::Better; 3557 else if (T1.isMoreQualifiedThan(T2)) 3558 return ImplicitConversionSequence::Worse; 3559 } 3560 } 3561 3562 // In Microsoft mode, prefer an integral conversion to a 3563 // floating-to-integral conversion if the integral conversion 3564 // is between types of the same size. 3565 // For example: 3566 // void f(float); 3567 // void f(int); 3568 // int main { 3569 // long a; 3570 // f(a); 3571 // } 3572 // Here, MSVC will call f(int) instead of generating a compile error 3573 // as clang will do in standard mode. 3574 if (S.getLangOpts().MicrosoftMode && 3575 SCS1.Second == ICK_Integral_Conversion && 3576 SCS2.Second == ICK_Floating_Integral && 3577 S.Context.getTypeSize(SCS1.getFromType()) == 3578 S.Context.getTypeSize(SCS1.getToType(2))) 3579 return ImplicitConversionSequence::Better; 3580 3581 return ImplicitConversionSequence::Indistinguishable; 3582 } 3583 3584 /// CompareQualificationConversions - Compares two standard conversion 3585 /// sequences to determine whether they can be ranked based on their 3586 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3587 ImplicitConversionSequence::CompareKind 3588 CompareQualificationConversions(Sema &S, 3589 const StandardConversionSequence& SCS1, 3590 const StandardConversionSequence& SCS2) { 3591 // C++ 13.3.3.2p3: 3592 // -- S1 and S2 differ only in their qualification conversion and 3593 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3594 // cv-qualification signature of type T1 is a proper subset of 3595 // the cv-qualification signature of type T2, and S1 is not the 3596 // deprecated string literal array-to-pointer conversion (4.2). 3597 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3598 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3599 return ImplicitConversionSequence::Indistinguishable; 3600 3601 // FIXME: the example in the standard doesn't use a qualification 3602 // conversion (!) 3603 QualType T1 = SCS1.getToType(2); 3604 QualType T2 = SCS2.getToType(2); 3605 T1 = S.Context.getCanonicalType(T1); 3606 T2 = S.Context.getCanonicalType(T2); 3607 Qualifiers T1Quals, T2Quals; 3608 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3609 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3610 3611 // If the types are the same, we won't learn anything by unwrapped 3612 // them. 3613 if (UnqualT1 == UnqualT2) 3614 return ImplicitConversionSequence::Indistinguishable; 3615 3616 // If the type is an array type, promote the element qualifiers to the type 3617 // for comparison. 3618 if (isa<ArrayType>(T1) && T1Quals) 3619 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3620 if (isa<ArrayType>(T2) && T2Quals) 3621 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3622 3623 ImplicitConversionSequence::CompareKind Result 3624 = ImplicitConversionSequence::Indistinguishable; 3625 3626 // Objective-C++ ARC: 3627 // Prefer qualification conversions not involving a change in lifetime 3628 // to qualification conversions that do not change lifetime. 3629 if (SCS1.QualificationIncludesObjCLifetime != 3630 SCS2.QualificationIncludesObjCLifetime) { 3631 Result = SCS1.QualificationIncludesObjCLifetime 3632 ? ImplicitConversionSequence::Worse 3633 : ImplicitConversionSequence::Better; 3634 } 3635 3636 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3637 // Within each iteration of the loop, we check the qualifiers to 3638 // determine if this still looks like a qualification 3639 // conversion. Then, if all is well, we unwrap one more level of 3640 // pointers or pointers-to-members and do it all again 3641 // until there are no more pointers or pointers-to-members left 3642 // to unwrap. This essentially mimics what 3643 // IsQualificationConversion does, but here we're checking for a 3644 // strict subset of qualifiers. 3645 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3646 // The qualifiers are the same, so this doesn't tell us anything 3647 // about how the sequences rank. 3648 ; 3649 else if (T2.isMoreQualifiedThan(T1)) { 3650 // T1 has fewer qualifiers, so it could be the better sequence. 3651 if (Result == ImplicitConversionSequence::Worse) 3652 // Neither has qualifiers that are a subset of the other's 3653 // qualifiers. 3654 return ImplicitConversionSequence::Indistinguishable; 3655 3656 Result = ImplicitConversionSequence::Better; 3657 } else if (T1.isMoreQualifiedThan(T2)) { 3658 // T2 has fewer qualifiers, so it could be the better sequence. 3659 if (Result == ImplicitConversionSequence::Better) 3660 // Neither has qualifiers that are a subset of the other's 3661 // qualifiers. 3662 return ImplicitConversionSequence::Indistinguishable; 3663 3664 Result = ImplicitConversionSequence::Worse; 3665 } else { 3666 // Qualifiers are disjoint. 3667 return ImplicitConversionSequence::Indistinguishable; 3668 } 3669 3670 // If the types after this point are equivalent, we're done. 3671 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3672 break; 3673 } 3674 3675 // Check that the winning standard conversion sequence isn't using 3676 // the deprecated string literal array to pointer conversion. 3677 switch (Result) { 3678 case ImplicitConversionSequence::Better: 3679 if (SCS1.DeprecatedStringLiteralToCharPtr) 3680 Result = ImplicitConversionSequence::Indistinguishable; 3681 break; 3682 3683 case ImplicitConversionSequence::Indistinguishable: 3684 break; 3685 3686 case ImplicitConversionSequence::Worse: 3687 if (SCS2.DeprecatedStringLiteralToCharPtr) 3688 Result = ImplicitConversionSequence::Indistinguishable; 3689 break; 3690 } 3691 3692 return Result; 3693 } 3694 3695 /// CompareDerivedToBaseConversions - Compares two standard conversion 3696 /// sequences to determine whether they can be ranked based on their 3697 /// various kinds of derived-to-base conversions (C++ 3698 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3699 /// conversions between Objective-C interface types. 3700 ImplicitConversionSequence::CompareKind 3701 CompareDerivedToBaseConversions(Sema &S, 3702 const StandardConversionSequence& SCS1, 3703 const StandardConversionSequence& SCS2) { 3704 QualType FromType1 = SCS1.getFromType(); 3705 QualType ToType1 = SCS1.getToType(1); 3706 QualType FromType2 = SCS2.getFromType(); 3707 QualType ToType2 = SCS2.getToType(1); 3708 3709 // Adjust the types we're converting from via the array-to-pointer 3710 // conversion, if we need to. 3711 if (SCS1.First == ICK_Array_To_Pointer) 3712 FromType1 = S.Context.getArrayDecayedType(FromType1); 3713 if (SCS2.First == ICK_Array_To_Pointer) 3714 FromType2 = S.Context.getArrayDecayedType(FromType2); 3715 3716 // Canonicalize all of the types. 3717 FromType1 = S.Context.getCanonicalType(FromType1); 3718 ToType1 = S.Context.getCanonicalType(ToType1); 3719 FromType2 = S.Context.getCanonicalType(FromType2); 3720 ToType2 = S.Context.getCanonicalType(ToType2); 3721 3722 // C++ [over.ics.rank]p4b3: 3723 // 3724 // If class B is derived directly or indirectly from class A and 3725 // class C is derived directly or indirectly from B, 3726 // 3727 // Compare based on pointer conversions. 3728 if (SCS1.Second == ICK_Pointer_Conversion && 3729 SCS2.Second == ICK_Pointer_Conversion && 3730 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3731 FromType1->isPointerType() && FromType2->isPointerType() && 3732 ToType1->isPointerType() && ToType2->isPointerType()) { 3733 QualType FromPointee1 3734 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3735 QualType ToPointee1 3736 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3737 QualType FromPointee2 3738 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3739 QualType ToPointee2 3740 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3741 3742 // -- conversion of C* to B* is better than conversion of C* to A*, 3743 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3744 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3745 return ImplicitConversionSequence::Better; 3746 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3747 return ImplicitConversionSequence::Worse; 3748 } 3749 3750 // -- conversion of B* to A* is better than conversion of C* to A*, 3751 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3752 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3753 return ImplicitConversionSequence::Better; 3754 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3755 return ImplicitConversionSequence::Worse; 3756 } 3757 } else if (SCS1.Second == ICK_Pointer_Conversion && 3758 SCS2.Second == ICK_Pointer_Conversion) { 3759 const ObjCObjectPointerType *FromPtr1 3760 = FromType1->getAs<ObjCObjectPointerType>(); 3761 const ObjCObjectPointerType *FromPtr2 3762 = FromType2->getAs<ObjCObjectPointerType>(); 3763 const ObjCObjectPointerType *ToPtr1 3764 = ToType1->getAs<ObjCObjectPointerType>(); 3765 const ObjCObjectPointerType *ToPtr2 3766 = ToType2->getAs<ObjCObjectPointerType>(); 3767 3768 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3769 // Apply the same conversion ranking rules for Objective-C pointer types 3770 // that we do for C++ pointers to class types. However, we employ the 3771 // Objective-C pseudo-subtyping relationship used for assignment of 3772 // Objective-C pointer types. 3773 bool FromAssignLeft 3774 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3775 bool FromAssignRight 3776 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3777 bool ToAssignLeft 3778 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3779 bool ToAssignRight 3780 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3781 3782 // A conversion to an a non-id object pointer type or qualified 'id' 3783 // type is better than a conversion to 'id'. 3784 if (ToPtr1->isObjCIdType() && 3785 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3786 return ImplicitConversionSequence::Worse; 3787 if (ToPtr2->isObjCIdType() && 3788 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3789 return ImplicitConversionSequence::Better; 3790 3791 // A conversion to a non-id object pointer type is better than a 3792 // conversion to a qualified 'id' type 3793 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3794 return ImplicitConversionSequence::Worse; 3795 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3796 return ImplicitConversionSequence::Better; 3797 3798 // A conversion to an a non-Class object pointer type or qualified 'Class' 3799 // type is better than a conversion to 'Class'. 3800 if (ToPtr1->isObjCClassType() && 3801 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3802 return ImplicitConversionSequence::Worse; 3803 if (ToPtr2->isObjCClassType() && 3804 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3805 return ImplicitConversionSequence::Better; 3806 3807 // A conversion to a non-Class object pointer type is better than a 3808 // conversion to a qualified 'Class' type. 3809 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3810 return ImplicitConversionSequence::Worse; 3811 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3812 return ImplicitConversionSequence::Better; 3813 3814 // -- "conversion of C* to B* is better than conversion of C* to A*," 3815 if (S.Context.hasSameType(FromType1, FromType2) && 3816 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3817 (ToAssignLeft != ToAssignRight)) 3818 return ToAssignLeft? ImplicitConversionSequence::Worse 3819 : ImplicitConversionSequence::Better; 3820 3821 // -- "conversion of B* to A* is better than conversion of C* to A*," 3822 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3823 (FromAssignLeft != FromAssignRight)) 3824 return FromAssignLeft? ImplicitConversionSequence::Better 3825 : ImplicitConversionSequence::Worse; 3826 } 3827 } 3828 3829 // Ranking of member-pointer types. 3830 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3831 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3832 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3833 const MemberPointerType * FromMemPointer1 = 3834 FromType1->getAs<MemberPointerType>(); 3835 const MemberPointerType * ToMemPointer1 = 3836 ToType1->getAs<MemberPointerType>(); 3837 const MemberPointerType * FromMemPointer2 = 3838 FromType2->getAs<MemberPointerType>(); 3839 const MemberPointerType * ToMemPointer2 = 3840 ToType2->getAs<MemberPointerType>(); 3841 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3842 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3843 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3844 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3845 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3846 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3847 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3848 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3849 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3850 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3851 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3852 return ImplicitConversionSequence::Worse; 3853 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3854 return ImplicitConversionSequence::Better; 3855 } 3856 // conversion of B::* to C::* is better than conversion of A::* to C::* 3857 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3858 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3859 return ImplicitConversionSequence::Better; 3860 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3861 return ImplicitConversionSequence::Worse; 3862 } 3863 } 3864 3865 if (SCS1.Second == ICK_Derived_To_Base) { 3866 // -- conversion of C to B is better than conversion of C to A, 3867 // -- binding of an expression of type C to a reference of type 3868 // B& is better than binding an expression of type C to a 3869 // reference of type A&, 3870 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3871 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3872 if (S.IsDerivedFrom(ToType1, ToType2)) 3873 return ImplicitConversionSequence::Better; 3874 else if (S.IsDerivedFrom(ToType2, ToType1)) 3875 return ImplicitConversionSequence::Worse; 3876 } 3877 3878 // -- conversion of B to A is better than conversion of C to A. 3879 // -- binding of an expression of type B to a reference of type 3880 // A& is better than binding an expression of type C to a 3881 // reference of type A&, 3882 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3883 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3884 if (S.IsDerivedFrom(FromType2, FromType1)) 3885 return ImplicitConversionSequence::Better; 3886 else if (S.IsDerivedFrom(FromType1, FromType2)) 3887 return ImplicitConversionSequence::Worse; 3888 } 3889 } 3890 3891 return ImplicitConversionSequence::Indistinguishable; 3892 } 3893 3894 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3895 /// determine whether they are reference-related, 3896 /// reference-compatible, reference-compatible with added 3897 /// qualification, or incompatible, for use in C++ initialization by 3898 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3899 /// type, and the first type (T1) is the pointee type of the reference 3900 /// type being initialized. 3901 Sema::ReferenceCompareResult 3902 Sema::CompareReferenceRelationship(SourceLocation Loc, 3903 QualType OrigT1, QualType OrigT2, 3904 bool &DerivedToBase, 3905 bool &ObjCConversion, 3906 bool &ObjCLifetimeConversion) { 3907 assert(!OrigT1->isReferenceType() && 3908 "T1 must be the pointee type of the reference type"); 3909 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3910 3911 QualType T1 = Context.getCanonicalType(OrigT1); 3912 QualType T2 = Context.getCanonicalType(OrigT2); 3913 Qualifiers T1Quals, T2Quals; 3914 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3915 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3916 3917 // C++ [dcl.init.ref]p4: 3918 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3919 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3920 // T1 is a base class of T2. 3921 DerivedToBase = false; 3922 ObjCConversion = false; 3923 ObjCLifetimeConversion = false; 3924 if (UnqualT1 == UnqualT2) { 3925 // Nothing to do. 3926 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3927 IsDerivedFrom(UnqualT2, UnqualT1)) 3928 DerivedToBase = true; 3929 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3930 UnqualT2->isObjCObjectOrInterfaceType() && 3931 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3932 ObjCConversion = true; 3933 else 3934 return Ref_Incompatible; 3935 3936 // At this point, we know that T1 and T2 are reference-related (at 3937 // least). 3938 3939 // If the type is an array type, promote the element qualifiers to the type 3940 // for comparison. 3941 if (isa<ArrayType>(T1) && T1Quals) 3942 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3943 if (isa<ArrayType>(T2) && T2Quals) 3944 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3945 3946 // C++ [dcl.init.ref]p4: 3947 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3948 // reference-related to T2 and cv1 is the same cv-qualification 3949 // as, or greater cv-qualification than, cv2. For purposes of 3950 // overload resolution, cases for which cv1 is greater 3951 // cv-qualification than cv2 are identified as 3952 // reference-compatible with added qualification (see 13.3.3.2). 3953 // 3954 // Note that we also require equivalence of Objective-C GC and address-space 3955 // qualifiers when performing these computations, so that e.g., an int in 3956 // address space 1 is not reference-compatible with an int in address 3957 // space 2. 3958 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3959 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3960 T1Quals.removeObjCLifetime(); 3961 T2Quals.removeObjCLifetime(); 3962 ObjCLifetimeConversion = true; 3963 } 3964 3965 if (T1Quals == T2Quals) 3966 return Ref_Compatible; 3967 else if (T1Quals.compatiblyIncludes(T2Quals)) 3968 return Ref_Compatible_With_Added_Qualification; 3969 else 3970 return Ref_Related; 3971 } 3972 3973 /// \brief Look for a user-defined conversion to an value reference-compatible 3974 /// with DeclType. Return true if something definite is found. 3975 static bool 3976 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3977 QualType DeclType, SourceLocation DeclLoc, 3978 Expr *Init, QualType T2, bool AllowRvalues, 3979 bool AllowExplicit) { 3980 assert(T2->isRecordType() && "Can only find conversions of record types."); 3981 CXXRecordDecl *T2RecordDecl 3982 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3983 3984 OverloadCandidateSet CandidateSet(DeclLoc); 3985 std::pair<CXXRecordDecl::conversion_iterator, 3986 CXXRecordDecl::conversion_iterator> 3987 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 3988 for (CXXRecordDecl::conversion_iterator 3989 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3990 NamedDecl *D = *I; 3991 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3992 if (isa<UsingShadowDecl>(D)) 3993 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3994 3995 FunctionTemplateDecl *ConvTemplate 3996 = dyn_cast<FunctionTemplateDecl>(D); 3997 CXXConversionDecl *Conv; 3998 if (ConvTemplate) 3999 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4000 else 4001 Conv = cast<CXXConversionDecl>(D); 4002 4003 // If this is an explicit conversion, and we're not allowed to consider 4004 // explicit conversions, skip it. 4005 if (!AllowExplicit && Conv->isExplicit()) 4006 continue; 4007 4008 if (AllowRvalues) { 4009 bool DerivedToBase = false; 4010 bool ObjCConversion = false; 4011 bool ObjCLifetimeConversion = false; 4012 4013 // If we are initializing an rvalue reference, don't permit conversion 4014 // functions that return lvalues. 4015 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4016 const ReferenceType *RefType 4017 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4018 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4019 continue; 4020 } 4021 4022 if (!ConvTemplate && 4023 S.CompareReferenceRelationship( 4024 DeclLoc, 4025 Conv->getConversionType().getNonReferenceType() 4026 .getUnqualifiedType(), 4027 DeclType.getNonReferenceType().getUnqualifiedType(), 4028 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4029 Sema::Ref_Incompatible) 4030 continue; 4031 } else { 4032 // If the conversion function doesn't return a reference type, 4033 // it can't be considered for this conversion. An rvalue reference 4034 // is only acceptable if its referencee is a function type. 4035 4036 const ReferenceType *RefType = 4037 Conv->getConversionType()->getAs<ReferenceType>(); 4038 if (!RefType || 4039 (!RefType->isLValueReferenceType() && 4040 !RefType->getPointeeType()->isFunctionType())) 4041 continue; 4042 } 4043 4044 if (ConvTemplate) 4045 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4046 Init, DeclType, CandidateSet); 4047 else 4048 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4049 DeclType, CandidateSet); 4050 } 4051 4052 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4053 4054 OverloadCandidateSet::iterator Best; 4055 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4056 case OR_Success: 4057 // C++ [over.ics.ref]p1: 4058 // 4059 // [...] If the parameter binds directly to the result of 4060 // applying a conversion function to the argument 4061 // expression, the implicit conversion sequence is a 4062 // user-defined conversion sequence (13.3.3.1.2), with the 4063 // second standard conversion sequence either an identity 4064 // conversion or, if the conversion function returns an 4065 // entity of a type that is a derived class of the parameter 4066 // type, a derived-to-base Conversion. 4067 if (!Best->FinalConversion.DirectBinding) 4068 return false; 4069 4070 ICS.setUserDefined(); 4071 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4072 ICS.UserDefined.After = Best->FinalConversion; 4073 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4074 ICS.UserDefined.ConversionFunction = Best->Function; 4075 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4076 ICS.UserDefined.EllipsisConversion = false; 4077 assert(ICS.UserDefined.After.ReferenceBinding && 4078 ICS.UserDefined.After.DirectBinding && 4079 "Expected a direct reference binding!"); 4080 return true; 4081 4082 case OR_Ambiguous: 4083 ICS.setAmbiguous(); 4084 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4085 Cand != CandidateSet.end(); ++Cand) 4086 if (Cand->Viable) 4087 ICS.Ambiguous.addConversion(Cand->Function); 4088 return true; 4089 4090 case OR_No_Viable_Function: 4091 case OR_Deleted: 4092 // There was no suitable conversion, or we found a deleted 4093 // conversion; continue with other checks. 4094 return false; 4095 } 4096 4097 llvm_unreachable("Invalid OverloadResult!"); 4098 } 4099 4100 /// \brief Compute an implicit conversion sequence for reference 4101 /// initialization. 4102 static ImplicitConversionSequence 4103 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4104 SourceLocation DeclLoc, 4105 bool SuppressUserConversions, 4106 bool AllowExplicit) { 4107 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4108 4109 // Most paths end in a failed conversion. 4110 ImplicitConversionSequence ICS; 4111 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4112 4113 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4114 QualType T2 = Init->getType(); 4115 4116 // If the initializer is the address of an overloaded function, try 4117 // to resolve the overloaded function. If all goes well, T2 is the 4118 // type of the resulting function. 4119 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4120 DeclAccessPair Found; 4121 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4122 false, Found)) 4123 T2 = Fn->getType(); 4124 } 4125 4126 // Compute some basic properties of the types and the initializer. 4127 bool isRValRef = DeclType->isRValueReferenceType(); 4128 bool DerivedToBase = false; 4129 bool ObjCConversion = false; 4130 bool ObjCLifetimeConversion = false; 4131 Expr::Classification InitCategory = Init->Classify(S.Context); 4132 Sema::ReferenceCompareResult RefRelationship 4133 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4134 ObjCConversion, ObjCLifetimeConversion); 4135 4136 4137 // C++0x [dcl.init.ref]p5: 4138 // A reference to type "cv1 T1" is initialized by an expression 4139 // of type "cv2 T2" as follows: 4140 4141 // -- If reference is an lvalue reference and the initializer expression 4142 if (!isRValRef) { 4143 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4144 // reference-compatible with "cv2 T2," or 4145 // 4146 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4147 if (InitCategory.isLValue() && 4148 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4149 // C++ [over.ics.ref]p1: 4150 // When a parameter of reference type binds directly (8.5.3) 4151 // to an argument expression, the implicit conversion sequence 4152 // is the identity conversion, unless the argument expression 4153 // has a type that is a derived class of the parameter type, 4154 // in which case the implicit conversion sequence is a 4155 // derived-to-base Conversion (13.3.3.1). 4156 ICS.setStandard(); 4157 ICS.Standard.First = ICK_Identity; 4158 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4159 : ObjCConversion? ICK_Compatible_Conversion 4160 : ICK_Identity; 4161 ICS.Standard.Third = ICK_Identity; 4162 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4163 ICS.Standard.setToType(0, T2); 4164 ICS.Standard.setToType(1, T1); 4165 ICS.Standard.setToType(2, T1); 4166 ICS.Standard.ReferenceBinding = true; 4167 ICS.Standard.DirectBinding = true; 4168 ICS.Standard.IsLvalueReference = !isRValRef; 4169 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4170 ICS.Standard.BindsToRvalue = false; 4171 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4172 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4173 ICS.Standard.CopyConstructor = 0; 4174 4175 // Nothing more to do: the inaccessibility/ambiguity check for 4176 // derived-to-base conversions is suppressed when we're 4177 // computing the implicit conversion sequence (C++ 4178 // [over.best.ics]p2). 4179 return ICS; 4180 } 4181 4182 // -- has a class type (i.e., T2 is a class type), where T1 is 4183 // not reference-related to T2, and can be implicitly 4184 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4185 // is reference-compatible with "cv3 T3" 92) (this 4186 // conversion is selected by enumerating the applicable 4187 // conversion functions (13.3.1.6) and choosing the best 4188 // one through overload resolution (13.3)), 4189 if (!SuppressUserConversions && T2->isRecordType() && 4190 !S.RequireCompleteType(DeclLoc, T2, 0) && 4191 RefRelationship == Sema::Ref_Incompatible) { 4192 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4193 Init, T2, /*AllowRvalues=*/false, 4194 AllowExplicit)) 4195 return ICS; 4196 } 4197 } 4198 4199 // -- Otherwise, the reference shall be an lvalue reference to a 4200 // non-volatile const type (i.e., cv1 shall be const), or the reference 4201 // shall be an rvalue reference. 4202 // 4203 // We actually handle one oddity of C++ [over.ics.ref] at this 4204 // point, which is that, due to p2 (which short-circuits reference 4205 // binding by only attempting a simple conversion for non-direct 4206 // bindings) and p3's strange wording, we allow a const volatile 4207 // reference to bind to an rvalue. Hence the check for the presence 4208 // of "const" rather than checking for "const" being the only 4209 // qualifier. 4210 // This is also the point where rvalue references and lvalue inits no longer 4211 // go together. 4212 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4213 return ICS; 4214 4215 // -- If the initializer expression 4216 // 4217 // -- is an xvalue, class prvalue, array prvalue or function 4218 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4219 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4220 (InitCategory.isXValue() || 4221 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4222 (InitCategory.isLValue() && T2->isFunctionType()))) { 4223 ICS.setStandard(); 4224 ICS.Standard.First = ICK_Identity; 4225 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4226 : ObjCConversion? ICK_Compatible_Conversion 4227 : ICK_Identity; 4228 ICS.Standard.Third = ICK_Identity; 4229 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4230 ICS.Standard.setToType(0, T2); 4231 ICS.Standard.setToType(1, T1); 4232 ICS.Standard.setToType(2, T1); 4233 ICS.Standard.ReferenceBinding = true; 4234 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4235 // binding unless we're binding to a class prvalue. 4236 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4237 // allow the use of rvalue references in C++98/03 for the benefit of 4238 // standard library implementors; therefore, we need the xvalue check here. 4239 ICS.Standard.DirectBinding = 4240 S.getLangOpts().CPlusPlus11 || 4241 (InitCategory.isPRValue() && !T2->isRecordType()); 4242 ICS.Standard.IsLvalueReference = !isRValRef; 4243 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4244 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4245 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4246 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4247 ICS.Standard.CopyConstructor = 0; 4248 return ICS; 4249 } 4250 4251 // -- has a class type (i.e., T2 is a class type), where T1 is not 4252 // reference-related to T2, and can be implicitly converted to 4253 // an xvalue, class prvalue, or function lvalue of type 4254 // "cv3 T3", where "cv1 T1" is reference-compatible with 4255 // "cv3 T3", 4256 // 4257 // then the reference is bound to the value of the initializer 4258 // expression in the first case and to the result of the conversion 4259 // in the second case (or, in either case, to an appropriate base 4260 // class subobject). 4261 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4262 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4263 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4264 Init, T2, /*AllowRvalues=*/true, 4265 AllowExplicit)) { 4266 // In the second case, if the reference is an rvalue reference 4267 // and the second standard conversion sequence of the 4268 // user-defined conversion sequence includes an lvalue-to-rvalue 4269 // conversion, the program is ill-formed. 4270 if (ICS.isUserDefined() && isRValRef && 4271 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4272 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4273 4274 return ICS; 4275 } 4276 4277 // -- Otherwise, a temporary of type "cv1 T1" is created and 4278 // initialized from the initializer expression using the 4279 // rules for a non-reference copy initialization (8.5). The 4280 // reference is then bound to the temporary. If T1 is 4281 // reference-related to T2, cv1 must be the same 4282 // cv-qualification as, or greater cv-qualification than, 4283 // cv2; otherwise, the program is ill-formed. 4284 if (RefRelationship == Sema::Ref_Related) { 4285 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4286 // we would be reference-compatible or reference-compatible with 4287 // added qualification. But that wasn't the case, so the reference 4288 // initialization fails. 4289 // 4290 // Note that we only want to check address spaces and cvr-qualifiers here. 4291 // ObjC GC and lifetime qualifiers aren't important. 4292 Qualifiers T1Quals = T1.getQualifiers(); 4293 Qualifiers T2Quals = T2.getQualifiers(); 4294 T1Quals.removeObjCGCAttr(); 4295 T1Quals.removeObjCLifetime(); 4296 T2Quals.removeObjCGCAttr(); 4297 T2Quals.removeObjCLifetime(); 4298 if (!T1Quals.compatiblyIncludes(T2Quals)) 4299 return ICS; 4300 } 4301 4302 // If at least one of the types is a class type, the types are not 4303 // related, and we aren't allowed any user conversions, the 4304 // reference binding fails. This case is important for breaking 4305 // recursion, since TryImplicitConversion below will attempt to 4306 // create a temporary through the use of a copy constructor. 4307 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4308 (T1->isRecordType() || T2->isRecordType())) 4309 return ICS; 4310 4311 // If T1 is reference-related to T2 and the reference is an rvalue 4312 // reference, the initializer expression shall not be an lvalue. 4313 if (RefRelationship >= Sema::Ref_Related && 4314 isRValRef && Init->Classify(S.Context).isLValue()) 4315 return ICS; 4316 4317 // C++ [over.ics.ref]p2: 4318 // When a parameter of reference type is not bound directly to 4319 // an argument expression, the conversion sequence is the one 4320 // required to convert the argument expression to the 4321 // underlying type of the reference according to 4322 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4323 // to copy-initializing a temporary of the underlying type with 4324 // the argument expression. Any difference in top-level 4325 // cv-qualification is subsumed by the initialization itself 4326 // and does not constitute a conversion. 4327 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4328 /*AllowExplicit=*/false, 4329 /*InOverloadResolution=*/false, 4330 /*CStyle=*/false, 4331 /*AllowObjCWritebackConversion=*/false); 4332 4333 // Of course, that's still a reference binding. 4334 if (ICS.isStandard()) { 4335 ICS.Standard.ReferenceBinding = true; 4336 ICS.Standard.IsLvalueReference = !isRValRef; 4337 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4338 ICS.Standard.BindsToRvalue = true; 4339 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4340 ICS.Standard.ObjCLifetimeConversionBinding = false; 4341 } else if (ICS.isUserDefined()) { 4342 // Don't allow rvalue references to bind to lvalues. 4343 if (DeclType->isRValueReferenceType()) { 4344 if (const ReferenceType *RefType 4345 = ICS.UserDefined.ConversionFunction->getResultType() 4346 ->getAs<LValueReferenceType>()) { 4347 if (!RefType->getPointeeType()->isFunctionType()) { 4348 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4349 DeclType); 4350 return ICS; 4351 } 4352 } 4353 } 4354 4355 ICS.UserDefined.After.ReferenceBinding = true; 4356 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4357 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4358 ICS.UserDefined.After.BindsToRvalue = true; 4359 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4360 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4361 } 4362 4363 return ICS; 4364 } 4365 4366 static ImplicitConversionSequence 4367 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4368 bool SuppressUserConversions, 4369 bool InOverloadResolution, 4370 bool AllowObjCWritebackConversion, 4371 bool AllowExplicit = false); 4372 4373 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4374 /// initializer list From. 4375 static ImplicitConversionSequence 4376 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4377 bool SuppressUserConversions, 4378 bool InOverloadResolution, 4379 bool AllowObjCWritebackConversion) { 4380 // C++11 [over.ics.list]p1: 4381 // When an argument is an initializer list, it is not an expression and 4382 // special rules apply for converting it to a parameter type. 4383 4384 ImplicitConversionSequence Result; 4385 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4386 Result.setListInitializationSequence(); 4387 4388 // We need a complete type for what follows. Incomplete types can never be 4389 // initialized from init lists. 4390 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4391 return Result; 4392 4393 // C++11 [over.ics.list]p2: 4394 // If the parameter type is std::initializer_list<X> or "array of X" and 4395 // all the elements can be implicitly converted to X, the implicit 4396 // conversion sequence is the worst conversion necessary to convert an 4397 // element of the list to X. 4398 bool toStdInitializerList = false; 4399 QualType X; 4400 if (ToType->isArrayType()) 4401 X = S.Context.getAsArrayType(ToType)->getElementType(); 4402 else 4403 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4404 if (!X.isNull()) { 4405 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4406 Expr *Init = From->getInit(i); 4407 ImplicitConversionSequence ICS = 4408 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4409 InOverloadResolution, 4410 AllowObjCWritebackConversion); 4411 // If a single element isn't convertible, fail. 4412 if (ICS.isBad()) { 4413 Result = ICS; 4414 break; 4415 } 4416 // Otherwise, look for the worst conversion. 4417 if (Result.isBad() || 4418 CompareImplicitConversionSequences(S, ICS, Result) == 4419 ImplicitConversionSequence::Worse) 4420 Result = ICS; 4421 } 4422 4423 // For an empty list, we won't have computed any conversion sequence. 4424 // Introduce the identity conversion sequence. 4425 if (From->getNumInits() == 0) { 4426 Result.setStandard(); 4427 Result.Standard.setAsIdentityConversion(); 4428 Result.Standard.setFromType(ToType); 4429 Result.Standard.setAllToTypes(ToType); 4430 } 4431 4432 Result.setListInitializationSequence(); 4433 Result.setStdInitializerListElement(toStdInitializerList); 4434 return Result; 4435 } 4436 4437 // C++11 [over.ics.list]p3: 4438 // Otherwise, if the parameter is a non-aggregate class X and overload 4439 // resolution chooses a single best constructor [...] the implicit 4440 // conversion sequence is a user-defined conversion sequence. If multiple 4441 // constructors are viable but none is better than the others, the 4442 // implicit conversion sequence is a user-defined conversion sequence. 4443 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4444 // This function can deal with initializer lists. 4445 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4446 /*AllowExplicit=*/false, 4447 InOverloadResolution, /*CStyle=*/false, 4448 AllowObjCWritebackConversion); 4449 Result.setListInitializationSequence(); 4450 return Result; 4451 } 4452 4453 // C++11 [over.ics.list]p4: 4454 // Otherwise, if the parameter has an aggregate type which can be 4455 // initialized from the initializer list [...] the implicit conversion 4456 // sequence is a user-defined conversion sequence. 4457 if (ToType->isAggregateType()) { 4458 // Type is an aggregate, argument is an init list. At this point it comes 4459 // down to checking whether the initialization works. 4460 // FIXME: Find out whether this parameter is consumed or not. 4461 InitializedEntity Entity = 4462 InitializedEntity::InitializeParameter(S.Context, ToType, 4463 /*Consumed=*/false); 4464 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4465 Result.setUserDefined(); 4466 Result.UserDefined.Before.setAsIdentityConversion(); 4467 // Initializer lists don't have a type. 4468 Result.UserDefined.Before.setFromType(QualType()); 4469 Result.UserDefined.Before.setAllToTypes(QualType()); 4470 4471 Result.UserDefined.After.setAsIdentityConversion(); 4472 Result.UserDefined.After.setFromType(ToType); 4473 Result.UserDefined.After.setAllToTypes(ToType); 4474 Result.UserDefined.ConversionFunction = 0; 4475 } 4476 return Result; 4477 } 4478 4479 // C++11 [over.ics.list]p5: 4480 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4481 if (ToType->isReferenceType()) { 4482 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4483 // mention initializer lists in any way. So we go by what list- 4484 // initialization would do and try to extrapolate from that. 4485 4486 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4487 4488 // If the initializer list has a single element that is reference-related 4489 // to the parameter type, we initialize the reference from that. 4490 if (From->getNumInits() == 1) { 4491 Expr *Init = From->getInit(0); 4492 4493 QualType T2 = Init->getType(); 4494 4495 // If the initializer is the address of an overloaded function, try 4496 // to resolve the overloaded function. If all goes well, T2 is the 4497 // type of the resulting function. 4498 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4499 DeclAccessPair Found; 4500 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4501 Init, ToType, false, Found)) 4502 T2 = Fn->getType(); 4503 } 4504 4505 // Compute some basic properties of the types and the initializer. 4506 bool dummy1 = false; 4507 bool dummy2 = false; 4508 bool dummy3 = false; 4509 Sema::ReferenceCompareResult RefRelationship 4510 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4511 dummy2, dummy3); 4512 4513 if (RefRelationship >= Sema::Ref_Related) 4514 return TryReferenceInit(S, Init, ToType, 4515 /*FIXME:*/From->getLocStart(), 4516 SuppressUserConversions, 4517 /*AllowExplicit=*/false); 4518 } 4519 4520 // Otherwise, we bind the reference to a temporary created from the 4521 // initializer list. 4522 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4523 InOverloadResolution, 4524 AllowObjCWritebackConversion); 4525 if (Result.isFailure()) 4526 return Result; 4527 assert(!Result.isEllipsis() && 4528 "Sub-initialization cannot result in ellipsis conversion."); 4529 4530 // Can we even bind to a temporary? 4531 if (ToType->isRValueReferenceType() || 4532 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4533 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4534 Result.UserDefined.After; 4535 SCS.ReferenceBinding = true; 4536 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4537 SCS.BindsToRvalue = true; 4538 SCS.BindsToFunctionLvalue = false; 4539 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4540 SCS.ObjCLifetimeConversionBinding = false; 4541 } else 4542 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4543 From, ToType); 4544 return Result; 4545 } 4546 4547 // C++11 [over.ics.list]p6: 4548 // Otherwise, if the parameter type is not a class: 4549 if (!ToType->isRecordType()) { 4550 // - if the initializer list has one element, the implicit conversion 4551 // sequence is the one required to convert the element to the 4552 // parameter type. 4553 unsigned NumInits = From->getNumInits(); 4554 if (NumInits == 1) 4555 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4556 SuppressUserConversions, 4557 InOverloadResolution, 4558 AllowObjCWritebackConversion); 4559 // - if the initializer list has no elements, the implicit conversion 4560 // sequence is the identity conversion. 4561 else if (NumInits == 0) { 4562 Result.setStandard(); 4563 Result.Standard.setAsIdentityConversion(); 4564 Result.Standard.setFromType(ToType); 4565 Result.Standard.setAllToTypes(ToType); 4566 } 4567 Result.setListInitializationSequence(); 4568 return Result; 4569 } 4570 4571 // C++11 [over.ics.list]p7: 4572 // In all cases other than those enumerated above, no conversion is possible 4573 return Result; 4574 } 4575 4576 /// TryCopyInitialization - Try to copy-initialize a value of type 4577 /// ToType from the expression From. Return the implicit conversion 4578 /// sequence required to pass this argument, which may be a bad 4579 /// conversion sequence (meaning that the argument cannot be passed to 4580 /// a parameter of this type). If @p SuppressUserConversions, then we 4581 /// do not permit any user-defined conversion sequences. 4582 static ImplicitConversionSequence 4583 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4584 bool SuppressUserConversions, 4585 bool InOverloadResolution, 4586 bool AllowObjCWritebackConversion, 4587 bool AllowExplicit) { 4588 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4589 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4590 InOverloadResolution,AllowObjCWritebackConversion); 4591 4592 if (ToType->isReferenceType()) 4593 return TryReferenceInit(S, From, ToType, 4594 /*FIXME:*/From->getLocStart(), 4595 SuppressUserConversions, 4596 AllowExplicit); 4597 4598 return TryImplicitConversion(S, From, ToType, 4599 SuppressUserConversions, 4600 /*AllowExplicit=*/false, 4601 InOverloadResolution, 4602 /*CStyle=*/false, 4603 AllowObjCWritebackConversion); 4604 } 4605 4606 static bool TryCopyInitialization(const CanQualType FromQTy, 4607 const CanQualType ToQTy, 4608 Sema &S, 4609 SourceLocation Loc, 4610 ExprValueKind FromVK) { 4611 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4612 ImplicitConversionSequence ICS = 4613 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4614 4615 return !ICS.isBad(); 4616 } 4617 4618 /// TryObjectArgumentInitialization - Try to initialize the object 4619 /// parameter of the given member function (@c Method) from the 4620 /// expression @p From. 4621 static ImplicitConversionSequence 4622 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4623 Expr::Classification FromClassification, 4624 CXXMethodDecl *Method, 4625 CXXRecordDecl *ActingContext) { 4626 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4627 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4628 // const volatile object. 4629 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4630 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4631 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4632 4633 // Set up the conversion sequence as a "bad" conversion, to allow us 4634 // to exit early. 4635 ImplicitConversionSequence ICS; 4636 4637 // We need to have an object of class type. 4638 QualType FromType = OrigFromType; 4639 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4640 FromType = PT->getPointeeType(); 4641 4642 // When we had a pointer, it's implicitly dereferenced, so we 4643 // better have an lvalue. 4644 assert(FromClassification.isLValue()); 4645 } 4646 4647 assert(FromType->isRecordType()); 4648 4649 // C++0x [over.match.funcs]p4: 4650 // For non-static member functions, the type of the implicit object 4651 // parameter is 4652 // 4653 // - "lvalue reference to cv X" for functions declared without a 4654 // ref-qualifier or with the & ref-qualifier 4655 // - "rvalue reference to cv X" for functions declared with the && 4656 // ref-qualifier 4657 // 4658 // where X is the class of which the function is a member and cv is the 4659 // cv-qualification on the member function declaration. 4660 // 4661 // However, when finding an implicit conversion sequence for the argument, we 4662 // are not allowed to create temporaries or perform user-defined conversions 4663 // (C++ [over.match.funcs]p5). We perform a simplified version of 4664 // reference binding here, that allows class rvalues to bind to 4665 // non-constant references. 4666 4667 // First check the qualifiers. 4668 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4669 if (ImplicitParamType.getCVRQualifiers() 4670 != FromTypeCanon.getLocalCVRQualifiers() && 4671 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4672 ICS.setBad(BadConversionSequence::bad_qualifiers, 4673 OrigFromType, ImplicitParamType); 4674 return ICS; 4675 } 4676 4677 // Check that we have either the same type or a derived type. It 4678 // affects the conversion rank. 4679 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4680 ImplicitConversionKind SecondKind; 4681 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4682 SecondKind = ICK_Identity; 4683 } else if (S.IsDerivedFrom(FromType, ClassType)) 4684 SecondKind = ICK_Derived_To_Base; 4685 else { 4686 ICS.setBad(BadConversionSequence::unrelated_class, 4687 FromType, ImplicitParamType); 4688 return ICS; 4689 } 4690 4691 // Check the ref-qualifier. 4692 switch (Method->getRefQualifier()) { 4693 case RQ_None: 4694 // Do nothing; we don't care about lvalueness or rvalueness. 4695 break; 4696 4697 case RQ_LValue: 4698 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4699 // non-const lvalue reference cannot bind to an rvalue 4700 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4701 ImplicitParamType); 4702 return ICS; 4703 } 4704 break; 4705 4706 case RQ_RValue: 4707 if (!FromClassification.isRValue()) { 4708 // rvalue reference cannot bind to an lvalue 4709 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4710 ImplicitParamType); 4711 return ICS; 4712 } 4713 break; 4714 } 4715 4716 // Success. Mark this as a reference binding. 4717 ICS.setStandard(); 4718 ICS.Standard.setAsIdentityConversion(); 4719 ICS.Standard.Second = SecondKind; 4720 ICS.Standard.setFromType(FromType); 4721 ICS.Standard.setAllToTypes(ImplicitParamType); 4722 ICS.Standard.ReferenceBinding = true; 4723 ICS.Standard.DirectBinding = true; 4724 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4725 ICS.Standard.BindsToFunctionLvalue = false; 4726 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4727 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4728 = (Method->getRefQualifier() == RQ_None); 4729 return ICS; 4730 } 4731 4732 /// PerformObjectArgumentInitialization - Perform initialization of 4733 /// the implicit object parameter for the given Method with the given 4734 /// expression. 4735 ExprResult 4736 Sema::PerformObjectArgumentInitialization(Expr *From, 4737 NestedNameSpecifier *Qualifier, 4738 NamedDecl *FoundDecl, 4739 CXXMethodDecl *Method) { 4740 QualType FromRecordType, DestType; 4741 QualType ImplicitParamRecordType = 4742 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4743 4744 Expr::Classification FromClassification; 4745 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4746 FromRecordType = PT->getPointeeType(); 4747 DestType = Method->getThisType(Context); 4748 FromClassification = Expr::Classification::makeSimpleLValue(); 4749 } else { 4750 FromRecordType = From->getType(); 4751 DestType = ImplicitParamRecordType; 4752 FromClassification = From->Classify(Context); 4753 } 4754 4755 // Note that we always use the true parent context when performing 4756 // the actual argument initialization. 4757 ImplicitConversionSequence ICS 4758 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4759 Method, Method->getParent()); 4760 if (ICS.isBad()) { 4761 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4762 Qualifiers FromQs = FromRecordType.getQualifiers(); 4763 Qualifiers ToQs = DestType.getQualifiers(); 4764 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4765 if (CVR) { 4766 Diag(From->getLocStart(), 4767 diag::err_member_function_call_bad_cvr) 4768 << Method->getDeclName() << FromRecordType << (CVR - 1) 4769 << From->getSourceRange(); 4770 Diag(Method->getLocation(), diag::note_previous_decl) 4771 << Method->getDeclName(); 4772 return ExprError(); 4773 } 4774 } 4775 4776 return Diag(From->getLocStart(), 4777 diag::err_implicit_object_parameter_init) 4778 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4779 } 4780 4781 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4782 ExprResult FromRes = 4783 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4784 if (FromRes.isInvalid()) 4785 return ExprError(); 4786 From = FromRes.take(); 4787 } 4788 4789 if (!Context.hasSameType(From->getType(), DestType)) 4790 From = ImpCastExprToType(From, DestType, CK_NoOp, 4791 From->getValueKind()).take(); 4792 return Owned(From); 4793 } 4794 4795 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4796 /// expression From to bool (C++0x [conv]p3). 4797 static ImplicitConversionSequence 4798 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4799 // FIXME: This is pretty broken. 4800 return TryImplicitConversion(S, From, S.Context.BoolTy, 4801 // FIXME: Are these flags correct? 4802 /*SuppressUserConversions=*/false, 4803 /*AllowExplicit=*/true, 4804 /*InOverloadResolution=*/false, 4805 /*CStyle=*/false, 4806 /*AllowObjCWritebackConversion=*/false); 4807 } 4808 4809 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4810 /// of the expression From to bool (C++0x [conv]p3). 4811 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4812 if (checkPlaceholderForOverload(*this, From)) 4813 return ExprError(); 4814 4815 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4816 if (!ICS.isBad()) 4817 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4818 4819 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4820 return Diag(From->getLocStart(), 4821 diag::err_typecheck_bool_condition) 4822 << From->getType() << From->getSourceRange(); 4823 return ExprError(); 4824 } 4825 4826 /// Check that the specified conversion is permitted in a converted constant 4827 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4828 /// is acceptable. 4829 static bool CheckConvertedConstantConversions(Sema &S, 4830 StandardConversionSequence &SCS) { 4831 // Since we know that the target type is an integral or unscoped enumeration 4832 // type, most conversion kinds are impossible. All possible First and Third 4833 // conversions are fine. 4834 switch (SCS.Second) { 4835 case ICK_Identity: 4836 case ICK_Integral_Promotion: 4837 case ICK_Integral_Conversion: 4838 return true; 4839 4840 case ICK_Boolean_Conversion: 4841 // Conversion from an integral or unscoped enumeration type to bool is 4842 // classified as ICK_Boolean_Conversion, but it's also an integral 4843 // conversion, so it's permitted in a converted constant expression. 4844 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4845 SCS.getToType(2)->isBooleanType(); 4846 4847 case ICK_Floating_Integral: 4848 case ICK_Complex_Real: 4849 return false; 4850 4851 case ICK_Lvalue_To_Rvalue: 4852 case ICK_Array_To_Pointer: 4853 case ICK_Function_To_Pointer: 4854 case ICK_NoReturn_Adjustment: 4855 case ICK_Qualification: 4856 case ICK_Compatible_Conversion: 4857 case ICK_Vector_Conversion: 4858 case ICK_Vector_Splat: 4859 case ICK_Derived_To_Base: 4860 case ICK_Pointer_Conversion: 4861 case ICK_Pointer_Member: 4862 case ICK_Block_Pointer_Conversion: 4863 case ICK_Writeback_Conversion: 4864 case ICK_Floating_Promotion: 4865 case ICK_Complex_Promotion: 4866 case ICK_Complex_Conversion: 4867 case ICK_Floating_Conversion: 4868 case ICK_TransparentUnionConversion: 4869 llvm_unreachable("unexpected second conversion kind"); 4870 4871 case ICK_Num_Conversion_Kinds: 4872 break; 4873 } 4874 4875 llvm_unreachable("unknown conversion kind"); 4876 } 4877 4878 /// CheckConvertedConstantExpression - Check that the expression From is a 4879 /// converted constant expression of type T, perform the conversion and produce 4880 /// the converted expression, per C++11 [expr.const]p3. 4881 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4882 llvm::APSInt &Value, 4883 CCEKind CCE) { 4884 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4885 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4886 4887 if (checkPlaceholderForOverload(*this, From)) 4888 return ExprError(); 4889 4890 // C++11 [expr.const]p3 with proposed wording fixes: 4891 // A converted constant expression of type T is a core constant expression, 4892 // implicitly converted to a prvalue of type T, where the converted 4893 // expression is a literal constant expression and the implicit conversion 4894 // sequence contains only user-defined conversions, lvalue-to-rvalue 4895 // conversions, integral promotions, and integral conversions other than 4896 // narrowing conversions. 4897 ImplicitConversionSequence ICS = 4898 TryImplicitConversion(From, T, 4899 /*SuppressUserConversions=*/false, 4900 /*AllowExplicit=*/false, 4901 /*InOverloadResolution=*/false, 4902 /*CStyle=*/false, 4903 /*AllowObjcWritebackConversion=*/false); 4904 StandardConversionSequence *SCS = 0; 4905 switch (ICS.getKind()) { 4906 case ImplicitConversionSequence::StandardConversion: 4907 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4908 return Diag(From->getLocStart(), 4909 diag::err_typecheck_converted_constant_expression_disallowed) 4910 << From->getType() << From->getSourceRange() << T; 4911 SCS = &ICS.Standard; 4912 break; 4913 case ImplicitConversionSequence::UserDefinedConversion: 4914 // We are converting from class type to an integral or enumeration type, so 4915 // the Before sequence must be trivial. 4916 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4917 return Diag(From->getLocStart(), 4918 diag::err_typecheck_converted_constant_expression_disallowed) 4919 << From->getType() << From->getSourceRange() << T; 4920 SCS = &ICS.UserDefined.After; 4921 break; 4922 case ImplicitConversionSequence::AmbiguousConversion: 4923 case ImplicitConversionSequence::BadConversion: 4924 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4925 return Diag(From->getLocStart(), 4926 diag::err_typecheck_converted_constant_expression) 4927 << From->getType() << From->getSourceRange() << T; 4928 return ExprError(); 4929 4930 case ImplicitConversionSequence::EllipsisConversion: 4931 llvm_unreachable("ellipsis conversion in converted constant expression"); 4932 } 4933 4934 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4935 if (Result.isInvalid()) 4936 return Result; 4937 4938 // Check for a narrowing implicit conversion. 4939 APValue PreNarrowingValue; 4940 QualType PreNarrowingType; 4941 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4942 PreNarrowingType)) { 4943 case NK_Variable_Narrowing: 4944 // Implicit conversion to a narrower type, and the value is not a constant 4945 // expression. We'll diagnose this in a moment. 4946 case NK_Not_Narrowing: 4947 break; 4948 4949 case NK_Constant_Narrowing: 4950 Diag(From->getLocStart(), 4951 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4952 diag::err_cce_narrowing) 4953 << CCE << /*Constant*/1 4954 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4955 break; 4956 4957 case NK_Type_Narrowing: 4958 Diag(From->getLocStart(), 4959 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4960 diag::err_cce_narrowing) 4961 << CCE << /*Constant*/0 << From->getType() << T; 4962 break; 4963 } 4964 4965 // Check the expression is a constant expression. 4966 SmallVector<PartialDiagnosticAt, 8> Notes; 4967 Expr::EvalResult Eval; 4968 Eval.Diag = &Notes; 4969 4970 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4971 // The expression can't be folded, so we can't keep it at this position in 4972 // the AST. 4973 Result = ExprError(); 4974 } else { 4975 Value = Eval.Val.getInt(); 4976 4977 if (Notes.empty()) { 4978 // It's a constant expression. 4979 return Result; 4980 } 4981 } 4982 4983 // It's not a constant expression. Produce an appropriate diagnostic. 4984 if (Notes.size() == 1 && 4985 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4986 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4987 else { 4988 Diag(From->getLocStart(), diag::err_expr_not_cce) 4989 << CCE << From->getSourceRange(); 4990 for (unsigned I = 0; I < Notes.size(); ++I) 4991 Diag(Notes[I].first, Notes[I].second); 4992 } 4993 return Result; 4994 } 4995 4996 /// dropPointerConversions - If the given standard conversion sequence 4997 /// involves any pointer conversions, remove them. This may change 4998 /// the result type of the conversion sequence. 4999 static void dropPointerConversion(StandardConversionSequence &SCS) { 5000 if (SCS.Second == ICK_Pointer_Conversion) { 5001 SCS.Second = ICK_Identity; 5002 SCS.Third = ICK_Identity; 5003 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5004 } 5005 } 5006 5007 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5008 /// convert the expression From to an Objective-C pointer type. 5009 static ImplicitConversionSequence 5010 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5011 // Do an implicit conversion to 'id'. 5012 QualType Ty = S.Context.getObjCIdType(); 5013 ImplicitConversionSequence ICS 5014 = TryImplicitConversion(S, From, Ty, 5015 // FIXME: Are these flags correct? 5016 /*SuppressUserConversions=*/false, 5017 /*AllowExplicit=*/true, 5018 /*InOverloadResolution=*/false, 5019 /*CStyle=*/false, 5020 /*AllowObjCWritebackConversion=*/false); 5021 5022 // Strip off any final conversions to 'id'. 5023 switch (ICS.getKind()) { 5024 case ImplicitConversionSequence::BadConversion: 5025 case ImplicitConversionSequence::AmbiguousConversion: 5026 case ImplicitConversionSequence::EllipsisConversion: 5027 break; 5028 5029 case ImplicitConversionSequence::UserDefinedConversion: 5030 dropPointerConversion(ICS.UserDefined.After); 5031 break; 5032 5033 case ImplicitConversionSequence::StandardConversion: 5034 dropPointerConversion(ICS.Standard); 5035 break; 5036 } 5037 5038 return ICS; 5039 } 5040 5041 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5042 /// conversion of the expression From to an Objective-C pointer type. 5043 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5044 if (checkPlaceholderForOverload(*this, From)) 5045 return ExprError(); 5046 5047 QualType Ty = Context.getObjCIdType(); 5048 ImplicitConversionSequence ICS = 5049 TryContextuallyConvertToObjCPointer(*this, From); 5050 if (!ICS.isBad()) 5051 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5052 return ExprError(); 5053 } 5054 5055 /// Determine whether the provided type is an integral type, or an enumeration 5056 /// type of a permitted flavor. 5057 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5058 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5059 : T->isIntegralOrUnscopedEnumerationType(); 5060 } 5061 5062 /// \brief Attempt to convert the given expression to an integral or 5063 /// enumeration type. 5064 /// 5065 /// This routine will attempt to convert an expression of class type to an 5066 /// integral or enumeration type, if that class type only has a single 5067 /// conversion to an integral or enumeration type. 5068 /// 5069 /// \param Loc The source location of the construct that requires the 5070 /// conversion. 5071 /// 5072 /// \param From The expression we're converting from. 5073 /// 5074 /// \param Diagnoser Used to output any diagnostics. 5075 /// 5076 /// \param AllowScopedEnumerations Specifies whether conversions to scoped 5077 /// enumerations should be considered. 5078 /// 5079 /// \returns The expression, converted to an integral or enumeration type if 5080 /// successful. 5081 ExprResult 5082 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5083 ICEConvertDiagnoser &Diagnoser, 5084 bool AllowScopedEnumerations) { 5085 // We can't perform any more checking for type-dependent expressions. 5086 if (From->isTypeDependent()) 5087 return Owned(From); 5088 5089 // Process placeholders immediately. 5090 if (From->hasPlaceholderType()) { 5091 ExprResult result = CheckPlaceholderExpr(From); 5092 if (result.isInvalid()) return result; 5093 From = result.take(); 5094 } 5095 5096 // If the expression already has integral or enumeration type, we're golden. 5097 QualType T = From->getType(); 5098 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5099 return DefaultLvalueConversion(From); 5100 5101 // FIXME: Check for missing '()' if T is a function type? 5102 5103 // If we don't have a class type in C++, there's no way we can get an 5104 // expression of integral or enumeration type. 5105 const RecordType *RecordTy = T->getAs<RecordType>(); 5106 if (!RecordTy || !getLangOpts().CPlusPlus) { 5107 if (!Diagnoser.Suppress) 5108 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5109 return Owned(From); 5110 } 5111 5112 // We must have a complete class type. 5113 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5114 ICEConvertDiagnoser &Diagnoser; 5115 Expr *From; 5116 5117 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5118 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5119 5120 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5121 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5122 } 5123 } IncompleteDiagnoser(Diagnoser, From); 5124 5125 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5126 return Owned(From); 5127 5128 // Look for a conversion to an integral or enumeration type. 5129 UnresolvedSet<4> ViableConversions; 5130 UnresolvedSet<4> ExplicitConversions; 5131 std::pair<CXXRecordDecl::conversion_iterator, 5132 CXXRecordDecl::conversion_iterator> Conversions 5133 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5134 5135 bool HadMultipleCandidates 5136 = (std::distance(Conversions.first, Conversions.second) > 1); 5137 5138 for (CXXRecordDecl::conversion_iterator 5139 I = Conversions.first, E = Conversions.second; I != E; ++I) { 5140 if (CXXConversionDecl *Conversion 5141 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5142 if (isIntegralOrEnumerationType( 5143 Conversion->getConversionType().getNonReferenceType(), 5144 AllowScopedEnumerations)) { 5145 if (Conversion->isExplicit()) 5146 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5147 else 5148 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5149 } 5150 } 5151 } 5152 5153 switch (ViableConversions.size()) { 5154 case 0: 5155 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5156 DeclAccessPair Found = ExplicitConversions[0]; 5157 CXXConversionDecl *Conversion 5158 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5159 5160 // The user probably meant to invoke the given explicit 5161 // conversion; use it. 5162 QualType ConvTy 5163 = Conversion->getConversionType().getNonReferenceType(); 5164 std::string TypeStr; 5165 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5166 5167 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5168 << FixItHint::CreateInsertion(From->getLocStart(), 5169 "static_cast<" + TypeStr + ">(") 5170 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5171 ")"); 5172 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5173 5174 // If we aren't in a SFINAE context, build a call to the 5175 // explicit conversion function. 5176 if (isSFINAEContext()) 5177 return ExprError(); 5178 5179 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5180 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5181 HadMultipleCandidates); 5182 if (Result.isInvalid()) 5183 return ExprError(); 5184 // Record usage of conversion in an implicit cast. 5185 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5186 CK_UserDefinedConversion, 5187 Result.get(), 0, 5188 Result.get()->getValueKind()); 5189 } 5190 5191 // We'll complain below about a non-integral condition type. 5192 break; 5193 5194 case 1: { 5195 // Apply this conversion. 5196 DeclAccessPair Found = ViableConversions[0]; 5197 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5198 5199 CXXConversionDecl *Conversion 5200 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5201 QualType ConvTy 5202 = Conversion->getConversionType().getNonReferenceType(); 5203 if (!Diagnoser.SuppressConversion) { 5204 if (isSFINAEContext()) 5205 return ExprError(); 5206 5207 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5208 << From->getSourceRange(); 5209 } 5210 5211 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5212 HadMultipleCandidates); 5213 if (Result.isInvalid()) 5214 return ExprError(); 5215 // Record usage of conversion in an implicit cast. 5216 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5217 CK_UserDefinedConversion, 5218 Result.get(), 0, 5219 Result.get()->getValueKind()); 5220 break; 5221 } 5222 5223 default: 5224 if (Diagnoser.Suppress) 5225 return ExprError(); 5226 5227 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5228 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5229 CXXConversionDecl *Conv 5230 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5231 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5232 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5233 } 5234 return Owned(From); 5235 } 5236 5237 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5238 !Diagnoser.Suppress) { 5239 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5240 << From->getSourceRange(); 5241 } 5242 5243 return DefaultLvalueConversion(From); 5244 } 5245 5246 /// AddOverloadCandidate - Adds the given function to the set of 5247 /// candidate functions, using the given function call arguments. If 5248 /// @p SuppressUserConversions, then don't allow user-defined 5249 /// conversions via constructors or conversion operators. 5250 /// 5251 /// \param PartialOverloading true if we are performing "partial" overloading 5252 /// based on an incomplete set of function arguments. This feature is used by 5253 /// code completion. 5254 void 5255 Sema::AddOverloadCandidate(FunctionDecl *Function, 5256 DeclAccessPair FoundDecl, 5257 ArrayRef<Expr *> Args, 5258 OverloadCandidateSet& CandidateSet, 5259 bool SuppressUserConversions, 5260 bool PartialOverloading, 5261 bool AllowExplicit) { 5262 const FunctionProtoType* Proto 5263 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5264 assert(Proto && "Functions without a prototype cannot be overloaded"); 5265 assert(!Function->getDescribedFunctionTemplate() && 5266 "Use AddTemplateOverloadCandidate for function templates"); 5267 5268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5269 if (!isa<CXXConstructorDecl>(Method)) { 5270 // If we get here, it's because we're calling a member function 5271 // that is named without a member access expression (e.g., 5272 // "this->f") that was either written explicitly or created 5273 // implicitly. This can happen with a qualified call to a member 5274 // function, e.g., X::f(). We use an empty type for the implied 5275 // object argument (C++ [over.call.func]p3), and the acting context 5276 // is irrelevant. 5277 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5278 QualType(), Expr::Classification::makeSimpleLValue(), 5279 Args, CandidateSet, SuppressUserConversions); 5280 return; 5281 } 5282 // We treat a constructor like a non-member function, since its object 5283 // argument doesn't participate in overload resolution. 5284 } 5285 5286 if (!CandidateSet.isNewCandidate(Function)) 5287 return; 5288 5289 // Overload resolution is always an unevaluated context. 5290 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5291 5292 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5293 // C++ [class.copy]p3: 5294 // A member function template is never instantiated to perform the copy 5295 // of a class object to an object of its class type. 5296 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5297 if (Args.size() == 1 && 5298 Constructor->isSpecializationCopyingObject() && 5299 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5300 IsDerivedFrom(Args[0]->getType(), ClassType))) 5301 return; 5302 } 5303 5304 // Add this candidate 5305 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5306 Candidate.FoundDecl = FoundDecl; 5307 Candidate.Function = Function; 5308 Candidate.Viable = true; 5309 Candidate.IsSurrogate = false; 5310 Candidate.IgnoreObjectArgument = false; 5311 Candidate.ExplicitCallArguments = Args.size(); 5312 5313 unsigned NumArgsInProto = Proto->getNumArgs(); 5314 5315 // (C++ 13.3.2p2): A candidate function having fewer than m 5316 // parameters is viable only if it has an ellipsis in its parameter 5317 // list (8.3.5). 5318 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5319 !Proto->isVariadic()) { 5320 Candidate.Viable = false; 5321 Candidate.FailureKind = ovl_fail_too_many_arguments; 5322 return; 5323 } 5324 5325 // (C++ 13.3.2p2): A candidate function having more than m parameters 5326 // is viable only if the (m+1)st parameter has a default argument 5327 // (8.3.6). For the purposes of overload resolution, the 5328 // parameter list is truncated on the right, so that there are 5329 // exactly m parameters. 5330 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5331 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5332 // Not enough arguments. 5333 Candidate.Viable = false; 5334 Candidate.FailureKind = ovl_fail_too_few_arguments; 5335 return; 5336 } 5337 5338 // (CUDA B.1): Check for invalid calls between targets. 5339 if (getLangOpts().CUDA) 5340 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5341 if (CheckCUDATarget(Caller, Function)) { 5342 Candidate.Viable = false; 5343 Candidate.FailureKind = ovl_fail_bad_target; 5344 return; 5345 } 5346 5347 // Determine the implicit conversion sequences for each of the 5348 // arguments. 5349 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5350 if (ArgIdx < NumArgsInProto) { 5351 // (C++ 13.3.2p3): for F to be a viable function, there shall 5352 // exist for each argument an implicit conversion sequence 5353 // (13.3.3.1) that converts that argument to the corresponding 5354 // parameter of F. 5355 QualType ParamType = Proto->getArgType(ArgIdx); 5356 Candidate.Conversions[ArgIdx] 5357 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5358 SuppressUserConversions, 5359 /*InOverloadResolution=*/true, 5360 /*AllowObjCWritebackConversion=*/ 5361 getLangOpts().ObjCAutoRefCount, 5362 AllowExplicit); 5363 if (Candidate.Conversions[ArgIdx].isBad()) { 5364 Candidate.Viable = false; 5365 Candidate.FailureKind = ovl_fail_bad_conversion; 5366 break; 5367 } 5368 } else { 5369 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5370 // argument for which there is no corresponding parameter is 5371 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5372 Candidate.Conversions[ArgIdx].setEllipsis(); 5373 } 5374 } 5375 } 5376 5377 /// \brief Add all of the function declarations in the given function set to 5378 /// the overload canddiate set. 5379 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5380 ArrayRef<Expr *> Args, 5381 OverloadCandidateSet& CandidateSet, 5382 bool SuppressUserConversions, 5383 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5384 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5385 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5387 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5388 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5389 cast<CXXMethodDecl>(FD)->getParent(), 5390 Args[0]->getType(), Args[0]->Classify(Context), 5391 Args.slice(1), CandidateSet, 5392 SuppressUserConversions); 5393 else 5394 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5395 SuppressUserConversions); 5396 } else { 5397 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5398 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5399 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5400 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5401 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5402 ExplicitTemplateArgs, 5403 Args[0]->getType(), 5404 Args[0]->Classify(Context), Args.slice(1), 5405 CandidateSet, SuppressUserConversions); 5406 else 5407 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5408 ExplicitTemplateArgs, Args, 5409 CandidateSet, SuppressUserConversions); 5410 } 5411 } 5412 } 5413 5414 /// AddMethodCandidate - Adds a named decl (which is some kind of 5415 /// method) as a method candidate to the given overload set. 5416 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5417 QualType ObjectType, 5418 Expr::Classification ObjectClassification, 5419 Expr **Args, unsigned NumArgs, 5420 OverloadCandidateSet& CandidateSet, 5421 bool SuppressUserConversions) { 5422 NamedDecl *Decl = FoundDecl.getDecl(); 5423 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5424 5425 if (isa<UsingShadowDecl>(Decl)) 5426 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5427 5428 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5429 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5430 "Expected a member function template"); 5431 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5432 /*ExplicitArgs*/ 0, 5433 ObjectType, ObjectClassification, 5434 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5435 SuppressUserConversions); 5436 } else { 5437 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5438 ObjectType, ObjectClassification, 5439 llvm::makeArrayRef(Args, NumArgs), 5440 CandidateSet, SuppressUserConversions); 5441 } 5442 } 5443 5444 /// AddMethodCandidate - Adds the given C++ member function to the set 5445 /// of candidate functions, using the given function call arguments 5446 /// and the object argument (@c Object). For example, in a call 5447 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5448 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5449 /// allow user-defined conversions via constructors or conversion 5450 /// operators. 5451 void 5452 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5453 CXXRecordDecl *ActingContext, QualType ObjectType, 5454 Expr::Classification ObjectClassification, 5455 ArrayRef<Expr *> Args, 5456 OverloadCandidateSet& CandidateSet, 5457 bool SuppressUserConversions) { 5458 const FunctionProtoType* Proto 5459 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5460 assert(Proto && "Methods without a prototype cannot be overloaded"); 5461 assert(!isa<CXXConstructorDecl>(Method) && 5462 "Use AddOverloadCandidate for constructors"); 5463 5464 if (!CandidateSet.isNewCandidate(Method)) 5465 return; 5466 5467 // Overload resolution is always an unevaluated context. 5468 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5469 5470 // Add this candidate 5471 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5472 Candidate.FoundDecl = FoundDecl; 5473 Candidate.Function = Method; 5474 Candidate.IsSurrogate = false; 5475 Candidate.IgnoreObjectArgument = false; 5476 Candidate.ExplicitCallArguments = Args.size(); 5477 5478 unsigned NumArgsInProto = Proto->getNumArgs(); 5479 5480 // (C++ 13.3.2p2): A candidate function having fewer than m 5481 // parameters is viable only if it has an ellipsis in its parameter 5482 // list (8.3.5). 5483 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5484 Candidate.Viable = false; 5485 Candidate.FailureKind = ovl_fail_too_many_arguments; 5486 return; 5487 } 5488 5489 // (C++ 13.3.2p2): A candidate function having more than m parameters 5490 // is viable only if the (m+1)st parameter has a default argument 5491 // (8.3.6). For the purposes of overload resolution, the 5492 // parameter list is truncated on the right, so that there are 5493 // exactly m parameters. 5494 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5495 if (Args.size() < MinRequiredArgs) { 5496 // Not enough arguments. 5497 Candidate.Viable = false; 5498 Candidate.FailureKind = ovl_fail_too_few_arguments; 5499 return; 5500 } 5501 5502 Candidate.Viable = true; 5503 5504 if (Method->isStatic() || ObjectType.isNull()) 5505 // The implicit object argument is ignored. 5506 Candidate.IgnoreObjectArgument = true; 5507 else { 5508 // Determine the implicit conversion sequence for the object 5509 // parameter. 5510 Candidate.Conversions[0] 5511 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5512 Method, ActingContext); 5513 if (Candidate.Conversions[0].isBad()) { 5514 Candidate.Viable = false; 5515 Candidate.FailureKind = ovl_fail_bad_conversion; 5516 return; 5517 } 5518 } 5519 5520 // Determine the implicit conversion sequences for each of the 5521 // arguments. 5522 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5523 if (ArgIdx < NumArgsInProto) { 5524 // (C++ 13.3.2p3): for F to be a viable function, there shall 5525 // exist for each argument an implicit conversion sequence 5526 // (13.3.3.1) that converts that argument to the corresponding 5527 // parameter of F. 5528 QualType ParamType = Proto->getArgType(ArgIdx); 5529 Candidate.Conversions[ArgIdx + 1] 5530 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5531 SuppressUserConversions, 5532 /*InOverloadResolution=*/true, 5533 /*AllowObjCWritebackConversion=*/ 5534 getLangOpts().ObjCAutoRefCount); 5535 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5536 Candidate.Viable = false; 5537 Candidate.FailureKind = ovl_fail_bad_conversion; 5538 break; 5539 } 5540 } else { 5541 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5542 // argument for which there is no corresponding parameter is 5543 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5544 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5545 } 5546 } 5547 } 5548 5549 /// \brief Add a C++ member function template as a candidate to the candidate 5550 /// set, using template argument deduction to produce an appropriate member 5551 /// function template specialization. 5552 void 5553 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5554 DeclAccessPair FoundDecl, 5555 CXXRecordDecl *ActingContext, 5556 TemplateArgumentListInfo *ExplicitTemplateArgs, 5557 QualType ObjectType, 5558 Expr::Classification ObjectClassification, 5559 ArrayRef<Expr *> Args, 5560 OverloadCandidateSet& CandidateSet, 5561 bool SuppressUserConversions) { 5562 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5563 return; 5564 5565 // C++ [over.match.funcs]p7: 5566 // In each case where a candidate is a function template, candidate 5567 // function template specializations are generated using template argument 5568 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5569 // candidate functions in the usual way.113) A given name can refer to one 5570 // or more function templates and also to a set of overloaded non-template 5571 // functions. In such a case, the candidate functions generated from each 5572 // function template are combined with the set of non-template candidate 5573 // functions. 5574 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5575 FunctionDecl *Specialization = 0; 5576 if (TemplateDeductionResult Result 5577 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5578 Specialization, Info)) { 5579 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5580 Candidate.FoundDecl = FoundDecl; 5581 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5582 Candidate.Viable = false; 5583 Candidate.FailureKind = ovl_fail_bad_deduction; 5584 Candidate.IsSurrogate = false; 5585 Candidate.IgnoreObjectArgument = false; 5586 Candidate.ExplicitCallArguments = Args.size(); 5587 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5588 Info); 5589 return; 5590 } 5591 5592 // Add the function template specialization produced by template argument 5593 // deduction as a candidate. 5594 assert(Specialization && "Missing member function template specialization?"); 5595 assert(isa<CXXMethodDecl>(Specialization) && 5596 "Specialization is not a member function?"); 5597 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5598 ActingContext, ObjectType, ObjectClassification, Args, 5599 CandidateSet, SuppressUserConversions); 5600 } 5601 5602 /// \brief Add a C++ function template specialization as a candidate 5603 /// in the candidate set, using template argument deduction to produce 5604 /// an appropriate function template specialization. 5605 void 5606 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5607 DeclAccessPair FoundDecl, 5608 TemplateArgumentListInfo *ExplicitTemplateArgs, 5609 ArrayRef<Expr *> Args, 5610 OverloadCandidateSet& CandidateSet, 5611 bool SuppressUserConversions) { 5612 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5613 return; 5614 5615 // C++ [over.match.funcs]p7: 5616 // In each case where a candidate is a function template, candidate 5617 // function template specializations are generated using template argument 5618 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5619 // candidate functions in the usual way.113) A given name can refer to one 5620 // or more function templates and also to a set of overloaded non-template 5621 // functions. In such a case, the candidate functions generated from each 5622 // function template are combined with the set of non-template candidate 5623 // functions. 5624 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5625 FunctionDecl *Specialization = 0; 5626 if (TemplateDeductionResult Result 5627 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5628 Specialization, Info)) { 5629 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5630 Candidate.FoundDecl = FoundDecl; 5631 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5632 Candidate.Viable = false; 5633 Candidate.FailureKind = ovl_fail_bad_deduction; 5634 Candidate.IsSurrogate = false; 5635 Candidate.IgnoreObjectArgument = false; 5636 Candidate.ExplicitCallArguments = Args.size(); 5637 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5638 Info); 5639 return; 5640 } 5641 5642 // Add the function template specialization produced by template argument 5643 // deduction as a candidate. 5644 assert(Specialization && "Missing function template specialization?"); 5645 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5646 SuppressUserConversions); 5647 } 5648 5649 /// AddConversionCandidate - Add a C++ conversion function as a 5650 /// candidate in the candidate set (C++ [over.match.conv], 5651 /// C++ [over.match.copy]). From is the expression we're converting from, 5652 /// and ToType is the type that we're eventually trying to convert to 5653 /// (which may or may not be the same type as the type that the 5654 /// conversion function produces). 5655 void 5656 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5657 DeclAccessPair FoundDecl, 5658 CXXRecordDecl *ActingContext, 5659 Expr *From, QualType ToType, 5660 OverloadCandidateSet& CandidateSet) { 5661 assert(!Conversion->getDescribedFunctionTemplate() && 5662 "Conversion function templates use AddTemplateConversionCandidate"); 5663 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5664 if (!CandidateSet.isNewCandidate(Conversion)) 5665 return; 5666 5667 // Overload resolution is always an unevaluated context. 5668 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5669 5670 // Add this candidate 5671 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5672 Candidate.FoundDecl = FoundDecl; 5673 Candidate.Function = Conversion; 5674 Candidate.IsSurrogate = false; 5675 Candidate.IgnoreObjectArgument = false; 5676 Candidate.FinalConversion.setAsIdentityConversion(); 5677 Candidate.FinalConversion.setFromType(ConvType); 5678 Candidate.FinalConversion.setAllToTypes(ToType); 5679 Candidate.Viable = true; 5680 Candidate.ExplicitCallArguments = 1; 5681 5682 // C++ [over.match.funcs]p4: 5683 // For conversion functions, the function is considered to be a member of 5684 // the class of the implicit implied object argument for the purpose of 5685 // defining the type of the implicit object parameter. 5686 // 5687 // Determine the implicit conversion sequence for the implicit 5688 // object parameter. 5689 QualType ImplicitParamType = From->getType(); 5690 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5691 ImplicitParamType = FromPtrType->getPointeeType(); 5692 CXXRecordDecl *ConversionContext 5693 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5694 5695 Candidate.Conversions[0] 5696 = TryObjectArgumentInitialization(*this, From->getType(), 5697 From->Classify(Context), 5698 Conversion, ConversionContext); 5699 5700 if (Candidate.Conversions[0].isBad()) { 5701 Candidate.Viable = false; 5702 Candidate.FailureKind = ovl_fail_bad_conversion; 5703 return; 5704 } 5705 5706 // We won't go through a user-define type conversion function to convert a 5707 // derived to base as such conversions are given Conversion Rank. They only 5708 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5709 QualType FromCanon 5710 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5711 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5712 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5713 Candidate.Viable = false; 5714 Candidate.FailureKind = ovl_fail_trivial_conversion; 5715 return; 5716 } 5717 5718 // To determine what the conversion from the result of calling the 5719 // conversion function to the type we're eventually trying to 5720 // convert to (ToType), we need to synthesize a call to the 5721 // conversion function and attempt copy initialization from it. This 5722 // makes sure that we get the right semantics with respect to 5723 // lvalues/rvalues and the type. Fortunately, we can allocate this 5724 // call on the stack and we don't need its arguments to be 5725 // well-formed. 5726 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5727 VK_LValue, From->getLocStart()); 5728 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5729 Context.getPointerType(Conversion->getType()), 5730 CK_FunctionToPointerDecay, 5731 &ConversionRef, VK_RValue); 5732 5733 QualType ConversionType = Conversion->getConversionType(); 5734 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5735 Candidate.Viable = false; 5736 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5737 return; 5738 } 5739 5740 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5741 5742 // Note that it is safe to allocate CallExpr on the stack here because 5743 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5744 // allocator). 5745 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5746 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5747 From->getLocStart()); 5748 ImplicitConversionSequence ICS = 5749 TryCopyInitialization(*this, &Call, ToType, 5750 /*SuppressUserConversions=*/true, 5751 /*InOverloadResolution=*/false, 5752 /*AllowObjCWritebackConversion=*/false); 5753 5754 switch (ICS.getKind()) { 5755 case ImplicitConversionSequence::StandardConversion: 5756 Candidate.FinalConversion = ICS.Standard; 5757 5758 // C++ [over.ics.user]p3: 5759 // If the user-defined conversion is specified by a specialization of a 5760 // conversion function template, the second standard conversion sequence 5761 // shall have exact match rank. 5762 if (Conversion->getPrimaryTemplate() && 5763 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5764 Candidate.Viable = false; 5765 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5766 } 5767 5768 // C++0x [dcl.init.ref]p5: 5769 // In the second case, if the reference is an rvalue reference and 5770 // the second standard conversion sequence of the user-defined 5771 // conversion sequence includes an lvalue-to-rvalue conversion, the 5772 // program is ill-formed. 5773 if (ToType->isRValueReferenceType() && 5774 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5775 Candidate.Viable = false; 5776 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5777 } 5778 break; 5779 5780 case ImplicitConversionSequence::BadConversion: 5781 Candidate.Viable = false; 5782 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5783 break; 5784 5785 default: 5786 llvm_unreachable( 5787 "Can only end up with a standard conversion sequence or failure"); 5788 } 5789 } 5790 5791 /// \brief Adds a conversion function template specialization 5792 /// candidate to the overload set, using template argument deduction 5793 /// to deduce the template arguments of the conversion function 5794 /// template from the type that we are converting to (C++ 5795 /// [temp.deduct.conv]). 5796 void 5797 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5798 DeclAccessPair FoundDecl, 5799 CXXRecordDecl *ActingDC, 5800 Expr *From, QualType ToType, 5801 OverloadCandidateSet &CandidateSet) { 5802 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5803 "Only conversion function templates permitted here"); 5804 5805 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5806 return; 5807 5808 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5809 CXXConversionDecl *Specialization = 0; 5810 if (TemplateDeductionResult Result 5811 = DeduceTemplateArguments(FunctionTemplate, ToType, 5812 Specialization, Info)) { 5813 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5814 Candidate.FoundDecl = FoundDecl; 5815 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5816 Candidate.Viable = false; 5817 Candidate.FailureKind = ovl_fail_bad_deduction; 5818 Candidate.IsSurrogate = false; 5819 Candidate.IgnoreObjectArgument = false; 5820 Candidate.ExplicitCallArguments = 1; 5821 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5822 Info); 5823 return; 5824 } 5825 5826 // Add the conversion function template specialization produced by 5827 // template argument deduction as a candidate. 5828 assert(Specialization && "Missing function template specialization?"); 5829 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5830 CandidateSet); 5831 } 5832 5833 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5834 /// converts the given @c Object to a function pointer via the 5835 /// conversion function @c Conversion, and then attempts to call it 5836 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 5837 /// the type of function that we'll eventually be calling. 5838 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5839 DeclAccessPair FoundDecl, 5840 CXXRecordDecl *ActingContext, 5841 const FunctionProtoType *Proto, 5842 Expr *Object, 5843 ArrayRef<Expr *> Args, 5844 OverloadCandidateSet& CandidateSet) { 5845 if (!CandidateSet.isNewCandidate(Conversion)) 5846 return; 5847 5848 // Overload resolution is always an unevaluated context. 5849 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5850 5851 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5852 Candidate.FoundDecl = FoundDecl; 5853 Candidate.Function = 0; 5854 Candidate.Surrogate = Conversion; 5855 Candidate.Viable = true; 5856 Candidate.IsSurrogate = true; 5857 Candidate.IgnoreObjectArgument = false; 5858 Candidate.ExplicitCallArguments = Args.size(); 5859 5860 // Determine the implicit conversion sequence for the implicit 5861 // object parameter. 5862 ImplicitConversionSequence ObjectInit 5863 = TryObjectArgumentInitialization(*this, Object->getType(), 5864 Object->Classify(Context), 5865 Conversion, ActingContext); 5866 if (ObjectInit.isBad()) { 5867 Candidate.Viable = false; 5868 Candidate.FailureKind = ovl_fail_bad_conversion; 5869 Candidate.Conversions[0] = ObjectInit; 5870 return; 5871 } 5872 5873 // The first conversion is actually a user-defined conversion whose 5874 // first conversion is ObjectInit's standard conversion (which is 5875 // effectively a reference binding). Record it as such. 5876 Candidate.Conversions[0].setUserDefined(); 5877 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5878 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5879 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5880 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5881 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5882 Candidate.Conversions[0].UserDefined.After 5883 = Candidate.Conversions[0].UserDefined.Before; 5884 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5885 5886 // Find the 5887 unsigned NumArgsInProto = Proto->getNumArgs(); 5888 5889 // (C++ 13.3.2p2): A candidate function having fewer than m 5890 // parameters is viable only if it has an ellipsis in its parameter 5891 // list (8.3.5). 5892 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5893 Candidate.Viable = false; 5894 Candidate.FailureKind = ovl_fail_too_many_arguments; 5895 return; 5896 } 5897 5898 // Function types don't have any default arguments, so just check if 5899 // we have enough arguments. 5900 if (Args.size() < NumArgsInProto) { 5901 // Not enough arguments. 5902 Candidate.Viable = false; 5903 Candidate.FailureKind = ovl_fail_too_few_arguments; 5904 return; 5905 } 5906 5907 // Determine the implicit conversion sequences for each of the 5908 // arguments. 5909 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5910 if (ArgIdx < NumArgsInProto) { 5911 // (C++ 13.3.2p3): for F to be a viable function, there shall 5912 // exist for each argument an implicit conversion sequence 5913 // (13.3.3.1) that converts that argument to the corresponding 5914 // parameter of F. 5915 QualType ParamType = Proto->getArgType(ArgIdx); 5916 Candidate.Conversions[ArgIdx + 1] 5917 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5918 /*SuppressUserConversions=*/false, 5919 /*InOverloadResolution=*/false, 5920 /*AllowObjCWritebackConversion=*/ 5921 getLangOpts().ObjCAutoRefCount); 5922 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5923 Candidate.Viable = false; 5924 Candidate.FailureKind = ovl_fail_bad_conversion; 5925 break; 5926 } 5927 } else { 5928 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5929 // argument for which there is no corresponding parameter is 5930 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5931 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5932 } 5933 } 5934 } 5935 5936 /// \brief Add overload candidates for overloaded operators that are 5937 /// member functions. 5938 /// 5939 /// Add the overloaded operator candidates that are member functions 5940 /// for the operator Op that was used in an operator expression such 5941 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 5942 /// CandidateSet will store the added overload candidates. (C++ 5943 /// [over.match.oper]). 5944 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5945 SourceLocation OpLoc, 5946 Expr **Args, unsigned NumArgs, 5947 OverloadCandidateSet& CandidateSet, 5948 SourceRange OpRange) { 5949 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5950 5951 // C++ [over.match.oper]p3: 5952 // For a unary operator @ with an operand of a type whose 5953 // cv-unqualified version is T1, and for a binary operator @ with 5954 // a left operand of a type whose cv-unqualified version is T1 and 5955 // a right operand of a type whose cv-unqualified version is T2, 5956 // three sets of candidate functions, designated member 5957 // candidates, non-member candidates and built-in candidates, are 5958 // constructed as follows: 5959 QualType T1 = Args[0]->getType(); 5960 5961 // -- If T1 is a class type, the set of member candidates is the 5962 // result of the qualified lookup of T1::operator@ 5963 // (13.3.1.1.1); otherwise, the set of member candidates is 5964 // empty. 5965 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5966 // Complete the type if it can be completed. Otherwise, we're done. 5967 if (RequireCompleteType(OpLoc, T1, 0)) 5968 return; 5969 5970 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5971 LookupQualifiedName(Operators, T1Rec->getDecl()); 5972 Operators.suppressDiagnostics(); 5973 5974 for (LookupResult::iterator Oper = Operators.begin(), 5975 OperEnd = Operators.end(); 5976 Oper != OperEnd; 5977 ++Oper) 5978 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5979 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5980 CandidateSet, 5981 /* SuppressUserConversions = */ false); 5982 } 5983 } 5984 5985 /// AddBuiltinCandidate - Add a candidate for a built-in 5986 /// operator. ResultTy and ParamTys are the result and parameter types 5987 /// of the built-in candidate, respectively. Args and NumArgs are the 5988 /// arguments being passed to the candidate. IsAssignmentOperator 5989 /// should be true when this built-in candidate is an assignment 5990 /// operator. NumContextualBoolArguments is the number of arguments 5991 /// (at the beginning of the argument list) that will be contextually 5992 /// converted to bool. 5993 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5994 Expr **Args, unsigned NumArgs, 5995 OverloadCandidateSet& CandidateSet, 5996 bool IsAssignmentOperator, 5997 unsigned NumContextualBoolArguments) { 5998 // Overload resolution is always an unevaluated context. 5999 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6000 6001 // Add this candidate 6002 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 6003 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6004 Candidate.Function = 0; 6005 Candidate.IsSurrogate = false; 6006 Candidate.IgnoreObjectArgument = false; 6007 Candidate.BuiltinTypes.ResultTy = ResultTy; 6008 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6009 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6010 6011 // Determine the implicit conversion sequences for each of the 6012 // arguments. 6013 Candidate.Viable = true; 6014 Candidate.ExplicitCallArguments = NumArgs; 6015 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6016 // C++ [over.match.oper]p4: 6017 // For the built-in assignment operators, conversions of the 6018 // left operand are restricted as follows: 6019 // -- no temporaries are introduced to hold the left operand, and 6020 // -- no user-defined conversions are applied to the left 6021 // operand to achieve a type match with the left-most 6022 // parameter of a built-in candidate. 6023 // 6024 // We block these conversions by turning off user-defined 6025 // conversions, since that is the only way that initialization of 6026 // a reference to a non-class type can occur from something that 6027 // is not of the same type. 6028 if (ArgIdx < NumContextualBoolArguments) { 6029 assert(ParamTys[ArgIdx] == Context.BoolTy && 6030 "Contextual conversion to bool requires bool type"); 6031 Candidate.Conversions[ArgIdx] 6032 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6033 } else { 6034 Candidate.Conversions[ArgIdx] 6035 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6036 ArgIdx == 0 && IsAssignmentOperator, 6037 /*InOverloadResolution=*/false, 6038 /*AllowObjCWritebackConversion=*/ 6039 getLangOpts().ObjCAutoRefCount); 6040 } 6041 if (Candidate.Conversions[ArgIdx].isBad()) { 6042 Candidate.Viable = false; 6043 Candidate.FailureKind = ovl_fail_bad_conversion; 6044 break; 6045 } 6046 } 6047 } 6048 6049 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6050 /// candidate operator functions for built-in operators (C++ 6051 /// [over.built]). The types are separated into pointer types and 6052 /// enumeration types. 6053 class BuiltinCandidateTypeSet { 6054 /// TypeSet - A set of types. 6055 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6056 6057 /// PointerTypes - The set of pointer types that will be used in the 6058 /// built-in candidates. 6059 TypeSet PointerTypes; 6060 6061 /// MemberPointerTypes - The set of member pointer types that will be 6062 /// used in the built-in candidates. 6063 TypeSet MemberPointerTypes; 6064 6065 /// EnumerationTypes - The set of enumeration types that will be 6066 /// used in the built-in candidates. 6067 TypeSet EnumerationTypes; 6068 6069 /// \brief The set of vector types that will be used in the built-in 6070 /// candidates. 6071 TypeSet VectorTypes; 6072 6073 /// \brief A flag indicating non-record types are viable candidates 6074 bool HasNonRecordTypes; 6075 6076 /// \brief A flag indicating whether either arithmetic or enumeration types 6077 /// were present in the candidate set. 6078 bool HasArithmeticOrEnumeralTypes; 6079 6080 /// \brief A flag indicating whether the nullptr type was present in the 6081 /// candidate set. 6082 bool HasNullPtrType; 6083 6084 /// Sema - The semantic analysis instance where we are building the 6085 /// candidate type set. 6086 Sema &SemaRef; 6087 6088 /// Context - The AST context in which we will build the type sets. 6089 ASTContext &Context; 6090 6091 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6092 const Qualifiers &VisibleQuals); 6093 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6094 6095 public: 6096 /// iterator - Iterates through the types that are part of the set. 6097 typedef TypeSet::iterator iterator; 6098 6099 BuiltinCandidateTypeSet(Sema &SemaRef) 6100 : HasNonRecordTypes(false), 6101 HasArithmeticOrEnumeralTypes(false), 6102 HasNullPtrType(false), 6103 SemaRef(SemaRef), 6104 Context(SemaRef.Context) { } 6105 6106 void AddTypesConvertedFrom(QualType Ty, 6107 SourceLocation Loc, 6108 bool AllowUserConversions, 6109 bool AllowExplicitConversions, 6110 const Qualifiers &VisibleTypeConversionsQuals); 6111 6112 /// pointer_begin - First pointer type found; 6113 iterator pointer_begin() { return PointerTypes.begin(); } 6114 6115 /// pointer_end - Past the last pointer type found; 6116 iterator pointer_end() { return PointerTypes.end(); } 6117 6118 /// member_pointer_begin - First member pointer type found; 6119 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6120 6121 /// member_pointer_end - Past the last member pointer type found; 6122 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6123 6124 /// enumeration_begin - First enumeration type found; 6125 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6126 6127 /// enumeration_end - Past the last enumeration type found; 6128 iterator enumeration_end() { return EnumerationTypes.end(); } 6129 6130 iterator vector_begin() { return VectorTypes.begin(); } 6131 iterator vector_end() { return VectorTypes.end(); } 6132 6133 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6134 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6135 bool hasNullPtrType() const { return HasNullPtrType; } 6136 }; 6137 6138 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6139 /// the set of pointer types along with any more-qualified variants of 6140 /// that type. For example, if @p Ty is "int const *", this routine 6141 /// will add "int const *", "int const volatile *", "int const 6142 /// restrict *", and "int const volatile restrict *" to the set of 6143 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6144 /// false otherwise. 6145 /// 6146 /// FIXME: what to do about extended qualifiers? 6147 bool 6148 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6149 const Qualifiers &VisibleQuals) { 6150 6151 // Insert this type. 6152 if (!PointerTypes.insert(Ty)) 6153 return false; 6154 6155 QualType PointeeTy; 6156 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6157 bool buildObjCPtr = false; 6158 if (!PointerTy) { 6159 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6160 PointeeTy = PTy->getPointeeType(); 6161 buildObjCPtr = true; 6162 } else { 6163 PointeeTy = PointerTy->getPointeeType(); 6164 } 6165 6166 // Don't add qualified variants of arrays. For one, they're not allowed 6167 // (the qualifier would sink to the element type), and for another, the 6168 // only overload situation where it matters is subscript or pointer +- int, 6169 // and those shouldn't have qualifier variants anyway. 6170 if (PointeeTy->isArrayType()) 6171 return true; 6172 6173 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6174 bool hasVolatile = VisibleQuals.hasVolatile(); 6175 bool hasRestrict = VisibleQuals.hasRestrict(); 6176 6177 // Iterate through all strict supersets of BaseCVR. 6178 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6179 if ((CVR | BaseCVR) != CVR) continue; 6180 // Skip over volatile if no volatile found anywhere in the types. 6181 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6182 6183 // Skip over restrict if no restrict found anywhere in the types, or if 6184 // the type cannot be restrict-qualified. 6185 if ((CVR & Qualifiers::Restrict) && 6186 (!hasRestrict || 6187 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6188 continue; 6189 6190 // Build qualified pointee type. 6191 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6192 6193 // Build qualified pointer type. 6194 QualType QPointerTy; 6195 if (!buildObjCPtr) 6196 QPointerTy = Context.getPointerType(QPointeeTy); 6197 else 6198 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6199 6200 // Insert qualified pointer type. 6201 PointerTypes.insert(QPointerTy); 6202 } 6203 6204 return true; 6205 } 6206 6207 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6208 /// to the set of pointer types along with any more-qualified variants of 6209 /// that type. For example, if @p Ty is "int const *", this routine 6210 /// will add "int const *", "int const volatile *", "int const 6211 /// restrict *", and "int const volatile restrict *" to the set of 6212 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6213 /// false otherwise. 6214 /// 6215 /// FIXME: what to do about extended qualifiers? 6216 bool 6217 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6218 QualType Ty) { 6219 // Insert this type. 6220 if (!MemberPointerTypes.insert(Ty)) 6221 return false; 6222 6223 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6224 assert(PointerTy && "type was not a member pointer type!"); 6225 6226 QualType PointeeTy = PointerTy->getPointeeType(); 6227 // Don't add qualified variants of arrays. For one, they're not allowed 6228 // (the qualifier would sink to the element type), and for another, the 6229 // only overload situation where it matters is subscript or pointer +- int, 6230 // and those shouldn't have qualifier variants anyway. 6231 if (PointeeTy->isArrayType()) 6232 return true; 6233 const Type *ClassTy = PointerTy->getClass(); 6234 6235 // Iterate through all strict supersets of the pointee type's CVR 6236 // qualifiers. 6237 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6238 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6239 if ((CVR | BaseCVR) != CVR) continue; 6240 6241 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6242 MemberPointerTypes.insert( 6243 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6244 } 6245 6246 return true; 6247 } 6248 6249 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6250 /// Ty can be implicit converted to the given set of @p Types. We're 6251 /// primarily interested in pointer types and enumeration types. We also 6252 /// take member pointer types, for the conditional operator. 6253 /// AllowUserConversions is true if we should look at the conversion 6254 /// functions of a class type, and AllowExplicitConversions if we 6255 /// should also include the explicit conversion functions of a class 6256 /// type. 6257 void 6258 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6259 SourceLocation Loc, 6260 bool AllowUserConversions, 6261 bool AllowExplicitConversions, 6262 const Qualifiers &VisibleQuals) { 6263 // Only deal with canonical types. 6264 Ty = Context.getCanonicalType(Ty); 6265 6266 // Look through reference types; they aren't part of the type of an 6267 // expression for the purposes of conversions. 6268 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6269 Ty = RefTy->getPointeeType(); 6270 6271 // If we're dealing with an array type, decay to the pointer. 6272 if (Ty->isArrayType()) 6273 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6274 6275 // Otherwise, we don't care about qualifiers on the type. 6276 Ty = Ty.getLocalUnqualifiedType(); 6277 6278 // Flag if we ever add a non-record type. 6279 const RecordType *TyRec = Ty->getAs<RecordType>(); 6280 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6281 6282 // Flag if we encounter an arithmetic type. 6283 HasArithmeticOrEnumeralTypes = 6284 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6285 6286 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6287 PointerTypes.insert(Ty); 6288 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6289 // Insert our type, and its more-qualified variants, into the set 6290 // of types. 6291 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6292 return; 6293 } else if (Ty->isMemberPointerType()) { 6294 // Member pointers are far easier, since the pointee can't be converted. 6295 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6296 return; 6297 } else if (Ty->isEnumeralType()) { 6298 HasArithmeticOrEnumeralTypes = true; 6299 EnumerationTypes.insert(Ty); 6300 } else if (Ty->isVectorType()) { 6301 // We treat vector types as arithmetic types in many contexts as an 6302 // extension. 6303 HasArithmeticOrEnumeralTypes = true; 6304 VectorTypes.insert(Ty); 6305 } else if (Ty->isNullPtrType()) { 6306 HasNullPtrType = true; 6307 } else if (AllowUserConversions && TyRec) { 6308 // No conversion functions in incomplete types. 6309 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6310 return; 6311 6312 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6313 std::pair<CXXRecordDecl::conversion_iterator, 6314 CXXRecordDecl::conversion_iterator> 6315 Conversions = ClassDecl->getVisibleConversionFunctions(); 6316 for (CXXRecordDecl::conversion_iterator 6317 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6318 NamedDecl *D = I.getDecl(); 6319 if (isa<UsingShadowDecl>(D)) 6320 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6321 6322 // Skip conversion function templates; they don't tell us anything 6323 // about which builtin types we can convert to. 6324 if (isa<FunctionTemplateDecl>(D)) 6325 continue; 6326 6327 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6328 if (AllowExplicitConversions || !Conv->isExplicit()) { 6329 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6330 VisibleQuals); 6331 } 6332 } 6333 } 6334 } 6335 6336 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6337 /// the volatile- and non-volatile-qualified assignment operators for the 6338 /// given type to the candidate set. 6339 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6340 QualType T, 6341 Expr **Args, 6342 unsigned NumArgs, 6343 OverloadCandidateSet &CandidateSet) { 6344 QualType ParamTypes[2]; 6345 6346 // T& operator=(T&, T) 6347 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6348 ParamTypes[1] = T; 6349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6350 /*IsAssignmentOperator=*/true); 6351 6352 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6353 // volatile T& operator=(volatile T&, T) 6354 ParamTypes[0] 6355 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6356 ParamTypes[1] = T; 6357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6358 /*IsAssignmentOperator=*/true); 6359 } 6360 } 6361 6362 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6363 /// if any, found in visible type conversion functions found in ArgExpr's type. 6364 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6365 Qualifiers VRQuals; 6366 const RecordType *TyRec; 6367 if (const MemberPointerType *RHSMPType = 6368 ArgExpr->getType()->getAs<MemberPointerType>()) 6369 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6370 else 6371 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6372 if (!TyRec) { 6373 // Just to be safe, assume the worst case. 6374 VRQuals.addVolatile(); 6375 VRQuals.addRestrict(); 6376 return VRQuals; 6377 } 6378 6379 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6380 if (!ClassDecl->hasDefinition()) 6381 return VRQuals; 6382 6383 std::pair<CXXRecordDecl::conversion_iterator, 6384 CXXRecordDecl::conversion_iterator> 6385 Conversions = ClassDecl->getVisibleConversionFunctions(); 6386 6387 for (CXXRecordDecl::conversion_iterator 6388 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6389 NamedDecl *D = I.getDecl(); 6390 if (isa<UsingShadowDecl>(D)) 6391 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6392 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6393 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6394 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6395 CanTy = ResTypeRef->getPointeeType(); 6396 // Need to go down the pointer/mempointer chain and add qualifiers 6397 // as see them. 6398 bool done = false; 6399 while (!done) { 6400 if (CanTy.isRestrictQualified()) 6401 VRQuals.addRestrict(); 6402 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6403 CanTy = ResTypePtr->getPointeeType(); 6404 else if (const MemberPointerType *ResTypeMPtr = 6405 CanTy->getAs<MemberPointerType>()) 6406 CanTy = ResTypeMPtr->getPointeeType(); 6407 else 6408 done = true; 6409 if (CanTy.isVolatileQualified()) 6410 VRQuals.addVolatile(); 6411 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6412 return VRQuals; 6413 } 6414 } 6415 } 6416 return VRQuals; 6417 } 6418 6419 namespace { 6420 6421 /// \brief Helper class to manage the addition of builtin operator overload 6422 /// candidates. It provides shared state and utility methods used throughout 6423 /// the process, as well as a helper method to add each group of builtin 6424 /// operator overloads from the standard to a candidate set. 6425 class BuiltinOperatorOverloadBuilder { 6426 // Common instance state available to all overload candidate addition methods. 6427 Sema &S; 6428 Expr **Args; 6429 unsigned NumArgs; 6430 Qualifiers VisibleTypeConversionsQuals; 6431 bool HasArithmeticOrEnumeralCandidateType; 6432 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6433 OverloadCandidateSet &CandidateSet; 6434 6435 // Define some constants used to index and iterate over the arithemetic types 6436 // provided via the getArithmeticType() method below. 6437 // The "promoted arithmetic types" are the arithmetic 6438 // types are that preserved by promotion (C++ [over.built]p2). 6439 static const unsigned FirstIntegralType = 3; 6440 static const unsigned LastIntegralType = 20; 6441 static const unsigned FirstPromotedIntegralType = 3, 6442 LastPromotedIntegralType = 11; 6443 static const unsigned FirstPromotedArithmeticType = 0, 6444 LastPromotedArithmeticType = 11; 6445 static const unsigned NumArithmeticTypes = 20; 6446 6447 /// \brief Get the canonical type for a given arithmetic type index. 6448 CanQualType getArithmeticType(unsigned index) { 6449 assert(index < NumArithmeticTypes); 6450 static CanQualType ASTContext::* const 6451 ArithmeticTypes[NumArithmeticTypes] = { 6452 // Start of promoted types. 6453 &ASTContext::FloatTy, 6454 &ASTContext::DoubleTy, 6455 &ASTContext::LongDoubleTy, 6456 6457 // Start of integral types. 6458 &ASTContext::IntTy, 6459 &ASTContext::LongTy, 6460 &ASTContext::LongLongTy, 6461 &ASTContext::Int128Ty, 6462 &ASTContext::UnsignedIntTy, 6463 &ASTContext::UnsignedLongTy, 6464 &ASTContext::UnsignedLongLongTy, 6465 &ASTContext::UnsignedInt128Ty, 6466 // End of promoted types. 6467 6468 &ASTContext::BoolTy, 6469 &ASTContext::CharTy, 6470 &ASTContext::WCharTy, 6471 &ASTContext::Char16Ty, 6472 &ASTContext::Char32Ty, 6473 &ASTContext::SignedCharTy, 6474 &ASTContext::ShortTy, 6475 &ASTContext::UnsignedCharTy, 6476 &ASTContext::UnsignedShortTy, 6477 // End of integral types. 6478 // FIXME: What about complex? What about half? 6479 }; 6480 return S.Context.*ArithmeticTypes[index]; 6481 } 6482 6483 /// \brief Gets the canonical type resulting from the usual arithemetic 6484 /// converions for the given arithmetic types. 6485 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6486 // Accelerator table for performing the usual arithmetic conversions. 6487 // The rules are basically: 6488 // - if either is floating-point, use the wider floating-point 6489 // - if same signedness, use the higher rank 6490 // - if same size, use unsigned of the higher rank 6491 // - use the larger type 6492 // These rules, together with the axiom that higher ranks are 6493 // never smaller, are sufficient to precompute all of these results 6494 // *except* when dealing with signed types of higher rank. 6495 // (we could precompute SLL x UI for all known platforms, but it's 6496 // better not to make any assumptions). 6497 // We assume that int128 has a higher rank than long long on all platforms. 6498 enum PromotedType { 6499 Dep=-1, 6500 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6501 }; 6502 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6503 [LastPromotedArithmeticType] = { 6504 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6505 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6506 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6507 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6508 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6509 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6510 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6511 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6512 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6513 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6514 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6515 }; 6516 6517 assert(L < LastPromotedArithmeticType); 6518 assert(R < LastPromotedArithmeticType); 6519 int Idx = ConversionsTable[L][R]; 6520 6521 // Fast path: the table gives us a concrete answer. 6522 if (Idx != Dep) return getArithmeticType(Idx); 6523 6524 // Slow path: we need to compare widths. 6525 // An invariant is that the signed type has higher rank. 6526 CanQualType LT = getArithmeticType(L), 6527 RT = getArithmeticType(R); 6528 unsigned LW = S.Context.getIntWidth(LT), 6529 RW = S.Context.getIntWidth(RT); 6530 6531 // If they're different widths, use the signed type. 6532 if (LW > RW) return LT; 6533 else if (LW < RW) return RT; 6534 6535 // Otherwise, use the unsigned type of the signed type's rank. 6536 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6537 assert(L == SLL || R == SLL); 6538 return S.Context.UnsignedLongLongTy; 6539 } 6540 6541 /// \brief Helper method to factor out the common pattern of adding overloads 6542 /// for '++' and '--' builtin operators. 6543 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6544 bool HasVolatile, 6545 bool HasRestrict) { 6546 QualType ParamTypes[2] = { 6547 S.Context.getLValueReferenceType(CandidateTy), 6548 S.Context.IntTy 6549 }; 6550 6551 // Non-volatile version. 6552 if (NumArgs == 1) 6553 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6554 else 6555 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6556 6557 // Use a heuristic to reduce number of builtin candidates in the set: 6558 // add volatile version only if there are conversions to a volatile type. 6559 if (HasVolatile) { 6560 ParamTypes[0] = 6561 S.Context.getLValueReferenceType( 6562 S.Context.getVolatileType(CandidateTy)); 6563 if (NumArgs == 1) 6564 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6565 else 6566 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6567 } 6568 6569 // Add restrict version only if there are conversions to a restrict type 6570 // and our candidate type is a non-restrict-qualified pointer. 6571 if (HasRestrict && CandidateTy->isAnyPointerType() && 6572 !CandidateTy.isRestrictQualified()) { 6573 ParamTypes[0] 6574 = S.Context.getLValueReferenceType( 6575 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6576 if (NumArgs == 1) 6577 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6578 else 6579 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6580 6581 if (HasVolatile) { 6582 ParamTypes[0] 6583 = S.Context.getLValueReferenceType( 6584 S.Context.getCVRQualifiedType(CandidateTy, 6585 (Qualifiers::Volatile | 6586 Qualifiers::Restrict))); 6587 if (NumArgs == 1) 6588 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6589 CandidateSet); 6590 else 6591 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6592 } 6593 } 6594 6595 } 6596 6597 public: 6598 BuiltinOperatorOverloadBuilder( 6599 Sema &S, Expr **Args, unsigned NumArgs, 6600 Qualifiers VisibleTypeConversionsQuals, 6601 bool HasArithmeticOrEnumeralCandidateType, 6602 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6603 OverloadCandidateSet &CandidateSet) 6604 : S(S), Args(Args), NumArgs(NumArgs), 6605 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6606 HasArithmeticOrEnumeralCandidateType( 6607 HasArithmeticOrEnumeralCandidateType), 6608 CandidateTypes(CandidateTypes), 6609 CandidateSet(CandidateSet) { 6610 // Validate some of our static helper constants in debug builds. 6611 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6612 "Invalid first promoted integral type"); 6613 assert(getArithmeticType(LastPromotedIntegralType - 1) 6614 == S.Context.UnsignedInt128Ty && 6615 "Invalid last promoted integral type"); 6616 assert(getArithmeticType(FirstPromotedArithmeticType) 6617 == S.Context.FloatTy && 6618 "Invalid first promoted arithmetic type"); 6619 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6620 == S.Context.UnsignedInt128Ty && 6621 "Invalid last promoted arithmetic type"); 6622 } 6623 6624 // C++ [over.built]p3: 6625 // 6626 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6627 // is either volatile or empty, there exist candidate operator 6628 // functions of the form 6629 // 6630 // VQ T& operator++(VQ T&); 6631 // T operator++(VQ T&, int); 6632 // 6633 // C++ [over.built]p4: 6634 // 6635 // For every pair (T, VQ), where T is an arithmetic type other 6636 // than bool, and VQ is either volatile or empty, there exist 6637 // candidate operator functions of the form 6638 // 6639 // VQ T& operator--(VQ T&); 6640 // T operator--(VQ T&, int); 6641 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6642 if (!HasArithmeticOrEnumeralCandidateType) 6643 return; 6644 6645 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6646 Arith < NumArithmeticTypes; ++Arith) { 6647 addPlusPlusMinusMinusStyleOverloads( 6648 getArithmeticType(Arith), 6649 VisibleTypeConversionsQuals.hasVolatile(), 6650 VisibleTypeConversionsQuals.hasRestrict()); 6651 } 6652 } 6653 6654 // C++ [over.built]p5: 6655 // 6656 // For every pair (T, VQ), where T is a cv-qualified or 6657 // cv-unqualified object type, and VQ is either volatile or 6658 // empty, there exist candidate operator functions of the form 6659 // 6660 // T*VQ& operator++(T*VQ&); 6661 // T*VQ& operator--(T*VQ&); 6662 // T* operator++(T*VQ&, int); 6663 // T* operator--(T*VQ&, int); 6664 void addPlusPlusMinusMinusPointerOverloads() { 6665 for (BuiltinCandidateTypeSet::iterator 6666 Ptr = CandidateTypes[0].pointer_begin(), 6667 PtrEnd = CandidateTypes[0].pointer_end(); 6668 Ptr != PtrEnd; ++Ptr) { 6669 // Skip pointer types that aren't pointers to object types. 6670 if (!(*Ptr)->getPointeeType()->isObjectType()) 6671 continue; 6672 6673 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6674 (!(*Ptr).isVolatileQualified() && 6675 VisibleTypeConversionsQuals.hasVolatile()), 6676 (!(*Ptr).isRestrictQualified() && 6677 VisibleTypeConversionsQuals.hasRestrict())); 6678 } 6679 } 6680 6681 // C++ [over.built]p6: 6682 // For every cv-qualified or cv-unqualified object type T, there 6683 // exist candidate operator functions of the form 6684 // 6685 // T& operator*(T*); 6686 // 6687 // C++ [over.built]p7: 6688 // For every function type T that does not have cv-qualifiers or a 6689 // ref-qualifier, there exist candidate operator functions of the form 6690 // T& operator*(T*); 6691 void addUnaryStarPointerOverloads() { 6692 for (BuiltinCandidateTypeSet::iterator 6693 Ptr = CandidateTypes[0].pointer_begin(), 6694 PtrEnd = CandidateTypes[0].pointer_end(); 6695 Ptr != PtrEnd; ++Ptr) { 6696 QualType ParamTy = *Ptr; 6697 QualType PointeeTy = ParamTy->getPointeeType(); 6698 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6699 continue; 6700 6701 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6702 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6703 continue; 6704 6705 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6706 &ParamTy, Args, 1, CandidateSet); 6707 } 6708 } 6709 6710 // C++ [over.built]p9: 6711 // For every promoted arithmetic type T, there exist candidate 6712 // operator functions of the form 6713 // 6714 // T operator+(T); 6715 // T operator-(T); 6716 void addUnaryPlusOrMinusArithmeticOverloads() { 6717 if (!HasArithmeticOrEnumeralCandidateType) 6718 return; 6719 6720 for (unsigned Arith = FirstPromotedArithmeticType; 6721 Arith < LastPromotedArithmeticType; ++Arith) { 6722 QualType ArithTy = getArithmeticType(Arith); 6723 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6724 } 6725 6726 // Extension: We also add these operators for vector types. 6727 for (BuiltinCandidateTypeSet::iterator 6728 Vec = CandidateTypes[0].vector_begin(), 6729 VecEnd = CandidateTypes[0].vector_end(); 6730 Vec != VecEnd; ++Vec) { 6731 QualType VecTy = *Vec; 6732 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6733 } 6734 } 6735 6736 // C++ [over.built]p8: 6737 // For every type T, there exist candidate operator functions of 6738 // the form 6739 // 6740 // T* operator+(T*); 6741 void addUnaryPlusPointerOverloads() { 6742 for (BuiltinCandidateTypeSet::iterator 6743 Ptr = CandidateTypes[0].pointer_begin(), 6744 PtrEnd = CandidateTypes[0].pointer_end(); 6745 Ptr != PtrEnd; ++Ptr) { 6746 QualType ParamTy = *Ptr; 6747 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6748 } 6749 } 6750 6751 // C++ [over.built]p10: 6752 // For every promoted integral type T, there exist candidate 6753 // operator functions of the form 6754 // 6755 // T operator~(T); 6756 void addUnaryTildePromotedIntegralOverloads() { 6757 if (!HasArithmeticOrEnumeralCandidateType) 6758 return; 6759 6760 for (unsigned Int = FirstPromotedIntegralType; 6761 Int < LastPromotedIntegralType; ++Int) { 6762 QualType IntTy = getArithmeticType(Int); 6763 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6764 } 6765 6766 // Extension: We also add this operator for vector types. 6767 for (BuiltinCandidateTypeSet::iterator 6768 Vec = CandidateTypes[0].vector_begin(), 6769 VecEnd = CandidateTypes[0].vector_end(); 6770 Vec != VecEnd; ++Vec) { 6771 QualType VecTy = *Vec; 6772 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6773 } 6774 } 6775 6776 // C++ [over.match.oper]p16: 6777 // For every pointer to member type T, there exist candidate operator 6778 // functions of the form 6779 // 6780 // bool operator==(T,T); 6781 // bool operator!=(T,T); 6782 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6783 /// Set of (canonical) types that we've already handled. 6784 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6785 6786 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6787 for (BuiltinCandidateTypeSet::iterator 6788 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6789 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6790 MemPtr != MemPtrEnd; 6791 ++MemPtr) { 6792 // Don't add the same builtin candidate twice. 6793 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6794 continue; 6795 6796 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6797 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6798 CandidateSet); 6799 } 6800 } 6801 } 6802 6803 // C++ [over.built]p15: 6804 // 6805 // For every T, where T is an enumeration type, a pointer type, or 6806 // std::nullptr_t, there exist candidate operator functions of the form 6807 // 6808 // bool operator<(T, T); 6809 // bool operator>(T, T); 6810 // bool operator<=(T, T); 6811 // bool operator>=(T, T); 6812 // bool operator==(T, T); 6813 // bool operator!=(T, T); 6814 void addRelationalPointerOrEnumeralOverloads() { 6815 // C++ [over.match.oper]p3: 6816 // [...]the built-in candidates include all of the candidate operator 6817 // functions defined in 13.6 that, compared to the given operator, [...] 6818 // do not have the same parameter-type-list as any non-template non-member 6819 // candidate. 6820 // 6821 // Note that in practice, this only affects enumeration types because there 6822 // aren't any built-in candidates of record type, and a user-defined operator 6823 // must have an operand of record or enumeration type. Also, the only other 6824 // overloaded operator with enumeration arguments, operator=, 6825 // cannot be overloaded for enumeration types, so this is the only place 6826 // where we must suppress candidates like this. 6827 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6828 UserDefinedBinaryOperators; 6829 6830 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6831 if (CandidateTypes[ArgIdx].enumeration_begin() != 6832 CandidateTypes[ArgIdx].enumeration_end()) { 6833 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6834 CEnd = CandidateSet.end(); 6835 C != CEnd; ++C) { 6836 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6837 continue; 6838 6839 if (C->Function->isFunctionTemplateSpecialization()) 6840 continue; 6841 6842 QualType FirstParamType = 6843 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6844 QualType SecondParamType = 6845 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6846 6847 // Skip if either parameter isn't of enumeral type. 6848 if (!FirstParamType->isEnumeralType() || 6849 !SecondParamType->isEnumeralType()) 6850 continue; 6851 6852 // Add this operator to the set of known user-defined operators. 6853 UserDefinedBinaryOperators.insert( 6854 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6855 S.Context.getCanonicalType(SecondParamType))); 6856 } 6857 } 6858 } 6859 6860 /// Set of (canonical) types that we've already handled. 6861 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6862 6863 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6864 for (BuiltinCandidateTypeSet::iterator 6865 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6866 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6867 Ptr != PtrEnd; ++Ptr) { 6868 // Don't add the same builtin candidate twice. 6869 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6870 continue; 6871 6872 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6873 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6874 CandidateSet); 6875 } 6876 for (BuiltinCandidateTypeSet::iterator 6877 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6878 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6879 Enum != EnumEnd; ++Enum) { 6880 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6881 6882 // Don't add the same builtin candidate twice, or if a user defined 6883 // candidate exists. 6884 if (!AddedTypes.insert(CanonType) || 6885 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6886 CanonType))) 6887 continue; 6888 6889 QualType ParamTypes[2] = { *Enum, *Enum }; 6890 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6891 CandidateSet); 6892 } 6893 6894 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6895 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6896 if (AddedTypes.insert(NullPtrTy) && 6897 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6898 NullPtrTy))) { 6899 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6900 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6901 CandidateSet); 6902 } 6903 } 6904 } 6905 } 6906 6907 // C++ [over.built]p13: 6908 // 6909 // For every cv-qualified or cv-unqualified object type T 6910 // there exist candidate operator functions of the form 6911 // 6912 // T* operator+(T*, ptrdiff_t); 6913 // T& operator[](T*, ptrdiff_t); [BELOW] 6914 // T* operator-(T*, ptrdiff_t); 6915 // T* operator+(ptrdiff_t, T*); 6916 // T& operator[](ptrdiff_t, T*); [BELOW] 6917 // 6918 // C++ [over.built]p14: 6919 // 6920 // For every T, where T is a pointer to object type, there 6921 // exist candidate operator functions of the form 6922 // 6923 // ptrdiff_t operator-(T, T); 6924 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6925 /// Set of (canonical) types that we've already handled. 6926 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6927 6928 for (int Arg = 0; Arg < 2; ++Arg) { 6929 QualType AsymetricParamTypes[2] = { 6930 S.Context.getPointerDiffType(), 6931 S.Context.getPointerDiffType(), 6932 }; 6933 for (BuiltinCandidateTypeSet::iterator 6934 Ptr = CandidateTypes[Arg].pointer_begin(), 6935 PtrEnd = CandidateTypes[Arg].pointer_end(); 6936 Ptr != PtrEnd; ++Ptr) { 6937 QualType PointeeTy = (*Ptr)->getPointeeType(); 6938 if (!PointeeTy->isObjectType()) 6939 continue; 6940 6941 AsymetricParamTypes[Arg] = *Ptr; 6942 if (Arg == 0 || Op == OO_Plus) { 6943 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6944 // T* operator+(ptrdiff_t, T*); 6945 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6946 CandidateSet); 6947 } 6948 if (Op == OO_Minus) { 6949 // ptrdiff_t operator-(T, T); 6950 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6951 continue; 6952 6953 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6954 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6955 Args, 2, CandidateSet); 6956 } 6957 } 6958 } 6959 } 6960 6961 // C++ [over.built]p12: 6962 // 6963 // For every pair of promoted arithmetic types L and R, there 6964 // exist candidate operator functions of the form 6965 // 6966 // LR operator*(L, R); 6967 // LR operator/(L, R); 6968 // LR operator+(L, R); 6969 // LR operator-(L, R); 6970 // bool operator<(L, R); 6971 // bool operator>(L, R); 6972 // bool operator<=(L, R); 6973 // bool operator>=(L, R); 6974 // bool operator==(L, R); 6975 // bool operator!=(L, R); 6976 // 6977 // where LR is the result of the usual arithmetic conversions 6978 // between types L and R. 6979 // 6980 // C++ [over.built]p24: 6981 // 6982 // For every pair of promoted arithmetic types L and R, there exist 6983 // candidate operator functions of the form 6984 // 6985 // LR operator?(bool, L, R); 6986 // 6987 // where LR is the result of the usual arithmetic conversions 6988 // between types L and R. 6989 // Our candidates ignore the first parameter. 6990 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6991 if (!HasArithmeticOrEnumeralCandidateType) 6992 return; 6993 6994 for (unsigned Left = FirstPromotedArithmeticType; 6995 Left < LastPromotedArithmeticType; ++Left) { 6996 for (unsigned Right = FirstPromotedArithmeticType; 6997 Right < LastPromotedArithmeticType; ++Right) { 6998 QualType LandR[2] = { getArithmeticType(Left), 6999 getArithmeticType(Right) }; 7000 QualType Result = 7001 isComparison ? S.Context.BoolTy 7002 : getUsualArithmeticConversions(Left, Right); 7003 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7004 } 7005 } 7006 7007 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7008 // conditional operator for vector types. 7009 for (BuiltinCandidateTypeSet::iterator 7010 Vec1 = CandidateTypes[0].vector_begin(), 7011 Vec1End = CandidateTypes[0].vector_end(); 7012 Vec1 != Vec1End; ++Vec1) { 7013 for (BuiltinCandidateTypeSet::iterator 7014 Vec2 = CandidateTypes[1].vector_begin(), 7015 Vec2End = CandidateTypes[1].vector_end(); 7016 Vec2 != Vec2End; ++Vec2) { 7017 QualType LandR[2] = { *Vec1, *Vec2 }; 7018 QualType Result = S.Context.BoolTy; 7019 if (!isComparison) { 7020 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7021 Result = *Vec1; 7022 else 7023 Result = *Vec2; 7024 } 7025 7026 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7027 } 7028 } 7029 } 7030 7031 // C++ [over.built]p17: 7032 // 7033 // For every pair of promoted integral types L and R, there 7034 // exist candidate operator functions of the form 7035 // 7036 // LR operator%(L, R); 7037 // LR operator&(L, R); 7038 // LR operator^(L, R); 7039 // LR operator|(L, R); 7040 // L operator<<(L, R); 7041 // L operator>>(L, R); 7042 // 7043 // where LR is the result of the usual arithmetic conversions 7044 // between types L and R. 7045 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7046 if (!HasArithmeticOrEnumeralCandidateType) 7047 return; 7048 7049 for (unsigned Left = FirstPromotedIntegralType; 7050 Left < LastPromotedIntegralType; ++Left) { 7051 for (unsigned Right = FirstPromotedIntegralType; 7052 Right < LastPromotedIntegralType; ++Right) { 7053 QualType LandR[2] = { getArithmeticType(Left), 7054 getArithmeticType(Right) }; 7055 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7056 ? LandR[0] 7057 : getUsualArithmeticConversions(Left, Right); 7058 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7059 } 7060 } 7061 } 7062 7063 // C++ [over.built]p20: 7064 // 7065 // For every pair (T, VQ), where T is an enumeration or 7066 // pointer to member type and VQ is either volatile or 7067 // empty, there exist candidate operator functions of the form 7068 // 7069 // VQ T& operator=(VQ T&, T); 7070 void addAssignmentMemberPointerOrEnumeralOverloads() { 7071 /// Set of (canonical) types that we've already handled. 7072 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7073 7074 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7075 for (BuiltinCandidateTypeSet::iterator 7076 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7077 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7078 Enum != EnumEnd; ++Enum) { 7079 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7080 continue; 7081 7082 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7083 CandidateSet); 7084 } 7085 7086 for (BuiltinCandidateTypeSet::iterator 7087 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7088 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7089 MemPtr != MemPtrEnd; ++MemPtr) { 7090 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7091 continue; 7092 7093 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7094 CandidateSet); 7095 } 7096 } 7097 } 7098 7099 // C++ [over.built]p19: 7100 // 7101 // For every pair (T, VQ), where T is any type and VQ is either 7102 // volatile or empty, there exist candidate operator functions 7103 // of the form 7104 // 7105 // T*VQ& operator=(T*VQ&, T*); 7106 // 7107 // C++ [over.built]p21: 7108 // 7109 // For every pair (T, VQ), where T is a cv-qualified or 7110 // cv-unqualified object type and VQ is either volatile or 7111 // empty, there exist candidate operator functions of the form 7112 // 7113 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7114 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7115 void addAssignmentPointerOverloads(bool isEqualOp) { 7116 /// Set of (canonical) types that we've already handled. 7117 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7118 7119 for (BuiltinCandidateTypeSet::iterator 7120 Ptr = CandidateTypes[0].pointer_begin(), 7121 PtrEnd = CandidateTypes[0].pointer_end(); 7122 Ptr != PtrEnd; ++Ptr) { 7123 // If this is operator=, keep track of the builtin candidates we added. 7124 if (isEqualOp) 7125 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7126 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7127 continue; 7128 7129 // non-volatile version 7130 QualType ParamTypes[2] = { 7131 S.Context.getLValueReferenceType(*Ptr), 7132 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7133 }; 7134 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7135 /*IsAssigmentOperator=*/ isEqualOp); 7136 7137 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7138 VisibleTypeConversionsQuals.hasVolatile(); 7139 if (NeedVolatile) { 7140 // volatile version 7141 ParamTypes[0] = 7142 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7143 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7144 /*IsAssigmentOperator=*/isEqualOp); 7145 } 7146 7147 if (!(*Ptr).isRestrictQualified() && 7148 VisibleTypeConversionsQuals.hasRestrict()) { 7149 // restrict version 7150 ParamTypes[0] 7151 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7152 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7153 /*IsAssigmentOperator=*/isEqualOp); 7154 7155 if (NeedVolatile) { 7156 // volatile restrict version 7157 ParamTypes[0] 7158 = S.Context.getLValueReferenceType( 7159 S.Context.getCVRQualifiedType(*Ptr, 7160 (Qualifiers::Volatile | 7161 Qualifiers::Restrict))); 7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7163 CandidateSet, 7164 /*IsAssigmentOperator=*/isEqualOp); 7165 } 7166 } 7167 } 7168 7169 if (isEqualOp) { 7170 for (BuiltinCandidateTypeSet::iterator 7171 Ptr = CandidateTypes[1].pointer_begin(), 7172 PtrEnd = CandidateTypes[1].pointer_end(); 7173 Ptr != PtrEnd; ++Ptr) { 7174 // Make sure we don't add the same candidate twice. 7175 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7176 continue; 7177 7178 QualType ParamTypes[2] = { 7179 S.Context.getLValueReferenceType(*Ptr), 7180 *Ptr, 7181 }; 7182 7183 // non-volatile version 7184 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7185 /*IsAssigmentOperator=*/true); 7186 7187 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7188 VisibleTypeConversionsQuals.hasVolatile(); 7189 if (NeedVolatile) { 7190 // volatile version 7191 ParamTypes[0] = 7192 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7194 CandidateSet, /*IsAssigmentOperator=*/true); 7195 } 7196 7197 if (!(*Ptr).isRestrictQualified() && 7198 VisibleTypeConversionsQuals.hasRestrict()) { 7199 // restrict version 7200 ParamTypes[0] 7201 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7203 CandidateSet, /*IsAssigmentOperator=*/true); 7204 7205 if (NeedVolatile) { 7206 // volatile restrict version 7207 ParamTypes[0] 7208 = S.Context.getLValueReferenceType( 7209 S.Context.getCVRQualifiedType(*Ptr, 7210 (Qualifiers::Volatile | 7211 Qualifiers::Restrict))); 7212 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7213 CandidateSet, /*IsAssigmentOperator=*/true); 7214 7215 } 7216 } 7217 } 7218 } 7219 } 7220 7221 // C++ [over.built]p18: 7222 // 7223 // For every triple (L, VQ, R), where L is an arithmetic type, 7224 // VQ is either volatile or empty, and R is a promoted 7225 // arithmetic type, there exist candidate operator functions of 7226 // the form 7227 // 7228 // VQ L& operator=(VQ L&, R); 7229 // VQ L& operator*=(VQ L&, R); 7230 // VQ L& operator/=(VQ L&, R); 7231 // VQ L& operator+=(VQ L&, R); 7232 // VQ L& operator-=(VQ L&, R); 7233 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7234 if (!HasArithmeticOrEnumeralCandidateType) 7235 return; 7236 7237 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7238 for (unsigned Right = FirstPromotedArithmeticType; 7239 Right < LastPromotedArithmeticType; ++Right) { 7240 QualType ParamTypes[2]; 7241 ParamTypes[1] = getArithmeticType(Right); 7242 7243 // Add this built-in operator as a candidate (VQ is empty). 7244 ParamTypes[0] = 7245 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7246 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7247 /*IsAssigmentOperator=*/isEqualOp); 7248 7249 // Add this built-in operator as a candidate (VQ is 'volatile'). 7250 if (VisibleTypeConversionsQuals.hasVolatile()) { 7251 ParamTypes[0] = 7252 S.Context.getVolatileType(getArithmeticType(Left)); 7253 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7254 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7255 CandidateSet, 7256 /*IsAssigmentOperator=*/isEqualOp); 7257 } 7258 } 7259 } 7260 7261 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7262 for (BuiltinCandidateTypeSet::iterator 7263 Vec1 = CandidateTypes[0].vector_begin(), 7264 Vec1End = CandidateTypes[0].vector_end(); 7265 Vec1 != Vec1End; ++Vec1) { 7266 for (BuiltinCandidateTypeSet::iterator 7267 Vec2 = CandidateTypes[1].vector_begin(), 7268 Vec2End = CandidateTypes[1].vector_end(); 7269 Vec2 != Vec2End; ++Vec2) { 7270 QualType ParamTypes[2]; 7271 ParamTypes[1] = *Vec2; 7272 // Add this built-in operator as a candidate (VQ is empty). 7273 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7274 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7275 /*IsAssigmentOperator=*/isEqualOp); 7276 7277 // Add this built-in operator as a candidate (VQ is 'volatile'). 7278 if (VisibleTypeConversionsQuals.hasVolatile()) { 7279 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7280 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7281 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7282 CandidateSet, 7283 /*IsAssigmentOperator=*/isEqualOp); 7284 } 7285 } 7286 } 7287 } 7288 7289 // C++ [over.built]p22: 7290 // 7291 // For every triple (L, VQ, R), where L is an integral type, VQ 7292 // is either volatile or empty, and R is a promoted integral 7293 // type, there exist candidate operator functions of the form 7294 // 7295 // VQ L& operator%=(VQ L&, R); 7296 // VQ L& operator<<=(VQ L&, R); 7297 // VQ L& operator>>=(VQ L&, R); 7298 // VQ L& operator&=(VQ L&, R); 7299 // VQ L& operator^=(VQ L&, R); 7300 // VQ L& operator|=(VQ L&, R); 7301 void addAssignmentIntegralOverloads() { 7302 if (!HasArithmeticOrEnumeralCandidateType) 7303 return; 7304 7305 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7306 for (unsigned Right = FirstPromotedIntegralType; 7307 Right < LastPromotedIntegralType; ++Right) { 7308 QualType ParamTypes[2]; 7309 ParamTypes[1] = getArithmeticType(Right); 7310 7311 // Add this built-in operator as a candidate (VQ is empty). 7312 ParamTypes[0] = 7313 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7315 if (VisibleTypeConversionsQuals.hasVolatile()) { 7316 // Add this built-in operator as a candidate (VQ is 'volatile'). 7317 ParamTypes[0] = getArithmeticType(Left); 7318 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7319 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7321 CandidateSet); 7322 } 7323 } 7324 } 7325 } 7326 7327 // C++ [over.operator]p23: 7328 // 7329 // There also exist candidate operator functions of the form 7330 // 7331 // bool operator!(bool); 7332 // bool operator&&(bool, bool); 7333 // bool operator||(bool, bool); 7334 void addExclaimOverload() { 7335 QualType ParamTy = S.Context.BoolTy; 7336 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7337 /*IsAssignmentOperator=*/false, 7338 /*NumContextualBoolArguments=*/1); 7339 } 7340 void addAmpAmpOrPipePipeOverload() { 7341 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7342 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7343 /*IsAssignmentOperator=*/false, 7344 /*NumContextualBoolArguments=*/2); 7345 } 7346 7347 // C++ [over.built]p13: 7348 // 7349 // For every cv-qualified or cv-unqualified object type T there 7350 // exist candidate operator functions of the form 7351 // 7352 // T* operator+(T*, ptrdiff_t); [ABOVE] 7353 // T& operator[](T*, ptrdiff_t); 7354 // T* operator-(T*, ptrdiff_t); [ABOVE] 7355 // T* operator+(ptrdiff_t, T*); [ABOVE] 7356 // T& operator[](ptrdiff_t, T*); 7357 void addSubscriptOverloads() { 7358 for (BuiltinCandidateTypeSet::iterator 7359 Ptr = CandidateTypes[0].pointer_begin(), 7360 PtrEnd = CandidateTypes[0].pointer_end(); 7361 Ptr != PtrEnd; ++Ptr) { 7362 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7363 QualType PointeeType = (*Ptr)->getPointeeType(); 7364 if (!PointeeType->isObjectType()) 7365 continue; 7366 7367 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7368 7369 // T& operator[](T*, ptrdiff_t) 7370 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7371 } 7372 7373 for (BuiltinCandidateTypeSet::iterator 7374 Ptr = CandidateTypes[1].pointer_begin(), 7375 PtrEnd = CandidateTypes[1].pointer_end(); 7376 Ptr != PtrEnd; ++Ptr) { 7377 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7378 QualType PointeeType = (*Ptr)->getPointeeType(); 7379 if (!PointeeType->isObjectType()) 7380 continue; 7381 7382 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7383 7384 // T& operator[](ptrdiff_t, T*) 7385 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7386 } 7387 } 7388 7389 // C++ [over.built]p11: 7390 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7391 // C1 is the same type as C2 or is a derived class of C2, T is an object 7392 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7393 // there exist candidate operator functions of the form 7394 // 7395 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7396 // 7397 // where CV12 is the union of CV1 and CV2. 7398 void addArrowStarOverloads() { 7399 for (BuiltinCandidateTypeSet::iterator 7400 Ptr = CandidateTypes[0].pointer_begin(), 7401 PtrEnd = CandidateTypes[0].pointer_end(); 7402 Ptr != PtrEnd; ++Ptr) { 7403 QualType C1Ty = (*Ptr); 7404 QualType C1; 7405 QualifierCollector Q1; 7406 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7407 if (!isa<RecordType>(C1)) 7408 continue; 7409 // heuristic to reduce number of builtin candidates in the set. 7410 // Add volatile/restrict version only if there are conversions to a 7411 // volatile/restrict type. 7412 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7413 continue; 7414 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7415 continue; 7416 for (BuiltinCandidateTypeSet::iterator 7417 MemPtr = CandidateTypes[1].member_pointer_begin(), 7418 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7419 MemPtr != MemPtrEnd; ++MemPtr) { 7420 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7421 QualType C2 = QualType(mptr->getClass(), 0); 7422 C2 = C2.getUnqualifiedType(); 7423 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7424 break; 7425 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7426 // build CV12 T& 7427 QualType T = mptr->getPointeeType(); 7428 if (!VisibleTypeConversionsQuals.hasVolatile() && 7429 T.isVolatileQualified()) 7430 continue; 7431 if (!VisibleTypeConversionsQuals.hasRestrict() && 7432 T.isRestrictQualified()) 7433 continue; 7434 T = Q1.apply(S.Context, T); 7435 QualType ResultTy = S.Context.getLValueReferenceType(T); 7436 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7437 } 7438 } 7439 } 7440 7441 // Note that we don't consider the first argument, since it has been 7442 // contextually converted to bool long ago. The candidates below are 7443 // therefore added as binary. 7444 // 7445 // C++ [over.built]p25: 7446 // For every type T, where T is a pointer, pointer-to-member, or scoped 7447 // enumeration type, there exist candidate operator functions of the form 7448 // 7449 // T operator?(bool, T, T); 7450 // 7451 void addConditionalOperatorOverloads() { 7452 /// Set of (canonical) types that we've already handled. 7453 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7454 7455 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7456 for (BuiltinCandidateTypeSet::iterator 7457 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7458 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7459 Ptr != PtrEnd; ++Ptr) { 7460 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7461 continue; 7462 7463 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7464 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7465 } 7466 7467 for (BuiltinCandidateTypeSet::iterator 7468 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7469 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7470 MemPtr != MemPtrEnd; ++MemPtr) { 7471 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7472 continue; 7473 7474 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7475 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7476 } 7477 7478 if (S.getLangOpts().CPlusPlus11) { 7479 for (BuiltinCandidateTypeSet::iterator 7480 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7481 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7482 Enum != EnumEnd; ++Enum) { 7483 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7484 continue; 7485 7486 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7487 continue; 7488 7489 QualType ParamTypes[2] = { *Enum, *Enum }; 7490 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7491 } 7492 } 7493 } 7494 } 7495 }; 7496 7497 } // end anonymous namespace 7498 7499 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7500 /// operator overloads to the candidate set (C++ [over.built]), based 7501 /// on the operator @p Op and the arguments given. For example, if the 7502 /// operator is a binary '+', this routine might add "int 7503 /// operator+(int, int)" to cover integer addition. 7504 void 7505 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7506 SourceLocation OpLoc, 7507 Expr **Args, unsigned NumArgs, 7508 OverloadCandidateSet& CandidateSet) { 7509 // Find all of the types that the arguments can convert to, but only 7510 // if the operator we're looking at has built-in operator candidates 7511 // that make use of these types. Also record whether we encounter non-record 7512 // candidate types or either arithmetic or enumeral candidate types. 7513 Qualifiers VisibleTypeConversionsQuals; 7514 VisibleTypeConversionsQuals.addConst(); 7515 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7516 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7517 7518 bool HasNonRecordCandidateType = false; 7519 bool HasArithmeticOrEnumeralCandidateType = false; 7520 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7521 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7522 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7523 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7524 OpLoc, 7525 true, 7526 (Op == OO_Exclaim || 7527 Op == OO_AmpAmp || 7528 Op == OO_PipePipe), 7529 VisibleTypeConversionsQuals); 7530 HasNonRecordCandidateType = HasNonRecordCandidateType || 7531 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7532 HasArithmeticOrEnumeralCandidateType = 7533 HasArithmeticOrEnumeralCandidateType || 7534 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7535 } 7536 7537 // Exit early when no non-record types have been added to the candidate set 7538 // for any of the arguments to the operator. 7539 // 7540 // We can't exit early for !, ||, or &&, since there we have always have 7541 // 'bool' overloads. 7542 if (!HasNonRecordCandidateType && 7543 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7544 return; 7545 7546 // Setup an object to manage the common state for building overloads. 7547 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7548 VisibleTypeConversionsQuals, 7549 HasArithmeticOrEnumeralCandidateType, 7550 CandidateTypes, CandidateSet); 7551 7552 // Dispatch over the operation to add in only those overloads which apply. 7553 switch (Op) { 7554 case OO_None: 7555 case NUM_OVERLOADED_OPERATORS: 7556 llvm_unreachable("Expected an overloaded operator"); 7557 7558 case OO_New: 7559 case OO_Delete: 7560 case OO_Array_New: 7561 case OO_Array_Delete: 7562 case OO_Call: 7563 llvm_unreachable( 7564 "Special operators don't use AddBuiltinOperatorCandidates"); 7565 7566 case OO_Comma: 7567 case OO_Arrow: 7568 // C++ [over.match.oper]p3: 7569 // -- For the operator ',', the unary operator '&', or the 7570 // operator '->', the built-in candidates set is empty. 7571 break; 7572 7573 case OO_Plus: // '+' is either unary or binary 7574 if (NumArgs == 1) 7575 OpBuilder.addUnaryPlusPointerOverloads(); 7576 // Fall through. 7577 7578 case OO_Minus: // '-' is either unary or binary 7579 if (NumArgs == 1) { 7580 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7581 } else { 7582 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7583 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7584 } 7585 break; 7586 7587 case OO_Star: // '*' is either unary or binary 7588 if (NumArgs == 1) 7589 OpBuilder.addUnaryStarPointerOverloads(); 7590 else 7591 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7592 break; 7593 7594 case OO_Slash: 7595 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7596 break; 7597 7598 case OO_PlusPlus: 7599 case OO_MinusMinus: 7600 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7601 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7602 break; 7603 7604 case OO_EqualEqual: 7605 case OO_ExclaimEqual: 7606 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7607 // Fall through. 7608 7609 case OO_Less: 7610 case OO_Greater: 7611 case OO_LessEqual: 7612 case OO_GreaterEqual: 7613 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7614 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7615 break; 7616 7617 case OO_Percent: 7618 case OO_Caret: 7619 case OO_Pipe: 7620 case OO_LessLess: 7621 case OO_GreaterGreater: 7622 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7623 break; 7624 7625 case OO_Amp: // '&' is either unary or binary 7626 if (NumArgs == 1) 7627 // C++ [over.match.oper]p3: 7628 // -- For the operator ',', the unary operator '&', or the 7629 // operator '->', the built-in candidates set is empty. 7630 break; 7631 7632 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7633 break; 7634 7635 case OO_Tilde: 7636 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7637 break; 7638 7639 case OO_Equal: 7640 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7641 // Fall through. 7642 7643 case OO_PlusEqual: 7644 case OO_MinusEqual: 7645 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7646 // Fall through. 7647 7648 case OO_StarEqual: 7649 case OO_SlashEqual: 7650 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7651 break; 7652 7653 case OO_PercentEqual: 7654 case OO_LessLessEqual: 7655 case OO_GreaterGreaterEqual: 7656 case OO_AmpEqual: 7657 case OO_CaretEqual: 7658 case OO_PipeEqual: 7659 OpBuilder.addAssignmentIntegralOverloads(); 7660 break; 7661 7662 case OO_Exclaim: 7663 OpBuilder.addExclaimOverload(); 7664 break; 7665 7666 case OO_AmpAmp: 7667 case OO_PipePipe: 7668 OpBuilder.addAmpAmpOrPipePipeOverload(); 7669 break; 7670 7671 case OO_Subscript: 7672 OpBuilder.addSubscriptOverloads(); 7673 break; 7674 7675 case OO_ArrowStar: 7676 OpBuilder.addArrowStarOverloads(); 7677 break; 7678 7679 case OO_Conditional: 7680 OpBuilder.addConditionalOperatorOverloads(); 7681 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7682 break; 7683 } 7684 } 7685 7686 /// \brief Add function candidates found via argument-dependent lookup 7687 /// to the set of overloading candidates. 7688 /// 7689 /// This routine performs argument-dependent name lookup based on the 7690 /// given function name (which may also be an operator name) and adds 7691 /// all of the overload candidates found by ADL to the overload 7692 /// candidate set (C++ [basic.lookup.argdep]). 7693 void 7694 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7695 bool Operator, SourceLocation Loc, 7696 ArrayRef<Expr *> Args, 7697 TemplateArgumentListInfo *ExplicitTemplateArgs, 7698 OverloadCandidateSet& CandidateSet, 7699 bool PartialOverloading) { 7700 ADLResult Fns; 7701 7702 // FIXME: This approach for uniquing ADL results (and removing 7703 // redundant candidates from the set) relies on pointer-equality, 7704 // which means we need to key off the canonical decl. However, 7705 // always going back to the canonical decl might not get us the 7706 // right set of default arguments. What default arguments are 7707 // we supposed to consider on ADL candidates, anyway? 7708 7709 // FIXME: Pass in the explicit template arguments? 7710 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7711 7712 // Erase all of the candidates we already knew about. 7713 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7714 CandEnd = CandidateSet.end(); 7715 Cand != CandEnd; ++Cand) 7716 if (Cand->Function) { 7717 Fns.erase(Cand->Function); 7718 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7719 Fns.erase(FunTmpl); 7720 } 7721 7722 // For each of the ADL candidates we found, add it to the overload 7723 // set. 7724 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7725 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7727 if (ExplicitTemplateArgs) 7728 continue; 7729 7730 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7731 PartialOverloading); 7732 } else 7733 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7734 FoundDecl, ExplicitTemplateArgs, 7735 Args, CandidateSet); 7736 } 7737 } 7738 7739 /// isBetterOverloadCandidate - Determines whether the first overload 7740 /// candidate is a better candidate than the second (C++ 13.3.3p1). 7741 bool 7742 isBetterOverloadCandidate(Sema &S, 7743 const OverloadCandidate &Cand1, 7744 const OverloadCandidate &Cand2, 7745 SourceLocation Loc, 7746 bool UserDefinedConversion) { 7747 // Define viable functions to be better candidates than non-viable 7748 // functions. 7749 if (!Cand2.Viable) 7750 return Cand1.Viable; 7751 else if (!Cand1.Viable) 7752 return false; 7753 7754 // C++ [over.match.best]p1: 7755 // 7756 // -- if F is a static member function, ICS1(F) is defined such 7757 // that ICS1(F) is neither better nor worse than ICS1(G) for 7758 // any function G, and, symmetrically, ICS1(G) is neither 7759 // better nor worse than ICS1(F). 7760 unsigned StartArg = 0; 7761 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7762 StartArg = 1; 7763 7764 // C++ [over.match.best]p1: 7765 // A viable function F1 is defined to be a better function than another 7766 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7767 // conversion sequence than ICSi(F2), and then... 7768 unsigned NumArgs = Cand1.NumConversions; 7769 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7770 bool HasBetterConversion = false; 7771 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7772 switch (CompareImplicitConversionSequences(S, 7773 Cand1.Conversions[ArgIdx], 7774 Cand2.Conversions[ArgIdx])) { 7775 case ImplicitConversionSequence::Better: 7776 // Cand1 has a better conversion sequence. 7777 HasBetterConversion = true; 7778 break; 7779 7780 case ImplicitConversionSequence::Worse: 7781 // Cand1 can't be better than Cand2. 7782 return false; 7783 7784 case ImplicitConversionSequence::Indistinguishable: 7785 // Do nothing. 7786 break; 7787 } 7788 } 7789 7790 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7791 // ICSj(F2), or, if not that, 7792 if (HasBetterConversion) 7793 return true; 7794 7795 // - F1 is a non-template function and F2 is a function template 7796 // specialization, or, if not that, 7797 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7798 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7799 return true; 7800 7801 // -- F1 and F2 are function template specializations, and the function 7802 // template for F1 is more specialized than the template for F2 7803 // according to the partial ordering rules described in 14.5.5.2, or, 7804 // if not that, 7805 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7806 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7807 if (FunctionTemplateDecl *BetterTemplate 7808 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7809 Cand2.Function->getPrimaryTemplate(), 7810 Loc, 7811 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7812 : TPOC_Call, 7813 Cand1.ExplicitCallArguments)) 7814 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7815 } 7816 7817 // -- the context is an initialization by user-defined conversion 7818 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7819 // from the return type of F1 to the destination type (i.e., 7820 // the type of the entity being initialized) is a better 7821 // conversion sequence than the standard conversion sequence 7822 // from the return type of F2 to the destination type. 7823 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7824 isa<CXXConversionDecl>(Cand1.Function) && 7825 isa<CXXConversionDecl>(Cand2.Function)) { 7826 // First check whether we prefer one of the conversion functions over the 7827 // other. This only distinguishes the results in non-standard, extension 7828 // cases such as the conversion from a lambda closure type to a function 7829 // pointer or block. 7830 ImplicitConversionSequence::CompareKind FuncResult 7831 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7832 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7833 return FuncResult; 7834 7835 switch (CompareStandardConversionSequences(S, 7836 Cand1.FinalConversion, 7837 Cand2.FinalConversion)) { 7838 case ImplicitConversionSequence::Better: 7839 // Cand1 has a better conversion sequence. 7840 return true; 7841 7842 case ImplicitConversionSequence::Worse: 7843 // Cand1 can't be better than Cand2. 7844 return false; 7845 7846 case ImplicitConversionSequence::Indistinguishable: 7847 // Do nothing 7848 break; 7849 } 7850 } 7851 7852 return false; 7853 } 7854 7855 /// \brief Computes the best viable function (C++ 13.3.3) 7856 /// within an overload candidate set. 7857 /// 7858 /// \param Loc The location of the function name (or operator symbol) for 7859 /// which overload resolution occurs. 7860 /// 7861 /// \param Best If overload resolution was successful or found a deleted 7862 /// function, \p Best points to the candidate function found. 7863 /// 7864 /// \returns The result of overload resolution. 7865 OverloadingResult 7866 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7867 iterator &Best, 7868 bool UserDefinedConversion) { 7869 // Find the best viable function. 7870 Best = end(); 7871 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7872 if (Cand->Viable) 7873 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7874 UserDefinedConversion)) 7875 Best = Cand; 7876 } 7877 7878 // If we didn't find any viable functions, abort. 7879 if (Best == end()) 7880 return OR_No_Viable_Function; 7881 7882 // Make sure that this function is better than every other viable 7883 // function. If not, we have an ambiguity. 7884 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7885 if (Cand->Viable && 7886 Cand != Best && 7887 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7888 UserDefinedConversion)) { 7889 Best = end(); 7890 return OR_Ambiguous; 7891 } 7892 } 7893 7894 // Best is the best viable function. 7895 if (Best->Function && 7896 (Best->Function->isDeleted() || 7897 S.isFunctionConsideredUnavailable(Best->Function))) 7898 return OR_Deleted; 7899 7900 return OR_Success; 7901 } 7902 7903 namespace { 7904 7905 enum OverloadCandidateKind { 7906 oc_function, 7907 oc_method, 7908 oc_constructor, 7909 oc_function_template, 7910 oc_method_template, 7911 oc_constructor_template, 7912 oc_implicit_default_constructor, 7913 oc_implicit_copy_constructor, 7914 oc_implicit_move_constructor, 7915 oc_implicit_copy_assignment, 7916 oc_implicit_move_assignment, 7917 oc_implicit_inherited_constructor 7918 }; 7919 7920 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7921 FunctionDecl *Fn, 7922 std::string &Description) { 7923 bool isTemplate = false; 7924 7925 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7926 isTemplate = true; 7927 Description = S.getTemplateArgumentBindingsText( 7928 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7929 } 7930 7931 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7932 if (!Ctor->isImplicit()) 7933 return isTemplate ? oc_constructor_template : oc_constructor; 7934 7935 if (Ctor->getInheritedConstructor()) 7936 return oc_implicit_inherited_constructor; 7937 7938 if (Ctor->isDefaultConstructor()) 7939 return oc_implicit_default_constructor; 7940 7941 if (Ctor->isMoveConstructor()) 7942 return oc_implicit_move_constructor; 7943 7944 assert(Ctor->isCopyConstructor() && 7945 "unexpected sort of implicit constructor"); 7946 return oc_implicit_copy_constructor; 7947 } 7948 7949 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7950 // This actually gets spelled 'candidate function' for now, but 7951 // it doesn't hurt to split it out. 7952 if (!Meth->isImplicit()) 7953 return isTemplate ? oc_method_template : oc_method; 7954 7955 if (Meth->isMoveAssignmentOperator()) 7956 return oc_implicit_move_assignment; 7957 7958 if (Meth->isCopyAssignmentOperator()) 7959 return oc_implicit_copy_assignment; 7960 7961 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7962 return oc_method; 7963 } 7964 7965 return isTemplate ? oc_function_template : oc_function; 7966 } 7967 7968 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7969 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7970 if (!Ctor) return; 7971 7972 Ctor = Ctor->getInheritedConstructor(); 7973 if (!Ctor) return; 7974 7975 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7976 } 7977 7978 } // end anonymous namespace 7979 7980 // Notes the location of an overload candidate. 7981 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7982 std::string FnDesc; 7983 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7984 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7985 << (unsigned) K << FnDesc; 7986 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7987 Diag(Fn->getLocation(), PD); 7988 MaybeEmitInheritedConstructorNote(*this, Fn); 7989 } 7990 7991 //Notes the location of all overload candidates designated through 7992 // OverloadedExpr 7993 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7994 assert(OverloadedExpr->getType() == Context.OverloadTy); 7995 7996 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7997 OverloadExpr *OvlExpr = Ovl.Expression; 7998 7999 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8000 IEnd = OvlExpr->decls_end(); 8001 I != IEnd; ++I) { 8002 if (FunctionTemplateDecl *FunTmpl = 8003 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8004 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8005 } else if (FunctionDecl *Fun 8006 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8007 NoteOverloadCandidate(Fun, DestType); 8008 } 8009 } 8010 } 8011 8012 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8013 /// "lead" diagnostic; it will be given two arguments, the source and 8014 /// target types of the conversion. 8015 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8016 Sema &S, 8017 SourceLocation CaretLoc, 8018 const PartialDiagnostic &PDiag) const { 8019 S.Diag(CaretLoc, PDiag) 8020 << Ambiguous.getFromType() << Ambiguous.getToType(); 8021 // FIXME: The note limiting machinery is borrowed from 8022 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8023 // refactoring here. 8024 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8025 unsigned CandsShown = 0; 8026 AmbiguousConversionSequence::const_iterator I, E; 8027 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8028 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8029 break; 8030 ++CandsShown; 8031 S.NoteOverloadCandidate(*I); 8032 } 8033 if (I != E) 8034 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8035 } 8036 8037 namespace { 8038 8039 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8040 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8041 assert(Conv.isBad()); 8042 assert(Cand->Function && "for now, candidate must be a function"); 8043 FunctionDecl *Fn = Cand->Function; 8044 8045 // There's a conversion slot for the object argument if this is a 8046 // non-constructor method. Note that 'I' corresponds the 8047 // conversion-slot index. 8048 bool isObjectArgument = false; 8049 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8050 if (I == 0) 8051 isObjectArgument = true; 8052 else 8053 I--; 8054 } 8055 8056 std::string FnDesc; 8057 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8058 8059 Expr *FromExpr = Conv.Bad.FromExpr; 8060 QualType FromTy = Conv.Bad.getFromType(); 8061 QualType ToTy = Conv.Bad.getToType(); 8062 8063 if (FromTy == S.Context.OverloadTy) { 8064 assert(FromExpr && "overload set argument came from implicit argument?"); 8065 Expr *E = FromExpr->IgnoreParens(); 8066 if (isa<UnaryOperator>(E)) 8067 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8068 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8069 8070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8071 << (unsigned) FnKind << FnDesc 8072 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8073 << ToTy << Name << I+1; 8074 MaybeEmitInheritedConstructorNote(S, Fn); 8075 return; 8076 } 8077 8078 // Do some hand-waving analysis to see if the non-viability is due 8079 // to a qualifier mismatch. 8080 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8081 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8082 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8083 CToTy = RT->getPointeeType(); 8084 else { 8085 // TODO: detect and diagnose the full richness of const mismatches. 8086 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8087 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8088 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8089 } 8090 8091 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8092 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8093 Qualifiers FromQs = CFromTy.getQualifiers(); 8094 Qualifiers ToQs = CToTy.getQualifiers(); 8095 8096 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8098 << (unsigned) FnKind << FnDesc 8099 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8100 << FromTy 8101 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8102 << (unsigned) isObjectArgument << I+1; 8103 MaybeEmitInheritedConstructorNote(S, Fn); 8104 return; 8105 } 8106 8107 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8109 << (unsigned) FnKind << FnDesc 8110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8111 << FromTy 8112 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8113 << (unsigned) isObjectArgument << I+1; 8114 MaybeEmitInheritedConstructorNote(S, Fn); 8115 return; 8116 } 8117 8118 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8120 << (unsigned) FnKind << FnDesc 8121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8122 << FromTy 8123 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8124 << (unsigned) isObjectArgument << I+1; 8125 MaybeEmitInheritedConstructorNote(S, Fn); 8126 return; 8127 } 8128 8129 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8130 assert(CVR && "unexpected qualifiers mismatch"); 8131 8132 if (isObjectArgument) { 8133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8134 << (unsigned) FnKind << FnDesc 8135 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8136 << FromTy << (CVR - 1); 8137 } else { 8138 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8139 << (unsigned) FnKind << FnDesc 8140 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8141 << FromTy << (CVR - 1) << I+1; 8142 } 8143 MaybeEmitInheritedConstructorNote(S, Fn); 8144 return; 8145 } 8146 8147 // Special diagnostic for failure to convert an initializer list, since 8148 // telling the user that it has type void is not useful. 8149 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8151 << (unsigned) FnKind << FnDesc 8152 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8153 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8154 MaybeEmitInheritedConstructorNote(S, Fn); 8155 return; 8156 } 8157 8158 // Diagnose references or pointers to incomplete types differently, 8159 // since it's far from impossible that the incompleteness triggered 8160 // the failure. 8161 QualType TempFromTy = FromTy.getNonReferenceType(); 8162 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8163 TempFromTy = PTy->getPointeeType(); 8164 if (TempFromTy->isIncompleteType()) { 8165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8166 << (unsigned) FnKind << FnDesc 8167 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8168 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8169 MaybeEmitInheritedConstructorNote(S, Fn); 8170 return; 8171 } 8172 8173 // Diagnose base -> derived pointer conversions. 8174 unsigned BaseToDerivedConversion = 0; 8175 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8176 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8177 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8178 FromPtrTy->getPointeeType()) && 8179 !FromPtrTy->getPointeeType()->isIncompleteType() && 8180 !ToPtrTy->getPointeeType()->isIncompleteType() && 8181 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8182 FromPtrTy->getPointeeType())) 8183 BaseToDerivedConversion = 1; 8184 } 8185 } else if (const ObjCObjectPointerType *FromPtrTy 8186 = FromTy->getAs<ObjCObjectPointerType>()) { 8187 if (const ObjCObjectPointerType *ToPtrTy 8188 = ToTy->getAs<ObjCObjectPointerType>()) 8189 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8190 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8191 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8192 FromPtrTy->getPointeeType()) && 8193 FromIface->isSuperClassOf(ToIface)) 8194 BaseToDerivedConversion = 2; 8195 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8196 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8197 !FromTy->isIncompleteType() && 8198 !ToRefTy->getPointeeType()->isIncompleteType() && 8199 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8200 BaseToDerivedConversion = 3; 8201 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8202 ToTy.getNonReferenceType().getCanonicalType() == 8203 FromTy.getNonReferenceType().getCanonicalType()) { 8204 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8205 << (unsigned) FnKind << FnDesc 8206 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8207 << (unsigned) isObjectArgument << I + 1; 8208 MaybeEmitInheritedConstructorNote(S, Fn); 8209 return; 8210 } 8211 } 8212 8213 if (BaseToDerivedConversion) { 8214 S.Diag(Fn->getLocation(), 8215 diag::note_ovl_candidate_bad_base_to_derived_conv) 8216 << (unsigned) FnKind << FnDesc 8217 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8218 << (BaseToDerivedConversion - 1) 8219 << FromTy << ToTy << I+1; 8220 MaybeEmitInheritedConstructorNote(S, Fn); 8221 return; 8222 } 8223 8224 if (isa<ObjCObjectPointerType>(CFromTy) && 8225 isa<PointerType>(CToTy)) { 8226 Qualifiers FromQs = CFromTy.getQualifiers(); 8227 Qualifiers ToQs = CToTy.getQualifiers(); 8228 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8229 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8230 << (unsigned) FnKind << FnDesc 8231 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8232 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8233 MaybeEmitInheritedConstructorNote(S, Fn); 8234 return; 8235 } 8236 } 8237 8238 // Emit the generic diagnostic and, optionally, add the hints to it. 8239 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8240 FDiag << (unsigned) FnKind << FnDesc 8241 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8242 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8243 << (unsigned) (Cand->Fix.Kind); 8244 8245 // If we can fix the conversion, suggest the FixIts. 8246 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8247 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8248 FDiag << *HI; 8249 S.Diag(Fn->getLocation(), FDiag); 8250 8251 MaybeEmitInheritedConstructorNote(S, Fn); 8252 } 8253 8254 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8255 unsigned NumFormalArgs) { 8256 // TODO: treat calls to a missing default constructor as a special case 8257 8258 FunctionDecl *Fn = Cand->Function; 8259 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8260 8261 unsigned MinParams = Fn->getMinRequiredArguments(); 8262 8263 // With invalid overloaded operators, it's possible that we think we 8264 // have an arity mismatch when it fact it looks like we have the 8265 // right number of arguments, because only overloaded operators have 8266 // the weird behavior of overloading member and non-member functions. 8267 // Just don't report anything. 8268 if (Fn->isInvalidDecl() && 8269 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8270 return; 8271 8272 // at least / at most / exactly 8273 unsigned mode, modeCount; 8274 if (NumFormalArgs < MinParams) { 8275 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8276 (Cand->FailureKind == ovl_fail_bad_deduction && 8277 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8278 if (MinParams != FnTy->getNumArgs() || 8279 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8280 mode = 0; // "at least" 8281 else 8282 mode = 2; // "exactly" 8283 modeCount = MinParams; 8284 } else { 8285 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8286 (Cand->FailureKind == ovl_fail_bad_deduction && 8287 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8288 if (MinParams != FnTy->getNumArgs()) 8289 mode = 1; // "at most" 8290 else 8291 mode = 2; // "exactly" 8292 modeCount = FnTy->getNumArgs(); 8293 } 8294 8295 std::string Description; 8296 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8297 8298 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8300 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8301 << Fn->getParamDecl(0) << NumFormalArgs; 8302 else 8303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8304 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8305 << modeCount << NumFormalArgs; 8306 MaybeEmitInheritedConstructorNote(S, Fn); 8307 } 8308 8309 /// Diagnose a failed template-argument deduction. 8310 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8311 unsigned NumArgs) { 8312 FunctionDecl *Fn = Cand->Function; // pattern 8313 8314 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8315 NamedDecl *ParamD; 8316 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8317 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8318 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8319 switch (Cand->DeductionFailure.Result) { 8320 case Sema::TDK_Success: 8321 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8322 8323 case Sema::TDK_Incomplete: { 8324 assert(ParamD && "no parameter found for incomplete deduction result"); 8325 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8326 << ParamD->getDeclName(); 8327 MaybeEmitInheritedConstructorNote(S, Fn); 8328 return; 8329 } 8330 8331 case Sema::TDK_Underqualified: { 8332 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8333 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8334 8335 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8336 8337 // Param will have been canonicalized, but it should just be a 8338 // qualified version of ParamD, so move the qualifiers to that. 8339 QualifierCollector Qs; 8340 Qs.strip(Param); 8341 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8342 assert(S.Context.hasSameType(Param, NonCanonParam)); 8343 8344 // Arg has also been canonicalized, but there's nothing we can do 8345 // about that. It also doesn't matter as much, because it won't 8346 // have any template parameters in it (because deduction isn't 8347 // done on dependent types). 8348 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8349 8350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8351 << ParamD->getDeclName() << Arg << NonCanonParam; 8352 MaybeEmitInheritedConstructorNote(S, Fn); 8353 return; 8354 } 8355 8356 case Sema::TDK_Inconsistent: { 8357 assert(ParamD && "no parameter found for inconsistent deduction result"); 8358 int which = 0; 8359 if (isa<TemplateTypeParmDecl>(ParamD)) 8360 which = 0; 8361 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8362 which = 1; 8363 else { 8364 which = 2; 8365 } 8366 8367 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8368 << which << ParamD->getDeclName() 8369 << *Cand->DeductionFailure.getFirstArg() 8370 << *Cand->DeductionFailure.getSecondArg(); 8371 MaybeEmitInheritedConstructorNote(S, Fn); 8372 return; 8373 } 8374 8375 case Sema::TDK_InvalidExplicitArguments: 8376 assert(ParamD && "no parameter found for invalid explicit arguments"); 8377 if (ParamD->getDeclName()) 8378 S.Diag(Fn->getLocation(), 8379 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8380 << ParamD->getDeclName(); 8381 else { 8382 int index = 0; 8383 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8384 index = TTP->getIndex(); 8385 else if (NonTypeTemplateParmDecl *NTTP 8386 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8387 index = NTTP->getIndex(); 8388 else 8389 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8390 S.Diag(Fn->getLocation(), 8391 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8392 << (index + 1); 8393 } 8394 MaybeEmitInheritedConstructorNote(S, Fn); 8395 return; 8396 8397 case Sema::TDK_TooManyArguments: 8398 case Sema::TDK_TooFewArguments: 8399 DiagnoseArityMismatch(S, Cand, NumArgs); 8400 return; 8401 8402 case Sema::TDK_InstantiationDepth: 8403 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8404 MaybeEmitInheritedConstructorNote(S, Fn); 8405 return; 8406 8407 case Sema::TDK_SubstitutionFailure: { 8408 // Format the template argument list into the argument string. 8409 SmallString<128> TemplateArgString; 8410 if (TemplateArgumentList *Args = 8411 Cand->DeductionFailure.getTemplateArgumentList()) { 8412 TemplateArgString = " "; 8413 TemplateArgString += S.getTemplateArgumentBindingsText( 8414 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8415 } 8416 8417 // If this candidate was disabled by enable_if, say so. 8418 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8419 if (PDiag && PDiag->second.getDiagID() == 8420 diag::err_typename_nested_not_found_enable_if) { 8421 // FIXME: Use the source range of the condition, and the fully-qualified 8422 // name of the enable_if template. These are both present in PDiag. 8423 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8424 << "'enable_if'" << TemplateArgString; 8425 return; 8426 } 8427 8428 // Format the SFINAE diagnostic into the argument string. 8429 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8430 // formatted message in another diagnostic. 8431 SmallString<128> SFINAEArgString; 8432 SourceRange R; 8433 if (PDiag) { 8434 SFINAEArgString = ": "; 8435 R = SourceRange(PDiag->first, PDiag->first); 8436 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8437 } 8438 8439 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8440 << TemplateArgString << SFINAEArgString << R; 8441 MaybeEmitInheritedConstructorNote(S, Fn); 8442 return; 8443 } 8444 8445 // TODO: diagnose these individually, then kill off 8446 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8447 case Sema::TDK_NonDeducedMismatch: 8448 case Sema::TDK_FailedOverloadResolution: 8449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8450 MaybeEmitInheritedConstructorNote(S, Fn); 8451 return; 8452 } 8453 } 8454 8455 /// CUDA: diagnose an invalid call across targets. 8456 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8457 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8458 FunctionDecl *Callee = Cand->Function; 8459 8460 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8461 CalleeTarget = S.IdentifyCUDATarget(Callee); 8462 8463 std::string FnDesc; 8464 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8465 8466 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8467 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8468 } 8469 8470 /// Generates a 'note' diagnostic for an overload candidate. We've 8471 /// already generated a primary error at the call site. 8472 /// 8473 /// It really does need to be a single diagnostic with its caret 8474 /// pointed at the candidate declaration. Yes, this creates some 8475 /// major challenges of technical writing. Yes, this makes pointing 8476 /// out problems with specific arguments quite awkward. It's still 8477 /// better than generating twenty screens of text for every failed 8478 /// overload. 8479 /// 8480 /// It would be great to be able to express per-candidate problems 8481 /// more richly for those diagnostic clients that cared, but we'd 8482 /// still have to be just as careful with the default diagnostics. 8483 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8484 unsigned NumArgs) { 8485 FunctionDecl *Fn = Cand->Function; 8486 8487 // Note deleted candidates, but only if they're viable. 8488 if (Cand->Viable && (Fn->isDeleted() || 8489 S.isFunctionConsideredUnavailable(Fn))) { 8490 std::string FnDesc; 8491 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8492 8493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8494 << FnKind << FnDesc 8495 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8496 MaybeEmitInheritedConstructorNote(S, Fn); 8497 return; 8498 } 8499 8500 // We don't really have anything else to say about viable candidates. 8501 if (Cand->Viable) { 8502 S.NoteOverloadCandidate(Fn); 8503 return; 8504 } 8505 8506 switch (Cand->FailureKind) { 8507 case ovl_fail_too_many_arguments: 8508 case ovl_fail_too_few_arguments: 8509 return DiagnoseArityMismatch(S, Cand, NumArgs); 8510 8511 case ovl_fail_bad_deduction: 8512 return DiagnoseBadDeduction(S, Cand, NumArgs); 8513 8514 case ovl_fail_trivial_conversion: 8515 case ovl_fail_bad_final_conversion: 8516 case ovl_fail_final_conversion_not_exact: 8517 return S.NoteOverloadCandidate(Fn); 8518 8519 case ovl_fail_bad_conversion: { 8520 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8521 for (unsigned N = Cand->NumConversions; I != N; ++I) 8522 if (Cand->Conversions[I].isBad()) 8523 return DiagnoseBadConversion(S, Cand, I); 8524 8525 // FIXME: this currently happens when we're called from SemaInit 8526 // when user-conversion overload fails. Figure out how to handle 8527 // those conditions and diagnose them well. 8528 return S.NoteOverloadCandidate(Fn); 8529 } 8530 8531 case ovl_fail_bad_target: 8532 return DiagnoseBadTarget(S, Cand); 8533 } 8534 } 8535 8536 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8537 // Desugar the type of the surrogate down to a function type, 8538 // retaining as many typedefs as possible while still showing 8539 // the function type (and, therefore, its parameter types). 8540 QualType FnType = Cand->Surrogate->getConversionType(); 8541 bool isLValueReference = false; 8542 bool isRValueReference = false; 8543 bool isPointer = false; 8544 if (const LValueReferenceType *FnTypeRef = 8545 FnType->getAs<LValueReferenceType>()) { 8546 FnType = FnTypeRef->getPointeeType(); 8547 isLValueReference = true; 8548 } else if (const RValueReferenceType *FnTypeRef = 8549 FnType->getAs<RValueReferenceType>()) { 8550 FnType = FnTypeRef->getPointeeType(); 8551 isRValueReference = true; 8552 } 8553 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8554 FnType = FnTypePtr->getPointeeType(); 8555 isPointer = true; 8556 } 8557 // Desugar down to a function type. 8558 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8559 // Reconstruct the pointer/reference as appropriate. 8560 if (isPointer) FnType = S.Context.getPointerType(FnType); 8561 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8562 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8563 8564 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8565 << FnType; 8566 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8567 } 8568 8569 void NoteBuiltinOperatorCandidate(Sema &S, 8570 StringRef Opc, 8571 SourceLocation OpLoc, 8572 OverloadCandidate *Cand) { 8573 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8574 std::string TypeStr("operator"); 8575 TypeStr += Opc; 8576 TypeStr += "("; 8577 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8578 if (Cand->NumConversions == 1) { 8579 TypeStr += ")"; 8580 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8581 } else { 8582 TypeStr += ", "; 8583 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8584 TypeStr += ")"; 8585 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8586 } 8587 } 8588 8589 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8590 OverloadCandidate *Cand) { 8591 unsigned NoOperands = Cand->NumConversions; 8592 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8593 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8594 if (ICS.isBad()) break; // all meaningless after first invalid 8595 if (!ICS.isAmbiguous()) continue; 8596 8597 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8598 S.PDiag(diag::note_ambiguous_type_conversion)); 8599 } 8600 } 8601 8602 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8603 if (Cand->Function) 8604 return Cand->Function->getLocation(); 8605 if (Cand->IsSurrogate) 8606 return Cand->Surrogate->getLocation(); 8607 return SourceLocation(); 8608 } 8609 8610 static unsigned 8611 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8612 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8613 case Sema::TDK_Success: 8614 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8615 8616 case Sema::TDK_Invalid: 8617 case Sema::TDK_Incomplete: 8618 return 1; 8619 8620 case Sema::TDK_Underqualified: 8621 case Sema::TDK_Inconsistent: 8622 return 2; 8623 8624 case Sema::TDK_SubstitutionFailure: 8625 case Sema::TDK_NonDeducedMismatch: 8626 return 3; 8627 8628 case Sema::TDK_InstantiationDepth: 8629 case Sema::TDK_FailedOverloadResolution: 8630 return 4; 8631 8632 case Sema::TDK_InvalidExplicitArguments: 8633 return 5; 8634 8635 case Sema::TDK_TooManyArguments: 8636 case Sema::TDK_TooFewArguments: 8637 return 6; 8638 } 8639 llvm_unreachable("Unhandled deduction result"); 8640 } 8641 8642 struct CompareOverloadCandidatesForDisplay { 8643 Sema &S; 8644 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8645 8646 bool operator()(const OverloadCandidate *L, 8647 const OverloadCandidate *R) { 8648 // Fast-path this check. 8649 if (L == R) return false; 8650 8651 // Order first by viability. 8652 if (L->Viable) { 8653 if (!R->Viable) return true; 8654 8655 // TODO: introduce a tri-valued comparison for overload 8656 // candidates. Would be more worthwhile if we had a sort 8657 // that could exploit it. 8658 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8659 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8660 } else if (R->Viable) 8661 return false; 8662 8663 assert(L->Viable == R->Viable); 8664 8665 // Criteria by which we can sort non-viable candidates: 8666 if (!L->Viable) { 8667 // 1. Arity mismatches come after other candidates. 8668 if (L->FailureKind == ovl_fail_too_many_arguments || 8669 L->FailureKind == ovl_fail_too_few_arguments) 8670 return false; 8671 if (R->FailureKind == ovl_fail_too_many_arguments || 8672 R->FailureKind == ovl_fail_too_few_arguments) 8673 return true; 8674 8675 // 2. Bad conversions come first and are ordered by the number 8676 // of bad conversions and quality of good conversions. 8677 if (L->FailureKind == ovl_fail_bad_conversion) { 8678 if (R->FailureKind != ovl_fail_bad_conversion) 8679 return true; 8680 8681 // The conversion that can be fixed with a smaller number of changes, 8682 // comes first. 8683 unsigned numLFixes = L->Fix.NumConversionsFixed; 8684 unsigned numRFixes = R->Fix.NumConversionsFixed; 8685 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8686 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8687 if (numLFixes != numRFixes) { 8688 if (numLFixes < numRFixes) 8689 return true; 8690 else 8691 return false; 8692 } 8693 8694 // If there's any ordering between the defined conversions... 8695 // FIXME: this might not be transitive. 8696 assert(L->NumConversions == R->NumConversions); 8697 8698 int leftBetter = 0; 8699 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8700 for (unsigned E = L->NumConversions; I != E; ++I) { 8701 switch (CompareImplicitConversionSequences(S, 8702 L->Conversions[I], 8703 R->Conversions[I])) { 8704 case ImplicitConversionSequence::Better: 8705 leftBetter++; 8706 break; 8707 8708 case ImplicitConversionSequence::Worse: 8709 leftBetter--; 8710 break; 8711 8712 case ImplicitConversionSequence::Indistinguishable: 8713 break; 8714 } 8715 } 8716 if (leftBetter > 0) return true; 8717 if (leftBetter < 0) return false; 8718 8719 } else if (R->FailureKind == ovl_fail_bad_conversion) 8720 return false; 8721 8722 if (L->FailureKind == ovl_fail_bad_deduction) { 8723 if (R->FailureKind != ovl_fail_bad_deduction) 8724 return true; 8725 8726 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8727 return RankDeductionFailure(L->DeductionFailure) 8728 < RankDeductionFailure(R->DeductionFailure); 8729 } else if (R->FailureKind == ovl_fail_bad_deduction) 8730 return false; 8731 8732 // TODO: others? 8733 } 8734 8735 // Sort everything else by location. 8736 SourceLocation LLoc = GetLocationForCandidate(L); 8737 SourceLocation RLoc = GetLocationForCandidate(R); 8738 8739 // Put candidates without locations (e.g. builtins) at the end. 8740 if (LLoc.isInvalid()) return false; 8741 if (RLoc.isInvalid()) return true; 8742 8743 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8744 } 8745 }; 8746 8747 /// CompleteNonViableCandidate - Normally, overload resolution only 8748 /// computes up to the first. Produces the FixIt set if possible. 8749 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8750 ArrayRef<Expr *> Args) { 8751 assert(!Cand->Viable); 8752 8753 // Don't do anything on failures other than bad conversion. 8754 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8755 8756 // We only want the FixIts if all the arguments can be corrected. 8757 bool Unfixable = false; 8758 // Use a implicit copy initialization to check conversion fixes. 8759 Cand->Fix.setConversionChecker(TryCopyInitialization); 8760 8761 // Skip forward to the first bad conversion. 8762 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8763 unsigned ConvCount = Cand->NumConversions; 8764 while (true) { 8765 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8766 ConvIdx++; 8767 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8768 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8769 break; 8770 } 8771 } 8772 8773 if (ConvIdx == ConvCount) 8774 return; 8775 8776 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8777 "remaining conversion is initialized?"); 8778 8779 // FIXME: this should probably be preserved from the overload 8780 // operation somehow. 8781 bool SuppressUserConversions = false; 8782 8783 const FunctionProtoType* Proto; 8784 unsigned ArgIdx = ConvIdx; 8785 8786 if (Cand->IsSurrogate) { 8787 QualType ConvType 8788 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8789 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8790 ConvType = ConvPtrType->getPointeeType(); 8791 Proto = ConvType->getAs<FunctionProtoType>(); 8792 ArgIdx--; 8793 } else if (Cand->Function) { 8794 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8795 if (isa<CXXMethodDecl>(Cand->Function) && 8796 !isa<CXXConstructorDecl>(Cand->Function)) 8797 ArgIdx--; 8798 } else { 8799 // Builtin binary operator with a bad first conversion. 8800 assert(ConvCount <= 3); 8801 for (; ConvIdx != ConvCount; ++ConvIdx) 8802 Cand->Conversions[ConvIdx] 8803 = TryCopyInitialization(S, Args[ConvIdx], 8804 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8805 SuppressUserConversions, 8806 /*InOverloadResolution*/ true, 8807 /*AllowObjCWritebackConversion=*/ 8808 S.getLangOpts().ObjCAutoRefCount); 8809 return; 8810 } 8811 8812 // Fill in the rest of the conversions. 8813 unsigned NumArgsInProto = Proto->getNumArgs(); 8814 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8815 if (ArgIdx < NumArgsInProto) { 8816 Cand->Conversions[ConvIdx] 8817 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8818 SuppressUserConversions, 8819 /*InOverloadResolution=*/true, 8820 /*AllowObjCWritebackConversion=*/ 8821 S.getLangOpts().ObjCAutoRefCount); 8822 // Store the FixIt in the candidate if it exists. 8823 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8824 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8825 } 8826 else 8827 Cand->Conversions[ConvIdx].setEllipsis(); 8828 } 8829 } 8830 8831 } // end anonymous namespace 8832 8833 /// PrintOverloadCandidates - When overload resolution fails, prints 8834 /// diagnostic messages containing the candidates in the candidate 8835 /// set. 8836 void OverloadCandidateSet::NoteCandidates(Sema &S, 8837 OverloadCandidateDisplayKind OCD, 8838 ArrayRef<Expr *> Args, 8839 StringRef Opc, 8840 SourceLocation OpLoc) { 8841 // Sort the candidates by viability and position. Sorting directly would 8842 // be prohibitive, so we make a set of pointers and sort those. 8843 SmallVector<OverloadCandidate*, 32> Cands; 8844 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8845 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8846 if (Cand->Viable) 8847 Cands.push_back(Cand); 8848 else if (OCD == OCD_AllCandidates) { 8849 CompleteNonViableCandidate(S, Cand, Args); 8850 if (Cand->Function || Cand->IsSurrogate) 8851 Cands.push_back(Cand); 8852 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8853 // want to list every possible builtin candidate. 8854 } 8855 } 8856 8857 std::sort(Cands.begin(), Cands.end(), 8858 CompareOverloadCandidatesForDisplay(S)); 8859 8860 bool ReportedAmbiguousConversions = false; 8861 8862 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8863 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8864 unsigned CandsShown = 0; 8865 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8866 OverloadCandidate *Cand = *I; 8867 8868 // Set an arbitrary limit on the number of candidate functions we'll spam 8869 // the user with. FIXME: This limit should depend on details of the 8870 // candidate list. 8871 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8872 break; 8873 } 8874 ++CandsShown; 8875 8876 if (Cand->Function) 8877 NoteFunctionCandidate(S, Cand, Args.size()); 8878 else if (Cand->IsSurrogate) 8879 NoteSurrogateCandidate(S, Cand); 8880 else { 8881 assert(Cand->Viable && 8882 "Non-viable built-in candidates are not added to Cands."); 8883 // Generally we only see ambiguities including viable builtin 8884 // operators if overload resolution got screwed up by an 8885 // ambiguous user-defined conversion. 8886 // 8887 // FIXME: It's quite possible for different conversions to see 8888 // different ambiguities, though. 8889 if (!ReportedAmbiguousConversions) { 8890 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8891 ReportedAmbiguousConversions = true; 8892 } 8893 8894 // If this is a viable builtin, print it. 8895 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8896 } 8897 } 8898 8899 if (I != E) 8900 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8901 } 8902 8903 // [PossiblyAFunctionType] --> [Return] 8904 // NonFunctionType --> NonFunctionType 8905 // R (A) --> R(A) 8906 // R (*)(A) --> R (A) 8907 // R (&)(A) --> R (A) 8908 // R (S::*)(A) --> R (A) 8909 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8910 QualType Ret = PossiblyAFunctionType; 8911 if (const PointerType *ToTypePtr = 8912 PossiblyAFunctionType->getAs<PointerType>()) 8913 Ret = ToTypePtr->getPointeeType(); 8914 else if (const ReferenceType *ToTypeRef = 8915 PossiblyAFunctionType->getAs<ReferenceType>()) 8916 Ret = ToTypeRef->getPointeeType(); 8917 else if (const MemberPointerType *MemTypePtr = 8918 PossiblyAFunctionType->getAs<MemberPointerType>()) 8919 Ret = MemTypePtr->getPointeeType(); 8920 Ret = 8921 Context.getCanonicalType(Ret).getUnqualifiedType(); 8922 return Ret; 8923 } 8924 8925 // A helper class to help with address of function resolution 8926 // - allows us to avoid passing around all those ugly parameters 8927 class AddressOfFunctionResolver 8928 { 8929 Sema& S; 8930 Expr* SourceExpr; 8931 const QualType& TargetType; 8932 QualType TargetFunctionType; // Extracted function type from target type 8933 8934 bool Complain; 8935 //DeclAccessPair& ResultFunctionAccessPair; 8936 ASTContext& Context; 8937 8938 bool TargetTypeIsNonStaticMemberFunction; 8939 bool FoundNonTemplateFunction; 8940 8941 OverloadExpr::FindResult OvlExprInfo; 8942 OverloadExpr *OvlExpr; 8943 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8944 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8945 8946 public: 8947 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8948 const QualType& TargetType, bool Complain) 8949 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8950 Complain(Complain), Context(S.getASTContext()), 8951 TargetTypeIsNonStaticMemberFunction( 8952 !!TargetType->getAs<MemberPointerType>()), 8953 FoundNonTemplateFunction(false), 8954 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8955 OvlExpr(OvlExprInfo.Expression) 8956 { 8957 ExtractUnqualifiedFunctionTypeFromTargetType(); 8958 8959 if (!TargetFunctionType->isFunctionType()) { 8960 if (OvlExpr->hasExplicitTemplateArgs()) { 8961 DeclAccessPair dap; 8962 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8963 OvlExpr, false, &dap) ) { 8964 8965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8966 if (!Method->isStatic()) { 8967 // If the target type is a non-function type and the function 8968 // found is a non-static member function, pretend as if that was 8969 // the target, it's the only possible type to end up with. 8970 TargetTypeIsNonStaticMemberFunction = true; 8971 8972 // And skip adding the function if its not in the proper form. 8973 // We'll diagnose this due to an empty set of functions. 8974 if (!OvlExprInfo.HasFormOfMemberPointer) 8975 return; 8976 } 8977 } 8978 8979 Matches.push_back(std::make_pair(dap,Fn)); 8980 } 8981 } 8982 return; 8983 } 8984 8985 if (OvlExpr->hasExplicitTemplateArgs()) 8986 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8987 8988 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8989 // C++ [over.over]p4: 8990 // If more than one function is selected, [...] 8991 if (Matches.size() > 1) { 8992 if (FoundNonTemplateFunction) 8993 EliminateAllTemplateMatches(); 8994 else 8995 EliminateAllExceptMostSpecializedTemplate(); 8996 } 8997 } 8998 } 8999 9000 private: 9001 bool isTargetTypeAFunction() const { 9002 return TargetFunctionType->isFunctionType(); 9003 } 9004 9005 // [ToType] [Return] 9006 9007 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9008 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9009 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9010 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9011 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9012 } 9013 9014 // return true if any matching specializations were found 9015 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9016 const DeclAccessPair& CurAccessFunPair) { 9017 if (CXXMethodDecl *Method 9018 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9019 // Skip non-static function templates when converting to pointer, and 9020 // static when converting to member pointer. 9021 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9022 return false; 9023 } 9024 else if (TargetTypeIsNonStaticMemberFunction) 9025 return false; 9026 9027 // C++ [over.over]p2: 9028 // If the name is a function template, template argument deduction is 9029 // done (14.8.2.2), and if the argument deduction succeeds, the 9030 // resulting template argument list is used to generate a single 9031 // function template specialization, which is added to the set of 9032 // overloaded functions considered. 9033 FunctionDecl *Specialization = 0; 9034 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9035 if (Sema::TemplateDeductionResult Result 9036 = S.DeduceTemplateArguments(FunctionTemplate, 9037 &OvlExplicitTemplateArgs, 9038 TargetFunctionType, Specialization, 9039 Info)) { 9040 // FIXME: make a note of the failed deduction for diagnostics. 9041 (void)Result; 9042 return false; 9043 } 9044 9045 // Template argument deduction ensures that we have an exact match. 9046 // This function template specicalization works. 9047 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9048 assert(TargetFunctionType 9049 == Context.getCanonicalType(Specialization->getType())); 9050 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9051 return true; 9052 } 9053 9054 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9055 const DeclAccessPair& CurAccessFunPair) { 9056 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9057 // Skip non-static functions when converting to pointer, and static 9058 // when converting to member pointer. 9059 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9060 return false; 9061 } 9062 else if (TargetTypeIsNonStaticMemberFunction) 9063 return false; 9064 9065 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9066 if (S.getLangOpts().CUDA) 9067 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9068 if (S.CheckCUDATarget(Caller, FunDecl)) 9069 return false; 9070 9071 QualType ResultTy; 9072 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9073 FunDecl->getType()) || 9074 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9075 ResultTy)) { 9076 Matches.push_back(std::make_pair(CurAccessFunPair, 9077 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9078 FoundNonTemplateFunction = true; 9079 return true; 9080 } 9081 } 9082 9083 return false; 9084 } 9085 9086 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9087 bool Ret = false; 9088 9089 // If the overload expression doesn't have the form of a pointer to 9090 // member, don't try to convert it to a pointer-to-member type. 9091 if (IsInvalidFormOfPointerToMemberFunction()) 9092 return false; 9093 9094 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9095 E = OvlExpr->decls_end(); 9096 I != E; ++I) { 9097 // Look through any using declarations to find the underlying function. 9098 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9099 9100 // C++ [over.over]p3: 9101 // Non-member functions and static member functions match 9102 // targets of type "pointer-to-function" or "reference-to-function." 9103 // Nonstatic member functions match targets of 9104 // type "pointer-to-member-function." 9105 // Note that according to DR 247, the containing class does not matter. 9106 if (FunctionTemplateDecl *FunctionTemplate 9107 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9108 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9109 Ret = true; 9110 } 9111 // If we have explicit template arguments supplied, skip non-templates. 9112 else if (!OvlExpr->hasExplicitTemplateArgs() && 9113 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9114 Ret = true; 9115 } 9116 assert(Ret || Matches.empty()); 9117 return Ret; 9118 } 9119 9120 void EliminateAllExceptMostSpecializedTemplate() { 9121 // [...] and any given function template specialization F1 is 9122 // eliminated if the set contains a second function template 9123 // specialization whose function template is more specialized 9124 // than the function template of F1 according to the partial 9125 // ordering rules of 14.5.5.2. 9126 9127 // The algorithm specified above is quadratic. We instead use a 9128 // two-pass algorithm (similar to the one used to identify the 9129 // best viable function in an overload set) that identifies the 9130 // best function template (if it exists). 9131 9132 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9133 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9134 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9135 9136 UnresolvedSetIterator Result = 9137 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9138 TPOC_Other, 0, SourceExpr->getLocStart(), 9139 S.PDiag(), 9140 S.PDiag(diag::err_addr_ovl_ambiguous) 9141 << Matches[0].second->getDeclName(), 9142 S.PDiag(diag::note_ovl_candidate) 9143 << (unsigned) oc_function_template, 9144 Complain, TargetFunctionType); 9145 9146 if (Result != MatchesCopy.end()) { 9147 // Make it the first and only element 9148 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9149 Matches[0].second = cast<FunctionDecl>(*Result); 9150 Matches.resize(1); 9151 } 9152 } 9153 9154 void EliminateAllTemplateMatches() { 9155 // [...] any function template specializations in the set are 9156 // eliminated if the set also contains a non-template function, [...] 9157 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9158 if (Matches[I].second->getPrimaryTemplate() == 0) 9159 ++I; 9160 else { 9161 Matches[I] = Matches[--N]; 9162 Matches.set_size(N); 9163 } 9164 } 9165 } 9166 9167 public: 9168 void ComplainNoMatchesFound() const { 9169 assert(Matches.empty()); 9170 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9171 << OvlExpr->getName() << TargetFunctionType 9172 << OvlExpr->getSourceRange(); 9173 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9174 } 9175 9176 bool IsInvalidFormOfPointerToMemberFunction() const { 9177 return TargetTypeIsNonStaticMemberFunction && 9178 !OvlExprInfo.HasFormOfMemberPointer; 9179 } 9180 9181 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9182 // TODO: Should we condition this on whether any functions might 9183 // have matched, or is it more appropriate to do that in callers? 9184 // TODO: a fixit wouldn't hurt. 9185 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9186 << TargetType << OvlExpr->getSourceRange(); 9187 } 9188 9189 void ComplainOfInvalidConversion() const { 9190 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9191 << OvlExpr->getName() << TargetType; 9192 } 9193 9194 void ComplainMultipleMatchesFound() const { 9195 assert(Matches.size() > 1); 9196 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9197 << OvlExpr->getName() 9198 << OvlExpr->getSourceRange(); 9199 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9200 } 9201 9202 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9203 9204 int getNumMatches() const { return Matches.size(); } 9205 9206 FunctionDecl* getMatchingFunctionDecl() const { 9207 if (Matches.size() != 1) return 0; 9208 return Matches[0].second; 9209 } 9210 9211 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9212 if (Matches.size() != 1) return 0; 9213 return &Matches[0].first; 9214 } 9215 }; 9216 9217 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9218 /// an overloaded function (C++ [over.over]), where @p From is an 9219 /// expression with overloaded function type and @p ToType is the type 9220 /// we're trying to resolve to. For example: 9221 /// 9222 /// @code 9223 /// int f(double); 9224 /// int f(int); 9225 /// 9226 /// int (*pfd)(double) = f; // selects f(double) 9227 /// @endcode 9228 /// 9229 /// This routine returns the resulting FunctionDecl if it could be 9230 /// resolved, and NULL otherwise. When @p Complain is true, this 9231 /// routine will emit diagnostics if there is an error. 9232 FunctionDecl * 9233 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9234 QualType TargetType, 9235 bool Complain, 9236 DeclAccessPair &FoundResult, 9237 bool *pHadMultipleCandidates) { 9238 assert(AddressOfExpr->getType() == Context.OverloadTy); 9239 9240 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9241 Complain); 9242 int NumMatches = Resolver.getNumMatches(); 9243 FunctionDecl* Fn = 0; 9244 if (NumMatches == 0 && Complain) { 9245 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9246 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9247 else 9248 Resolver.ComplainNoMatchesFound(); 9249 } 9250 else if (NumMatches > 1 && Complain) 9251 Resolver.ComplainMultipleMatchesFound(); 9252 else if (NumMatches == 1) { 9253 Fn = Resolver.getMatchingFunctionDecl(); 9254 assert(Fn); 9255 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9256 if (Complain) 9257 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9258 } 9259 9260 if (pHadMultipleCandidates) 9261 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9262 return Fn; 9263 } 9264 9265 /// \brief Given an expression that refers to an overloaded function, try to 9266 /// resolve that overloaded function expression down to a single function. 9267 /// 9268 /// This routine can only resolve template-ids that refer to a single function 9269 /// template, where that template-id refers to a single template whose template 9270 /// arguments are either provided by the template-id or have defaults, 9271 /// as described in C++0x [temp.arg.explicit]p3. 9272 FunctionDecl * 9273 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9274 bool Complain, 9275 DeclAccessPair *FoundResult) { 9276 // C++ [over.over]p1: 9277 // [...] [Note: any redundant set of parentheses surrounding the 9278 // overloaded function name is ignored (5.1). ] 9279 // C++ [over.over]p1: 9280 // [...] The overloaded function name can be preceded by the & 9281 // operator. 9282 9283 // If we didn't actually find any template-ids, we're done. 9284 if (!ovl->hasExplicitTemplateArgs()) 9285 return 0; 9286 9287 TemplateArgumentListInfo ExplicitTemplateArgs; 9288 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9289 9290 // Look through all of the overloaded functions, searching for one 9291 // whose type matches exactly. 9292 FunctionDecl *Matched = 0; 9293 for (UnresolvedSetIterator I = ovl->decls_begin(), 9294 E = ovl->decls_end(); I != E; ++I) { 9295 // C++0x [temp.arg.explicit]p3: 9296 // [...] In contexts where deduction is done and fails, or in contexts 9297 // where deduction is not done, if a template argument list is 9298 // specified and it, along with any default template arguments, 9299 // identifies a single function template specialization, then the 9300 // template-id is an lvalue for the function template specialization. 9301 FunctionTemplateDecl *FunctionTemplate 9302 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9303 9304 // C++ [over.over]p2: 9305 // If the name is a function template, template argument deduction is 9306 // done (14.8.2.2), and if the argument deduction succeeds, the 9307 // resulting template argument list is used to generate a single 9308 // function template specialization, which is added to the set of 9309 // overloaded functions considered. 9310 FunctionDecl *Specialization = 0; 9311 TemplateDeductionInfo Info(ovl->getNameLoc()); 9312 if (TemplateDeductionResult Result 9313 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9314 Specialization, Info)) { 9315 // FIXME: make a note of the failed deduction for diagnostics. 9316 (void)Result; 9317 continue; 9318 } 9319 9320 assert(Specialization && "no specialization and no error?"); 9321 9322 // Multiple matches; we can't resolve to a single declaration. 9323 if (Matched) { 9324 if (Complain) { 9325 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9326 << ovl->getName(); 9327 NoteAllOverloadCandidates(ovl); 9328 } 9329 return 0; 9330 } 9331 9332 Matched = Specialization; 9333 if (FoundResult) *FoundResult = I.getPair(); 9334 } 9335 9336 return Matched; 9337 } 9338 9339 9340 9341 9342 // Resolve and fix an overloaded expression that can be resolved 9343 // because it identifies a single function template specialization. 9344 // 9345 // Last three arguments should only be supplied if Complain = true 9346 // 9347 // Return true if it was logically possible to so resolve the 9348 // expression, regardless of whether or not it succeeded. Always 9349 // returns true if 'complain' is set. 9350 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9351 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9352 bool complain, const SourceRange& OpRangeForComplaining, 9353 QualType DestTypeForComplaining, 9354 unsigned DiagIDForComplaining) { 9355 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9356 9357 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9358 9359 DeclAccessPair found; 9360 ExprResult SingleFunctionExpression; 9361 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9362 ovl.Expression, /*complain*/ false, &found)) { 9363 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9364 SrcExpr = ExprError(); 9365 return true; 9366 } 9367 9368 // It is only correct to resolve to an instance method if we're 9369 // resolving a form that's permitted to be a pointer to member. 9370 // Otherwise we'll end up making a bound member expression, which 9371 // is illegal in all the contexts we resolve like this. 9372 if (!ovl.HasFormOfMemberPointer && 9373 isa<CXXMethodDecl>(fn) && 9374 cast<CXXMethodDecl>(fn)->isInstance()) { 9375 if (!complain) return false; 9376 9377 Diag(ovl.Expression->getExprLoc(), 9378 diag::err_bound_member_function) 9379 << 0 << ovl.Expression->getSourceRange(); 9380 9381 // TODO: I believe we only end up here if there's a mix of 9382 // static and non-static candidates (otherwise the expression 9383 // would have 'bound member' type, not 'overload' type). 9384 // Ideally we would note which candidate was chosen and why 9385 // the static candidates were rejected. 9386 SrcExpr = ExprError(); 9387 return true; 9388 } 9389 9390 // Fix the expression to refer to 'fn'. 9391 SingleFunctionExpression = 9392 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9393 9394 // If desired, do function-to-pointer decay. 9395 if (doFunctionPointerConverion) { 9396 SingleFunctionExpression = 9397 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9398 if (SingleFunctionExpression.isInvalid()) { 9399 SrcExpr = ExprError(); 9400 return true; 9401 } 9402 } 9403 } 9404 9405 if (!SingleFunctionExpression.isUsable()) { 9406 if (complain) { 9407 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9408 << ovl.Expression->getName() 9409 << DestTypeForComplaining 9410 << OpRangeForComplaining 9411 << ovl.Expression->getQualifierLoc().getSourceRange(); 9412 NoteAllOverloadCandidates(SrcExpr.get()); 9413 9414 SrcExpr = ExprError(); 9415 return true; 9416 } 9417 9418 return false; 9419 } 9420 9421 SrcExpr = SingleFunctionExpression; 9422 return true; 9423 } 9424 9425 /// \brief Add a single candidate to the overload set. 9426 static void AddOverloadedCallCandidate(Sema &S, 9427 DeclAccessPair FoundDecl, 9428 TemplateArgumentListInfo *ExplicitTemplateArgs, 9429 ArrayRef<Expr *> Args, 9430 OverloadCandidateSet &CandidateSet, 9431 bool PartialOverloading, 9432 bool KnownValid) { 9433 NamedDecl *Callee = FoundDecl.getDecl(); 9434 if (isa<UsingShadowDecl>(Callee)) 9435 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9436 9437 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9438 if (ExplicitTemplateArgs) { 9439 assert(!KnownValid && "Explicit template arguments?"); 9440 return; 9441 } 9442 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9443 PartialOverloading); 9444 return; 9445 } 9446 9447 if (FunctionTemplateDecl *FuncTemplate 9448 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9449 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9450 ExplicitTemplateArgs, Args, CandidateSet); 9451 return; 9452 } 9453 9454 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9455 } 9456 9457 /// \brief Add the overload candidates named by callee and/or found by argument 9458 /// dependent lookup to the given overload set. 9459 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9460 ArrayRef<Expr *> Args, 9461 OverloadCandidateSet &CandidateSet, 9462 bool PartialOverloading) { 9463 9464 #ifndef NDEBUG 9465 // Verify that ArgumentDependentLookup is consistent with the rules 9466 // in C++0x [basic.lookup.argdep]p3: 9467 // 9468 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9469 // and let Y be the lookup set produced by argument dependent 9470 // lookup (defined as follows). If X contains 9471 // 9472 // -- a declaration of a class member, or 9473 // 9474 // -- a block-scope function declaration that is not a 9475 // using-declaration, or 9476 // 9477 // -- a declaration that is neither a function or a function 9478 // template 9479 // 9480 // then Y is empty. 9481 9482 if (ULE->requiresADL()) { 9483 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9484 E = ULE->decls_end(); I != E; ++I) { 9485 assert(!(*I)->getDeclContext()->isRecord()); 9486 assert(isa<UsingShadowDecl>(*I) || 9487 !(*I)->getDeclContext()->isFunctionOrMethod()); 9488 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9489 } 9490 } 9491 #endif 9492 9493 // It would be nice to avoid this copy. 9494 TemplateArgumentListInfo TABuffer; 9495 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9496 if (ULE->hasExplicitTemplateArgs()) { 9497 ULE->copyTemplateArgumentsInto(TABuffer); 9498 ExplicitTemplateArgs = &TABuffer; 9499 } 9500 9501 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9502 E = ULE->decls_end(); I != E; ++I) 9503 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9504 CandidateSet, PartialOverloading, 9505 /*KnownValid*/ true); 9506 9507 if (ULE->requiresADL()) 9508 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9509 ULE->getExprLoc(), 9510 Args, ExplicitTemplateArgs, 9511 CandidateSet, PartialOverloading); 9512 } 9513 9514 /// Attempt to recover from an ill-formed use of a non-dependent name in a 9515 /// template, where the non-dependent name was declared after the template 9516 /// was defined. This is common in code written for a compilers which do not 9517 /// correctly implement two-stage name lookup. 9518 /// 9519 /// Returns true if a viable candidate was found and a diagnostic was issued. 9520 static bool 9521 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9522 const CXXScopeSpec &SS, LookupResult &R, 9523 TemplateArgumentListInfo *ExplicitTemplateArgs, 9524 ArrayRef<Expr *> Args) { 9525 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9526 return false; 9527 9528 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9529 if (DC->isTransparentContext()) 9530 continue; 9531 9532 SemaRef.LookupQualifiedName(R, DC); 9533 9534 if (!R.empty()) { 9535 R.suppressDiagnostics(); 9536 9537 if (isa<CXXRecordDecl>(DC)) { 9538 // Don't diagnose names we find in classes; we get much better 9539 // diagnostics for these from DiagnoseEmptyLookup. 9540 R.clear(); 9541 return false; 9542 } 9543 9544 OverloadCandidateSet Candidates(FnLoc); 9545 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9546 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9547 ExplicitTemplateArgs, Args, 9548 Candidates, false, /*KnownValid*/ false); 9549 9550 OverloadCandidateSet::iterator Best; 9551 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9552 // No viable functions. Don't bother the user with notes for functions 9553 // which don't work and shouldn't be found anyway. 9554 R.clear(); 9555 return false; 9556 } 9557 9558 // Find the namespaces where ADL would have looked, and suggest 9559 // declaring the function there instead. 9560 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9561 Sema::AssociatedClassSet AssociatedClasses; 9562 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9563 AssociatedNamespaces, 9564 AssociatedClasses); 9565 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9566 DeclContext *Std = SemaRef.getStdNamespace(); 9567 for (Sema::AssociatedNamespaceSet::iterator 9568 it = AssociatedNamespaces.begin(), 9569 end = AssociatedNamespaces.end(); it != end; ++it) { 9570 // Never suggest declaring a function within namespace 'std'. 9571 if (Std && Std->Encloses(*it)) 9572 continue; 9573 9574 // Never suggest declaring a function within a namespace with a reserved 9575 // name, like __gnu_cxx. 9576 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9577 if (NS && 9578 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9579 continue; 9580 9581 SuggestedNamespaces.insert(*it); 9582 } 9583 9584 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9585 << R.getLookupName(); 9586 if (SuggestedNamespaces.empty()) { 9587 SemaRef.Diag(Best->Function->getLocation(), 9588 diag::note_not_found_by_two_phase_lookup) 9589 << R.getLookupName() << 0; 9590 } else if (SuggestedNamespaces.size() == 1) { 9591 SemaRef.Diag(Best->Function->getLocation(), 9592 diag::note_not_found_by_two_phase_lookup) 9593 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9594 } else { 9595 // FIXME: It would be useful to list the associated namespaces here, 9596 // but the diagnostics infrastructure doesn't provide a way to produce 9597 // a localized representation of a list of items. 9598 SemaRef.Diag(Best->Function->getLocation(), 9599 diag::note_not_found_by_two_phase_lookup) 9600 << R.getLookupName() << 2; 9601 } 9602 9603 // Try to recover by calling this function. 9604 return true; 9605 } 9606 9607 R.clear(); 9608 } 9609 9610 return false; 9611 } 9612 9613 /// Attempt to recover from ill-formed use of a non-dependent operator in a 9614 /// template, where the non-dependent operator was declared after the template 9615 /// was defined. 9616 /// 9617 /// Returns true if a viable candidate was found and a diagnostic was issued. 9618 static bool 9619 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9620 SourceLocation OpLoc, 9621 ArrayRef<Expr *> Args) { 9622 DeclarationName OpName = 9623 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9624 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9625 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9626 /*ExplicitTemplateArgs=*/0, Args); 9627 } 9628 9629 namespace { 9630 // Callback to limit the allowed keywords and to only accept typo corrections 9631 // that are keywords or whose decls refer to functions (or template functions) 9632 // that accept the given number of arguments. 9633 class RecoveryCallCCC : public CorrectionCandidateCallback { 9634 public: 9635 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9636 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9637 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9638 WantRemainingKeywords = false; 9639 } 9640 9641 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9642 if (!candidate.getCorrectionDecl()) 9643 return candidate.isKeyword(); 9644 9645 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9646 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9647 FunctionDecl *FD = 0; 9648 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9649 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9650 FD = FTD->getTemplatedDecl(); 9651 if (!HasExplicitTemplateArgs && !FD) { 9652 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9653 // If the Decl is neither a function nor a template function, 9654 // determine if it is a pointer or reference to a function. If so, 9655 // check against the number of arguments expected for the pointee. 9656 QualType ValType = cast<ValueDecl>(ND)->getType(); 9657 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9658 ValType = ValType->getPointeeType(); 9659 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9660 if (FPT->getNumArgs() == NumArgs) 9661 return true; 9662 } 9663 } 9664 if (FD && FD->getNumParams() >= NumArgs && 9665 FD->getMinRequiredArguments() <= NumArgs) 9666 return true; 9667 } 9668 return false; 9669 } 9670 9671 private: 9672 unsigned NumArgs; 9673 bool HasExplicitTemplateArgs; 9674 }; 9675 9676 // Callback that effectively disabled typo correction 9677 class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9678 public: 9679 NoTypoCorrectionCCC() { 9680 WantTypeSpecifiers = false; 9681 WantExpressionKeywords = false; 9682 WantCXXNamedCasts = false; 9683 WantRemainingKeywords = false; 9684 } 9685 9686 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9687 return false; 9688 } 9689 }; 9690 9691 class BuildRecoveryCallExprRAII { 9692 Sema &SemaRef; 9693 public: 9694 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9695 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9696 SemaRef.IsBuildingRecoveryCallExpr = true; 9697 } 9698 9699 ~BuildRecoveryCallExprRAII() { 9700 SemaRef.IsBuildingRecoveryCallExpr = false; 9701 } 9702 }; 9703 9704 } 9705 9706 /// Attempts to recover from a call where no functions were found. 9707 /// 9708 /// Returns true if new candidates were found. 9709 static ExprResult 9710 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9711 UnresolvedLookupExpr *ULE, 9712 SourceLocation LParenLoc, 9713 llvm::MutableArrayRef<Expr *> Args, 9714 SourceLocation RParenLoc, 9715 bool EmptyLookup, bool AllowTypoCorrection) { 9716 // Do not try to recover if it is already building a recovery call. 9717 // This stops infinite loops for template instantiations like 9718 // 9719 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9720 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9721 // 9722 if (SemaRef.IsBuildingRecoveryCallExpr) 9723 return ExprError(); 9724 BuildRecoveryCallExprRAII RCE(SemaRef); 9725 9726 CXXScopeSpec SS; 9727 SS.Adopt(ULE->getQualifierLoc()); 9728 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9729 9730 TemplateArgumentListInfo TABuffer; 9731 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9732 if (ULE->hasExplicitTemplateArgs()) { 9733 ULE->copyTemplateArgumentsInto(TABuffer); 9734 ExplicitTemplateArgs = &TABuffer; 9735 } 9736 9737 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9738 Sema::LookupOrdinaryName); 9739 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9740 NoTypoCorrectionCCC RejectAll; 9741 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9742 (CorrectionCandidateCallback*)&Validator : 9743 (CorrectionCandidateCallback*)&RejectAll; 9744 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9745 ExplicitTemplateArgs, Args) && 9746 (!EmptyLookup || 9747 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9748 ExplicitTemplateArgs, Args))) 9749 return ExprError(); 9750 9751 assert(!R.empty() && "lookup results empty despite recovery"); 9752 9753 // Build an implicit member call if appropriate. Just drop the 9754 // casts and such from the call, we don't really care. 9755 ExprResult NewFn = ExprError(); 9756 if ((*R.begin())->isCXXClassMember()) 9757 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9758 R, ExplicitTemplateArgs); 9759 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9760 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9761 ExplicitTemplateArgs); 9762 else 9763 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9764 9765 if (NewFn.isInvalid()) 9766 return ExprError(); 9767 9768 // This shouldn't cause an infinite loop because we're giving it 9769 // an expression with viable lookup results, which should never 9770 // end up here. 9771 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9772 MultiExprArg(Args.data(), Args.size()), 9773 RParenLoc); 9774 } 9775 9776 /// \brief Constructs and populates an OverloadedCandidateSet from 9777 /// the given function. 9778 /// \returns true when an the ExprResult output parameter has been set. 9779 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9780 UnresolvedLookupExpr *ULE, 9781 Expr **Args, unsigned NumArgs, 9782 SourceLocation RParenLoc, 9783 OverloadCandidateSet *CandidateSet, 9784 ExprResult *Result) { 9785 #ifndef NDEBUG 9786 if (ULE->requiresADL()) { 9787 // To do ADL, we must have found an unqualified name. 9788 assert(!ULE->getQualifier() && "qualified name with ADL"); 9789 9790 // We don't perform ADL for implicit declarations of builtins. 9791 // Verify that this was correctly set up. 9792 FunctionDecl *F; 9793 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9794 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9795 F->getBuiltinID() && F->isImplicit()) 9796 llvm_unreachable("performing ADL for builtin"); 9797 9798 // We don't perform ADL in C. 9799 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9800 } 9801 #endif 9802 9803 UnbridgedCastsSet UnbridgedCasts; 9804 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9805 *Result = ExprError(); 9806 return true; 9807 } 9808 9809 // Add the functions denoted by the callee to the set of candidate 9810 // functions, including those from argument-dependent lookup. 9811 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9812 *CandidateSet); 9813 9814 // If we found nothing, try to recover. 9815 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9816 // out if it fails. 9817 if (CandidateSet->empty()) { 9818 // In Microsoft mode, if we are inside a template class member function then 9819 // create a type dependent CallExpr. The goal is to postpone name lookup 9820 // to instantiation time to be able to search into type dependent base 9821 // classes. 9822 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9823 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9824 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9825 llvm::makeArrayRef(Args, NumArgs), 9826 Context.DependentTy, VK_RValue, 9827 RParenLoc); 9828 CE->setTypeDependent(true); 9829 *Result = Owned(CE); 9830 return true; 9831 } 9832 return false; 9833 } 9834 9835 UnbridgedCasts.restore(); 9836 return false; 9837 } 9838 9839 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9840 /// the completed call expression. If overload resolution fails, emits 9841 /// diagnostics and returns ExprError() 9842 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9843 UnresolvedLookupExpr *ULE, 9844 SourceLocation LParenLoc, 9845 Expr **Args, unsigned NumArgs, 9846 SourceLocation RParenLoc, 9847 Expr *ExecConfig, 9848 OverloadCandidateSet *CandidateSet, 9849 OverloadCandidateSet::iterator *Best, 9850 OverloadingResult OverloadResult, 9851 bool AllowTypoCorrection) { 9852 if (CandidateSet->empty()) 9853 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9854 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9855 RParenLoc, /*EmptyLookup=*/true, 9856 AllowTypoCorrection); 9857 9858 switch (OverloadResult) { 9859 case OR_Success: { 9860 FunctionDecl *FDecl = (*Best)->Function; 9861 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9862 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9863 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9864 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9865 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9866 RParenLoc, ExecConfig); 9867 } 9868 9869 case OR_No_Viable_Function: { 9870 // Try to recover by looking for viable functions which the user might 9871 // have meant to call. 9872 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9873 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9874 RParenLoc, 9875 /*EmptyLookup=*/false, 9876 AllowTypoCorrection); 9877 if (!Recovery.isInvalid()) 9878 return Recovery; 9879 9880 SemaRef.Diag(Fn->getLocStart(), 9881 diag::err_ovl_no_viable_function_in_call) 9882 << ULE->getName() << Fn->getSourceRange(); 9883 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9884 llvm::makeArrayRef(Args, NumArgs)); 9885 break; 9886 } 9887 9888 case OR_Ambiguous: 9889 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9890 << ULE->getName() << Fn->getSourceRange(); 9891 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9892 llvm::makeArrayRef(Args, NumArgs)); 9893 break; 9894 9895 case OR_Deleted: { 9896 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9897 << (*Best)->Function->isDeleted() 9898 << ULE->getName() 9899 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9900 << Fn->getSourceRange(); 9901 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9902 llvm::makeArrayRef(Args, NumArgs)); 9903 9904 // We emitted an error for the unvailable/deleted function call but keep 9905 // the call in the AST. 9906 FunctionDecl *FDecl = (*Best)->Function; 9907 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9908 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9909 RParenLoc, ExecConfig); 9910 } 9911 } 9912 9913 // Overload resolution failed. 9914 return ExprError(); 9915 } 9916 9917 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 9918 /// (which eventually refers to the declaration Func) and the call 9919 /// arguments Args/NumArgs, attempt to resolve the function call down 9920 /// to a specific function. If overload resolution succeeds, returns 9921 /// the call expression produced by overload resolution. 9922 /// Otherwise, emits diagnostics and returns ExprError. 9923 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9924 UnresolvedLookupExpr *ULE, 9925 SourceLocation LParenLoc, 9926 Expr **Args, unsigned NumArgs, 9927 SourceLocation RParenLoc, 9928 Expr *ExecConfig, 9929 bool AllowTypoCorrection) { 9930 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9931 ExprResult result; 9932 9933 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9934 &CandidateSet, &result)) 9935 return result; 9936 9937 OverloadCandidateSet::iterator Best; 9938 OverloadingResult OverloadResult = 9939 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9940 9941 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9942 RParenLoc, ExecConfig, &CandidateSet, 9943 &Best, OverloadResult, 9944 AllowTypoCorrection); 9945 } 9946 9947 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9948 return Functions.size() > 1 || 9949 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9950 } 9951 9952 /// \brief Create a unary operation that may resolve to an overloaded 9953 /// operator. 9954 /// 9955 /// \param OpLoc The location of the operator itself (e.g., '*'). 9956 /// 9957 /// \param OpcIn The UnaryOperator::Opcode that describes this 9958 /// operator. 9959 /// 9960 /// \param Fns The set of non-member functions that will be 9961 /// considered by overload resolution. The caller needs to build this 9962 /// set based on the context using, e.g., 9963 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9964 /// set should not contain any member functions; those will be added 9965 /// by CreateOverloadedUnaryOp(). 9966 /// 9967 /// \param Input The input argument. 9968 ExprResult 9969 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9970 const UnresolvedSetImpl &Fns, 9971 Expr *Input) { 9972 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9973 9974 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9975 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9976 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9977 // TODO: provide better source location info. 9978 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9979 9980 if (checkPlaceholderForOverload(*this, Input)) 9981 return ExprError(); 9982 9983 Expr *Args[2] = { Input, 0 }; 9984 unsigned NumArgs = 1; 9985 9986 // For post-increment and post-decrement, add the implicit '0' as 9987 // the second argument, so that we know this is a post-increment or 9988 // post-decrement. 9989 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9990 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9991 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9992 SourceLocation()); 9993 NumArgs = 2; 9994 } 9995 9996 if (Input->isTypeDependent()) { 9997 if (Fns.empty()) 9998 return Owned(new (Context) UnaryOperator(Input, 9999 Opc, 10000 Context.DependentTy, 10001 VK_RValue, OK_Ordinary, 10002 OpLoc)); 10003 10004 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10005 UnresolvedLookupExpr *Fn 10006 = UnresolvedLookupExpr::Create(Context, NamingClass, 10007 NestedNameSpecifierLoc(), OpNameInfo, 10008 /*ADL*/ true, IsOverloaded(Fns), 10009 Fns.begin(), Fns.end()); 10010 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10011 llvm::makeArrayRef(Args, NumArgs), 10012 Context.DependentTy, 10013 VK_RValue, 10014 OpLoc, false)); 10015 } 10016 10017 // Build an empty overload set. 10018 OverloadCandidateSet CandidateSet(OpLoc); 10019 10020 // Add the candidates from the given function set. 10021 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10022 false); 10023 10024 // Add operator candidates that are member functions. 10025 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10026 10027 // Add candidates from ADL. 10028 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10029 OpLoc, llvm::makeArrayRef(Args, NumArgs), 10030 /*ExplicitTemplateArgs*/ 0, 10031 CandidateSet); 10032 10033 // Add builtin operator candidates. 10034 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10035 10036 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10037 10038 // Perform overload resolution. 10039 OverloadCandidateSet::iterator Best; 10040 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10041 case OR_Success: { 10042 // We found a built-in operator or an overloaded operator. 10043 FunctionDecl *FnDecl = Best->Function; 10044 10045 if (FnDecl) { 10046 // We matched an overloaded operator. Build a call to that 10047 // operator. 10048 10049 MarkFunctionReferenced(OpLoc, FnDecl); 10050 10051 // Convert the arguments. 10052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10053 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10054 10055 ExprResult InputRes = 10056 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10057 Best->FoundDecl, Method); 10058 if (InputRes.isInvalid()) 10059 return ExprError(); 10060 Input = InputRes.take(); 10061 } else { 10062 // Convert the arguments. 10063 ExprResult InputInit 10064 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10065 Context, 10066 FnDecl->getParamDecl(0)), 10067 SourceLocation(), 10068 Input); 10069 if (InputInit.isInvalid()) 10070 return ExprError(); 10071 Input = InputInit.take(); 10072 } 10073 10074 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10075 10076 // Determine the result type. 10077 QualType ResultTy = FnDecl->getResultType(); 10078 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10079 ResultTy = ResultTy.getNonLValueExprType(Context); 10080 10081 // Build the actual expression node. 10082 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10083 HadMultipleCandidates, OpLoc); 10084 if (FnExpr.isInvalid()) 10085 return ExprError(); 10086 10087 Args[0] = Input; 10088 CallExpr *TheCall = 10089 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10090 llvm::makeArrayRef(Args, NumArgs), 10091 ResultTy, VK, OpLoc, false); 10092 10093 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10094 FnDecl)) 10095 return ExprError(); 10096 10097 return MaybeBindToTemporary(TheCall); 10098 } else { 10099 // We matched a built-in operator. Convert the arguments, then 10100 // break out so that we will build the appropriate built-in 10101 // operator node. 10102 ExprResult InputRes = 10103 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10104 Best->Conversions[0], AA_Passing); 10105 if (InputRes.isInvalid()) 10106 return ExprError(); 10107 Input = InputRes.take(); 10108 break; 10109 } 10110 } 10111 10112 case OR_No_Viable_Function: 10113 // This is an erroneous use of an operator which can be overloaded by 10114 // a non-member function. Check for non-member operators which were 10115 // defined too late to be candidates. 10116 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10117 llvm::makeArrayRef(Args, NumArgs))) 10118 // FIXME: Recover by calling the found function. 10119 return ExprError(); 10120 10121 // No viable function; fall through to handling this as a 10122 // built-in operator, which will produce an error message for us. 10123 break; 10124 10125 case OR_Ambiguous: 10126 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10127 << UnaryOperator::getOpcodeStr(Opc) 10128 << Input->getType() 10129 << Input->getSourceRange(); 10130 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10131 llvm::makeArrayRef(Args, NumArgs), 10132 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10133 return ExprError(); 10134 10135 case OR_Deleted: 10136 Diag(OpLoc, diag::err_ovl_deleted_oper) 10137 << Best->Function->isDeleted() 10138 << UnaryOperator::getOpcodeStr(Opc) 10139 << getDeletedOrUnavailableSuffix(Best->Function) 10140 << Input->getSourceRange(); 10141 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10142 llvm::makeArrayRef(Args, NumArgs), 10143 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10144 return ExprError(); 10145 } 10146 10147 // Either we found no viable overloaded operator or we matched a 10148 // built-in operator. In either case, fall through to trying to 10149 // build a built-in operation. 10150 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10151 } 10152 10153 /// \brief Create a binary operation that may resolve to an overloaded 10154 /// operator. 10155 /// 10156 /// \param OpLoc The location of the operator itself (e.g., '+'). 10157 /// 10158 /// \param OpcIn The BinaryOperator::Opcode that describes this 10159 /// operator. 10160 /// 10161 /// \param Fns The set of non-member functions that will be 10162 /// considered by overload resolution. The caller needs to build this 10163 /// set based on the context using, e.g., 10164 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10165 /// set should not contain any member functions; those will be added 10166 /// by CreateOverloadedBinOp(). 10167 /// 10168 /// \param LHS Left-hand argument. 10169 /// \param RHS Right-hand argument. 10170 ExprResult 10171 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10172 unsigned OpcIn, 10173 const UnresolvedSetImpl &Fns, 10174 Expr *LHS, Expr *RHS) { 10175 Expr *Args[2] = { LHS, RHS }; 10176 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10177 10178 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10179 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10180 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10181 10182 // If either side is type-dependent, create an appropriate dependent 10183 // expression. 10184 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10185 if (Fns.empty()) { 10186 // If there are no functions to store, just build a dependent 10187 // BinaryOperator or CompoundAssignment. 10188 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10189 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10190 Context.DependentTy, 10191 VK_RValue, OK_Ordinary, 10192 OpLoc, 10193 FPFeatures.fp_contract)); 10194 10195 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10196 Context.DependentTy, 10197 VK_LValue, 10198 OK_Ordinary, 10199 Context.DependentTy, 10200 Context.DependentTy, 10201 OpLoc, 10202 FPFeatures.fp_contract)); 10203 } 10204 10205 // FIXME: save results of ADL from here? 10206 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10207 // TODO: provide better source location info in DNLoc component. 10208 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10209 UnresolvedLookupExpr *Fn 10210 = UnresolvedLookupExpr::Create(Context, NamingClass, 10211 NestedNameSpecifierLoc(), OpNameInfo, 10212 /*ADL*/ true, IsOverloaded(Fns), 10213 Fns.begin(), Fns.end()); 10214 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10215 Context.DependentTy, VK_RValue, 10216 OpLoc, FPFeatures.fp_contract)); 10217 } 10218 10219 // Always do placeholder-like conversions on the RHS. 10220 if (checkPlaceholderForOverload(*this, Args[1])) 10221 return ExprError(); 10222 10223 // Do placeholder-like conversion on the LHS; note that we should 10224 // not get here with a PseudoObject LHS. 10225 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10226 if (checkPlaceholderForOverload(*this, Args[0])) 10227 return ExprError(); 10228 10229 // If this is the assignment operator, we only perform overload resolution 10230 // if the left-hand side is a class or enumeration type. This is actually 10231 // a hack. The standard requires that we do overload resolution between the 10232 // various built-in candidates, but as DR507 points out, this can lead to 10233 // problems. So we do it this way, which pretty much follows what GCC does. 10234 // Note that we go the traditional code path for compound assignment forms. 10235 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10236 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10237 10238 // If this is the .* operator, which is not overloadable, just 10239 // create a built-in binary operator. 10240 if (Opc == BO_PtrMemD) 10241 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10242 10243 // Build an empty overload set. 10244 OverloadCandidateSet CandidateSet(OpLoc); 10245 10246 // Add the candidates from the given function set. 10247 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10248 10249 // Add operator candidates that are member functions. 10250 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10251 10252 // Add candidates from ADL. 10253 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10254 OpLoc, Args, 10255 /*ExplicitTemplateArgs*/ 0, 10256 CandidateSet); 10257 10258 // Add builtin operator candidates. 10259 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10260 10261 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10262 10263 // Perform overload resolution. 10264 OverloadCandidateSet::iterator Best; 10265 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10266 case OR_Success: { 10267 // We found a built-in operator or an overloaded operator. 10268 FunctionDecl *FnDecl = Best->Function; 10269 10270 if (FnDecl) { 10271 // We matched an overloaded operator. Build a call to that 10272 // operator. 10273 10274 MarkFunctionReferenced(OpLoc, FnDecl); 10275 10276 // Convert the arguments. 10277 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10278 // Best->Access is only meaningful for class members. 10279 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10280 10281 ExprResult Arg1 = 10282 PerformCopyInitialization( 10283 InitializedEntity::InitializeParameter(Context, 10284 FnDecl->getParamDecl(0)), 10285 SourceLocation(), Owned(Args[1])); 10286 if (Arg1.isInvalid()) 10287 return ExprError(); 10288 10289 ExprResult Arg0 = 10290 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10291 Best->FoundDecl, Method); 10292 if (Arg0.isInvalid()) 10293 return ExprError(); 10294 Args[0] = Arg0.takeAs<Expr>(); 10295 Args[1] = RHS = Arg1.takeAs<Expr>(); 10296 } else { 10297 // Convert the arguments. 10298 ExprResult Arg0 = PerformCopyInitialization( 10299 InitializedEntity::InitializeParameter(Context, 10300 FnDecl->getParamDecl(0)), 10301 SourceLocation(), Owned(Args[0])); 10302 if (Arg0.isInvalid()) 10303 return ExprError(); 10304 10305 ExprResult Arg1 = 10306 PerformCopyInitialization( 10307 InitializedEntity::InitializeParameter(Context, 10308 FnDecl->getParamDecl(1)), 10309 SourceLocation(), Owned(Args[1])); 10310 if (Arg1.isInvalid()) 10311 return ExprError(); 10312 Args[0] = LHS = Arg0.takeAs<Expr>(); 10313 Args[1] = RHS = Arg1.takeAs<Expr>(); 10314 } 10315 10316 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10317 10318 // Determine the result type. 10319 QualType ResultTy = FnDecl->getResultType(); 10320 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10321 ResultTy = ResultTy.getNonLValueExprType(Context); 10322 10323 // Build the actual expression node. 10324 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10325 HadMultipleCandidates, OpLoc); 10326 if (FnExpr.isInvalid()) 10327 return ExprError(); 10328 10329 CXXOperatorCallExpr *TheCall = 10330 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10331 Args, ResultTy, VK, OpLoc, 10332 FPFeatures.fp_contract); 10333 10334 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10335 FnDecl)) 10336 return ExprError(); 10337 10338 return MaybeBindToTemporary(TheCall); 10339 } else { 10340 // We matched a built-in operator. Convert the arguments, then 10341 // break out so that we will build the appropriate built-in 10342 // operator node. 10343 ExprResult ArgsRes0 = 10344 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10345 Best->Conversions[0], AA_Passing); 10346 if (ArgsRes0.isInvalid()) 10347 return ExprError(); 10348 Args[0] = ArgsRes0.take(); 10349 10350 ExprResult ArgsRes1 = 10351 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10352 Best->Conversions[1], AA_Passing); 10353 if (ArgsRes1.isInvalid()) 10354 return ExprError(); 10355 Args[1] = ArgsRes1.take(); 10356 break; 10357 } 10358 } 10359 10360 case OR_No_Viable_Function: { 10361 // C++ [over.match.oper]p9: 10362 // If the operator is the operator , [...] and there are no 10363 // viable functions, then the operator is assumed to be the 10364 // built-in operator and interpreted according to clause 5. 10365 if (Opc == BO_Comma) 10366 break; 10367 10368 // For class as left operand for assignment or compound assigment 10369 // operator do not fall through to handling in built-in, but report that 10370 // no overloaded assignment operator found 10371 ExprResult Result = ExprError(); 10372 if (Args[0]->getType()->isRecordType() && 10373 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10374 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10375 << BinaryOperator::getOpcodeStr(Opc) 10376 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10377 } else { 10378 // This is an erroneous use of an operator which can be overloaded by 10379 // a non-member function. Check for non-member operators which were 10380 // defined too late to be candidates. 10381 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10382 // FIXME: Recover by calling the found function. 10383 return ExprError(); 10384 10385 // No viable function; try to create a built-in operation, which will 10386 // produce an error. Then, show the non-viable candidates. 10387 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10388 } 10389 assert(Result.isInvalid() && 10390 "C++ binary operator overloading is missing candidates!"); 10391 if (Result.isInvalid()) 10392 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10393 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10394 return Result; 10395 } 10396 10397 case OR_Ambiguous: 10398 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10399 << BinaryOperator::getOpcodeStr(Opc) 10400 << Args[0]->getType() << Args[1]->getType() 10401 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10402 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10403 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10404 return ExprError(); 10405 10406 case OR_Deleted: 10407 if (isImplicitlyDeleted(Best->Function)) { 10408 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10409 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10410 << Context.getRecordType(Method->getParent()) 10411 << getSpecialMember(Method); 10412 10413 // The user probably meant to call this special member. Just 10414 // explain why it's deleted. 10415 NoteDeletedFunction(Method); 10416 return ExprError(); 10417 } else { 10418 Diag(OpLoc, diag::err_ovl_deleted_oper) 10419 << Best->Function->isDeleted() 10420 << BinaryOperator::getOpcodeStr(Opc) 10421 << getDeletedOrUnavailableSuffix(Best->Function) 10422 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10423 } 10424 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10425 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10426 return ExprError(); 10427 } 10428 10429 // We matched a built-in operator; build it. 10430 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10431 } 10432 10433 ExprResult 10434 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10435 SourceLocation RLoc, 10436 Expr *Base, Expr *Idx) { 10437 Expr *Args[2] = { Base, Idx }; 10438 DeclarationName OpName = 10439 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10440 10441 // If either side is type-dependent, create an appropriate dependent 10442 // expression. 10443 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10444 10445 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10446 // CHECKME: no 'operator' keyword? 10447 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10448 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10449 UnresolvedLookupExpr *Fn 10450 = UnresolvedLookupExpr::Create(Context, NamingClass, 10451 NestedNameSpecifierLoc(), OpNameInfo, 10452 /*ADL*/ true, /*Overloaded*/ false, 10453 UnresolvedSetIterator(), 10454 UnresolvedSetIterator()); 10455 // Can't add any actual overloads yet 10456 10457 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10458 Args, 10459 Context.DependentTy, 10460 VK_RValue, 10461 RLoc, false)); 10462 } 10463 10464 // Handle placeholders on both operands. 10465 if (checkPlaceholderForOverload(*this, Args[0])) 10466 return ExprError(); 10467 if (checkPlaceholderForOverload(*this, Args[1])) 10468 return ExprError(); 10469 10470 // Build an empty overload set. 10471 OverloadCandidateSet CandidateSet(LLoc); 10472 10473 // Subscript can only be overloaded as a member function. 10474 10475 // Add operator candidates that are member functions. 10476 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10477 10478 // Add builtin operator candidates. 10479 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10480 10481 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10482 10483 // Perform overload resolution. 10484 OverloadCandidateSet::iterator Best; 10485 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10486 case OR_Success: { 10487 // We found a built-in operator or an overloaded operator. 10488 FunctionDecl *FnDecl = Best->Function; 10489 10490 if (FnDecl) { 10491 // We matched an overloaded operator. Build a call to that 10492 // operator. 10493 10494 MarkFunctionReferenced(LLoc, FnDecl); 10495 10496 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10497 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10498 10499 // Convert the arguments. 10500 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10501 ExprResult Arg0 = 10502 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10503 Best->FoundDecl, Method); 10504 if (Arg0.isInvalid()) 10505 return ExprError(); 10506 Args[0] = Arg0.take(); 10507 10508 // Convert the arguments. 10509 ExprResult InputInit 10510 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10511 Context, 10512 FnDecl->getParamDecl(0)), 10513 SourceLocation(), 10514 Owned(Args[1])); 10515 if (InputInit.isInvalid()) 10516 return ExprError(); 10517 10518 Args[1] = InputInit.takeAs<Expr>(); 10519 10520 // Determine the result type 10521 QualType ResultTy = FnDecl->getResultType(); 10522 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10523 ResultTy = ResultTy.getNonLValueExprType(Context); 10524 10525 // Build the actual expression node. 10526 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10527 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10528 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10529 HadMultipleCandidates, 10530 OpLocInfo.getLoc(), 10531 OpLocInfo.getInfo()); 10532 if (FnExpr.isInvalid()) 10533 return ExprError(); 10534 10535 CXXOperatorCallExpr *TheCall = 10536 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10537 FnExpr.take(), Args, 10538 ResultTy, VK, RLoc, 10539 false); 10540 10541 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10542 FnDecl)) 10543 return ExprError(); 10544 10545 return MaybeBindToTemporary(TheCall); 10546 } else { 10547 // We matched a built-in operator. Convert the arguments, then 10548 // break out so that we will build the appropriate built-in 10549 // operator node. 10550 ExprResult ArgsRes0 = 10551 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10552 Best->Conversions[0], AA_Passing); 10553 if (ArgsRes0.isInvalid()) 10554 return ExprError(); 10555 Args[0] = ArgsRes0.take(); 10556 10557 ExprResult ArgsRes1 = 10558 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10559 Best->Conversions[1], AA_Passing); 10560 if (ArgsRes1.isInvalid()) 10561 return ExprError(); 10562 Args[1] = ArgsRes1.take(); 10563 10564 break; 10565 } 10566 } 10567 10568 case OR_No_Viable_Function: { 10569 if (CandidateSet.empty()) 10570 Diag(LLoc, diag::err_ovl_no_oper) 10571 << Args[0]->getType() << /*subscript*/ 0 10572 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10573 else 10574 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10575 << Args[0]->getType() 10576 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10577 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10578 "[]", LLoc); 10579 return ExprError(); 10580 } 10581 10582 case OR_Ambiguous: 10583 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10584 << "[]" 10585 << Args[0]->getType() << Args[1]->getType() 10586 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10587 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10588 "[]", LLoc); 10589 return ExprError(); 10590 10591 case OR_Deleted: 10592 Diag(LLoc, diag::err_ovl_deleted_oper) 10593 << Best->Function->isDeleted() << "[]" 10594 << getDeletedOrUnavailableSuffix(Best->Function) 10595 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10596 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10597 "[]", LLoc); 10598 return ExprError(); 10599 } 10600 10601 // We matched a built-in operator; build it. 10602 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10603 } 10604 10605 /// BuildCallToMemberFunction - Build a call to a member 10606 /// function. MemExpr is the expression that refers to the member 10607 /// function (and includes the object parameter), Args/NumArgs are the 10608 /// arguments to the function call (not including the object 10609 /// parameter). The caller needs to validate that the member 10610 /// expression refers to a non-static member function or an overloaded 10611 /// member function. 10612 ExprResult 10613 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10614 SourceLocation LParenLoc, Expr **Args, 10615 unsigned NumArgs, SourceLocation RParenLoc) { 10616 assert(MemExprE->getType() == Context.BoundMemberTy || 10617 MemExprE->getType() == Context.OverloadTy); 10618 10619 // Dig out the member expression. This holds both the object 10620 // argument and the member function we're referring to. 10621 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10622 10623 // Determine whether this is a call to a pointer-to-member function. 10624 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10625 assert(op->getType() == Context.BoundMemberTy); 10626 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10627 10628 QualType fnType = 10629 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10630 10631 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10632 QualType resultType = proto->getCallResultType(Context); 10633 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10634 10635 // Check that the object type isn't more qualified than the 10636 // member function we're calling. 10637 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10638 10639 QualType objectType = op->getLHS()->getType(); 10640 if (op->getOpcode() == BO_PtrMemI) 10641 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10642 Qualifiers objectQuals = objectType.getQualifiers(); 10643 10644 Qualifiers difference = objectQuals - funcQuals; 10645 difference.removeObjCGCAttr(); 10646 difference.removeAddressSpace(); 10647 if (difference) { 10648 std::string qualsString = difference.getAsString(); 10649 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10650 << fnType.getUnqualifiedType() 10651 << qualsString 10652 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10653 } 10654 10655 CXXMemberCallExpr *call 10656 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10657 llvm::makeArrayRef(Args, NumArgs), 10658 resultType, valueKind, RParenLoc); 10659 10660 if (CheckCallReturnType(proto->getResultType(), 10661 op->getRHS()->getLocStart(), 10662 call, 0)) 10663 return ExprError(); 10664 10665 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10666 return ExprError(); 10667 10668 return MaybeBindToTemporary(call); 10669 } 10670 10671 UnbridgedCastsSet UnbridgedCasts; 10672 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10673 return ExprError(); 10674 10675 MemberExpr *MemExpr; 10676 CXXMethodDecl *Method = 0; 10677 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10678 NestedNameSpecifier *Qualifier = 0; 10679 if (isa<MemberExpr>(NakedMemExpr)) { 10680 MemExpr = cast<MemberExpr>(NakedMemExpr); 10681 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10682 FoundDecl = MemExpr->getFoundDecl(); 10683 Qualifier = MemExpr->getQualifier(); 10684 UnbridgedCasts.restore(); 10685 } else { 10686 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10687 Qualifier = UnresExpr->getQualifier(); 10688 10689 QualType ObjectType = UnresExpr->getBaseType(); 10690 Expr::Classification ObjectClassification 10691 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10692 : UnresExpr->getBase()->Classify(Context); 10693 10694 // Add overload candidates 10695 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10696 10697 // FIXME: avoid copy. 10698 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10699 if (UnresExpr->hasExplicitTemplateArgs()) { 10700 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10701 TemplateArgs = &TemplateArgsBuffer; 10702 } 10703 10704 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10705 E = UnresExpr->decls_end(); I != E; ++I) { 10706 10707 NamedDecl *Func = *I; 10708 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10709 if (isa<UsingShadowDecl>(Func)) 10710 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10711 10712 10713 // Microsoft supports direct constructor calls. 10714 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10715 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10716 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10717 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10718 // If explicit template arguments were provided, we can't call a 10719 // non-template member function. 10720 if (TemplateArgs) 10721 continue; 10722 10723 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10724 ObjectClassification, 10725 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10726 /*SuppressUserConversions=*/false); 10727 } else { 10728 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10729 I.getPair(), ActingDC, TemplateArgs, 10730 ObjectType, ObjectClassification, 10731 llvm::makeArrayRef(Args, NumArgs), 10732 CandidateSet, 10733 /*SuppressUsedConversions=*/false); 10734 } 10735 } 10736 10737 DeclarationName DeclName = UnresExpr->getMemberName(); 10738 10739 UnbridgedCasts.restore(); 10740 10741 OverloadCandidateSet::iterator Best; 10742 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10743 Best)) { 10744 case OR_Success: 10745 Method = cast<CXXMethodDecl>(Best->Function); 10746 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10747 FoundDecl = Best->FoundDecl; 10748 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10749 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10750 break; 10751 10752 case OR_No_Viable_Function: 10753 Diag(UnresExpr->getMemberLoc(), 10754 diag::err_ovl_no_viable_member_function_in_call) 10755 << DeclName << MemExprE->getSourceRange(); 10756 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10757 llvm::makeArrayRef(Args, NumArgs)); 10758 // FIXME: Leaking incoming expressions! 10759 return ExprError(); 10760 10761 case OR_Ambiguous: 10762 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10763 << DeclName << MemExprE->getSourceRange(); 10764 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10765 llvm::makeArrayRef(Args, NumArgs)); 10766 // FIXME: Leaking incoming expressions! 10767 return ExprError(); 10768 10769 case OR_Deleted: 10770 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10771 << Best->Function->isDeleted() 10772 << DeclName 10773 << getDeletedOrUnavailableSuffix(Best->Function) 10774 << MemExprE->getSourceRange(); 10775 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10776 llvm::makeArrayRef(Args, NumArgs)); 10777 // FIXME: Leaking incoming expressions! 10778 return ExprError(); 10779 } 10780 10781 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10782 10783 // If overload resolution picked a static member, build a 10784 // non-member call based on that function. 10785 if (Method->isStatic()) { 10786 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10787 Args, NumArgs, RParenLoc); 10788 } 10789 10790 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10791 } 10792 10793 QualType ResultType = Method->getResultType(); 10794 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10795 ResultType = ResultType.getNonLValueExprType(Context); 10796 10797 assert(Method && "Member call to something that isn't a method?"); 10798 CXXMemberCallExpr *TheCall = 10799 new (Context) CXXMemberCallExpr(Context, MemExprE, 10800 llvm::makeArrayRef(Args, NumArgs), 10801 ResultType, VK, RParenLoc); 10802 10803 // Check for a valid return type. 10804 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10805 TheCall, Method)) 10806 return ExprError(); 10807 10808 // Convert the object argument (for a non-static member function call). 10809 // We only need to do this if there was actually an overload; otherwise 10810 // it was done at lookup. 10811 if (!Method->isStatic()) { 10812 ExprResult ObjectArg = 10813 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10814 FoundDecl, Method); 10815 if (ObjectArg.isInvalid()) 10816 return ExprError(); 10817 MemExpr->setBase(ObjectArg.take()); 10818 } 10819 10820 // Convert the rest of the arguments 10821 const FunctionProtoType *Proto = 10822 Method->getType()->getAs<FunctionProtoType>(); 10823 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10824 RParenLoc)) 10825 return ExprError(); 10826 10827 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10828 10829 if (CheckFunctionCall(Method, TheCall, Proto)) 10830 return ExprError(); 10831 10832 if ((isa<CXXConstructorDecl>(CurContext) || 10833 isa<CXXDestructorDecl>(CurContext)) && 10834 TheCall->getMethodDecl()->isPure()) { 10835 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10836 10837 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10838 Diag(MemExpr->getLocStart(), 10839 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10840 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10841 << MD->getParent()->getDeclName(); 10842 10843 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10844 } 10845 } 10846 return MaybeBindToTemporary(TheCall); 10847 } 10848 10849 /// BuildCallToObjectOfClassType - Build a call to an object of class 10850 /// type (C++ [over.call.object]), which can end up invoking an 10851 /// overloaded function call operator (@c operator()) or performing a 10852 /// user-defined conversion on the object argument. 10853 ExprResult 10854 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10855 SourceLocation LParenLoc, 10856 Expr **Args, unsigned NumArgs, 10857 SourceLocation RParenLoc) { 10858 if (checkPlaceholderForOverload(*this, Obj)) 10859 return ExprError(); 10860 ExprResult Object = Owned(Obj); 10861 10862 UnbridgedCastsSet UnbridgedCasts; 10863 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10864 return ExprError(); 10865 10866 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10867 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10868 10869 // C++ [over.call.object]p1: 10870 // If the primary-expression E in the function call syntax 10871 // evaluates to a class object of type "cv T", then the set of 10872 // candidate functions includes at least the function call 10873 // operators of T. The function call operators of T are obtained by 10874 // ordinary lookup of the name operator() in the context of 10875 // (E).operator(). 10876 OverloadCandidateSet CandidateSet(LParenLoc); 10877 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10878 10879 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10880 diag::err_incomplete_object_call, Object.get())) 10881 return true; 10882 10883 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10884 LookupQualifiedName(R, Record->getDecl()); 10885 R.suppressDiagnostics(); 10886 10887 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10888 Oper != OperEnd; ++Oper) { 10889 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10890 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10891 /*SuppressUserConversions=*/ false); 10892 } 10893 10894 // C++ [over.call.object]p2: 10895 // In addition, for each (non-explicit in C++0x) conversion function 10896 // declared in T of the form 10897 // 10898 // operator conversion-type-id () cv-qualifier; 10899 // 10900 // where cv-qualifier is the same cv-qualification as, or a 10901 // greater cv-qualification than, cv, and where conversion-type-id 10902 // denotes the type "pointer to function of (P1,...,Pn) returning 10903 // R", or the type "reference to pointer to function of 10904 // (P1,...,Pn) returning R", or the type "reference to function 10905 // of (P1,...,Pn) returning R", a surrogate call function [...] 10906 // is also considered as a candidate function. Similarly, 10907 // surrogate call functions are added to the set of candidate 10908 // functions for each conversion function declared in an 10909 // accessible base class provided the function is not hidden 10910 // within T by another intervening declaration. 10911 std::pair<CXXRecordDecl::conversion_iterator, 10912 CXXRecordDecl::conversion_iterator> Conversions 10913 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10914 for (CXXRecordDecl::conversion_iterator 10915 I = Conversions.first, E = Conversions.second; I != E; ++I) { 10916 NamedDecl *D = *I; 10917 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10918 if (isa<UsingShadowDecl>(D)) 10919 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10920 10921 // Skip over templated conversion functions; they aren't 10922 // surrogates. 10923 if (isa<FunctionTemplateDecl>(D)) 10924 continue; 10925 10926 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10927 if (!Conv->isExplicit()) { 10928 // Strip the reference type (if any) and then the pointer type (if 10929 // any) to get down to what might be a function type. 10930 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10931 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10932 ConvType = ConvPtrType->getPointeeType(); 10933 10934 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10935 { 10936 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10937 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10938 CandidateSet); 10939 } 10940 } 10941 } 10942 10943 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10944 10945 // Perform overload resolution. 10946 OverloadCandidateSet::iterator Best; 10947 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10948 Best)) { 10949 case OR_Success: 10950 // Overload resolution succeeded; we'll build the appropriate call 10951 // below. 10952 break; 10953 10954 case OR_No_Viable_Function: 10955 if (CandidateSet.empty()) 10956 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10957 << Object.get()->getType() << /*call*/ 1 10958 << Object.get()->getSourceRange(); 10959 else 10960 Diag(Object.get()->getLocStart(), 10961 diag::err_ovl_no_viable_object_call) 10962 << Object.get()->getType() << Object.get()->getSourceRange(); 10963 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10964 llvm::makeArrayRef(Args, NumArgs)); 10965 break; 10966 10967 case OR_Ambiguous: 10968 Diag(Object.get()->getLocStart(), 10969 diag::err_ovl_ambiguous_object_call) 10970 << Object.get()->getType() << Object.get()->getSourceRange(); 10971 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10972 llvm::makeArrayRef(Args, NumArgs)); 10973 break; 10974 10975 case OR_Deleted: 10976 Diag(Object.get()->getLocStart(), 10977 diag::err_ovl_deleted_object_call) 10978 << Best->Function->isDeleted() 10979 << Object.get()->getType() 10980 << getDeletedOrUnavailableSuffix(Best->Function) 10981 << Object.get()->getSourceRange(); 10982 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10983 llvm::makeArrayRef(Args, NumArgs)); 10984 break; 10985 } 10986 10987 if (Best == CandidateSet.end()) 10988 return true; 10989 10990 UnbridgedCasts.restore(); 10991 10992 if (Best->Function == 0) { 10993 // Since there is no function declaration, this is one of the 10994 // surrogate candidates. Dig out the conversion function. 10995 CXXConversionDecl *Conv 10996 = cast<CXXConversionDecl>( 10997 Best->Conversions[0].UserDefined.ConversionFunction); 10998 10999 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11000 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 11001 11002 // We selected one of the surrogate functions that converts the 11003 // object parameter to a function pointer. Perform the conversion 11004 // on the object argument, then let ActOnCallExpr finish the job. 11005 11006 // Create an implicit member expr to refer to the conversion operator. 11007 // and then call it. 11008 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11009 Conv, HadMultipleCandidates); 11010 if (Call.isInvalid()) 11011 return ExprError(); 11012 // Record usage of conversion in an implicit cast. 11013 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11014 CK_UserDefinedConversion, 11015 Call.get(), 0, VK_RValue)); 11016 11017 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 11018 RParenLoc); 11019 } 11020 11021 MarkFunctionReferenced(LParenLoc, Best->Function); 11022 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11023 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 11024 11025 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11026 // that calls this method, using Object for the implicit object 11027 // parameter and passing along the remaining arguments. 11028 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11029 11030 // An error diagnostic has already been printed when parsing the declaration. 11031 if (Method->isInvalidDecl()) 11032 return ExprError(); 11033 11034 const FunctionProtoType *Proto = 11035 Method->getType()->getAs<FunctionProtoType>(); 11036 11037 unsigned NumArgsInProto = Proto->getNumArgs(); 11038 unsigned NumArgsToCheck = NumArgs; 11039 11040 // Build the full argument list for the method call (the 11041 // implicit object parameter is placed at the beginning of the 11042 // list). 11043 Expr **MethodArgs; 11044 if (NumArgs < NumArgsInProto) { 11045 NumArgsToCheck = NumArgsInProto; 11046 MethodArgs = new Expr*[NumArgsInProto + 1]; 11047 } else { 11048 MethodArgs = new Expr*[NumArgs + 1]; 11049 } 11050 MethodArgs[0] = Object.get(); 11051 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11052 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11053 11054 DeclarationNameInfo OpLocInfo( 11055 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11056 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11057 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 11058 HadMultipleCandidates, 11059 OpLocInfo.getLoc(), 11060 OpLocInfo.getInfo()); 11061 if (NewFn.isInvalid()) 11062 return true; 11063 11064 // Once we've built TheCall, all of the expressions are properly 11065 // owned. 11066 QualType ResultTy = Method->getResultType(); 11067 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11068 ResultTy = ResultTy.getNonLValueExprType(Context); 11069 11070 CXXOperatorCallExpr *TheCall = 11071 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11072 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11073 ResultTy, VK, RParenLoc, false); 11074 delete [] MethodArgs; 11075 11076 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11077 Method)) 11078 return true; 11079 11080 // We may have default arguments. If so, we need to allocate more 11081 // slots in the call for them. 11082 if (NumArgs < NumArgsInProto) 11083 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11084 else if (NumArgs > NumArgsInProto) 11085 NumArgsToCheck = NumArgsInProto; 11086 11087 bool IsError = false; 11088 11089 // Initialize the implicit object parameter. 11090 ExprResult ObjRes = 11091 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11092 Best->FoundDecl, Method); 11093 if (ObjRes.isInvalid()) 11094 IsError = true; 11095 else 11096 Object = ObjRes; 11097 TheCall->setArg(0, Object.take()); 11098 11099 // Check the argument types. 11100 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11101 Expr *Arg; 11102 if (i < NumArgs) { 11103 Arg = Args[i]; 11104 11105 // Pass the argument. 11106 11107 ExprResult InputInit 11108 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11109 Context, 11110 Method->getParamDecl(i)), 11111 SourceLocation(), Arg); 11112 11113 IsError |= InputInit.isInvalid(); 11114 Arg = InputInit.takeAs<Expr>(); 11115 } else { 11116 ExprResult DefArg 11117 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11118 if (DefArg.isInvalid()) { 11119 IsError = true; 11120 break; 11121 } 11122 11123 Arg = DefArg.takeAs<Expr>(); 11124 } 11125 11126 TheCall->setArg(i + 1, Arg); 11127 } 11128 11129 // If this is a variadic call, handle args passed through "...". 11130 if (Proto->isVariadic()) { 11131 // Promote the arguments (C99 6.5.2.2p7). 11132 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11133 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11134 IsError |= Arg.isInvalid(); 11135 TheCall->setArg(i + 1, Arg.take()); 11136 } 11137 } 11138 11139 if (IsError) return true; 11140 11141 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11142 11143 if (CheckFunctionCall(Method, TheCall, Proto)) 11144 return true; 11145 11146 return MaybeBindToTemporary(TheCall); 11147 } 11148 11149 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11150 /// (if one exists), where @c Base is an expression of class type and 11151 /// @c Member is the name of the member we're trying to find. 11152 ExprResult 11153 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11154 assert(Base->getType()->isRecordType() && 11155 "left-hand side must have class type"); 11156 11157 if (checkPlaceholderForOverload(*this, Base)) 11158 return ExprError(); 11159 11160 SourceLocation Loc = Base->getExprLoc(); 11161 11162 // C++ [over.ref]p1: 11163 // 11164 // [...] An expression x->m is interpreted as (x.operator->())->m 11165 // for a class object x of type T if T::operator->() exists and if 11166 // the operator is selected as the best match function by the 11167 // overload resolution mechanism (13.3). 11168 DeclarationName OpName = 11169 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11170 OverloadCandidateSet CandidateSet(Loc); 11171 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11172 11173 if (RequireCompleteType(Loc, Base->getType(), 11174 diag::err_typecheck_incomplete_tag, Base)) 11175 return ExprError(); 11176 11177 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11178 LookupQualifiedName(R, BaseRecord->getDecl()); 11179 R.suppressDiagnostics(); 11180 11181 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11182 Oper != OperEnd; ++Oper) { 11183 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11184 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11185 } 11186 11187 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11188 11189 // Perform overload resolution. 11190 OverloadCandidateSet::iterator Best; 11191 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11192 case OR_Success: 11193 // Overload resolution succeeded; we'll build the call below. 11194 break; 11195 11196 case OR_No_Viable_Function: 11197 if (CandidateSet.empty()) 11198 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11199 << Base->getType() << Base->getSourceRange(); 11200 else 11201 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11202 << "operator->" << Base->getSourceRange(); 11203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11204 return ExprError(); 11205 11206 case OR_Ambiguous: 11207 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11208 << "->" << Base->getType() << Base->getSourceRange(); 11209 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11210 return ExprError(); 11211 11212 case OR_Deleted: 11213 Diag(OpLoc, diag::err_ovl_deleted_oper) 11214 << Best->Function->isDeleted() 11215 << "->" 11216 << getDeletedOrUnavailableSuffix(Best->Function) 11217 << Base->getSourceRange(); 11218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11219 return ExprError(); 11220 } 11221 11222 MarkFunctionReferenced(OpLoc, Best->Function); 11223 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11224 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11225 11226 // Convert the object parameter. 11227 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11228 ExprResult BaseResult = 11229 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11230 Best->FoundDecl, Method); 11231 if (BaseResult.isInvalid()) 11232 return ExprError(); 11233 Base = BaseResult.take(); 11234 11235 // Build the operator call. 11236 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11237 HadMultipleCandidates, OpLoc); 11238 if (FnExpr.isInvalid()) 11239 return ExprError(); 11240 11241 QualType ResultTy = Method->getResultType(); 11242 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11243 ResultTy = ResultTy.getNonLValueExprType(Context); 11244 CXXOperatorCallExpr *TheCall = 11245 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11246 Base, ResultTy, VK, OpLoc, false); 11247 11248 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11249 Method)) 11250 return ExprError(); 11251 11252 return MaybeBindToTemporary(TheCall); 11253 } 11254 11255 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11256 /// a literal operator described by the provided lookup results. 11257 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11258 DeclarationNameInfo &SuffixInfo, 11259 ArrayRef<Expr*> Args, 11260 SourceLocation LitEndLoc, 11261 TemplateArgumentListInfo *TemplateArgs) { 11262 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11263 11264 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11265 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11266 TemplateArgs); 11267 11268 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11269 11270 // Perform overload resolution. This will usually be trivial, but might need 11271 // to perform substitutions for a literal operator template. 11272 OverloadCandidateSet::iterator Best; 11273 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11274 case OR_Success: 11275 case OR_Deleted: 11276 break; 11277 11278 case OR_No_Viable_Function: 11279 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11280 << R.getLookupName(); 11281 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11282 return ExprError(); 11283 11284 case OR_Ambiguous: 11285 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11286 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11287 return ExprError(); 11288 } 11289 11290 FunctionDecl *FD = Best->Function; 11291 MarkFunctionReferenced(UDSuffixLoc, FD); 11292 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11293 11294 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11295 SuffixInfo.getLoc(), 11296 SuffixInfo.getInfo()); 11297 if (Fn.isInvalid()) 11298 return true; 11299 11300 // Check the argument types. This should almost always be a no-op, except 11301 // that array-to-pointer decay is applied to string literals. 11302 Expr *ConvArgs[2]; 11303 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11304 ExprResult InputInit = PerformCopyInitialization( 11305 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11306 SourceLocation(), Args[ArgIdx]); 11307 if (InputInit.isInvalid()) 11308 return true; 11309 ConvArgs[ArgIdx] = InputInit.take(); 11310 } 11311 11312 QualType ResultTy = FD->getResultType(); 11313 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11314 ResultTy = ResultTy.getNonLValueExprType(Context); 11315 11316 UserDefinedLiteral *UDL = 11317 new (Context) UserDefinedLiteral(Context, Fn.take(), 11318 llvm::makeArrayRef(ConvArgs, Args.size()), 11319 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11320 11321 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11322 return ExprError(); 11323 11324 if (CheckFunctionCall(FD, UDL, NULL)) 11325 return ExprError(); 11326 11327 return MaybeBindToTemporary(UDL); 11328 } 11329 11330 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11331 /// given LookupResult is non-empty, it is assumed to describe a member which 11332 /// will be invoked. Otherwise, the function will be found via argument 11333 /// dependent lookup. 11334 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11335 /// otherwise CallExpr is set to ExprError() and some non-success value 11336 /// is returned. 11337 Sema::ForRangeStatus 11338 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11339 SourceLocation RangeLoc, VarDecl *Decl, 11340 BeginEndFunction BEF, 11341 const DeclarationNameInfo &NameInfo, 11342 LookupResult &MemberLookup, 11343 OverloadCandidateSet *CandidateSet, 11344 Expr *Range, ExprResult *CallExpr) { 11345 CandidateSet->clear(); 11346 if (!MemberLookup.empty()) { 11347 ExprResult MemberRef = 11348 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11349 /*IsPtr=*/false, CXXScopeSpec(), 11350 /*TemplateKWLoc=*/SourceLocation(), 11351 /*FirstQualifierInScope=*/0, 11352 MemberLookup, 11353 /*TemplateArgs=*/0); 11354 if (MemberRef.isInvalid()) { 11355 *CallExpr = ExprError(); 11356 Diag(Range->getLocStart(), diag::note_in_for_range) 11357 << RangeLoc << BEF << Range->getType(); 11358 return FRS_DiagnosticIssued; 11359 } 11360 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11361 if (CallExpr->isInvalid()) { 11362 *CallExpr = ExprError(); 11363 Diag(Range->getLocStart(), diag::note_in_for_range) 11364 << RangeLoc << BEF << Range->getType(); 11365 return FRS_DiagnosticIssued; 11366 } 11367 } else { 11368 UnresolvedSet<0> FoundNames; 11369 UnresolvedLookupExpr *Fn = 11370 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11371 NestedNameSpecifierLoc(), NameInfo, 11372 /*NeedsADL=*/true, /*Overloaded=*/false, 11373 FoundNames.begin(), FoundNames.end()); 11374 11375 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11376 CandidateSet, CallExpr); 11377 if (CandidateSet->empty() || CandidateSetError) { 11378 *CallExpr = ExprError(); 11379 return FRS_NoViableFunction; 11380 } 11381 OverloadCandidateSet::iterator Best; 11382 OverloadingResult OverloadResult = 11383 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11384 11385 if (OverloadResult == OR_No_Viable_Function) { 11386 *CallExpr = ExprError(); 11387 return FRS_NoViableFunction; 11388 } 11389 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11390 Loc, 0, CandidateSet, &Best, 11391 OverloadResult, 11392 /*AllowTypoCorrection=*/false); 11393 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11394 *CallExpr = ExprError(); 11395 Diag(Range->getLocStart(), diag::note_in_for_range) 11396 << RangeLoc << BEF << Range->getType(); 11397 return FRS_DiagnosticIssued; 11398 } 11399 } 11400 return FRS_Success; 11401 } 11402 11403 11404 /// FixOverloadedFunctionReference - E is an expression that refers to 11405 /// a C++ overloaded function (possibly with some parentheses and 11406 /// perhaps a '&' around it). We have resolved the overloaded function 11407 /// to the function declaration Fn, so patch up the expression E to 11408 /// refer (possibly indirectly) to Fn. Returns the new expr. 11409 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11410 FunctionDecl *Fn) { 11411 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11412 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11413 Found, Fn); 11414 if (SubExpr == PE->getSubExpr()) 11415 return PE; 11416 11417 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11418 } 11419 11420 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11421 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11422 Found, Fn); 11423 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11424 SubExpr->getType()) && 11425 "Implicit cast type cannot be determined from overload"); 11426 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11427 if (SubExpr == ICE->getSubExpr()) 11428 return ICE; 11429 11430 return ImplicitCastExpr::Create(Context, ICE->getType(), 11431 ICE->getCastKind(), 11432 SubExpr, 0, 11433 ICE->getValueKind()); 11434 } 11435 11436 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11437 assert(UnOp->getOpcode() == UO_AddrOf && 11438 "Can only take the address of an overloaded function"); 11439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11440 if (Method->isStatic()) { 11441 // Do nothing: static member functions aren't any different 11442 // from non-member functions. 11443 } else { 11444 // Fix the sub expression, which really has to be an 11445 // UnresolvedLookupExpr holding an overloaded member function 11446 // or template. 11447 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11448 Found, Fn); 11449 if (SubExpr == UnOp->getSubExpr()) 11450 return UnOp; 11451 11452 assert(isa<DeclRefExpr>(SubExpr) 11453 && "fixed to something other than a decl ref"); 11454 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11455 && "fixed to a member ref with no nested name qualifier"); 11456 11457 // We have taken the address of a pointer to member 11458 // function. Perform the computation here so that we get the 11459 // appropriate pointer to member type. 11460 QualType ClassType 11461 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11462 QualType MemPtrType 11463 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11464 11465 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11466 VK_RValue, OK_Ordinary, 11467 UnOp->getOperatorLoc()); 11468 } 11469 } 11470 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11471 Found, Fn); 11472 if (SubExpr == UnOp->getSubExpr()) 11473 return UnOp; 11474 11475 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11476 Context.getPointerType(SubExpr->getType()), 11477 VK_RValue, OK_Ordinary, 11478 UnOp->getOperatorLoc()); 11479 } 11480 11481 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11482 // FIXME: avoid copy. 11483 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11484 if (ULE->hasExplicitTemplateArgs()) { 11485 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11486 TemplateArgs = &TemplateArgsBuffer; 11487 } 11488 11489 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11490 ULE->getQualifierLoc(), 11491 ULE->getTemplateKeywordLoc(), 11492 Fn, 11493 /*enclosing*/ false, // FIXME? 11494 ULE->getNameLoc(), 11495 Fn->getType(), 11496 VK_LValue, 11497 Found.getDecl(), 11498 TemplateArgs); 11499 MarkDeclRefReferenced(DRE); 11500 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11501 return DRE; 11502 } 11503 11504 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11505 // FIXME: avoid copy. 11506 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11507 if (MemExpr->hasExplicitTemplateArgs()) { 11508 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11509 TemplateArgs = &TemplateArgsBuffer; 11510 } 11511 11512 Expr *Base; 11513 11514 // If we're filling in a static method where we used to have an 11515 // implicit member access, rewrite to a simple decl ref. 11516 if (MemExpr->isImplicitAccess()) { 11517 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11518 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11519 MemExpr->getQualifierLoc(), 11520 MemExpr->getTemplateKeywordLoc(), 11521 Fn, 11522 /*enclosing*/ false, 11523 MemExpr->getMemberLoc(), 11524 Fn->getType(), 11525 VK_LValue, 11526 Found.getDecl(), 11527 TemplateArgs); 11528 MarkDeclRefReferenced(DRE); 11529 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11530 return DRE; 11531 } else { 11532 SourceLocation Loc = MemExpr->getMemberLoc(); 11533 if (MemExpr->getQualifier()) 11534 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11535 CheckCXXThisCapture(Loc); 11536 Base = new (Context) CXXThisExpr(Loc, 11537 MemExpr->getBaseType(), 11538 /*isImplicit=*/true); 11539 } 11540 } else 11541 Base = MemExpr->getBase(); 11542 11543 ExprValueKind valueKind; 11544 QualType type; 11545 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11546 valueKind = VK_LValue; 11547 type = Fn->getType(); 11548 } else { 11549 valueKind = VK_RValue; 11550 type = Context.BoundMemberTy; 11551 } 11552 11553 MemberExpr *ME = MemberExpr::Create(Context, Base, 11554 MemExpr->isArrow(), 11555 MemExpr->getQualifierLoc(), 11556 MemExpr->getTemplateKeywordLoc(), 11557 Fn, 11558 Found, 11559 MemExpr->getMemberNameInfo(), 11560 TemplateArgs, 11561 type, valueKind, OK_Ordinary); 11562 ME->setHadMultipleCandidates(true); 11563 MarkMemberReferenced(ME); 11564 return ME; 11565 } 11566 11567 llvm_unreachable("Invalid reference to overloaded function"); 11568 } 11569 11570 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11571 DeclAccessPair Found, 11572 FunctionDecl *Fn) { 11573 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11574 } 11575 11576 } // end namespace clang 11577