1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
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"
39 /// A convenience routine for creating a decayed reference to a function.
41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 bool HadMultipleCandidates,
43 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
48 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
49 VK_LValue, Loc, LocInfo);
50 if (HadMultipleCandidates)
51 DRE->setHadMultipleCandidates(true);
53 S.MarkDeclRefReferenced(DRE);
55 ExprResult E = S.Owned(DRE);
56 E = S.DefaultFunctionArrayConversion(E.take());
62 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
63 bool InOverloadResolution,
64 StandardConversionSequence &SCS,
66 bool AllowObjCWritebackConversion);
68 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
70 bool InOverloadResolution,
71 StandardConversionSequence &SCS,
73 static OverloadingResult
74 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
75 UserDefinedConversionSequence& User,
76 OverloadCandidateSet& Conversions,
80 static ImplicitConversionSequence::CompareKind
81 CompareStandardConversionSequences(Sema &S,
82 const StandardConversionSequence& SCS1,
83 const StandardConversionSequence& SCS2);
85 static ImplicitConversionSequence::CompareKind
86 CompareQualificationConversions(Sema &S,
87 const StandardConversionSequence& SCS1,
88 const StandardConversionSequence& SCS2);
90 static ImplicitConversionSequence::CompareKind
91 CompareDerivedToBaseConversions(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
97 /// GetConversionCategory - Retrieve the implicit conversion
98 /// category corresponding to the given implicit conversion kind.
99 ImplicitConversionCategory
100 GetConversionCategory(ImplicitConversionKind Kind) {
101 static const ImplicitConversionCategory
102 Category[(int)ICK_Num_Conversion_Kinds] = {
104 ICC_Lvalue_Transformation,
105 ICC_Lvalue_Transformation,
106 ICC_Lvalue_Transformation,
108 ICC_Qualification_Adjustment,
126 return Category[(int)Kind];
129 /// GetConversionRank - Retrieve the implicit conversion rank
130 /// corresponding to the given implicit conversion kind.
131 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
132 static const ImplicitConversionRank
133 Rank[(int)ICK_Num_Conversion_Kinds] = {
154 ICR_Complex_Real_Conversion,
157 ICR_Writeback_Conversion
159 return Rank[(int)Kind];
162 /// GetImplicitConversionName - Return the name of this kind of
163 /// implicit conversion.
164 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
165 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
169 "Function-to-pointer",
170 "Noreturn adjustment",
172 "Integral promotion",
173 "Floating point promotion",
175 "Integral conversion",
176 "Floating conversion",
177 "Complex conversion",
178 "Floating-integral conversion",
179 "Pointer conversion",
180 "Pointer-to-member conversion",
181 "Boolean conversion",
182 "Compatible-types conversion",
183 "Derived-to-base conversion",
186 "Complex-real conversion",
187 "Block Pointer conversion",
188 "Transparent Union Conversion"
189 "Writeback conversion"
194 /// StandardConversionSequence - Set the standard conversion
195 /// sequence to the identity conversion.
196 void StandardConversionSequence::setAsIdentityConversion() {
197 First = ICK_Identity;
198 Second = ICK_Identity;
199 Third = ICK_Identity;
200 DeprecatedStringLiteralToCharPtr = false;
201 QualificationIncludesObjCLifetime = false;
202 ReferenceBinding = false;
203 DirectBinding = false;
204 IsLvalueReference = true;
205 BindsToFunctionLvalue = false;
206 BindsToRvalue = false;
207 BindsImplicitObjectArgumentWithoutRefQualifier = false;
208 ObjCLifetimeConversionBinding = false;
212 /// getRank - Retrieve the rank of this standard conversion sequence
213 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
214 /// implicit conversions.
215 ImplicitConversionRank StandardConversionSequence::getRank() const {
216 ImplicitConversionRank Rank = ICR_Exact_Match;
217 if (GetConversionRank(First) > Rank)
218 Rank = GetConversionRank(First);
219 if (GetConversionRank(Second) > Rank)
220 Rank = GetConversionRank(Second);
221 if (GetConversionRank(Third) > Rank)
222 Rank = GetConversionRank(Third);
226 /// isPointerConversionToBool - Determines whether this conversion is
227 /// a conversion of a pointer or pointer-to-member to bool. This is
228 /// used as part of the ranking of standard conversion sequences
229 /// (C++ 13.3.3.2p4).
230 bool StandardConversionSequence::isPointerConversionToBool() const {
231 // Note that FromType has not necessarily been transformed by the
232 // array-to-pointer or function-to-pointer implicit conversions, so
233 // check for their presence as well as checking whether FromType is
235 if (getToType(1)->isBooleanType() &&
236 (getFromType()->isPointerType() ||
237 getFromType()->isObjCObjectPointerType() ||
238 getFromType()->isBlockPointerType() ||
239 getFromType()->isNullPtrType() ||
240 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
246 /// isPointerConversionToVoidPointer - Determines whether this
247 /// conversion is a conversion of a pointer to a void pointer. This is
248 /// used as part of the ranking of standard conversion sequences (C++
251 StandardConversionSequence::
252 isPointerConversionToVoidPointer(ASTContext& Context) const {
253 QualType FromType = getFromType();
254 QualType ToType = getToType(1);
256 // Note that FromType has not necessarily been transformed by the
257 // array-to-pointer implicit conversion, so check for its presence
258 // and redo the conversion to get a pointer.
259 if (First == ICK_Array_To_Pointer)
260 FromType = Context.getArrayDecayedType(FromType);
262 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
263 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
264 return ToPtrType->getPointeeType()->isVoidType();
269 /// Skip any implicit casts which could be either part of a narrowing conversion
270 /// or after one in an implicit conversion.
271 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
272 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
273 switch (ICE->getCastKind()) {
275 case CK_IntegralCast:
276 case CK_IntegralToBoolean:
277 case CK_IntegralToFloating:
278 case CK_FloatingToIntegral:
279 case CK_FloatingToBoolean:
280 case CK_FloatingCast:
281 Converted = ICE->getSubExpr();
292 /// Check if this standard conversion sequence represents a narrowing
293 /// conversion, according to C++11 [dcl.init.list]p7.
295 /// \param Ctx The AST context.
296 /// \param Converted The result of applying this standard conversion sequence.
297 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
298 /// value of the expression prior to the narrowing conversion.
299 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
300 /// type of the expression prior to the narrowing conversion.
302 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
303 const Expr *Converted,
304 APValue &ConstantValue,
305 QualType &ConstantType) const {
306 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
308 // C++11 [dcl.init.list]p7:
309 // A narrowing conversion is an implicit conversion ...
310 QualType FromType = getToType(0);
311 QualType ToType = getToType(1);
313 // -- from a floating-point type to an integer type, or
315 // -- from an integer type or unscoped enumeration type to a floating-point
316 // type, except where the source is a constant expression and the actual
317 // value after conversion will fit into the target type and will produce
318 // the original value when converted back to the original type, or
319 case ICK_Floating_Integral:
320 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
321 return NK_Type_Narrowing;
322 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
323 llvm::APSInt IntConstantValue;
324 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
326 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
327 // Convert the integer to the floating type.
328 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
329 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
330 llvm::APFloat::rmNearestTiesToEven);
332 llvm::APSInt ConvertedValue = IntConstantValue;
334 Result.convertToInteger(ConvertedValue,
335 llvm::APFloat::rmTowardZero, &ignored);
336 // If the resulting value is different, this was a narrowing conversion.
337 if (IntConstantValue != ConvertedValue) {
338 ConstantValue = APValue(IntConstantValue);
339 ConstantType = Initializer->getType();
340 return NK_Constant_Narrowing;
343 // Variables are always narrowings.
344 return NK_Variable_Narrowing;
347 return NK_Not_Narrowing;
349 // -- from long double to double or float, or from double to float, except
350 // where the source is a constant expression and the actual value after
351 // conversion is within the range of values that can be represented (even
352 // if it cannot be represented exactly), or
353 case ICK_Floating_Conversion:
354 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
355 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
356 // FromType is larger than ToType.
357 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
358 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
360 assert(ConstantValue.isFloat());
361 llvm::APFloat FloatVal = ConstantValue.getFloat();
362 // Convert the source value into the target type.
364 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
365 Ctx.getFloatTypeSemantics(ToType),
366 llvm::APFloat::rmNearestTiesToEven, &ignored);
367 // If there was no overflow, the source value is within the range of
368 // values that can be represented.
369 if (ConvertStatus & llvm::APFloat::opOverflow) {
370 ConstantType = Initializer->getType();
371 return NK_Constant_Narrowing;
374 return NK_Variable_Narrowing;
377 return NK_Not_Narrowing;
379 // -- from an integer type or unscoped enumeration type to an integer type
380 // that cannot represent all the values of the original type, except where
381 // the source is a constant expression and the actual value after
382 // conversion will fit into the target type and will produce the original
383 // value when converted back to the original type.
384 case ICK_Boolean_Conversion: // Bools are integers too.
385 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
386 // Boolean conversions can be from pointers and pointers to members
387 // [conv.bool], and those aren't considered narrowing conversions.
388 return NK_Not_Narrowing;
389 } // Otherwise, fall through to the integral case.
390 case ICK_Integral_Conversion: {
391 assert(FromType->isIntegralOrUnscopedEnumerationType());
392 assert(ToType->isIntegralOrUnscopedEnumerationType());
393 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
394 const unsigned FromWidth = Ctx.getIntWidth(FromType);
395 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
396 const unsigned ToWidth = Ctx.getIntWidth(ToType);
398 if (FromWidth > ToWidth ||
399 (FromWidth == ToWidth && FromSigned != ToSigned) ||
400 (FromSigned && !ToSigned)) {
401 // Not all values of FromType can be represented in ToType.
402 llvm::APSInt InitializerValue;
403 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
404 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
405 // Such conversions on variables are always narrowing.
406 return NK_Variable_Narrowing;
408 bool Narrowing = false;
409 if (FromWidth < ToWidth) {
410 // Negative -> unsigned is narrowing. Otherwise, more bits is never
412 if (InitializerValue.isSigned() && InitializerValue.isNegative())
415 // Add a bit to the InitializerValue so we don't have to worry about
416 // signed vs. unsigned comparisons.
417 InitializerValue = InitializerValue.extend(
418 InitializerValue.getBitWidth() + 1);
419 // Convert the initializer to and from the target width and signed-ness.
420 llvm::APSInt ConvertedValue = InitializerValue;
421 ConvertedValue = ConvertedValue.trunc(ToWidth);
422 ConvertedValue.setIsSigned(ToSigned);
423 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
424 ConvertedValue.setIsSigned(InitializerValue.isSigned());
425 // If the result is different, this was a narrowing conversion.
426 if (ConvertedValue != InitializerValue)
430 ConstantType = Initializer->getType();
431 ConstantValue = APValue(InitializerValue);
432 return NK_Constant_Narrowing;
435 return NK_Not_Narrowing;
439 // Other kinds of conversions are not narrowings.
440 return NK_Not_Narrowing;
444 /// DebugPrint - Print this standard conversion sequence to standard
445 /// error. Useful for debugging overloading issues.
446 void StandardConversionSequence::DebugPrint() const {
447 raw_ostream &OS = llvm::errs();
448 bool PrintedSomething = false;
449 if (First != ICK_Identity) {
450 OS << GetImplicitConversionName(First);
451 PrintedSomething = true;
454 if (Second != ICK_Identity) {
455 if (PrintedSomething) {
458 OS << GetImplicitConversionName(Second);
460 if (CopyConstructor) {
461 OS << " (by copy constructor)";
462 } else if (DirectBinding) {
463 OS << " (direct reference binding)";
464 } else if (ReferenceBinding) {
465 OS << " (reference binding)";
467 PrintedSomething = true;
470 if (Third != ICK_Identity) {
471 if (PrintedSomething) {
474 OS << GetImplicitConversionName(Third);
475 PrintedSomething = true;
478 if (!PrintedSomething) {
479 OS << "No conversions required";
483 /// DebugPrint - Print this user-defined conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 void UserDefinedConversionSequence::DebugPrint() const {
486 raw_ostream &OS = llvm::errs();
487 if (Before.First || Before.Second || Before.Third) {
491 if (ConversionFunction)
492 OS << '\'' << *ConversionFunction << '\'';
494 OS << "aggregate initialization";
495 if (After.First || After.Second || After.Third) {
501 /// DebugPrint - Print this implicit conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void ImplicitConversionSequence::DebugPrint() const {
504 raw_ostream &OS = llvm::errs();
505 switch (ConversionKind) {
506 case StandardConversion:
507 OS << "Standard conversion: ";
508 Standard.DebugPrint();
510 case UserDefinedConversion:
511 OS << "User-defined conversion: ";
512 UserDefined.DebugPrint();
514 case EllipsisConversion:
515 OS << "Ellipsis conversion";
517 case AmbiguousConversion:
518 OS << "Ambiguous conversion";
521 OS << "Bad conversion";
528 void AmbiguousConversionSequence::construct() {
529 new (&conversions()) ConversionSet();
532 void AmbiguousConversionSequence::destruct() {
533 conversions().~ConversionSet();
537 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
538 FromTypePtr = O.FromTypePtr;
539 ToTypePtr = O.ToTypePtr;
540 new (&conversions()) ConversionSet(O.conversions());
544 // Structure used by OverloadCandidate::DeductionFailureInfo to store
545 // template argument information.
546 struct DFIArguments {
547 TemplateArgument FirstArg;
548 TemplateArgument SecondArg;
550 // Structure used by OverloadCandidate::DeductionFailureInfo to store
551 // template parameter and template argument information.
552 struct DFIParamWithArguments : DFIArguments {
553 TemplateParameter Param;
557 /// \brief Convert from Sema's representation of template deduction information
558 /// to the form used in overload-candidate information.
559 OverloadCandidate::DeductionFailureInfo
560 static MakeDeductionFailureInfo(ASTContext &Context,
561 Sema::TemplateDeductionResult TDK,
562 TemplateDeductionInfo &Info) {
563 OverloadCandidate::DeductionFailureInfo Result;
564 Result.Result = static_cast<unsigned>(TDK);
565 Result.HasDiagnostic = false;
568 case Sema::TDK_Success:
569 case Sema::TDK_Invalid:
570 case Sema::TDK_InstantiationDepth:
571 case Sema::TDK_TooManyArguments:
572 case Sema::TDK_TooFewArguments:
575 case Sema::TDK_Incomplete:
576 case Sema::TDK_InvalidExplicitArguments:
577 Result.Data = Info.Param.getOpaqueValue();
580 case Sema::TDK_NonDeducedMismatch: {
581 // FIXME: Should allocate from normal heap so that we can free this later.
582 DFIArguments *Saved = new (Context) DFIArguments;
583 Saved->FirstArg = Info.FirstArg;
584 Saved->SecondArg = Info.SecondArg;
589 case Sema::TDK_Inconsistent:
590 case Sema::TDK_Underqualified: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
593 Saved->Param = Info.Param;
594 Saved->FirstArg = Info.FirstArg;
595 Saved->SecondArg = Info.SecondArg;
600 case Sema::TDK_SubstitutionFailure:
601 Result.Data = Info.take();
602 if (Info.hasSFINAEDiagnostic()) {
603 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
604 SourceLocation(), PartialDiagnostic::NullDiagnostic());
605 Info.takeSFINAEDiagnostic(*Diag);
606 Result.HasDiagnostic = true;
610 case Sema::TDK_FailedOverloadResolution:
611 Result.Data = Info.Expression;
614 case Sema::TDK_MiscellaneousDeductionFailure:
621 void OverloadCandidate::DeductionFailureInfo::Destroy() {
622 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
623 case Sema::TDK_Success:
624 case Sema::TDK_Invalid:
625 case Sema::TDK_InstantiationDepth:
626 case Sema::TDK_Incomplete:
627 case Sema::TDK_TooManyArguments:
628 case Sema::TDK_TooFewArguments:
629 case Sema::TDK_InvalidExplicitArguments:
630 case Sema::TDK_FailedOverloadResolution:
633 case Sema::TDK_Inconsistent:
634 case Sema::TDK_Underqualified:
635 case Sema::TDK_NonDeducedMismatch:
636 // FIXME: Destroy the data?
640 case Sema::TDK_SubstitutionFailure:
641 // FIXME: Destroy the template argument list?
643 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
644 Diag->~PartialDiagnosticAt();
645 HasDiagnostic = false;
650 case Sema::TDK_MiscellaneousDeductionFailure:
655 PartialDiagnosticAt *
656 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
658 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
663 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
666 case Sema::TDK_Invalid:
667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_TooManyArguments:
669 case Sema::TDK_TooFewArguments:
670 case Sema::TDK_SubstitutionFailure:
671 case Sema::TDK_NonDeducedMismatch:
672 case Sema::TDK_FailedOverloadResolution:
673 return TemplateParameter();
675 case Sema::TDK_Incomplete:
676 case Sema::TDK_InvalidExplicitArguments:
677 return TemplateParameter::getFromOpaqueValue(Data);
679 case Sema::TDK_Inconsistent:
680 case Sema::TDK_Underqualified:
681 return static_cast<DFIParamWithArguments*>(Data)->Param;
684 case Sema::TDK_MiscellaneousDeductionFailure:
688 return TemplateParameter();
691 TemplateArgumentList *
692 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694 case Sema::TDK_Success:
695 case Sema::TDK_Invalid:
696 case Sema::TDK_InstantiationDepth:
697 case Sema::TDK_TooManyArguments:
698 case Sema::TDK_TooFewArguments:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_InvalidExplicitArguments:
701 case Sema::TDK_Inconsistent:
702 case Sema::TDK_Underqualified:
703 case Sema::TDK_NonDeducedMismatch:
704 case Sema::TDK_FailedOverloadResolution:
707 case Sema::TDK_SubstitutionFailure:
708 return static_cast<TemplateArgumentList*>(Data);
711 case Sema::TDK_MiscellaneousDeductionFailure:
718 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720 case Sema::TDK_Success:
721 case Sema::TDK_Invalid:
722 case Sema::TDK_InstantiationDepth:
723 case Sema::TDK_Incomplete:
724 case Sema::TDK_TooManyArguments:
725 case Sema::TDK_TooFewArguments:
726 case Sema::TDK_InvalidExplicitArguments:
727 case Sema::TDK_SubstitutionFailure:
728 case Sema::TDK_FailedOverloadResolution:
731 case Sema::TDK_Inconsistent:
732 case Sema::TDK_Underqualified:
733 case Sema::TDK_NonDeducedMismatch:
734 return &static_cast<DFIArguments*>(Data)->FirstArg;
737 case Sema::TDK_MiscellaneousDeductionFailure:
744 const TemplateArgument *
745 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
746 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
747 case Sema::TDK_Success:
748 case Sema::TDK_Invalid:
749 case Sema::TDK_InstantiationDepth:
750 case Sema::TDK_Incomplete:
751 case Sema::TDK_TooManyArguments:
752 case Sema::TDK_TooFewArguments:
753 case Sema::TDK_InvalidExplicitArguments:
754 case Sema::TDK_SubstitutionFailure:
755 case Sema::TDK_FailedOverloadResolution:
758 case Sema::TDK_Inconsistent:
759 case Sema::TDK_Underqualified:
760 case Sema::TDK_NonDeducedMismatch:
761 return &static_cast<DFIArguments*>(Data)->SecondArg;
764 case Sema::TDK_MiscellaneousDeductionFailure:
772 OverloadCandidate::DeductionFailureInfo::getExpr() {
773 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
774 Sema::TDK_FailedOverloadResolution)
775 return static_cast<Expr*>(Data);
780 void OverloadCandidateSet::destroyCandidates() {
781 for (iterator i = begin(), e = end(); i != e; ++i) {
782 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
783 i->Conversions[ii].~ImplicitConversionSequence();
784 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
785 i->DeductionFailure.Destroy();
789 void OverloadCandidateSet::clear() {
791 NumInlineSequences = 0;
797 class UnbridgedCastsSet {
802 SmallVector<Entry, 2> Entries;
805 void save(Sema &S, Expr *&E) {
806 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
807 Entry entry = { &E, E };
808 Entries.push_back(entry);
809 E = S.stripARCUnbridgedCast(E);
813 for (SmallVectorImpl<Entry>::iterator
814 i = Entries.begin(), e = Entries.end(); i != e; ++i)
820 /// checkPlaceholderForOverload - Do any interesting placeholder-like
821 /// preprocessing on the given expression.
823 /// \param unbridgedCasts a collection to which to add unbridged casts;
824 /// without this, they will be immediately diagnosed as errors
826 /// Return true on unrecoverable error.
827 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
828 UnbridgedCastsSet *unbridgedCasts = 0) {
829 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
830 // We can't handle overloaded expressions here because overload
831 // resolution might reasonably tweak them.
832 if (placeholder->getKind() == BuiltinType::Overload) return false;
834 // If the context potentially accepts unbridged ARC casts, strip
835 // the unbridged cast and add it to the collection for later restoration.
836 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
838 unbridgedCasts->save(S, E);
842 // Go ahead and check everything else.
843 ExprResult result = S.CheckPlaceholderExpr(E);
844 if (result.isInvalid())
855 /// checkArgPlaceholdersForOverload - Check a set of call operands for
857 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
859 UnbridgedCastsSet &unbridged) {
860 for (unsigned i = 0; i != numArgs; ++i)
861 if (checkPlaceholderForOverload(S, args[i], &unbridged))
867 // IsOverload - Determine whether the given New declaration is an
868 // overload of the declarations in Old. This routine returns false if
869 // New and Old cannot be overloaded, e.g., if New has the same
870 // signature as some function in Old (C++ 1.3.10) or if the Old
871 // declarations aren't functions (or function templates) at all. When
872 // it does return false, MatchedDecl will point to the decl that New
873 // cannot be overloaded with. This decl may be a UsingShadowDecl on
874 // top of the underlying declaration.
876 // Example: Given the following input:
878 // void f(int, float); // #1
879 // void f(int, int); // #2
880 // int f(int, int); // #3
882 // When we process #1, there is no previous declaration of "f",
883 // so IsOverload will not be used.
885 // When we process #2, Old contains only the FunctionDecl for #1. By
886 // comparing the parameter types, we see that #1 and #2 are overloaded
887 // (since they have different signatures), so this routine returns
888 // false; MatchedDecl is unchanged.
890 // When we process #3, Old is an overload set containing #1 and #2. We
891 // compare the signatures of #3 to #1 (they're overloaded, so we do
892 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
893 // identical (return types of functions are not part of the
894 // signature), IsOverload returns false and MatchedDecl will be set to
895 // point to the FunctionDecl for #2.
897 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
898 // into a class by a using declaration. The rules for whether to hide
899 // shadow declarations ignore some properties which otherwise figure
900 // into a function template's signature.
902 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
903 NamedDecl *&Match, bool NewIsUsingDecl) {
904 for (LookupResult::iterator I = Old.begin(), E = Old.end();
906 NamedDecl *OldD = *I;
908 bool OldIsUsingDecl = false;
909 if (isa<UsingShadowDecl>(OldD)) {
910 OldIsUsingDecl = true;
912 // We can always introduce two using declarations into the same
913 // context, even if they have identical signatures.
914 if (NewIsUsingDecl) continue;
916 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
919 // If either declaration was introduced by a using declaration,
920 // we'll need to use slightly different rules for matching.
921 // Essentially, these rules are the normal rules, except that
922 // function templates hide function templates with different
923 // return types or template parameter lists.
924 bool UseMemberUsingDeclRules =
925 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
926 !New->getFriendObjectKind();
928 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
929 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
930 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
931 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
938 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
939 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
940 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
941 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
945 if (!shouldLinkPossiblyHiddenDecl(*I, New))
951 } else if (isa<UsingDecl>(OldD)) {
952 // We can overload with these, which can show up when doing
953 // redeclaration checks for UsingDecls.
954 assert(Old.getLookupKind() == LookupUsingDeclName);
955 } else if (isa<TagDecl>(OldD)) {
956 // We can always overload with tags by hiding them.
957 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
958 // Optimistically assume that an unresolved using decl will
959 // overload; if it doesn't, we'll have to diagnose during
960 // template instantiation.
963 // Only function declarations can be overloaded; object and type
964 // declarations cannot be overloaded.
966 return Ovl_NonFunction;
973 static bool canBeOverloaded(const FunctionDecl &D) {
974 if (D.getAttr<OverloadableAttr>())
979 // Main cannot be overloaded (basic.start.main).
986 static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
987 bool UseUsingDeclRules) {
988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
992 // A function template can be overloaded with other function templates
993 // and with normal (non-template) functions.
994 if ((OldTemplate == 0) != (NewTemplate == 0))
997 // Is the function New an overload of the function Old?
998 QualType OldQType = S.Context.getCanonicalType(Old->getType());
999 QualType NewQType = S.Context.getCanonicalType(New->getType());
1001 // Compare the signatures (C++ 1.3.10) of the two functions to
1002 // determine whether they are overloads. If we find any mismatch
1003 // in the signature, they are overloads.
1005 // If either of these functions is a K&R-style function (no
1006 // prototype), then we consider them to have matching signatures.
1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1011 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1012 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1014 // The signature of a function includes the types of its
1015 // parameters (C++ 1.3.10), which includes the presence or absence
1016 // of the ellipsis; see C++ DR 357).
1017 if (OldQType != NewQType &&
1018 (OldType->getNumArgs() != NewType->getNumArgs() ||
1019 OldType->isVariadic() != NewType->isVariadic() ||
1020 !S.FunctionArgTypesAreEqual(OldType, NewType)))
1023 // C++ [temp.over.link]p4:
1024 // The signature of a function template consists of its function
1025 // signature, its return type and its template parameter list. The names
1026 // of the template parameters are significant only for establishing the
1027 // relationship between the template parameters and the rest of the
1030 // We check the return type and template parameter lists for function
1031 // templates first; the remaining checks follow.
1033 // However, we don't consider either of these when deciding whether
1034 // a member introduced by a shadow declaration is hidden.
1035 if (!UseUsingDeclRules && NewTemplate &&
1036 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037 OldTemplate->getTemplateParameters(),
1038 false, S.TPL_TemplateMatch) ||
1039 OldType->getResultType() != NewType->getResultType()))
1042 // If the function is a class member, its signature includes the
1043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1045 // As part of this, also check whether one of the member functions
1046 // is static, in which case they are not overloads (C++
1047 // 13.1p2). While not part of the definition of the signature,
1048 // this check is important to determine whether these functions
1049 // can be overloaded.
1050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1052 if (OldMethod && NewMethod &&
1053 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055 if (!UseUsingDeclRules &&
1056 (OldMethod->getRefQualifier() == RQ_None ||
1057 NewMethod->getRefQualifier() == RQ_None)) {
1058 // C++0x [over.load]p2:
1059 // - Member function declarations with the same name and the same
1060 // parameter-type-list as well as member function template
1061 // declarations with the same name, the same parameter-type-list, and
1062 // the same template parameter lists cannot be overloaded if any of
1063 // them, but not all, have a ref-qualifier (8.3.5).
1064 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1066 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1071 // We may not have applied the implicit const for a constexpr member
1072 // function yet (because we haven't yet resolved whether this is a static
1073 // or non-static member function). Add it now, on the assumption that this
1074 // is a redeclaration of OldMethod.
1075 unsigned NewQuals = NewMethod->getTypeQualifiers();
1076 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
1077 NewQuals |= Qualifiers::Const;
1078 if (OldMethod->getTypeQualifiers() != NewQuals)
1082 // The signatures match; this is not an overload.
1086 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1087 bool UseUsingDeclRules) {
1088 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1091 // If both of the functions are extern "C", then they are not
1093 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1099 /// \brief Checks availability of the function depending on the current
1100 /// function context. Inside an unavailable function, unavailability is ignored.
1102 /// \returns true if \arg FD is unavailable and current context is inside
1103 /// an available function, false otherwise.
1104 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1105 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1108 /// \brief Tries a user-defined conversion from From to ToType.
1110 /// Produces an implicit conversion sequence for when a standard conversion
1111 /// is not an option. See TryImplicitConversion for more information.
1112 static ImplicitConversionSequence
1113 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1114 bool SuppressUserConversions,
1116 bool InOverloadResolution,
1118 bool AllowObjCWritebackConversion) {
1119 ImplicitConversionSequence ICS;
1121 if (SuppressUserConversions) {
1122 // We're not in the case above, so there is no conversion that
1124 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1128 // Attempt user-defined conversion.
1129 OverloadCandidateSet Conversions(From->getExprLoc());
1130 OverloadingResult UserDefResult
1131 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1134 if (UserDefResult == OR_Success) {
1135 ICS.setUserDefined();
1136 // C++ [over.ics.user]p4:
1137 // A conversion of an expression of class type to the same class
1138 // type is given Exact Match rank, and a conversion of an
1139 // expression of class type to a base class of that type is
1140 // given Conversion rank, in spite of the fact that a copy
1141 // constructor (i.e., a user-defined conversion function) is
1142 // called for those cases.
1143 if (CXXConstructorDecl *Constructor
1144 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1146 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1148 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1149 if (Constructor->isCopyConstructor() &&
1150 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1151 // Turn this into a "standard" conversion sequence, so that it
1152 // gets ranked with standard conversion sequences.
1154 ICS.Standard.setAsIdentityConversion();
1155 ICS.Standard.setFromType(From->getType());
1156 ICS.Standard.setAllToTypes(ToType);
1157 ICS.Standard.CopyConstructor = Constructor;
1158 if (ToCanon != FromCanon)
1159 ICS.Standard.Second = ICK_Derived_To_Base;
1163 // C++ [over.best.ics]p4:
1164 // However, when considering the argument of a user-defined
1165 // conversion function that is a candidate by 13.3.1.3 when
1166 // invoked for the copying of the temporary in the second step
1167 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1168 // 13.3.1.6 in all cases, only standard conversion sequences and
1169 // ellipsis conversion sequences are allowed.
1170 if (SuppressUserConversions && ICS.isUserDefined()) {
1171 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1173 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1175 ICS.Ambiguous.setFromType(From->getType());
1176 ICS.Ambiguous.setToType(ToType);
1177 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1178 Cand != Conversions.end(); ++Cand)
1180 ICS.Ambiguous.addConversion(Cand->Function);
1182 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1188 /// TryImplicitConversion - Attempt to perform an implicit conversion
1189 /// from the given expression (Expr) to the given type (ToType). This
1190 /// function returns an implicit conversion sequence that can be used
1191 /// to perform the initialization. Given
1193 /// void f(float f);
1194 /// void g(int i) { f(i); }
1196 /// this routine would produce an implicit conversion sequence to
1197 /// describe the initialization of f from i, which will be a standard
1198 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1199 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1201 /// Note that this routine only determines how the conversion can be
1202 /// performed; it does not actually perform the conversion. As such,
1203 /// it will not produce any diagnostics if no conversion is available,
1204 /// but will instead return an implicit conversion sequence of kind
1205 /// "BadConversion".
1207 /// If @p SuppressUserConversions, then user-defined conversions are
1209 /// If @p AllowExplicit, then explicit user-defined conversions are
1212 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1213 /// writeback conversion, which allows __autoreleasing id* parameters to
1214 /// be initialized with __strong id* or __weak id* arguments.
1215 static ImplicitConversionSequence
1216 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1217 bool SuppressUserConversions,
1219 bool InOverloadResolution,
1221 bool AllowObjCWritebackConversion) {
1222 ImplicitConversionSequence ICS;
1223 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1224 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1229 if (!S.getLangOpts().CPlusPlus) {
1230 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1234 // C++ [over.ics.user]p4:
1235 // A conversion of an expression of class type to the same class
1236 // type is given Exact Match rank, and a conversion of an
1237 // expression of class type to a base class of that type is
1238 // given Conversion rank, in spite of the fact that a copy/move
1239 // constructor (i.e., a user-defined conversion function) is
1240 // called for those cases.
1241 QualType FromType = From->getType();
1242 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1243 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1244 S.IsDerivedFrom(FromType, ToType))) {
1246 ICS.Standard.setAsIdentityConversion();
1247 ICS.Standard.setFromType(FromType);
1248 ICS.Standard.setAllToTypes(ToType);
1250 // We don't actually check at this point whether there is a valid
1251 // copy/move constructor, since overloading just assumes that it
1252 // exists. When we actually perform initialization, we'll find the
1253 // appropriate constructor to copy the returned object, if needed.
1254 ICS.Standard.CopyConstructor = 0;
1256 // Determine whether this is considered a derived-to-base conversion.
1257 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1258 ICS.Standard.Second = ICK_Derived_To_Base;
1263 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1264 AllowExplicit, InOverloadResolution, CStyle,
1265 AllowObjCWritebackConversion);
1268 ImplicitConversionSequence
1269 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1270 bool SuppressUserConversions,
1272 bool InOverloadResolution,
1274 bool AllowObjCWritebackConversion) {
1275 return clang::TryImplicitConversion(*this, From, ToType,
1276 SuppressUserConversions, AllowExplicit,
1277 InOverloadResolution, CStyle,
1278 AllowObjCWritebackConversion);
1281 /// PerformImplicitConversion - Perform an implicit conversion of the
1282 /// expression From to the type ToType. Returns the
1283 /// converted expression. Flavor is the kind of conversion we're
1284 /// performing, used in the error message. If @p AllowExplicit,
1285 /// explicit user-defined conversions are permitted.
1287 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1288 AssignmentAction Action, bool AllowExplicit) {
1289 ImplicitConversionSequence ICS;
1290 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1294 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1295 AssignmentAction Action, bool AllowExplicit,
1296 ImplicitConversionSequence& ICS) {
1297 if (checkPlaceholderForOverload(*this, From))
1300 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1301 bool AllowObjCWritebackConversion
1302 = getLangOpts().ObjCAutoRefCount &&
1303 (Action == AA_Passing || Action == AA_Sending);
1305 ICS = clang::TryImplicitConversion(*this, From, ToType,
1306 /*SuppressUserConversions=*/false,
1308 /*InOverloadResolution=*/false,
1310 AllowObjCWritebackConversion);
1311 return PerformImplicitConversion(From, ToType, ICS, Action);
1314 /// \brief Determine whether the conversion from FromType to ToType is a valid
1315 /// conversion that strips "noreturn" off the nested function type.
1316 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1317 QualType &ResultTy) {
1318 if (Context.hasSameUnqualifiedType(FromType, ToType))
1321 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1322 // where F adds one of the following at most once:
1324 // - a member pointer
1325 // - a block pointer
1326 CanQualType CanTo = Context.getCanonicalType(ToType);
1327 CanQualType CanFrom = Context.getCanonicalType(FromType);
1328 Type::TypeClass TyClass = CanTo->getTypeClass();
1329 if (TyClass != CanFrom->getTypeClass()) return false;
1330 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1331 if (TyClass == Type::Pointer) {
1332 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1333 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1334 } else if (TyClass == Type::BlockPointer) {
1335 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1336 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1337 } else if (TyClass == Type::MemberPointer) {
1338 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1339 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1344 TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1350 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1351 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1352 if (!EInfo.getNoReturn()) return false;
1354 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1355 assert(QualType(FromFn, 0).isCanonical());
1356 if (QualType(FromFn, 0) != CanTo) return false;
1362 /// \brief Determine whether the conversion from FromType to ToType is a valid
1363 /// vector conversion.
1365 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1367 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1368 QualType ToType, ImplicitConversionKind &ICK) {
1369 // We need at least one of these types to be a vector type to have a vector
1371 if (!ToType->isVectorType() && !FromType->isVectorType())
1374 // Identical types require no conversions.
1375 if (Context.hasSameUnqualifiedType(FromType, ToType))
1378 // There are no conversions between extended vector types, only identity.
1379 if (ToType->isExtVectorType()) {
1380 // There are no conversions between extended vector types other than the
1381 // identity conversion.
1382 if (FromType->isExtVectorType())
1385 // Vector splat from any arithmetic type to a vector.
1386 if (FromType->isArithmeticType()) {
1387 ICK = ICK_Vector_Splat;
1392 // We can perform the conversion between vector types in the following cases:
1393 // 1)vector types are equivalent AltiVec and GCC vector types
1394 // 2)lax vector conversions are permitted and the vector types are of the
1396 if (ToType->isVectorType() && FromType->isVectorType()) {
1397 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1398 (Context.getLangOpts().LaxVectorConversions &&
1399 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1400 ICK = ICK_Vector_Conversion;
1408 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1409 bool InOverloadResolution,
1410 StandardConversionSequence &SCS,
1413 /// IsStandardConversion - Determines whether there is a standard
1414 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1415 /// expression From to the type ToType. Standard conversion sequences
1416 /// only consider non-class types; for conversions that involve class
1417 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1418 /// contain the standard conversion sequence required to perform this
1419 /// conversion and this routine will return true. Otherwise, this
1420 /// routine will return false and the value of SCS is unspecified.
1421 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1422 bool InOverloadResolution,
1423 StandardConversionSequence &SCS,
1425 bool AllowObjCWritebackConversion) {
1426 QualType FromType = From->getType();
1428 // Standard conversions (C++ [conv])
1429 SCS.setAsIdentityConversion();
1430 SCS.DeprecatedStringLiteralToCharPtr = false;
1431 SCS.IncompatibleObjC = false;
1432 SCS.setFromType(FromType);
1433 SCS.CopyConstructor = 0;
1435 // There are no standard conversions for class types in C++, so
1436 // abort early. When overloading in C, however, we do permit
1437 if (FromType->isRecordType() || ToType->isRecordType()) {
1438 if (S.getLangOpts().CPlusPlus)
1441 // When we're overloading in C, we allow, as standard conversions,
1444 // The first conversion can be an lvalue-to-rvalue conversion,
1445 // array-to-pointer conversion, or function-to-pointer conversion
1448 if (FromType == S.Context.OverloadTy) {
1449 DeclAccessPair AccessPair;
1450 if (FunctionDecl *Fn
1451 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1453 // We were able to resolve the address of the overloaded function,
1454 // so we can convert to the type of that function.
1455 FromType = Fn->getType();
1457 // we can sometimes resolve &foo<int> regardless of ToType, so check
1458 // if the type matches (identity) or we are converting to bool
1459 if (!S.Context.hasSameUnqualifiedType(
1460 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1462 // if the function type matches except for [[noreturn]], it's ok
1463 if (!S.IsNoReturnConversion(FromType,
1464 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1465 // otherwise, only a boolean conversion is standard
1466 if (!ToType->isBooleanType())
1470 // Check if the "from" expression is taking the address of an overloaded
1471 // function and recompute the FromType accordingly. Take advantage of the
1472 // fact that non-static member functions *must* have such an address-of
1474 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1475 if (Method && !Method->isStatic()) {
1476 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1477 "Non-unary operator on non-static member address");
1478 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1480 "Non-address-of operator on non-static member address");
1481 const Type *ClassType
1482 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1483 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1484 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1485 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1487 "Non-address-of operator for overloaded function expression");
1488 FromType = S.Context.getPointerType(FromType);
1491 // Check that we've computed the proper type after overload resolution.
1492 assert(S.Context.hasSameType(
1494 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1499 // Lvalue-to-rvalue conversion (C++11 4.1):
1500 // A glvalue (3.10) of a non-function, non-array type T can
1501 // be converted to a prvalue.
1502 bool argIsLValue = From->isGLValue();
1504 !FromType->isFunctionType() && !FromType->isArrayType() &&
1505 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1506 SCS.First = ICK_Lvalue_To_Rvalue;
1509 // ... if the lvalue has atomic type, the value has the non-atomic version
1510 // of the type of the lvalue ...
1511 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1512 FromType = Atomic->getValueType();
1514 // If T is a non-class type, the type of the rvalue is the
1515 // cv-unqualified version of T. Otherwise, the type of the rvalue
1516 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1517 // just strip the qualifiers because they don't matter.
1518 FromType = FromType.getUnqualifiedType();
1519 } else if (FromType->isArrayType()) {
1520 // Array-to-pointer conversion (C++ 4.2)
1521 SCS.First = ICK_Array_To_Pointer;
1523 // An lvalue or rvalue of type "array of N T" or "array of unknown
1524 // bound of T" can be converted to an rvalue of type "pointer to
1526 FromType = S.Context.getArrayDecayedType(FromType);
1528 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1529 // This conversion is deprecated. (C++ D.4).
1530 SCS.DeprecatedStringLiteralToCharPtr = true;
1532 // For the purpose of ranking in overload resolution
1533 // (13.3.3.1.1), this conversion is considered an
1534 // array-to-pointer conversion followed by a qualification
1535 // conversion (4.4). (C++ 4.2p2)
1536 SCS.Second = ICK_Identity;
1537 SCS.Third = ICK_Qualification;
1538 SCS.QualificationIncludesObjCLifetime = false;
1539 SCS.setAllToTypes(FromType);
1542 } else if (FromType->isFunctionType() && argIsLValue) {
1543 // Function-to-pointer conversion (C++ 4.3).
1544 SCS.First = ICK_Function_To_Pointer;
1546 // An lvalue of function type T can be converted to an rvalue of
1547 // type "pointer to T." The result is a pointer to the
1548 // function. (C++ 4.3p1).
1549 FromType = S.Context.getPointerType(FromType);
1551 // We don't require any conversions for the first step.
1552 SCS.First = ICK_Identity;
1554 SCS.setToType(0, FromType);
1556 // The second conversion can be an integral promotion, floating
1557 // point promotion, integral conversion, floating point conversion,
1558 // floating-integral conversion, pointer conversion,
1559 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1560 // For overloading in C, this can also be a "compatible-type"
1562 bool IncompatibleObjC = false;
1563 ImplicitConversionKind SecondICK = ICK_Identity;
1564 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1565 // The unqualified versions of the types are the same: there's no
1566 // conversion to do.
1567 SCS.Second = ICK_Identity;
1568 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1569 // Integral promotion (C++ 4.5).
1570 SCS.Second = ICK_Integral_Promotion;
1571 FromType = ToType.getUnqualifiedType();
1572 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1573 // Floating point promotion (C++ 4.6).
1574 SCS.Second = ICK_Floating_Promotion;
1575 FromType = ToType.getUnqualifiedType();
1576 } else if (S.IsComplexPromotion(FromType, ToType)) {
1577 // Complex promotion (Clang extension)
1578 SCS.Second = ICK_Complex_Promotion;
1579 FromType = ToType.getUnqualifiedType();
1580 } else if (ToType->isBooleanType() &&
1581 (FromType->isArithmeticType() ||
1582 FromType->isAnyPointerType() ||
1583 FromType->isBlockPointerType() ||
1584 FromType->isMemberPointerType() ||
1585 FromType->isNullPtrType())) {
1586 // Boolean conversions (C++ 4.12).
1587 SCS.Second = ICK_Boolean_Conversion;
1588 FromType = S.Context.BoolTy;
1589 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1590 ToType->isIntegralType(S.Context)) {
1591 // Integral conversions (C++ 4.7).
1592 SCS.Second = ICK_Integral_Conversion;
1593 FromType = ToType.getUnqualifiedType();
1594 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1595 // Complex conversions (C99 6.3.1.6)
1596 SCS.Second = ICK_Complex_Conversion;
1597 FromType = ToType.getUnqualifiedType();
1598 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1599 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1600 // Complex-real conversions (C99 6.3.1.7)
1601 SCS.Second = ICK_Complex_Real;
1602 FromType = ToType.getUnqualifiedType();
1603 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1604 // Floating point conversions (C++ 4.8).
1605 SCS.Second = ICK_Floating_Conversion;
1606 FromType = ToType.getUnqualifiedType();
1607 } else if ((FromType->isRealFloatingType() &&
1608 ToType->isIntegralType(S.Context)) ||
1609 (FromType->isIntegralOrUnscopedEnumerationType() &&
1610 ToType->isRealFloatingType())) {
1611 // Floating-integral conversions (C++ 4.9).
1612 SCS.Second = ICK_Floating_Integral;
1613 FromType = ToType.getUnqualifiedType();
1614 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1615 SCS.Second = ICK_Block_Pointer_Conversion;
1616 } else if (AllowObjCWritebackConversion &&
1617 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1618 SCS.Second = ICK_Writeback_Conversion;
1619 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1620 FromType, IncompatibleObjC)) {
1621 // Pointer conversions (C++ 4.10).
1622 SCS.Second = ICK_Pointer_Conversion;
1623 SCS.IncompatibleObjC = IncompatibleObjC;
1624 FromType = FromType.getUnqualifiedType();
1625 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1626 InOverloadResolution, FromType)) {
1627 // Pointer to member conversions (4.11).
1628 SCS.Second = ICK_Pointer_Member;
1629 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1630 SCS.Second = SecondICK;
1631 FromType = ToType.getUnqualifiedType();
1632 } else if (!S.getLangOpts().CPlusPlus &&
1633 S.Context.typesAreCompatible(ToType, FromType)) {
1634 // Compatible conversions (Clang extension for C function overloading)
1635 SCS.Second = ICK_Compatible_Conversion;
1636 FromType = ToType.getUnqualifiedType();
1637 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1638 // Treat a conversion that strips "noreturn" as an identity conversion.
1639 SCS.Second = ICK_NoReturn_Adjustment;
1640 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1641 InOverloadResolution,
1643 SCS.Second = ICK_TransparentUnionConversion;
1645 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1647 // tryAtomicConversion has updated the standard conversion sequence
1650 } else if (ToType->isEventT() &&
1651 From->isIntegerConstantExpr(S.getASTContext()) &&
1652 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1653 SCS.Second = ICK_Zero_Event_Conversion;
1656 // No second conversion required.
1657 SCS.Second = ICK_Identity;
1659 SCS.setToType(1, FromType);
1663 // The third conversion can be a qualification conversion (C++ 4p1).
1664 bool ObjCLifetimeConversion;
1665 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1666 ObjCLifetimeConversion)) {
1667 SCS.Third = ICK_Qualification;
1668 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1670 CanonFrom = S.Context.getCanonicalType(FromType);
1671 CanonTo = S.Context.getCanonicalType(ToType);
1673 // No conversion required
1674 SCS.Third = ICK_Identity;
1676 // C++ [over.best.ics]p6:
1677 // [...] Any difference in top-level cv-qualification is
1678 // subsumed by the initialization itself and does not constitute
1679 // a conversion. [...]
1680 CanonFrom = S.Context.getCanonicalType(FromType);
1681 CanonTo = S.Context.getCanonicalType(ToType);
1682 if (CanonFrom.getLocalUnqualifiedType()
1683 == CanonTo.getLocalUnqualifiedType() &&
1684 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1686 CanonFrom = CanonTo;
1689 SCS.setToType(2, FromType);
1691 // If we have not converted the argument type to the parameter type,
1692 // this is a bad conversion sequence.
1693 if (CanonFrom != CanonTo)
1700 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1702 bool InOverloadResolution,
1703 StandardConversionSequence &SCS,
1706 const RecordType *UT = ToType->getAsUnionType();
1707 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1709 // The field to initialize within the transparent union.
1710 RecordDecl *UD = UT->getDecl();
1711 // It's compatible if the expression matches any of the fields.
1712 for (RecordDecl::field_iterator it = UD->field_begin(),
1713 itend = UD->field_end();
1714 it != itend; ++it) {
1715 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1716 CStyle, /*ObjCWritebackConversion=*/false)) {
1717 ToType = it->getType();
1724 /// IsIntegralPromotion - Determines whether the conversion from the
1725 /// expression From (whose potentially-adjusted type is FromType) to
1726 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1727 /// sets PromotedType to the promoted type.
1728 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1729 const BuiltinType *To = ToType->getAs<BuiltinType>();
1730 // All integers are built-in.
1735 // An rvalue of type char, signed char, unsigned char, short int, or
1736 // unsigned short int can be converted to an rvalue of type int if
1737 // int can represent all the values of the source type; otherwise,
1738 // the source rvalue can be converted to an rvalue of type unsigned
1740 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1741 !FromType->isEnumeralType()) {
1742 if (// We can promote any signed, promotable integer type to an int
1743 (FromType->isSignedIntegerType() ||
1744 // We can promote any unsigned integer type whose size is
1745 // less than int to an int.
1746 (!FromType->isSignedIntegerType() &&
1747 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1748 return To->getKind() == BuiltinType::Int;
1751 return To->getKind() == BuiltinType::UInt;
1754 // C++11 [conv.prom]p3:
1755 // A prvalue of an unscoped enumeration type whose underlying type is not
1756 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1757 // following types that can represent all the values of the enumeration
1758 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1759 // unsigned int, long int, unsigned long int, long long int, or unsigned
1760 // long long int. If none of the types in that list can represent all the
1761 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1762 // type can be converted to an rvalue a prvalue of the extended integer type
1763 // with lowest integer conversion rank (4.13) greater than the rank of long
1764 // long in which all the values of the enumeration can be represented. If
1765 // there are two such extended types, the signed one is chosen.
1766 // C++11 [conv.prom]p4:
1767 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1768 // can be converted to a prvalue of its underlying type. Moreover, if
1769 // integral promotion can be applied to its underlying type, a prvalue of an
1770 // unscoped enumeration type whose underlying type is fixed can also be
1771 // converted to a prvalue of the promoted underlying type.
1772 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1773 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1774 // provided for a scoped enumeration.
1775 if (FromEnumType->getDecl()->isScoped())
1778 // We can perform an integral promotion to the underlying type of the enum,
1779 // even if that's not the promoted type.
1780 if (FromEnumType->getDecl()->isFixed()) {
1781 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1782 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1783 IsIntegralPromotion(From, Underlying, ToType);
1786 // We have already pre-calculated the promotion type, so this is trivial.
1787 if (ToType->isIntegerType() &&
1788 !RequireCompleteType(From->getLocStart(), FromType, 0))
1789 return Context.hasSameUnqualifiedType(ToType,
1790 FromEnumType->getDecl()->getPromotionType());
1793 // C++0x [conv.prom]p2:
1794 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1795 // to an rvalue a prvalue of the first of the following types that can
1796 // represent all the values of its underlying type: int, unsigned int,
1797 // long int, unsigned long int, long long int, or unsigned long long int.
1798 // If none of the types in that list can represent all the values of its
1799 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1800 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1802 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1803 ToType->isIntegerType()) {
1804 // Determine whether the type we're converting from is signed or
1806 bool FromIsSigned = FromType->isSignedIntegerType();
1807 uint64_t FromSize = Context.getTypeSize(FromType);
1809 // The types we'll try to promote to, in the appropriate
1810 // order. Try each of these types.
1811 QualType PromoteTypes[6] = {
1812 Context.IntTy, Context.UnsignedIntTy,
1813 Context.LongTy, Context.UnsignedLongTy ,
1814 Context.LongLongTy, Context.UnsignedLongLongTy
1816 for (int Idx = 0; Idx < 6; ++Idx) {
1817 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1818 if (FromSize < ToSize ||
1819 (FromSize == ToSize &&
1820 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1821 // We found the type that we can promote to. If this is the
1822 // type we wanted, we have a promotion. Otherwise, no
1824 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1829 // An rvalue for an integral bit-field (9.6) can be converted to an
1830 // rvalue of type int if int can represent all the values of the
1831 // bit-field; otherwise, it can be converted to unsigned int if
1832 // unsigned int can represent all the values of the bit-field. If
1833 // the bit-field is larger yet, no integral promotion applies to
1834 // it. If the bit-field has an enumerated type, it is treated as any
1835 // other value of that type for promotion purposes (C++ 4.5p3).
1836 // FIXME: We should delay checking of bit-fields until we actually perform the
1840 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1842 if (FromType->isIntegralType(Context) &&
1843 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1844 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1845 ToSize = Context.getTypeSize(ToType);
1847 // Are we promoting to an int from a bitfield that fits in an int?
1848 if (BitWidth < ToSize ||
1849 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1850 return To->getKind() == BuiltinType::Int;
1853 // Are we promoting to an unsigned int from an unsigned bitfield
1854 // that fits into an unsigned int?
1855 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1856 return To->getKind() == BuiltinType::UInt;
1863 // An rvalue of type bool can be converted to an rvalue of type int,
1864 // with false becoming zero and true becoming one (C++ 4.5p4).
1865 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1872 /// IsFloatingPointPromotion - Determines whether the conversion from
1873 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1874 /// returns true and sets PromotedType to the promoted type.
1875 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1876 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1877 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1878 /// An rvalue of type float can be converted to an rvalue of type
1879 /// double. (C++ 4.6p1).
1880 if (FromBuiltin->getKind() == BuiltinType::Float &&
1881 ToBuiltin->getKind() == BuiltinType::Double)
1885 // When a float is promoted to double or long double, or a
1886 // double is promoted to long double [...].
1887 if (!getLangOpts().CPlusPlus &&
1888 (FromBuiltin->getKind() == BuiltinType::Float ||
1889 FromBuiltin->getKind() == BuiltinType::Double) &&
1890 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1893 // Half can be promoted to float.
1894 if (!getLangOpts().NativeHalfType &&
1895 FromBuiltin->getKind() == BuiltinType::Half &&
1896 ToBuiltin->getKind() == BuiltinType::Float)
1903 /// \brief Determine if a conversion is a complex promotion.
1905 /// A complex promotion is defined as a complex -> complex conversion
1906 /// where the conversion between the underlying real types is a
1907 /// floating-point or integral promotion.
1908 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1909 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1913 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1917 return IsFloatingPointPromotion(FromComplex->getElementType(),
1918 ToComplex->getElementType()) ||
1919 IsIntegralPromotion(0, FromComplex->getElementType(),
1920 ToComplex->getElementType());
1923 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1924 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1925 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1926 /// if non-empty, will be a pointer to ToType that may or may not have
1927 /// the right set of qualifiers on its pointee.
1930 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1931 QualType ToPointee, QualType ToType,
1932 ASTContext &Context,
1933 bool StripObjCLifetime = false) {
1934 assert((FromPtr->getTypeClass() == Type::Pointer ||
1935 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1936 "Invalid similarly-qualified pointer type");
1938 /// Conversions to 'id' subsume cv-qualifier conversions.
1939 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1940 return ToType.getUnqualifiedType();
1942 QualType CanonFromPointee
1943 = Context.getCanonicalType(FromPtr->getPointeeType());
1944 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1945 Qualifiers Quals = CanonFromPointee.getQualifiers();
1947 if (StripObjCLifetime)
1948 Quals.removeObjCLifetime();
1950 // Exact qualifier match -> return the pointer type we're converting to.
1951 if (CanonToPointee.getLocalQualifiers() == Quals) {
1952 // ToType is exactly what we need. Return it.
1953 if (!ToType.isNull())
1954 return ToType.getUnqualifiedType();
1956 // Build a pointer to ToPointee. It has the right qualifiers
1958 if (isa<ObjCObjectPointerType>(ToType))
1959 return Context.getObjCObjectPointerType(ToPointee);
1960 return Context.getPointerType(ToPointee);
1963 // Just build a canonical type that has the right qualifiers.
1964 QualType QualifiedCanonToPointee
1965 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1967 if (isa<ObjCObjectPointerType>(ToType))
1968 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1969 return Context.getPointerType(QualifiedCanonToPointee);
1972 static bool isNullPointerConstantForConversion(Expr *Expr,
1973 bool InOverloadResolution,
1974 ASTContext &Context) {
1975 // Handle value-dependent integral null pointer constants correctly.
1976 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1977 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1978 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1979 return !InOverloadResolution;
1981 return Expr->isNullPointerConstant(Context,
1982 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1983 : Expr::NPC_ValueDependentIsNull);
1986 /// IsPointerConversion - Determines whether the conversion of the
1987 /// expression From, which has the (possibly adjusted) type FromType,
1988 /// can be converted to the type ToType via a pointer conversion (C++
1989 /// 4.10). If so, returns true and places the converted type (that
1990 /// might differ from ToType in its cv-qualifiers at some level) into
1993 /// This routine also supports conversions to and from block pointers
1994 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1995 /// pointers to interfaces. FIXME: Once we've determined the
1996 /// appropriate overloading rules for Objective-C, we may want to
1997 /// split the Objective-C checks into a different routine; however,
1998 /// GCC seems to consider all of these conversions to be pointer
1999 /// conversions, so for now they live here. IncompatibleObjC will be
2000 /// set if the conversion is an allowed Objective-C conversion that
2001 /// should result in a warning.
2002 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2003 bool InOverloadResolution,
2004 QualType& ConvertedType,
2005 bool &IncompatibleObjC) {
2006 IncompatibleObjC = false;
2007 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2011 // Conversion from a null pointer constant to any Objective-C pointer type.
2012 if (ToType->isObjCObjectPointerType() &&
2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2014 ConvertedType = ToType;
2018 // Blocks: Block pointers can be converted to void*.
2019 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2020 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2021 ConvertedType = ToType;
2024 // Blocks: A null pointer constant can be converted to a block
2026 if (ToType->isBlockPointerType() &&
2027 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2028 ConvertedType = ToType;
2032 // If the left-hand-side is nullptr_t, the right side can be a null
2033 // pointer constant.
2034 if (ToType->isNullPtrType() &&
2035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2036 ConvertedType = ToType;
2040 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2044 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2045 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2046 ConvertedType = ToType;
2050 // Beyond this point, both types need to be pointers
2051 // , including objective-c pointers.
2052 QualType ToPointeeType = ToTypePtr->getPointeeType();
2053 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2054 !getLangOpts().ObjCAutoRefCount) {
2055 ConvertedType = BuildSimilarlyQualifiedPointerType(
2056 FromType->getAs<ObjCObjectPointerType>(),
2061 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2065 QualType FromPointeeType = FromTypePtr->getPointeeType();
2067 // If the unqualified pointee types are the same, this can't be a
2068 // pointer conversion, so don't do all of the work below.
2069 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2072 // An rvalue of type "pointer to cv T," where T is an object type,
2073 // can be converted to an rvalue of type "pointer to cv void" (C++
2075 if (FromPointeeType->isIncompleteOrObjectType() &&
2076 ToPointeeType->isVoidType()) {
2077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2080 /*StripObjCLifetime=*/true);
2084 // MSVC allows implicit function to void* type conversion.
2085 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2086 ToPointeeType->isVoidType()) {
2087 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2093 // When we're overloading in C, we allow a special kind of pointer
2094 // conversion for compatible-but-not-identical pointee types.
2095 if (!getLangOpts().CPlusPlus &&
2096 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2103 // C++ [conv.ptr]p3:
2105 // An rvalue of type "pointer to cv D," where D is a class type,
2106 // can be converted to an rvalue of type "pointer to cv B," where
2107 // B is a base class (clause 10) of D. If B is an inaccessible
2108 // (clause 11) or ambiguous (10.2) base class of D, a program that
2109 // necessitates this conversion is ill-formed. The result of the
2110 // conversion is a pointer to the base class sub-object of the
2111 // derived class object. The null pointer value is converted to
2112 // the null pointer value of the destination type.
2114 // Note that we do not check for ambiguity or inaccessibility
2115 // here. That is handled by CheckPointerConversion.
2116 if (getLangOpts().CPlusPlus &&
2117 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2118 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2119 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2120 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2121 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2127 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2128 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2129 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2138 /// \brief Adopt the given qualifiers for the given type.
2139 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2140 Qualifiers TQs = T.getQualifiers();
2142 // Check whether qualifiers already match.
2146 if (Qs.compatiblyIncludes(TQs))
2147 return Context.getQualifiedType(T, Qs);
2149 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2152 /// isObjCPointerConversion - Determines whether this is an
2153 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2154 /// with the same arguments and return values.
2155 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2156 QualType& ConvertedType,
2157 bool &IncompatibleObjC) {
2158 if (!getLangOpts().ObjC1)
2161 // The set of qualifiers on the type we're converting from.
2162 Qualifiers FromQualifiers = FromType.getQualifiers();
2164 // First, we handle all conversions on ObjC object pointer types.
2165 const ObjCObjectPointerType* ToObjCPtr =
2166 ToType->getAs<ObjCObjectPointerType>();
2167 const ObjCObjectPointerType *FromObjCPtr =
2168 FromType->getAs<ObjCObjectPointerType>();
2170 if (ToObjCPtr && FromObjCPtr) {
2171 // If the pointee types are the same (ignoring qualifications),
2172 // then this is not a pointer conversion.
2173 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2174 FromObjCPtr->getPointeeType()))
2177 // Check for compatible
2178 // Objective C++: We're able to convert between "id" or "Class" and a
2179 // pointer to any interface (in both directions).
2180 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2181 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2184 // Conversions with Objective-C's id<...>.
2185 if ((FromObjCPtr->isObjCQualifiedIdType() ||
2186 ToObjCPtr->isObjCQualifiedIdType()) &&
2187 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2188 /*compare=*/false)) {
2189 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2192 // Objective C++: We're able to convert from a pointer to an
2193 // interface to a pointer to a different interface.
2194 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2195 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2196 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2197 if (getLangOpts().CPlusPlus && LHS && RHS &&
2198 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2199 FromObjCPtr->getPointeeType()))
2201 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2202 ToObjCPtr->getPointeeType(),
2204 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2208 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2209 // Okay: this is some kind of implicit downcast of Objective-C
2210 // interfaces, which is permitted. However, we're going to
2211 // complain about it.
2212 IncompatibleObjC = true;
2213 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2214 ToObjCPtr->getPointeeType(),
2216 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2220 // Beyond this point, both types need to be C pointers or block pointers.
2221 QualType ToPointeeType;
2222 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2223 ToPointeeType = ToCPtr->getPointeeType();
2224 else if (const BlockPointerType *ToBlockPtr =
2225 ToType->getAs<BlockPointerType>()) {
2226 // Objective C++: We're able to convert from a pointer to any object
2227 // to a block pointer type.
2228 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2229 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2232 ToPointeeType = ToBlockPtr->getPointeeType();
2234 else if (FromType->getAs<BlockPointerType>() &&
2235 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2236 // Objective C++: We're able to convert from a block pointer type to a
2237 // pointer to any object.
2238 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2244 QualType FromPointeeType;
2245 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2246 FromPointeeType = FromCPtr->getPointeeType();
2247 else if (const BlockPointerType *FromBlockPtr =
2248 FromType->getAs<BlockPointerType>())
2249 FromPointeeType = FromBlockPtr->getPointeeType();
2253 // If we have pointers to pointers, recursively check whether this
2254 // is an Objective-C conversion.
2255 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2256 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2257 IncompatibleObjC)) {
2258 // We always complain about this conversion.
2259 IncompatibleObjC = true;
2260 ConvertedType = Context.getPointerType(ConvertedType);
2261 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2264 // Allow conversion of pointee being objective-c pointer to another one;
2266 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2267 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2268 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2269 IncompatibleObjC)) {
2271 ConvertedType = Context.getPointerType(ConvertedType);
2272 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2276 // If we have pointers to functions or blocks, check whether the only
2277 // differences in the argument and result types are in Objective-C
2278 // pointer conversions. If so, we permit the conversion (but
2279 // complain about it).
2280 const FunctionProtoType *FromFunctionType
2281 = FromPointeeType->getAs<FunctionProtoType>();
2282 const FunctionProtoType *ToFunctionType
2283 = ToPointeeType->getAs<FunctionProtoType>();
2284 if (FromFunctionType && ToFunctionType) {
2285 // If the function types are exactly the same, this isn't an
2286 // Objective-C pointer conversion.
2287 if (Context.getCanonicalType(FromPointeeType)
2288 == Context.getCanonicalType(ToPointeeType))
2291 // Perform the quick checks that will tell us whether these
2292 // function types are obviously different.
2293 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2294 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2295 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2298 bool HasObjCConversion = false;
2299 if (Context.getCanonicalType(FromFunctionType->getResultType())
2300 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2301 // Okay, the types match exactly. Nothing to do.
2302 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2303 ToFunctionType->getResultType(),
2304 ConvertedType, IncompatibleObjC)) {
2305 // Okay, we have an Objective-C pointer conversion.
2306 HasObjCConversion = true;
2308 // Function types are too different. Abort.
2312 // Check argument types.
2313 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2314 ArgIdx != NumArgs; ++ArgIdx) {
2315 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2316 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2317 if (Context.getCanonicalType(FromArgType)
2318 == Context.getCanonicalType(ToArgType)) {
2319 // Okay, the types match exactly. Nothing to do.
2320 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2321 ConvertedType, IncompatibleObjC)) {
2322 // Okay, we have an Objective-C pointer conversion.
2323 HasObjCConversion = true;
2325 // Argument types are too different. Abort.
2330 if (HasObjCConversion) {
2331 // We had an Objective-C conversion. Allow this pointer
2332 // conversion, but complain about it.
2333 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2334 IncompatibleObjC = true;
2342 /// \brief Determine whether this is an Objective-C writeback conversion,
2343 /// used for parameter passing when performing automatic reference counting.
2345 /// \param FromType The type we're converting form.
2347 /// \param ToType The type we're converting to.
2349 /// \param ConvertedType The type that will be produced after applying
2350 /// this conversion.
2351 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2352 QualType &ConvertedType) {
2353 if (!getLangOpts().ObjCAutoRefCount ||
2354 Context.hasSameUnqualifiedType(FromType, ToType))
2357 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2359 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2360 ToPointee = ToPointer->getPointeeType();
2364 Qualifiers ToQuals = ToPointee.getQualifiers();
2365 if (!ToPointee->isObjCLifetimeType() ||
2366 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2367 !ToQuals.withoutObjCLifetime().empty())
2370 // Argument must be a pointer to __strong to __weak.
2371 QualType FromPointee;
2372 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2373 FromPointee = FromPointer->getPointeeType();
2377 Qualifiers FromQuals = FromPointee.getQualifiers();
2378 if (!FromPointee->isObjCLifetimeType() ||
2379 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2380 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2383 // Make sure that we have compatible qualifiers.
2384 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2385 if (!ToQuals.compatiblyIncludes(FromQuals))
2388 // Remove qualifiers from the pointee type we're converting from; they
2389 // aren't used in the compatibility check belong, and we'll be adding back
2390 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2391 FromPointee = FromPointee.getUnqualifiedType();
2393 // The unqualified form of the pointee types must be compatible.
2394 ToPointee = ToPointee.getUnqualifiedType();
2395 bool IncompatibleObjC;
2396 if (Context.typesAreCompatible(FromPointee, ToPointee))
2397 FromPointee = ToPointee;
2398 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2402 /// \brief Construct the type we're converting to, which is a pointer to
2403 /// __autoreleasing pointee.
2404 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2405 ConvertedType = Context.getPointerType(FromPointee);
2409 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2410 QualType& ConvertedType) {
2411 QualType ToPointeeType;
2412 if (const BlockPointerType *ToBlockPtr =
2413 ToType->getAs<BlockPointerType>())
2414 ToPointeeType = ToBlockPtr->getPointeeType();
2418 QualType FromPointeeType;
2419 if (const BlockPointerType *FromBlockPtr =
2420 FromType->getAs<BlockPointerType>())
2421 FromPointeeType = FromBlockPtr->getPointeeType();
2424 // We have pointer to blocks, check whether the only
2425 // differences in the argument and result types are in Objective-C
2426 // pointer conversions. If so, we permit the conversion.
2428 const FunctionProtoType *FromFunctionType
2429 = FromPointeeType->getAs<FunctionProtoType>();
2430 const FunctionProtoType *ToFunctionType
2431 = ToPointeeType->getAs<FunctionProtoType>();
2433 if (!FromFunctionType || !ToFunctionType)
2436 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2439 // Perform the quick checks that will tell us whether these
2440 // function types are obviously different.
2441 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2442 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2445 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2446 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2447 if (FromEInfo != ToEInfo)
2450 bool IncompatibleObjC = false;
2451 if (Context.hasSameType(FromFunctionType->getResultType(),
2452 ToFunctionType->getResultType())) {
2453 // Okay, the types match exactly. Nothing to do.
2455 QualType RHS = FromFunctionType->getResultType();
2456 QualType LHS = ToFunctionType->getResultType();
2457 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2458 !RHS.hasQualifiers() && LHS.hasQualifiers())
2459 LHS = LHS.getUnqualifiedType();
2461 if (Context.hasSameType(RHS,LHS)) {
2463 } else if (isObjCPointerConversion(RHS, LHS,
2464 ConvertedType, IncompatibleObjC)) {
2465 if (IncompatibleObjC)
2467 // Okay, we have an Objective-C pointer conversion.
2473 // Check argument types.
2474 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2475 ArgIdx != NumArgs; ++ArgIdx) {
2476 IncompatibleObjC = false;
2477 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2478 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2479 if (Context.hasSameType(FromArgType, ToArgType)) {
2480 // Okay, the types match exactly. Nothing to do.
2481 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2482 ConvertedType, IncompatibleObjC)) {
2483 if (IncompatibleObjC)
2485 // Okay, we have an Objective-C pointer conversion.
2487 // Argument types are too different. Abort.
2490 if (LangOpts.ObjCAutoRefCount &&
2491 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2495 ConvertedType = ToType;
2503 ft_parameter_mismatch,
2505 ft_qualifer_mismatch
2508 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2509 /// function types. Catches different number of parameter, mismatch in
2510 /// parameter types, and different return types.
2511 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2512 QualType FromType, QualType ToType) {
2513 // If either type is not valid, include no extra info.
2514 if (FromType.isNull() || ToType.isNull()) {
2515 PDiag << ft_default;
2519 // Get the function type from the pointers.
2520 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2521 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2522 *ToMember = ToType->getAs<MemberPointerType>();
2523 if (FromMember->getClass() != ToMember->getClass()) {
2524 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2525 << QualType(FromMember->getClass(), 0);
2528 FromType = FromMember->getPointeeType();
2529 ToType = ToMember->getPointeeType();
2532 if (FromType->isPointerType())
2533 FromType = FromType->getPointeeType();
2534 if (ToType->isPointerType())
2535 ToType = ToType->getPointeeType();
2537 // Remove references.
2538 FromType = FromType.getNonReferenceType();
2539 ToType = ToType.getNonReferenceType();
2541 // Don't print extra info for non-specialized template functions.
2542 if (FromType->isInstantiationDependentType() &&
2543 !FromType->getAs<TemplateSpecializationType>()) {
2544 PDiag << ft_default;
2548 // No extra info for same types.
2549 if (Context.hasSameType(FromType, ToType)) {
2550 PDiag << ft_default;
2554 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2555 *ToFunction = ToType->getAs<FunctionProtoType>();
2557 // Both types need to be function types.
2558 if (!FromFunction || !ToFunction) {
2559 PDiag << ft_default;
2563 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2564 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2565 << FromFunction->getNumArgs();
2569 // Handle different parameter types.
2571 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2572 PDiag << ft_parameter_mismatch << ArgPos + 1
2573 << ToFunction->getArgType(ArgPos)
2574 << FromFunction->getArgType(ArgPos);
2578 // Handle different return type.
2579 if (!Context.hasSameType(FromFunction->getResultType(),
2580 ToFunction->getResultType())) {
2581 PDiag << ft_return_type << ToFunction->getResultType()
2582 << FromFunction->getResultType();
2586 unsigned FromQuals = FromFunction->getTypeQuals(),
2587 ToQuals = ToFunction->getTypeQuals();
2588 if (FromQuals != ToQuals) {
2589 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2593 // Unable to find a difference, so add no extra info.
2594 PDiag << ft_default;
2597 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2598 /// for equality of their argument types. Caller has already checked that
2599 /// they have same number of arguments. This routine assumes that Objective-C
2600 /// pointer types which only differ in their protocol qualifiers are equal.
2601 /// If the parameters are different, ArgPos will have the parameter index
2602 /// of the first different parameter.
2603 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2604 const FunctionProtoType *NewType,
2606 if (!getLangOpts().ObjC1) {
2607 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2608 N = NewType->arg_type_begin(),
2609 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2610 if (!Context.hasSameType(*O, *N)) {
2611 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2618 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2619 N = NewType->arg_type_begin(),
2620 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2621 QualType ToType = (*O);
2622 QualType FromType = (*N);
2623 if (!Context.hasSameType(ToType, FromType)) {
2624 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2625 if (const PointerType *PTFr = FromType->getAs<PointerType>())
2626 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2627 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2628 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2629 PTFr->getPointeeType()->isObjCQualifiedClassType()))
2632 else if (const ObjCObjectPointerType *PTTo =
2633 ToType->getAs<ObjCObjectPointerType>()) {
2634 if (const ObjCObjectPointerType *PTFr =
2635 FromType->getAs<ObjCObjectPointerType>())
2636 if (Context.hasSameUnqualifiedType(
2637 PTTo->getObjectType()->getBaseType(),
2638 PTFr->getObjectType()->getBaseType()))
2641 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2648 /// CheckPointerConversion - Check the pointer conversion from the
2649 /// expression From to the type ToType. This routine checks for
2650 /// ambiguous or inaccessible derived-to-base pointer
2651 /// conversions for which IsPointerConversion has already returned
2652 /// true. It returns true and produces a diagnostic if there was an
2653 /// error, or returns false otherwise.
2654 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2656 CXXCastPath& BasePath,
2657 bool IgnoreBaseAccess) {
2658 QualType FromType = From->getType();
2659 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2663 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2664 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2665 Expr::NPCK_ZeroExpression) {
2666 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2667 DiagRuntimeBehavior(From->getExprLoc(), From,
2668 PDiag(diag::warn_impcast_bool_to_null_pointer)
2669 << ToType << From->getSourceRange());
2670 else if (!isUnevaluatedContext())
2671 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2672 << ToType << From->getSourceRange();
2674 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2675 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2676 QualType FromPointeeType = FromPtrType->getPointeeType(),
2677 ToPointeeType = ToPtrType->getPointeeType();
2679 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2680 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2681 // We must have a derived-to-base conversion. Check an
2682 // ambiguous or inaccessible conversion.
2683 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2685 From->getSourceRange(), &BasePath,
2689 // The conversion was successful.
2690 Kind = CK_DerivedToBase;
2693 } else if (const ObjCObjectPointerType *ToPtrType =
2694 ToType->getAs<ObjCObjectPointerType>()) {
2695 if (const ObjCObjectPointerType *FromPtrType =
2696 FromType->getAs<ObjCObjectPointerType>()) {
2697 // Objective-C++ conversions are always okay.
2698 // FIXME: We should have a different class of conversions for the
2699 // Objective-C++ implicit conversions.
2700 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2702 } else if (FromType->isBlockPointerType()) {
2703 Kind = CK_BlockPointerToObjCPointerCast;
2705 Kind = CK_CPointerToObjCPointerCast;
2707 } else if (ToType->isBlockPointerType()) {
2708 if (!FromType->isBlockPointerType())
2709 Kind = CK_AnyPointerToBlockPointerCast;
2712 // We shouldn't fall into this case unless it's valid for other
2714 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2715 Kind = CK_NullToPointer;
2720 /// IsMemberPointerConversion - Determines whether the conversion of the
2721 /// expression From, which has the (possibly adjusted) type FromType, can be
2722 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2723 /// If so, returns true and places the converted type (that might differ from
2724 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2725 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2727 bool InOverloadResolution,
2728 QualType &ConvertedType) {
2729 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2733 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2734 if (From->isNullPointerConstant(Context,
2735 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2736 : Expr::NPC_ValueDependentIsNull)) {
2737 ConvertedType = ToType;
2741 // Otherwise, both types have to be member pointers.
2742 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2746 // A pointer to member of B can be converted to a pointer to member of D,
2747 // where D is derived from B (C++ 4.11p2).
2748 QualType FromClass(FromTypePtr->getClass(), 0);
2749 QualType ToClass(ToTypePtr->getClass(), 0);
2751 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2752 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2753 IsDerivedFrom(ToClass, FromClass)) {
2754 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2755 ToClass.getTypePtr());
2762 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2763 /// expression From to the type ToType. This routine checks for ambiguous or
2764 /// virtual or inaccessible base-to-derived member pointer conversions
2765 /// for which IsMemberPointerConversion has already returned true. It returns
2766 /// true and produces a diagnostic if there was an error, or returns false
2768 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2770 CXXCastPath &BasePath,
2771 bool IgnoreBaseAccess) {
2772 QualType FromType = From->getType();
2773 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2775 // This must be a null pointer to member pointer conversion
2776 assert(From->isNullPointerConstant(Context,
2777 Expr::NPC_ValueDependentIsNull) &&
2778 "Expr must be null pointer constant!");
2779 Kind = CK_NullToMemberPointer;
2783 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2784 assert(ToPtrType && "No member pointer cast has a target type "
2785 "that is not a member pointer.");
2787 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2788 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2790 // FIXME: What about dependent types?
2791 assert(FromClass->isRecordType() && "Pointer into non-class.");
2792 assert(ToClass->isRecordType() && "Pointer into non-class.");
2794 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2795 /*DetectVirtual=*/true);
2796 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2797 assert(DerivationOkay &&
2798 "Should not have been called if derivation isn't OK.");
2799 (void)DerivationOkay;
2801 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2802 getUnqualifiedType())) {
2803 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2804 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2805 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2809 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2810 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2811 << FromClass << ToClass << QualType(VBase, 0)
2812 << From->getSourceRange();
2816 if (!IgnoreBaseAccess)
2817 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2819 diag::err_downcast_from_inaccessible_base);
2821 // Must be a base to derived member conversion.
2822 BuildBasePathArray(Paths, BasePath);
2823 Kind = CK_BaseToDerivedMemberPointer;
2827 /// IsQualificationConversion - Determines whether the conversion from
2828 /// an rvalue of type FromType to ToType is a qualification conversion
2831 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2832 /// when the qualification conversion involves a change in the Objective-C
2833 /// object lifetime.
2835 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2836 bool CStyle, bool &ObjCLifetimeConversion) {
2837 FromType = Context.getCanonicalType(FromType);
2838 ToType = Context.getCanonicalType(ToType);
2839 ObjCLifetimeConversion = false;
2841 // If FromType and ToType are the same type, this is not a
2842 // qualification conversion.
2843 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2847 // A conversion can add cv-qualifiers at levels other than the first
2848 // in multi-level pointers, subject to the following rules: [...]
2849 bool PreviousToQualsIncludeConst = true;
2850 bool UnwrappedAnyPointer = false;
2851 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2852 // Within each iteration of the loop, we check the qualifiers to
2853 // determine if this still looks like a qualification
2854 // conversion. Then, if all is well, we unwrap one more level of
2855 // pointers or pointers-to-members and do it all again
2856 // until there are no more pointers or pointers-to-members left to
2858 UnwrappedAnyPointer = true;
2860 Qualifiers FromQuals = FromType.getQualifiers();
2861 Qualifiers ToQuals = ToType.getQualifiers();
2864 // Check Objective-C lifetime conversions.
2865 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2866 UnwrappedAnyPointer) {
2867 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2868 ObjCLifetimeConversion = true;
2869 FromQuals.removeObjCLifetime();
2870 ToQuals.removeObjCLifetime();
2872 // Qualification conversions cannot cast between different
2873 // Objective-C lifetime qualifiers.
2878 // Allow addition/removal of GC attributes but not changing GC attributes.
2879 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2880 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2881 FromQuals.removeObjCGCAttr();
2882 ToQuals.removeObjCGCAttr();
2885 // -- for every j > 0, if const is in cv 1,j then const is in cv
2886 // 2,j, and similarly for volatile.
2887 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2890 // -- if the cv 1,j and cv 2,j are different, then const is in
2891 // every cv for 0 < k < j.
2892 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2893 && !PreviousToQualsIncludeConst)
2896 // Keep track of whether all prior cv-qualifiers in the "to" type
2898 PreviousToQualsIncludeConst
2899 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2902 // We are left with FromType and ToType being the pointee types
2903 // after unwrapping the original FromType and ToType the same number
2904 // of types. If we unwrapped any pointers, and if FromType and
2905 // ToType have the same unqualified type (since we checked
2906 // qualifiers above), then this is a qualification conversion.
2907 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2910 /// \brief - Determine whether this is a conversion from a scalar type to an
2913 /// If successful, updates \c SCS's second and third steps in the conversion
2914 /// sequence to finish the conversion.
2915 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2916 bool InOverloadResolution,
2917 StandardConversionSequence &SCS,
2919 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2923 StandardConversionSequence InnerSCS;
2924 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2925 InOverloadResolution, InnerSCS,
2926 CStyle, /*AllowObjCWritebackConversion=*/false))
2929 SCS.Second = InnerSCS.Second;
2930 SCS.setToType(1, InnerSCS.getToType(1));
2931 SCS.Third = InnerSCS.Third;
2932 SCS.QualificationIncludesObjCLifetime
2933 = InnerSCS.QualificationIncludesObjCLifetime;
2934 SCS.setToType(2, InnerSCS.getToType(2));
2938 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2939 CXXConstructorDecl *Constructor,
2941 const FunctionProtoType *CtorType =
2942 Constructor->getType()->getAs<FunctionProtoType>();
2943 if (CtorType->getNumArgs() > 0) {
2944 QualType FirstArg = CtorType->getArgType(0);
2945 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2951 static OverloadingResult
2952 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2954 UserDefinedConversionSequence &User,
2955 OverloadCandidateSet &CandidateSet,
2956 bool AllowExplicit) {
2957 DeclContext::lookup_result R = S.LookupConstructors(To);
2958 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2959 Con != ConEnd; ++Con) {
2960 NamedDecl *D = *Con;
2961 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2963 // Find the constructor (which may be a template).
2964 CXXConstructorDecl *Constructor = 0;
2965 FunctionTemplateDecl *ConstructorTmpl
2966 = dyn_cast<FunctionTemplateDecl>(D);
2967 if (ConstructorTmpl)
2969 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2971 Constructor = cast<CXXConstructorDecl>(D);
2973 bool Usable = !Constructor->isInvalidDecl() &&
2974 S.isInitListConstructor(Constructor) &&
2975 (AllowExplicit || !Constructor->isExplicit());
2977 // If the first argument is (a reference to) the target type,
2978 // suppress conversions.
2979 bool SuppressUserConversions =
2980 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2981 if (ConstructorTmpl)
2982 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2985 SuppressUserConversions);
2987 S.AddOverloadCandidate(Constructor, FoundDecl,
2989 SuppressUserConversions);
2993 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2995 OverloadCandidateSet::iterator Best;
2996 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2998 // Record the standard conversion we used and the conversion function.
2999 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3000 QualType ThisType = Constructor->getThisType(S.Context);
3001 // Initializer lists don't have conversions as such.
3002 User.Before.setAsIdentityConversion();
3003 User.HadMultipleCandidates = HadMultipleCandidates;
3004 User.ConversionFunction = Constructor;
3005 User.FoundConversionFunction = Best->FoundDecl;
3006 User.After.setAsIdentityConversion();
3007 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3008 User.After.setAllToTypes(ToType);
3012 case OR_No_Viable_Function:
3013 return OR_No_Viable_Function;
3017 return OR_Ambiguous;
3020 llvm_unreachable("Invalid OverloadResult!");
3023 /// Determines whether there is a user-defined conversion sequence
3024 /// (C++ [over.ics.user]) that converts expression From to the type
3025 /// ToType. If such a conversion exists, User will contain the
3026 /// user-defined conversion sequence that performs such a conversion
3027 /// and this routine will return true. Otherwise, this routine returns
3028 /// false and User is unspecified.
3030 /// \param AllowExplicit true if the conversion should consider C++0x
3031 /// "explicit" conversion functions as well as non-explicit conversion
3032 /// functions (C++0x [class.conv.fct]p2).
3033 static OverloadingResult
3034 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3035 UserDefinedConversionSequence &User,
3036 OverloadCandidateSet &CandidateSet,
3037 bool AllowExplicit) {
3038 // Whether we will only visit constructors.
3039 bool ConstructorsOnly = false;
3041 // If the type we are conversion to is a class type, enumerate its
3043 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3044 // C++ [over.match.ctor]p1:
3045 // When objects of class type are direct-initialized (8.5), or
3046 // copy-initialized from an expression of the same or a
3047 // derived class type (8.5), overload resolution selects the
3048 // constructor. [...] For copy-initialization, the candidate
3049 // functions are all the converting constructors (12.3.1) of
3050 // that class. The argument list is the expression-list within
3051 // the parentheses of the initializer.
3052 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3053 (From->getType()->getAs<RecordType>() &&
3054 S.IsDerivedFrom(From->getType(), ToType)))
3055 ConstructorsOnly = true;
3057 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3058 // RequireCompleteType may have returned true due to some invalid decl
3059 // during template instantiation, but ToType may be complete enough now
3060 // to try to recover.
3061 if (ToType->isIncompleteType()) {
3062 // We're not going to find any constructors.
3063 } else if (CXXRecordDecl *ToRecordDecl
3064 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3066 Expr **Args = &From;
3067 unsigned NumArgs = 1;
3068 bool ListInitializing = false;
3069 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3070 // But first, see if there is an init-list-contructor that will work.
3071 OverloadingResult Result = IsInitializerListConstructorConversion(
3072 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3073 if (Result != OR_No_Viable_Function)
3076 CandidateSet.clear();
3078 // If we're list-initializing, we pass the individual elements as
3079 // arguments, not the entire list.
3080 Args = InitList->getInits();
3081 NumArgs = InitList->getNumInits();
3082 ListInitializing = true;
3085 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3086 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3087 Con != ConEnd; ++Con) {
3088 NamedDecl *D = *Con;
3089 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3091 // Find the constructor (which may be a template).
3092 CXXConstructorDecl *Constructor = 0;
3093 FunctionTemplateDecl *ConstructorTmpl
3094 = dyn_cast<FunctionTemplateDecl>(D);
3095 if (ConstructorTmpl)
3097 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3099 Constructor = cast<CXXConstructorDecl>(D);
3101 bool Usable = !Constructor->isInvalidDecl();
3102 if (ListInitializing)
3103 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3105 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3107 bool SuppressUserConversions = !ConstructorsOnly;
3108 if (SuppressUserConversions && ListInitializing) {
3109 SuppressUserConversions = false;
3111 // If the first argument is (a reference to) the target type,
3112 // suppress conversions.
3113 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3114 S.Context, Constructor, ToType);
3117 if (ConstructorTmpl)
3118 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3120 llvm::makeArrayRef(Args, NumArgs),
3121 CandidateSet, SuppressUserConversions);
3123 // Allow one user-defined conversion when user specifies a
3124 // From->ToType conversion via an static cast (c-style, etc).
3125 S.AddOverloadCandidate(Constructor, FoundDecl,
3126 llvm::makeArrayRef(Args, NumArgs),
3127 CandidateSet, SuppressUserConversions);
3133 // Enumerate conversion functions, if we're allowed to.
3134 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3135 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3136 // No conversion functions from incomplete types.
3137 } else if (const RecordType *FromRecordType
3138 = From->getType()->getAs<RecordType>()) {
3139 if (CXXRecordDecl *FromRecordDecl
3140 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3141 // Add all of the conversion functions as candidates.
3142 std::pair<CXXRecordDecl::conversion_iterator,
3143 CXXRecordDecl::conversion_iterator>
3144 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3145 for (CXXRecordDecl::conversion_iterator
3146 I = Conversions.first, E = Conversions.second; I != E; ++I) {
3147 DeclAccessPair FoundDecl = I.getPair();
3148 NamedDecl *D = FoundDecl.getDecl();
3149 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3150 if (isa<UsingShadowDecl>(D))
3151 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3153 CXXConversionDecl *Conv;
3154 FunctionTemplateDecl *ConvTemplate;
3155 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3156 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3158 Conv = cast<CXXConversionDecl>(D);
3160 if (AllowExplicit || !Conv->isExplicit()) {
3162 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3163 ActingContext, From, ToType,
3166 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3167 From, ToType, CandidateSet);
3173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3175 OverloadCandidateSet::iterator Best;
3176 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3178 // Record the standard conversion we used and the conversion function.
3179 if (CXXConstructorDecl *Constructor
3180 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3181 // C++ [over.ics.user]p1:
3182 // If the user-defined conversion is specified by a
3183 // constructor (12.3.1), the initial standard conversion
3184 // sequence converts the source type to the type required by
3185 // the argument of the constructor.
3187 QualType ThisType = Constructor->getThisType(S.Context);
3188 if (isa<InitListExpr>(From)) {
3189 // Initializer lists don't have conversions as such.
3190 User.Before.setAsIdentityConversion();
3192 if (Best->Conversions[0].isEllipsis())
3193 User.EllipsisConversion = true;
3195 User.Before = Best->Conversions[0].Standard;
3196 User.EllipsisConversion = false;
3199 User.HadMultipleCandidates = HadMultipleCandidates;
3200 User.ConversionFunction = Constructor;
3201 User.FoundConversionFunction = Best->FoundDecl;
3202 User.After.setAsIdentityConversion();
3203 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3204 User.After.setAllToTypes(ToType);
3207 if (CXXConversionDecl *Conversion
3208 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3209 // C++ [over.ics.user]p1:
3211 // [...] If the user-defined conversion is specified by a
3212 // conversion function (12.3.2), the initial standard
3213 // conversion sequence converts the source type to the
3214 // implicit object parameter of the conversion function.
3215 User.Before = Best->Conversions[0].Standard;
3216 User.HadMultipleCandidates = HadMultipleCandidates;
3217 User.ConversionFunction = Conversion;
3218 User.FoundConversionFunction = Best->FoundDecl;
3219 User.EllipsisConversion = false;
3221 // C++ [over.ics.user]p2:
3222 // The second standard conversion sequence converts the
3223 // result of the user-defined conversion to the target type
3224 // for the sequence. Since an implicit conversion sequence
3225 // is an initialization, the special rules for
3226 // initialization by user-defined conversion apply when
3227 // selecting the best user-defined conversion for a
3228 // user-defined conversion sequence (see 13.3.3 and
3230 User.After = Best->FinalConversion;
3233 llvm_unreachable("Not a constructor or conversion function?");
3235 case OR_No_Viable_Function:
3236 return OR_No_Viable_Function;
3238 // No conversion here! We're done.
3242 return OR_Ambiguous;
3245 llvm_unreachable("Invalid OverloadResult!");
3249 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3250 ImplicitConversionSequence ICS;
3251 OverloadCandidateSet CandidateSet(From->getExprLoc());
3252 OverloadingResult OvResult =
3253 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3254 CandidateSet, false);
3255 if (OvResult == OR_Ambiguous)
3256 Diag(From->getLocStart(),
3257 diag::err_typecheck_ambiguous_condition)
3258 << From->getType() << ToType << From->getSourceRange();
3259 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3260 Diag(From->getLocStart(),
3261 diag::err_typecheck_nonviable_condition)
3262 << From->getType() << ToType << From->getSourceRange();
3265 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3269 /// \brief Compare the user-defined conversion functions or constructors
3270 /// of two user-defined conversion sequences to determine whether any ordering
3272 static ImplicitConversionSequence::CompareKind
3273 compareConversionFunctions(Sema &S,
3274 FunctionDecl *Function1,
3275 FunctionDecl *Function2) {
3276 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3277 return ImplicitConversionSequence::Indistinguishable;
3280 // If both conversion functions are implicitly-declared conversions from
3281 // a lambda closure type to a function pointer and a block pointer,
3282 // respectively, always prefer the conversion to a function pointer,
3283 // because the function pointer is more lightweight and is more likely
3284 // to keep code working.
3285 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3287 return ImplicitConversionSequence::Indistinguishable;
3289 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3291 return ImplicitConversionSequence::Indistinguishable;
3293 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3294 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3295 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3296 if (Block1 != Block2)
3297 return Block1? ImplicitConversionSequence::Worse
3298 : ImplicitConversionSequence::Better;
3301 return ImplicitConversionSequence::Indistinguishable;
3304 /// CompareImplicitConversionSequences - Compare two implicit
3305 /// conversion sequences to determine whether one is better than the
3306 /// other or if they are indistinguishable (C++ 13.3.3.2).
3307 static ImplicitConversionSequence::CompareKind
3308 CompareImplicitConversionSequences(Sema &S,
3309 const ImplicitConversionSequence& ICS1,
3310 const ImplicitConversionSequence& ICS2)
3312 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3313 // conversion sequences (as defined in 13.3.3.1)
3314 // -- a standard conversion sequence (13.3.3.1.1) is a better
3315 // conversion sequence than a user-defined conversion sequence or
3316 // an ellipsis conversion sequence, and
3317 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3318 // conversion sequence than an ellipsis conversion sequence
3321 // C++0x [over.best.ics]p10:
3322 // For the purpose of ranking implicit conversion sequences as
3323 // described in 13.3.3.2, the ambiguous conversion sequence is
3324 // treated as a user-defined sequence that is indistinguishable
3325 // from any other user-defined conversion sequence.
3326 if (ICS1.getKindRank() < ICS2.getKindRank())
3327 return ImplicitConversionSequence::Better;
3328 if (ICS2.getKindRank() < ICS1.getKindRank())
3329 return ImplicitConversionSequence::Worse;
3331 // The following checks require both conversion sequences to be of
3333 if (ICS1.getKind() != ICS2.getKind())
3334 return ImplicitConversionSequence::Indistinguishable;
3336 ImplicitConversionSequence::CompareKind Result =
3337 ImplicitConversionSequence::Indistinguishable;
3339 // Two implicit conversion sequences of the same form are
3340 // indistinguishable conversion sequences unless one of the
3341 // following rules apply: (C++ 13.3.3.2p3):
3342 if (ICS1.isStandard())
3343 Result = CompareStandardConversionSequences(S,
3344 ICS1.Standard, ICS2.Standard);
3345 else if (ICS1.isUserDefined()) {
3346 // User-defined conversion sequence U1 is a better conversion
3347 // sequence than another user-defined conversion sequence U2 if
3348 // they contain the same user-defined conversion function or
3349 // constructor and if the second standard conversion sequence of
3350 // U1 is better than the second standard conversion sequence of
3351 // U2 (C++ 13.3.3.2p3).
3352 if (ICS1.UserDefined.ConversionFunction ==
3353 ICS2.UserDefined.ConversionFunction)
3354 Result = CompareStandardConversionSequences(S,
3355 ICS1.UserDefined.After,
3356 ICS2.UserDefined.After);
3358 Result = compareConversionFunctions(S,
3359 ICS1.UserDefined.ConversionFunction,
3360 ICS2.UserDefined.ConversionFunction);
3363 // List-initialization sequence L1 is a better conversion sequence than
3364 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3365 // for some X and L2 does not.
3366 if (Result == ImplicitConversionSequence::Indistinguishable &&
3368 ICS1.isListInitializationSequence() &&
3369 ICS2.isListInitializationSequence()) {
3370 if (ICS1.isStdInitializerListElement() &&
3371 !ICS2.isStdInitializerListElement())
3372 return ImplicitConversionSequence::Better;
3373 if (!ICS1.isStdInitializerListElement() &&
3374 ICS2.isStdInitializerListElement())
3375 return ImplicitConversionSequence::Worse;
3381 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3382 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3384 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3385 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3388 return Context.hasSameUnqualifiedType(T1, T2);
3391 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3392 // determine if one is a proper subset of the other.
3393 static ImplicitConversionSequence::CompareKind
3394 compareStandardConversionSubsets(ASTContext &Context,
3395 const StandardConversionSequence& SCS1,
3396 const StandardConversionSequence& SCS2) {
3397 ImplicitConversionSequence::CompareKind Result
3398 = ImplicitConversionSequence::Indistinguishable;
3400 // the identity conversion sequence is considered to be a subsequence of
3401 // any non-identity conversion sequence
3402 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3403 return ImplicitConversionSequence::Better;
3404 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3405 return ImplicitConversionSequence::Worse;
3407 if (SCS1.Second != SCS2.Second) {
3408 if (SCS1.Second == ICK_Identity)
3409 Result = ImplicitConversionSequence::Better;
3410 else if (SCS2.Second == ICK_Identity)
3411 Result = ImplicitConversionSequence::Worse;
3413 return ImplicitConversionSequence::Indistinguishable;
3414 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3415 return ImplicitConversionSequence::Indistinguishable;
3417 if (SCS1.Third == SCS2.Third) {
3418 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3419 : ImplicitConversionSequence::Indistinguishable;
3422 if (SCS1.Third == ICK_Identity)
3423 return Result == ImplicitConversionSequence::Worse
3424 ? ImplicitConversionSequence::Indistinguishable
3425 : ImplicitConversionSequence::Better;
3427 if (SCS2.Third == ICK_Identity)
3428 return Result == ImplicitConversionSequence::Better
3429 ? ImplicitConversionSequence::Indistinguishable
3430 : ImplicitConversionSequence::Worse;
3432 return ImplicitConversionSequence::Indistinguishable;
3435 /// \brief Determine whether one of the given reference bindings is better
3436 /// than the other based on what kind of bindings they are.
3437 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3438 const StandardConversionSequence &SCS2) {
3439 // C++0x [over.ics.rank]p3b4:
3440 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3441 // implicit object parameter of a non-static member function declared
3442 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3443 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3444 // lvalue reference to a function lvalue and S2 binds an rvalue
3447 // FIXME: Rvalue references. We're going rogue with the above edits,
3448 // because the semantics in the current C++0x working paper (N3225 at the
3449 // time of this writing) break the standard definition of std::forward
3450 // and std::reference_wrapper when dealing with references to functions.
3451 // Proposed wording changes submitted to CWG for consideration.
3452 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3453 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3456 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3457 SCS2.IsLvalueReference) ||
3458 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3459 !SCS2.IsLvalueReference);
3462 /// CompareStandardConversionSequences - Compare two standard
3463 /// conversion sequences to determine whether one is better than the
3464 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3465 static ImplicitConversionSequence::CompareKind
3466 CompareStandardConversionSequences(Sema &S,
3467 const StandardConversionSequence& SCS1,
3468 const StandardConversionSequence& SCS2)
3470 // Standard conversion sequence S1 is a better conversion sequence
3471 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3473 // -- S1 is a proper subsequence of S2 (comparing the conversion
3474 // sequences in the canonical form defined by 13.3.3.1.1,
3475 // excluding any Lvalue Transformation; the identity conversion
3476 // sequence is considered to be a subsequence of any
3477 // non-identity conversion sequence) or, if not that,
3478 if (ImplicitConversionSequence::CompareKind CK
3479 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3482 // -- the rank of S1 is better than the rank of S2 (by the rules
3483 // defined below), or, if not that,
3484 ImplicitConversionRank Rank1 = SCS1.getRank();
3485 ImplicitConversionRank Rank2 = SCS2.getRank();
3487 return ImplicitConversionSequence::Better;
3488 else if (Rank2 < Rank1)
3489 return ImplicitConversionSequence::Worse;
3491 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3492 // are indistinguishable unless one of the following rules
3495 // A conversion that is not a conversion of a pointer, or
3496 // pointer to member, to bool is better than another conversion
3497 // that is such a conversion.
3498 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3499 return SCS2.isPointerConversionToBool()
3500 ? ImplicitConversionSequence::Better
3501 : ImplicitConversionSequence::Worse;
3503 // C++ [over.ics.rank]p4b2:
3505 // If class B is derived directly or indirectly from class A,
3506 // conversion of B* to A* is better than conversion of B* to
3507 // void*, and conversion of A* to void* is better than conversion
3509 bool SCS1ConvertsToVoid
3510 = SCS1.isPointerConversionToVoidPointer(S.Context);
3511 bool SCS2ConvertsToVoid
3512 = SCS2.isPointerConversionToVoidPointer(S.Context);
3513 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3514 // Exactly one of the conversion sequences is a conversion to
3515 // a void pointer; it's the worse conversion.
3516 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3517 : ImplicitConversionSequence::Worse;
3518 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3519 // Neither conversion sequence converts to a void pointer; compare
3520 // their derived-to-base conversions.
3521 if (ImplicitConversionSequence::CompareKind DerivedCK
3522 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3524 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3525 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3526 // Both conversion sequences are conversions to void
3527 // pointers. Compare the source types to determine if there's an
3528 // inheritance relationship in their sources.
3529 QualType FromType1 = SCS1.getFromType();
3530 QualType FromType2 = SCS2.getFromType();
3532 // Adjust the types we're converting from via the array-to-pointer
3533 // conversion, if we need to.
3534 if (SCS1.First == ICK_Array_To_Pointer)
3535 FromType1 = S.Context.getArrayDecayedType(FromType1);
3536 if (SCS2.First == ICK_Array_To_Pointer)
3537 FromType2 = S.Context.getArrayDecayedType(FromType2);
3539 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3540 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3542 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3543 return ImplicitConversionSequence::Better;
3544 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3545 return ImplicitConversionSequence::Worse;
3547 // Objective-C++: If one interface is more specific than the
3548 // other, it is the better one.
3549 const ObjCObjectPointerType* FromObjCPtr1
3550 = FromType1->getAs<ObjCObjectPointerType>();
3551 const ObjCObjectPointerType* FromObjCPtr2
3552 = FromType2->getAs<ObjCObjectPointerType>();
3553 if (FromObjCPtr1 && FromObjCPtr2) {
3554 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3556 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3558 if (AssignLeft != AssignRight) {
3559 return AssignLeft? ImplicitConversionSequence::Better
3560 : ImplicitConversionSequence::Worse;
3565 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3567 if (ImplicitConversionSequence::CompareKind QualCK
3568 = CompareQualificationConversions(S, SCS1, SCS2))
3571 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3572 // Check for a better reference binding based on the kind of bindings.
3573 if (isBetterReferenceBindingKind(SCS1, SCS2))
3574 return ImplicitConversionSequence::Better;
3575 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3576 return ImplicitConversionSequence::Worse;
3578 // C++ [over.ics.rank]p3b4:
3579 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3580 // which the references refer are the same type except for
3581 // top-level cv-qualifiers, and the type to which the reference
3582 // initialized by S2 refers is more cv-qualified than the type
3583 // to which the reference initialized by S1 refers.
3584 QualType T1 = SCS1.getToType(2);
3585 QualType T2 = SCS2.getToType(2);
3586 T1 = S.Context.getCanonicalType(T1);
3587 T2 = S.Context.getCanonicalType(T2);
3588 Qualifiers T1Quals, T2Quals;
3589 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3590 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3591 if (UnqualT1 == UnqualT2) {
3592 // Objective-C++ ARC: If the references refer to objects with different
3593 // lifetimes, prefer bindings that don't change lifetime.
3594 if (SCS1.ObjCLifetimeConversionBinding !=
3595 SCS2.ObjCLifetimeConversionBinding) {
3596 return SCS1.ObjCLifetimeConversionBinding
3597 ? ImplicitConversionSequence::Worse
3598 : ImplicitConversionSequence::Better;
3601 // If the type is an array type, promote the element qualifiers to the
3602 // type for comparison.
3603 if (isa<ArrayType>(T1) && T1Quals)
3604 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3605 if (isa<ArrayType>(T2) && T2Quals)
3606 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3607 if (T2.isMoreQualifiedThan(T1))
3608 return ImplicitConversionSequence::Better;
3609 else if (T1.isMoreQualifiedThan(T2))
3610 return ImplicitConversionSequence::Worse;
3614 // In Microsoft mode, prefer an integral conversion to a
3615 // floating-to-integral conversion if the integral conversion
3616 // is between types of the same size.
3624 // Here, MSVC will call f(int) instead of generating a compile error
3625 // as clang will do in standard mode.
3626 if (S.getLangOpts().MicrosoftMode &&
3627 SCS1.Second == ICK_Integral_Conversion &&
3628 SCS2.Second == ICK_Floating_Integral &&
3629 S.Context.getTypeSize(SCS1.getFromType()) ==
3630 S.Context.getTypeSize(SCS1.getToType(2)))
3631 return ImplicitConversionSequence::Better;
3633 return ImplicitConversionSequence::Indistinguishable;
3636 /// CompareQualificationConversions - Compares two standard conversion
3637 /// sequences to determine whether they can be ranked based on their
3638 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3639 ImplicitConversionSequence::CompareKind
3640 CompareQualificationConversions(Sema &S,
3641 const StandardConversionSequence& SCS1,
3642 const StandardConversionSequence& SCS2) {
3644 // -- S1 and S2 differ only in their qualification conversion and
3645 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3646 // cv-qualification signature of type T1 is a proper subset of
3647 // the cv-qualification signature of type T2, and S1 is not the
3648 // deprecated string literal array-to-pointer conversion (4.2).
3649 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3650 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3651 return ImplicitConversionSequence::Indistinguishable;
3653 // FIXME: the example in the standard doesn't use a qualification
3655 QualType T1 = SCS1.getToType(2);
3656 QualType T2 = SCS2.getToType(2);
3657 T1 = S.Context.getCanonicalType(T1);
3658 T2 = S.Context.getCanonicalType(T2);
3659 Qualifiers T1Quals, T2Quals;
3660 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3661 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3663 // If the types are the same, we won't learn anything by unwrapped
3665 if (UnqualT1 == UnqualT2)
3666 return ImplicitConversionSequence::Indistinguishable;
3668 // If the type is an array type, promote the element qualifiers to the type
3670 if (isa<ArrayType>(T1) && T1Quals)
3671 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3672 if (isa<ArrayType>(T2) && T2Quals)
3673 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3675 ImplicitConversionSequence::CompareKind Result
3676 = ImplicitConversionSequence::Indistinguishable;
3678 // Objective-C++ ARC:
3679 // Prefer qualification conversions not involving a change in lifetime
3680 // to qualification conversions that do not change lifetime.
3681 if (SCS1.QualificationIncludesObjCLifetime !=
3682 SCS2.QualificationIncludesObjCLifetime) {
3683 Result = SCS1.QualificationIncludesObjCLifetime
3684 ? ImplicitConversionSequence::Worse
3685 : ImplicitConversionSequence::Better;
3688 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3689 // Within each iteration of the loop, we check the qualifiers to
3690 // determine if this still looks like a qualification
3691 // conversion. Then, if all is well, we unwrap one more level of
3692 // pointers or pointers-to-members and do it all again
3693 // until there are no more pointers or pointers-to-members left
3694 // to unwrap. This essentially mimics what
3695 // IsQualificationConversion does, but here we're checking for a
3696 // strict subset of qualifiers.
3697 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3698 // The qualifiers are the same, so this doesn't tell us anything
3699 // about how the sequences rank.
3701 else if (T2.isMoreQualifiedThan(T1)) {
3702 // T1 has fewer qualifiers, so it could be the better sequence.
3703 if (Result == ImplicitConversionSequence::Worse)
3704 // Neither has qualifiers that are a subset of the other's
3706 return ImplicitConversionSequence::Indistinguishable;
3708 Result = ImplicitConversionSequence::Better;
3709 } else if (T1.isMoreQualifiedThan(T2)) {
3710 // T2 has fewer qualifiers, so it could be the better sequence.
3711 if (Result == ImplicitConversionSequence::Better)
3712 // Neither has qualifiers that are a subset of the other's
3714 return ImplicitConversionSequence::Indistinguishable;
3716 Result = ImplicitConversionSequence::Worse;
3718 // Qualifiers are disjoint.
3719 return ImplicitConversionSequence::Indistinguishable;
3722 // If the types after this point are equivalent, we're done.
3723 if (S.Context.hasSameUnqualifiedType(T1, T2))
3727 // Check that the winning standard conversion sequence isn't using
3728 // the deprecated string literal array to pointer conversion.
3730 case ImplicitConversionSequence::Better:
3731 if (SCS1.DeprecatedStringLiteralToCharPtr)
3732 Result = ImplicitConversionSequence::Indistinguishable;
3735 case ImplicitConversionSequence::Indistinguishable:
3738 case ImplicitConversionSequence::Worse:
3739 if (SCS2.DeprecatedStringLiteralToCharPtr)
3740 Result = ImplicitConversionSequence::Indistinguishable;
3747 /// CompareDerivedToBaseConversions - Compares two standard conversion
3748 /// sequences to determine whether they can be ranked based on their
3749 /// various kinds of derived-to-base conversions (C++
3750 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3751 /// conversions between Objective-C interface types.
3752 ImplicitConversionSequence::CompareKind
3753 CompareDerivedToBaseConversions(Sema &S,
3754 const StandardConversionSequence& SCS1,
3755 const StandardConversionSequence& SCS2) {
3756 QualType FromType1 = SCS1.getFromType();
3757 QualType ToType1 = SCS1.getToType(1);
3758 QualType FromType2 = SCS2.getFromType();
3759 QualType ToType2 = SCS2.getToType(1);
3761 // Adjust the types we're converting from via the array-to-pointer
3762 // conversion, if we need to.
3763 if (SCS1.First == ICK_Array_To_Pointer)
3764 FromType1 = S.Context.getArrayDecayedType(FromType1);
3765 if (SCS2.First == ICK_Array_To_Pointer)
3766 FromType2 = S.Context.getArrayDecayedType(FromType2);
3768 // Canonicalize all of the types.
3769 FromType1 = S.Context.getCanonicalType(FromType1);
3770 ToType1 = S.Context.getCanonicalType(ToType1);
3771 FromType2 = S.Context.getCanonicalType(FromType2);
3772 ToType2 = S.Context.getCanonicalType(ToType2);
3774 // C++ [over.ics.rank]p4b3:
3776 // If class B is derived directly or indirectly from class A and
3777 // class C is derived directly or indirectly from B,
3779 // Compare based on pointer conversions.
3780 if (SCS1.Second == ICK_Pointer_Conversion &&
3781 SCS2.Second == ICK_Pointer_Conversion &&
3782 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3783 FromType1->isPointerType() && FromType2->isPointerType() &&
3784 ToType1->isPointerType() && ToType2->isPointerType()) {
3785 QualType FromPointee1
3786 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3788 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3789 QualType FromPointee2
3790 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3792 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3794 // -- conversion of C* to B* is better than conversion of C* to A*,
3795 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3796 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3797 return ImplicitConversionSequence::Better;
3798 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3799 return ImplicitConversionSequence::Worse;
3802 // -- conversion of B* to A* is better than conversion of C* to A*,
3803 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3804 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3805 return ImplicitConversionSequence::Better;
3806 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3807 return ImplicitConversionSequence::Worse;
3809 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3810 SCS2.Second == ICK_Pointer_Conversion) {
3811 const ObjCObjectPointerType *FromPtr1
3812 = FromType1->getAs<ObjCObjectPointerType>();
3813 const ObjCObjectPointerType *FromPtr2
3814 = FromType2->getAs<ObjCObjectPointerType>();
3815 const ObjCObjectPointerType *ToPtr1
3816 = ToType1->getAs<ObjCObjectPointerType>();
3817 const ObjCObjectPointerType *ToPtr2
3818 = ToType2->getAs<ObjCObjectPointerType>();
3820 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3821 // Apply the same conversion ranking rules for Objective-C pointer types
3822 // that we do for C++ pointers to class types. However, we employ the
3823 // Objective-C pseudo-subtyping relationship used for assignment of
3824 // Objective-C pointer types.
3826 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3827 bool FromAssignRight
3828 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3830 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3832 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3834 // A conversion to an a non-id object pointer type or qualified 'id'
3835 // type is better than a conversion to 'id'.
3836 if (ToPtr1->isObjCIdType() &&
3837 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3838 return ImplicitConversionSequence::Worse;
3839 if (ToPtr2->isObjCIdType() &&
3840 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3841 return ImplicitConversionSequence::Better;
3843 // A conversion to a non-id object pointer type is better than a
3844 // conversion to a qualified 'id' type
3845 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3846 return ImplicitConversionSequence::Worse;
3847 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3848 return ImplicitConversionSequence::Better;
3850 // A conversion to an a non-Class object pointer type or qualified 'Class'
3851 // type is better than a conversion to 'Class'.
3852 if (ToPtr1->isObjCClassType() &&
3853 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3854 return ImplicitConversionSequence::Worse;
3855 if (ToPtr2->isObjCClassType() &&
3856 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3857 return ImplicitConversionSequence::Better;
3859 // A conversion to a non-Class object pointer type is better than a
3860 // conversion to a qualified 'Class' type.
3861 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3862 return ImplicitConversionSequence::Worse;
3863 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3864 return ImplicitConversionSequence::Better;
3866 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3867 if (S.Context.hasSameType(FromType1, FromType2) &&
3868 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3869 (ToAssignLeft != ToAssignRight))
3870 return ToAssignLeft? ImplicitConversionSequence::Worse
3871 : ImplicitConversionSequence::Better;
3873 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3874 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3875 (FromAssignLeft != FromAssignRight))
3876 return FromAssignLeft? ImplicitConversionSequence::Better
3877 : ImplicitConversionSequence::Worse;
3881 // Ranking of member-pointer types.
3882 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3883 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3884 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3885 const MemberPointerType * FromMemPointer1 =
3886 FromType1->getAs<MemberPointerType>();
3887 const MemberPointerType * ToMemPointer1 =
3888 ToType1->getAs<MemberPointerType>();
3889 const MemberPointerType * FromMemPointer2 =
3890 FromType2->getAs<MemberPointerType>();
3891 const MemberPointerType * ToMemPointer2 =
3892 ToType2->getAs<MemberPointerType>();
3893 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3894 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3895 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3896 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3897 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3898 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3899 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3900 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3901 // conversion of A::* to B::* is better than conversion of A::* to C::*,
3902 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3903 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3904 return ImplicitConversionSequence::Worse;
3905 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3906 return ImplicitConversionSequence::Better;
3908 // conversion of B::* to C::* is better than conversion of A::* to C::*
3909 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3910 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3911 return ImplicitConversionSequence::Better;
3912 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3913 return ImplicitConversionSequence::Worse;
3917 if (SCS1.Second == ICK_Derived_To_Base) {
3918 // -- conversion of C to B is better than conversion of C to A,
3919 // -- binding of an expression of type C to a reference of type
3920 // B& is better than binding an expression of type C to a
3921 // reference of type A&,
3922 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924 if (S.IsDerivedFrom(ToType1, ToType2))
3925 return ImplicitConversionSequence::Better;
3926 else if (S.IsDerivedFrom(ToType2, ToType1))
3927 return ImplicitConversionSequence::Worse;
3930 // -- conversion of B to A is better than conversion of C to A.
3931 // -- binding of an expression of type B to a reference of type
3932 // A& is better than binding an expression of type C to a
3933 // reference of type A&,
3934 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3935 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3936 if (S.IsDerivedFrom(FromType2, FromType1))
3937 return ImplicitConversionSequence::Better;
3938 else if (S.IsDerivedFrom(FromType1, FromType2))
3939 return ImplicitConversionSequence::Worse;
3943 return ImplicitConversionSequence::Indistinguishable;
3946 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3948 static bool isTypeValid(QualType T) {
3949 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3950 return !Record->isInvalidDecl();
3955 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3956 /// determine whether they are reference-related,
3957 /// reference-compatible, reference-compatible with added
3958 /// qualification, or incompatible, for use in C++ initialization by
3959 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3960 /// type, and the first type (T1) is the pointee type of the reference
3961 /// type being initialized.
3962 Sema::ReferenceCompareResult
3963 Sema::CompareReferenceRelationship(SourceLocation Loc,
3964 QualType OrigT1, QualType OrigT2,
3965 bool &DerivedToBase,
3966 bool &ObjCConversion,
3967 bool &ObjCLifetimeConversion) {
3968 assert(!OrigT1->isReferenceType() &&
3969 "T1 must be the pointee type of the reference type");
3970 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3972 QualType T1 = Context.getCanonicalType(OrigT1);
3973 QualType T2 = Context.getCanonicalType(OrigT2);
3974 Qualifiers T1Quals, T2Quals;
3975 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3976 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3978 // C++ [dcl.init.ref]p4:
3979 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3980 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3981 // T1 is a base class of T2.
3982 DerivedToBase = false;
3983 ObjCConversion = false;
3984 ObjCLifetimeConversion = false;
3985 if (UnqualT1 == UnqualT2) {
3987 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3988 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3989 IsDerivedFrom(UnqualT2, UnqualT1))
3990 DerivedToBase = true;
3991 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3992 UnqualT2->isObjCObjectOrInterfaceType() &&
3993 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3994 ObjCConversion = true;
3996 return Ref_Incompatible;
3998 // At this point, we know that T1 and T2 are reference-related (at
4001 // If the type is an array type, promote the element qualifiers to the type
4003 if (isa<ArrayType>(T1) && T1Quals)
4004 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4005 if (isa<ArrayType>(T2) && T2Quals)
4006 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4008 // C++ [dcl.init.ref]p4:
4009 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4010 // reference-related to T2 and cv1 is the same cv-qualification
4011 // as, or greater cv-qualification than, cv2. For purposes of
4012 // overload resolution, cases for which cv1 is greater
4013 // cv-qualification than cv2 are identified as
4014 // reference-compatible with added qualification (see 13.3.3.2).
4016 // Note that we also require equivalence of Objective-C GC and address-space
4017 // qualifiers when performing these computations, so that e.g., an int in
4018 // address space 1 is not reference-compatible with an int in address
4020 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4021 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4022 T1Quals.removeObjCLifetime();
4023 T2Quals.removeObjCLifetime();
4024 ObjCLifetimeConversion = true;
4027 if (T1Quals == T2Quals)
4028 return Ref_Compatible;
4029 else if (T1Quals.compatiblyIncludes(T2Quals))
4030 return Ref_Compatible_With_Added_Qualification;
4035 /// \brief Look for a user-defined conversion to an value reference-compatible
4036 /// with DeclType. Return true if something definite is found.
4038 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4039 QualType DeclType, SourceLocation DeclLoc,
4040 Expr *Init, QualType T2, bool AllowRvalues,
4041 bool AllowExplicit) {
4042 assert(T2->isRecordType() && "Can only find conversions of record types.");
4043 CXXRecordDecl *T2RecordDecl
4044 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4046 OverloadCandidateSet CandidateSet(DeclLoc);
4047 std::pair<CXXRecordDecl::conversion_iterator,
4048 CXXRecordDecl::conversion_iterator>
4049 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4050 for (CXXRecordDecl::conversion_iterator
4051 I = Conversions.first, E = Conversions.second; I != E; ++I) {
4053 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4054 if (isa<UsingShadowDecl>(D))
4055 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4057 FunctionTemplateDecl *ConvTemplate
4058 = dyn_cast<FunctionTemplateDecl>(D);
4059 CXXConversionDecl *Conv;
4061 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4063 Conv = cast<CXXConversionDecl>(D);
4065 // If this is an explicit conversion, and we're not allowed to consider
4066 // explicit conversions, skip it.
4067 if (!AllowExplicit && Conv->isExplicit())
4071 bool DerivedToBase = false;
4072 bool ObjCConversion = false;
4073 bool ObjCLifetimeConversion = false;
4075 // If we are initializing an rvalue reference, don't permit conversion
4076 // functions that return lvalues.
4077 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4078 const ReferenceType *RefType
4079 = Conv->getConversionType()->getAs<LValueReferenceType>();
4080 if (RefType && !RefType->getPointeeType()->isFunctionType())
4084 if (!ConvTemplate &&
4085 S.CompareReferenceRelationship(
4087 Conv->getConversionType().getNonReferenceType()
4088 .getUnqualifiedType(),
4089 DeclType.getNonReferenceType().getUnqualifiedType(),
4090 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4091 Sema::Ref_Incompatible)
4094 // If the conversion function doesn't return a reference type,
4095 // it can't be considered for this conversion. An rvalue reference
4096 // is only acceptable if its referencee is a function type.
4098 const ReferenceType *RefType =
4099 Conv->getConversionType()->getAs<ReferenceType>();
4101 (!RefType->isLValueReferenceType() &&
4102 !RefType->getPointeeType()->isFunctionType()))
4107 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4108 Init, DeclType, CandidateSet);
4110 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4111 DeclType, CandidateSet);
4114 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4116 OverloadCandidateSet::iterator Best;
4117 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4119 // C++ [over.ics.ref]p1:
4121 // [...] If the parameter binds directly to the result of
4122 // applying a conversion function to the argument
4123 // expression, the implicit conversion sequence is a
4124 // user-defined conversion sequence (13.3.3.1.2), with the
4125 // second standard conversion sequence either an identity
4126 // conversion or, if the conversion function returns an
4127 // entity of a type that is a derived class of the parameter
4128 // type, a derived-to-base Conversion.
4129 if (!Best->FinalConversion.DirectBinding)
4132 ICS.setUserDefined();
4133 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4134 ICS.UserDefined.After = Best->FinalConversion;
4135 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4136 ICS.UserDefined.ConversionFunction = Best->Function;
4137 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4138 ICS.UserDefined.EllipsisConversion = false;
4139 assert(ICS.UserDefined.After.ReferenceBinding &&
4140 ICS.UserDefined.After.DirectBinding &&
4141 "Expected a direct reference binding!");
4146 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4147 Cand != CandidateSet.end(); ++Cand)
4149 ICS.Ambiguous.addConversion(Cand->Function);
4152 case OR_No_Viable_Function:
4154 // There was no suitable conversion, or we found a deleted
4155 // conversion; continue with other checks.
4159 llvm_unreachable("Invalid OverloadResult!");
4162 /// \brief Compute an implicit conversion sequence for reference
4164 static ImplicitConversionSequence
4165 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4166 SourceLocation DeclLoc,
4167 bool SuppressUserConversions,
4168 bool AllowExplicit) {
4169 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4171 // Most paths end in a failed conversion.
4172 ImplicitConversionSequence ICS;
4173 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4175 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4176 QualType T2 = Init->getType();
4178 // If the initializer is the address of an overloaded function, try
4179 // to resolve the overloaded function. If all goes well, T2 is the
4180 // type of the resulting function.
4181 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4182 DeclAccessPair Found;
4183 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4188 // Compute some basic properties of the types and the initializer.
4189 bool isRValRef = DeclType->isRValueReferenceType();
4190 bool DerivedToBase = false;
4191 bool ObjCConversion = false;
4192 bool ObjCLifetimeConversion = false;
4193 Expr::Classification InitCategory = Init->Classify(S.Context);
4194 Sema::ReferenceCompareResult RefRelationship
4195 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4196 ObjCConversion, ObjCLifetimeConversion);
4199 // C++0x [dcl.init.ref]p5:
4200 // A reference to type "cv1 T1" is initialized by an expression
4201 // of type "cv2 T2" as follows:
4203 // -- If reference is an lvalue reference and the initializer expression
4205 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4206 // reference-compatible with "cv2 T2," or
4208 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4209 if (InitCategory.isLValue() &&
4210 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4211 // C++ [over.ics.ref]p1:
4212 // When a parameter of reference type binds directly (8.5.3)
4213 // to an argument expression, the implicit conversion sequence
4214 // is the identity conversion, unless the argument expression
4215 // has a type that is a derived class of the parameter type,
4216 // in which case the implicit conversion sequence is a
4217 // derived-to-base Conversion (13.3.3.1).
4219 ICS.Standard.First = ICK_Identity;
4220 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4221 : ObjCConversion? ICK_Compatible_Conversion
4223 ICS.Standard.Third = ICK_Identity;
4224 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4225 ICS.Standard.setToType(0, T2);
4226 ICS.Standard.setToType(1, T1);
4227 ICS.Standard.setToType(2, T1);
4228 ICS.Standard.ReferenceBinding = true;
4229 ICS.Standard.DirectBinding = true;
4230 ICS.Standard.IsLvalueReference = !isRValRef;
4231 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4232 ICS.Standard.BindsToRvalue = false;
4233 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4234 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4235 ICS.Standard.CopyConstructor = 0;
4237 // Nothing more to do: the inaccessibility/ambiguity check for
4238 // derived-to-base conversions is suppressed when we're
4239 // computing the implicit conversion sequence (C++
4240 // [over.best.ics]p2).
4244 // -- has a class type (i.e., T2 is a class type), where T1 is
4245 // not reference-related to T2, and can be implicitly
4246 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4247 // is reference-compatible with "cv3 T3" 92) (this
4248 // conversion is selected by enumerating the applicable
4249 // conversion functions (13.3.1.6) and choosing the best
4250 // one through overload resolution (13.3)),
4251 if (!SuppressUserConversions && T2->isRecordType() &&
4252 !S.RequireCompleteType(DeclLoc, T2, 0) &&
4253 RefRelationship == Sema::Ref_Incompatible) {
4254 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4255 Init, T2, /*AllowRvalues=*/false,
4261 // -- Otherwise, the reference shall be an lvalue reference to a
4262 // non-volatile const type (i.e., cv1 shall be const), or the reference
4263 // shall be an rvalue reference.
4265 // We actually handle one oddity of C++ [over.ics.ref] at this
4266 // point, which is that, due to p2 (which short-circuits reference
4267 // binding by only attempting a simple conversion for non-direct
4268 // bindings) and p3's strange wording, we allow a const volatile
4269 // reference to bind to an rvalue. Hence the check for the presence
4270 // of "const" rather than checking for "const" being the only
4272 // This is also the point where rvalue references and lvalue inits no longer
4274 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4277 // -- If the initializer expression
4279 // -- is an xvalue, class prvalue, array prvalue or function
4280 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4281 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4282 (InitCategory.isXValue() ||
4283 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4284 (InitCategory.isLValue() && T2->isFunctionType()))) {
4286 ICS.Standard.First = ICK_Identity;
4287 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4288 : ObjCConversion? ICK_Compatible_Conversion
4290 ICS.Standard.Third = ICK_Identity;
4291 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4292 ICS.Standard.setToType(0, T2);
4293 ICS.Standard.setToType(1, T1);
4294 ICS.Standard.setToType(2, T1);
4295 ICS.Standard.ReferenceBinding = true;
4296 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4297 // binding unless we're binding to a class prvalue.
4298 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4299 // allow the use of rvalue references in C++98/03 for the benefit of
4300 // standard library implementors; therefore, we need the xvalue check here.
4301 ICS.Standard.DirectBinding =
4302 S.getLangOpts().CPlusPlus11 ||
4303 (InitCategory.isPRValue() && !T2->isRecordType());
4304 ICS.Standard.IsLvalueReference = !isRValRef;
4305 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4306 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4307 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4308 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4309 ICS.Standard.CopyConstructor = 0;
4313 // -- has a class type (i.e., T2 is a class type), where T1 is not
4314 // reference-related to T2, and can be implicitly converted to
4315 // an xvalue, class prvalue, or function lvalue of type
4316 // "cv3 T3", where "cv1 T1" is reference-compatible with
4319 // then the reference is bound to the value of the initializer
4320 // expression in the first case and to the result of the conversion
4321 // in the second case (or, in either case, to an appropriate base
4322 // class subobject).
4323 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4324 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4325 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4326 Init, T2, /*AllowRvalues=*/true,
4328 // In the second case, if the reference is an rvalue reference
4329 // and the second standard conversion sequence of the
4330 // user-defined conversion sequence includes an lvalue-to-rvalue
4331 // conversion, the program is ill-formed.
4332 if (ICS.isUserDefined() && isRValRef &&
4333 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4334 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4339 // -- Otherwise, a temporary of type "cv1 T1" is created and
4340 // initialized from the initializer expression using the
4341 // rules for a non-reference copy initialization (8.5). The
4342 // reference is then bound to the temporary. If T1 is
4343 // reference-related to T2, cv1 must be the same
4344 // cv-qualification as, or greater cv-qualification than,
4345 // cv2; otherwise, the program is ill-formed.
4346 if (RefRelationship == Sema::Ref_Related) {
4347 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4348 // we would be reference-compatible or reference-compatible with
4349 // added qualification. But that wasn't the case, so the reference
4350 // initialization fails.
4352 // Note that we only want to check address spaces and cvr-qualifiers here.
4353 // ObjC GC and lifetime qualifiers aren't important.
4354 Qualifiers T1Quals = T1.getQualifiers();
4355 Qualifiers T2Quals = T2.getQualifiers();
4356 T1Quals.removeObjCGCAttr();
4357 T1Quals.removeObjCLifetime();
4358 T2Quals.removeObjCGCAttr();
4359 T2Quals.removeObjCLifetime();
4360 if (!T1Quals.compatiblyIncludes(T2Quals))
4364 // If at least one of the types is a class type, the types are not
4365 // related, and we aren't allowed any user conversions, the
4366 // reference binding fails. This case is important for breaking
4367 // recursion, since TryImplicitConversion below will attempt to
4368 // create a temporary through the use of a copy constructor.
4369 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4370 (T1->isRecordType() || T2->isRecordType()))
4373 // If T1 is reference-related to T2 and the reference is an rvalue
4374 // reference, the initializer expression shall not be an lvalue.
4375 if (RefRelationship >= Sema::Ref_Related &&
4376 isRValRef && Init->Classify(S.Context).isLValue())
4379 // C++ [over.ics.ref]p2:
4380 // When a parameter of reference type is not bound directly to
4381 // an argument expression, the conversion sequence is the one
4382 // required to convert the argument expression to the
4383 // underlying type of the reference according to
4384 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4385 // to copy-initializing a temporary of the underlying type with
4386 // the argument expression. Any difference in top-level
4387 // cv-qualification is subsumed by the initialization itself
4388 // and does not constitute a conversion.
4389 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4390 /*AllowExplicit=*/false,
4391 /*InOverloadResolution=*/false,
4393 /*AllowObjCWritebackConversion=*/false);
4395 // Of course, that's still a reference binding.
4396 if (ICS.isStandard()) {
4397 ICS.Standard.ReferenceBinding = true;
4398 ICS.Standard.IsLvalueReference = !isRValRef;
4399 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4400 ICS.Standard.BindsToRvalue = true;
4401 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4402 ICS.Standard.ObjCLifetimeConversionBinding = false;
4403 } else if (ICS.isUserDefined()) {
4404 // Don't allow rvalue references to bind to lvalues.
4405 if (DeclType->isRValueReferenceType()) {
4406 if (const ReferenceType *RefType
4407 = ICS.UserDefined.ConversionFunction->getResultType()
4408 ->getAs<LValueReferenceType>()) {
4409 if (!RefType->getPointeeType()->isFunctionType()) {
4410 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4417 ICS.UserDefined.After.ReferenceBinding = true;
4418 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4419 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4420 ICS.UserDefined.After.BindsToRvalue = true;
4421 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4422 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4428 static ImplicitConversionSequence
4429 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4430 bool SuppressUserConversions,
4431 bool InOverloadResolution,
4432 bool AllowObjCWritebackConversion,
4433 bool AllowExplicit = false);
4435 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4436 /// initializer list From.
4437 static ImplicitConversionSequence
4438 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4439 bool SuppressUserConversions,
4440 bool InOverloadResolution,
4441 bool AllowObjCWritebackConversion) {
4442 // C++11 [over.ics.list]p1:
4443 // When an argument is an initializer list, it is not an expression and
4444 // special rules apply for converting it to a parameter type.
4446 ImplicitConversionSequence Result;
4447 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4448 Result.setListInitializationSequence();
4450 // We need a complete type for what follows. Incomplete types can never be
4451 // initialized from init lists.
4452 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4455 // C++11 [over.ics.list]p2:
4456 // If the parameter type is std::initializer_list<X> or "array of X" and
4457 // all the elements can be implicitly converted to X, the implicit
4458 // conversion sequence is the worst conversion necessary to convert an
4459 // element of the list to X.
4460 bool toStdInitializerList = false;
4462 if (ToType->isArrayType())
4463 X = S.Context.getAsArrayType(ToType)->getElementType();
4465 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4467 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4468 Expr *Init = From->getInit(i);
4469 ImplicitConversionSequence ICS =
4470 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4471 InOverloadResolution,
4472 AllowObjCWritebackConversion);
4473 // If a single element isn't convertible, fail.
4478 // Otherwise, look for the worst conversion.
4479 if (Result.isBad() ||
4480 CompareImplicitConversionSequences(S, ICS, Result) ==
4481 ImplicitConversionSequence::Worse)
4485 // For an empty list, we won't have computed any conversion sequence.
4486 // Introduce the identity conversion sequence.
4487 if (From->getNumInits() == 0) {
4488 Result.setStandard();
4489 Result.Standard.setAsIdentityConversion();
4490 Result.Standard.setFromType(ToType);
4491 Result.Standard.setAllToTypes(ToType);
4494 Result.setListInitializationSequence();
4495 Result.setStdInitializerListElement(toStdInitializerList);
4499 // C++11 [over.ics.list]p3:
4500 // Otherwise, if the parameter is a non-aggregate class X and overload
4501 // resolution chooses a single best constructor [...] the implicit
4502 // conversion sequence is a user-defined conversion sequence. If multiple
4503 // constructors are viable but none is better than the others, the
4504 // implicit conversion sequence is a user-defined conversion sequence.
4505 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4506 // This function can deal with initializer lists.
4507 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4508 /*AllowExplicit=*/false,
4509 InOverloadResolution, /*CStyle=*/false,
4510 AllowObjCWritebackConversion);
4511 Result.setListInitializationSequence();
4515 // C++11 [over.ics.list]p4:
4516 // Otherwise, if the parameter has an aggregate type which can be
4517 // initialized from the initializer list [...] the implicit conversion
4518 // sequence is a user-defined conversion sequence.
4519 if (ToType->isAggregateType()) {
4520 // Type is an aggregate, argument is an init list. At this point it comes
4521 // down to checking whether the initialization works.
4522 // FIXME: Find out whether this parameter is consumed or not.
4523 InitializedEntity Entity =
4524 InitializedEntity::InitializeParameter(S.Context, ToType,
4525 /*Consumed=*/false);
4526 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4527 Result.setUserDefined();
4528 Result.UserDefined.Before.setAsIdentityConversion();
4529 // Initializer lists don't have a type.
4530 Result.UserDefined.Before.setFromType(QualType());
4531 Result.UserDefined.Before.setAllToTypes(QualType());
4533 Result.UserDefined.After.setAsIdentityConversion();
4534 Result.UserDefined.After.setFromType(ToType);
4535 Result.UserDefined.After.setAllToTypes(ToType);
4536 Result.UserDefined.ConversionFunction = 0;
4541 // C++11 [over.ics.list]p5:
4542 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4543 if (ToType->isReferenceType()) {
4544 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4545 // mention initializer lists in any way. So we go by what list-
4546 // initialization would do and try to extrapolate from that.
4548 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4550 // If the initializer list has a single element that is reference-related
4551 // to the parameter type, we initialize the reference from that.
4552 if (From->getNumInits() == 1) {
4553 Expr *Init = From->getInit(0);
4555 QualType T2 = Init->getType();
4557 // If the initializer is the address of an overloaded function, try
4558 // to resolve the overloaded function. If all goes well, T2 is the
4559 // type of the resulting function.
4560 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4561 DeclAccessPair Found;
4562 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4563 Init, ToType, false, Found))
4567 // Compute some basic properties of the types and the initializer.
4568 bool dummy1 = false;
4569 bool dummy2 = false;
4570 bool dummy3 = false;
4571 Sema::ReferenceCompareResult RefRelationship
4572 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4575 if (RefRelationship >= Sema::Ref_Related)
4576 return TryReferenceInit(S, Init, ToType,
4577 /*FIXME:*/From->getLocStart(),
4578 SuppressUserConversions,
4579 /*AllowExplicit=*/false);
4582 // Otherwise, we bind the reference to a temporary created from the
4583 // initializer list.
4584 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4585 InOverloadResolution,
4586 AllowObjCWritebackConversion);
4587 if (Result.isFailure())
4589 assert(!Result.isEllipsis() &&
4590 "Sub-initialization cannot result in ellipsis conversion.");
4592 // Can we even bind to a temporary?
4593 if (ToType->isRValueReferenceType() ||
4594 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4595 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4596 Result.UserDefined.After;
4597 SCS.ReferenceBinding = true;
4598 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4599 SCS.BindsToRvalue = true;
4600 SCS.BindsToFunctionLvalue = false;
4601 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4602 SCS.ObjCLifetimeConversionBinding = false;
4604 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4609 // C++11 [over.ics.list]p6:
4610 // Otherwise, if the parameter type is not a class:
4611 if (!ToType->isRecordType()) {
4612 // - if the initializer list has one element, the implicit conversion
4613 // sequence is the one required to convert the element to the
4615 unsigned NumInits = From->getNumInits();
4617 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4618 SuppressUserConversions,
4619 InOverloadResolution,
4620 AllowObjCWritebackConversion);
4621 // - if the initializer list has no elements, the implicit conversion
4622 // sequence is the identity conversion.
4623 else if (NumInits == 0) {
4624 Result.setStandard();
4625 Result.Standard.setAsIdentityConversion();
4626 Result.Standard.setFromType(ToType);
4627 Result.Standard.setAllToTypes(ToType);
4629 Result.setListInitializationSequence();
4633 // C++11 [over.ics.list]p7:
4634 // In all cases other than those enumerated above, no conversion is possible
4638 /// TryCopyInitialization - Try to copy-initialize a value of type
4639 /// ToType from the expression From. Return the implicit conversion
4640 /// sequence required to pass this argument, which may be a bad
4641 /// conversion sequence (meaning that the argument cannot be passed to
4642 /// a parameter of this type). If @p SuppressUserConversions, then we
4643 /// do not permit any user-defined conversion sequences.
4644 static ImplicitConversionSequence
4645 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4646 bool SuppressUserConversions,
4647 bool InOverloadResolution,
4648 bool AllowObjCWritebackConversion,
4649 bool AllowExplicit) {
4650 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4651 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4652 InOverloadResolution,AllowObjCWritebackConversion);
4654 if (ToType->isReferenceType())
4655 return TryReferenceInit(S, From, ToType,
4656 /*FIXME:*/From->getLocStart(),
4657 SuppressUserConversions,
4660 return TryImplicitConversion(S, From, ToType,
4661 SuppressUserConversions,
4662 /*AllowExplicit=*/false,
4663 InOverloadResolution,
4665 AllowObjCWritebackConversion);
4668 static bool TryCopyInitialization(const CanQualType FromQTy,
4669 const CanQualType ToQTy,
4672 ExprValueKind FromVK) {
4673 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4674 ImplicitConversionSequence ICS =
4675 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4677 return !ICS.isBad();
4680 /// TryObjectArgumentInitialization - Try to initialize the object
4681 /// parameter of the given member function (@c Method) from the
4682 /// expression @p From.
4683 static ImplicitConversionSequence
4684 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4685 Expr::Classification FromClassification,
4686 CXXMethodDecl *Method,
4687 CXXRecordDecl *ActingContext) {
4688 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4689 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4690 // const volatile object.
4691 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4692 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4693 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4695 // Set up the conversion sequence as a "bad" conversion, to allow us
4697 ImplicitConversionSequence ICS;
4699 // We need to have an object of class type.
4700 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4701 FromType = PT->getPointeeType();
4703 // When we had a pointer, it's implicitly dereferenced, so we
4704 // better have an lvalue.
4705 assert(FromClassification.isLValue());
4708 assert(FromType->isRecordType());
4710 // C++0x [over.match.funcs]p4:
4711 // For non-static member functions, the type of the implicit object
4714 // - "lvalue reference to cv X" for functions declared without a
4715 // ref-qualifier or with the & ref-qualifier
4716 // - "rvalue reference to cv X" for functions declared with the &&
4719 // where X is the class of which the function is a member and cv is the
4720 // cv-qualification on the member function declaration.
4722 // However, when finding an implicit conversion sequence for the argument, we
4723 // are not allowed to create temporaries or perform user-defined conversions
4724 // (C++ [over.match.funcs]p5). We perform a simplified version of
4725 // reference binding here, that allows class rvalues to bind to
4726 // non-constant references.
4728 // First check the qualifiers.
4729 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4730 if (ImplicitParamType.getCVRQualifiers()
4731 != FromTypeCanon.getLocalCVRQualifiers() &&
4732 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4733 ICS.setBad(BadConversionSequence::bad_qualifiers,
4734 FromType, ImplicitParamType);
4738 // Check that we have either the same type or a derived type. It
4739 // affects the conversion rank.
4740 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4741 ImplicitConversionKind SecondKind;
4742 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4743 SecondKind = ICK_Identity;
4744 } else if (S.IsDerivedFrom(FromType, ClassType))
4745 SecondKind = ICK_Derived_To_Base;
4747 ICS.setBad(BadConversionSequence::unrelated_class,
4748 FromType, ImplicitParamType);
4752 // Check the ref-qualifier.
4753 switch (Method->getRefQualifier()) {
4755 // Do nothing; we don't care about lvalueness or rvalueness.
4759 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4760 // non-const lvalue reference cannot bind to an rvalue
4761 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4768 if (!FromClassification.isRValue()) {
4769 // rvalue reference cannot bind to an lvalue
4770 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4777 // Success. Mark this as a reference binding.
4779 ICS.Standard.setAsIdentityConversion();
4780 ICS.Standard.Second = SecondKind;
4781 ICS.Standard.setFromType(FromType);
4782 ICS.Standard.setAllToTypes(ImplicitParamType);
4783 ICS.Standard.ReferenceBinding = true;
4784 ICS.Standard.DirectBinding = true;
4785 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4786 ICS.Standard.BindsToFunctionLvalue = false;
4787 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4788 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4789 = (Method->getRefQualifier() == RQ_None);
4793 /// PerformObjectArgumentInitialization - Perform initialization of
4794 /// the implicit object parameter for the given Method with the given
4797 Sema::PerformObjectArgumentInitialization(Expr *From,
4798 NestedNameSpecifier *Qualifier,
4799 NamedDecl *FoundDecl,
4800 CXXMethodDecl *Method) {
4801 QualType FromRecordType, DestType;
4802 QualType ImplicitParamRecordType =
4803 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4805 Expr::Classification FromClassification;
4806 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4807 FromRecordType = PT->getPointeeType();
4808 DestType = Method->getThisType(Context);
4809 FromClassification = Expr::Classification::makeSimpleLValue();
4811 FromRecordType = From->getType();
4812 DestType = ImplicitParamRecordType;
4813 FromClassification = From->Classify(Context);
4816 // Note that we always use the true parent context when performing
4817 // the actual argument initialization.
4818 ImplicitConversionSequence ICS
4819 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4820 Method, Method->getParent());
4822 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4823 Qualifiers FromQs = FromRecordType.getQualifiers();
4824 Qualifiers ToQs = DestType.getQualifiers();
4825 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4827 Diag(From->getLocStart(),
4828 diag::err_member_function_call_bad_cvr)
4829 << Method->getDeclName() << FromRecordType << (CVR - 1)
4830 << From->getSourceRange();
4831 Diag(Method->getLocation(), diag::note_previous_decl)
4832 << Method->getDeclName();
4837 return Diag(From->getLocStart(),
4838 diag::err_implicit_object_parameter_init)
4839 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4842 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4843 ExprResult FromRes =
4844 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4845 if (FromRes.isInvalid())
4847 From = FromRes.take();
4850 if (!Context.hasSameType(From->getType(), DestType))
4851 From = ImpCastExprToType(From, DestType, CK_NoOp,
4852 From->getValueKind()).take();
4856 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4857 /// expression From to bool (C++0x [conv]p3).
4858 static ImplicitConversionSequence
4859 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4860 // FIXME: This is pretty broken.
4861 return TryImplicitConversion(S, From, S.Context.BoolTy,
4862 // FIXME: Are these flags correct?
4863 /*SuppressUserConversions=*/false,
4864 /*AllowExplicit=*/true,
4865 /*InOverloadResolution=*/false,
4867 /*AllowObjCWritebackConversion=*/false);
4870 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4871 /// of the expression From to bool (C++0x [conv]p3).
4872 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4873 if (checkPlaceholderForOverload(*this, From))
4876 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4878 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4880 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4881 return Diag(From->getLocStart(),
4882 diag::err_typecheck_bool_condition)
4883 << From->getType() << From->getSourceRange();
4887 /// Check that the specified conversion is permitted in a converted constant
4888 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4890 static bool CheckConvertedConstantConversions(Sema &S,
4891 StandardConversionSequence &SCS) {
4892 // Since we know that the target type is an integral or unscoped enumeration
4893 // type, most conversion kinds are impossible. All possible First and Third
4894 // conversions are fine.
4895 switch (SCS.Second) {
4897 case ICK_Integral_Promotion:
4898 case ICK_Integral_Conversion:
4899 case ICK_Zero_Event_Conversion:
4902 case ICK_Boolean_Conversion:
4903 // Conversion from an integral or unscoped enumeration type to bool is
4904 // classified as ICK_Boolean_Conversion, but it's also an integral
4905 // conversion, so it's permitted in a converted constant expression.
4906 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4907 SCS.getToType(2)->isBooleanType();
4909 case ICK_Floating_Integral:
4910 case ICK_Complex_Real:
4913 case ICK_Lvalue_To_Rvalue:
4914 case ICK_Array_To_Pointer:
4915 case ICK_Function_To_Pointer:
4916 case ICK_NoReturn_Adjustment:
4917 case ICK_Qualification:
4918 case ICK_Compatible_Conversion:
4919 case ICK_Vector_Conversion:
4920 case ICK_Vector_Splat:
4921 case ICK_Derived_To_Base:
4922 case ICK_Pointer_Conversion:
4923 case ICK_Pointer_Member:
4924 case ICK_Block_Pointer_Conversion:
4925 case ICK_Writeback_Conversion:
4926 case ICK_Floating_Promotion:
4927 case ICK_Complex_Promotion:
4928 case ICK_Complex_Conversion:
4929 case ICK_Floating_Conversion:
4930 case ICK_TransparentUnionConversion:
4931 llvm_unreachable("unexpected second conversion kind");
4933 case ICK_Num_Conversion_Kinds:
4937 llvm_unreachable("unknown conversion kind");
4940 /// CheckConvertedConstantExpression - Check that the expression From is a
4941 /// converted constant expression of type T, perform the conversion and produce
4942 /// the converted expression, per C++11 [expr.const]p3.
4943 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4944 llvm::APSInt &Value,
4946 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4947 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4949 if (checkPlaceholderForOverload(*this, From))
4952 // C++11 [expr.const]p3 with proposed wording fixes:
4953 // A converted constant expression of type T is a core constant expression,
4954 // implicitly converted to a prvalue of type T, where the converted
4955 // expression is a literal constant expression and the implicit conversion
4956 // sequence contains only user-defined conversions, lvalue-to-rvalue
4957 // conversions, integral promotions, and integral conversions other than
4958 // narrowing conversions.
4959 ImplicitConversionSequence ICS =
4960 TryImplicitConversion(From, T,
4961 /*SuppressUserConversions=*/false,
4962 /*AllowExplicit=*/false,
4963 /*InOverloadResolution=*/false,
4965 /*AllowObjcWritebackConversion=*/false);
4966 StandardConversionSequence *SCS = 0;
4967 switch (ICS.getKind()) {
4968 case ImplicitConversionSequence::StandardConversion:
4969 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4970 return Diag(From->getLocStart(),
4971 diag::err_typecheck_converted_constant_expression_disallowed)
4972 << From->getType() << From->getSourceRange() << T;
4973 SCS = &ICS.Standard;
4975 case ImplicitConversionSequence::UserDefinedConversion:
4976 // We are converting from class type to an integral or enumeration type, so
4977 // the Before sequence must be trivial.
4978 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4979 return Diag(From->getLocStart(),
4980 diag::err_typecheck_converted_constant_expression_disallowed)
4981 << From->getType() << From->getSourceRange() << T;
4982 SCS = &ICS.UserDefined.After;
4984 case ImplicitConversionSequence::AmbiguousConversion:
4985 case ImplicitConversionSequence::BadConversion:
4986 if (!DiagnoseMultipleUserDefinedConversion(From, T))
4987 return Diag(From->getLocStart(),
4988 diag::err_typecheck_converted_constant_expression)
4989 << From->getType() << From->getSourceRange() << T;
4992 case ImplicitConversionSequence::EllipsisConversion:
4993 llvm_unreachable("ellipsis conversion in converted constant expression");
4996 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4997 if (Result.isInvalid())
5000 // Check for a narrowing implicit conversion.
5001 APValue PreNarrowingValue;
5002 QualType PreNarrowingType;
5003 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5004 PreNarrowingType)) {
5005 case NK_Variable_Narrowing:
5006 // Implicit conversion to a narrower type, and the value is not a constant
5007 // expression. We'll diagnose this in a moment.
5008 case NK_Not_Narrowing:
5011 case NK_Constant_Narrowing:
5012 Diag(From->getLocStart(),
5013 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5014 diag::err_cce_narrowing)
5015 << CCE << /*Constant*/1
5016 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5019 case NK_Type_Narrowing:
5020 Diag(From->getLocStart(),
5021 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5022 diag::err_cce_narrowing)
5023 << CCE << /*Constant*/0 << From->getType() << T;
5027 // Check the expression is a constant expression.
5028 SmallVector<PartialDiagnosticAt, 8> Notes;
5029 Expr::EvalResult Eval;
5032 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5033 // The expression can't be folded, so we can't keep it at this position in
5035 Result = ExprError();
5037 Value = Eval.Val.getInt();
5039 if (Notes.empty()) {
5040 // It's a constant expression.
5045 // It's not a constant expression. Produce an appropriate diagnostic.
5046 if (Notes.size() == 1 &&
5047 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5048 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5050 Diag(From->getLocStart(), diag::err_expr_not_cce)
5051 << CCE << From->getSourceRange();
5052 for (unsigned I = 0; I < Notes.size(); ++I)
5053 Diag(Notes[I].first, Notes[I].second);
5058 /// dropPointerConversions - If the given standard conversion sequence
5059 /// involves any pointer conversions, remove them. This may change
5060 /// the result type of the conversion sequence.
5061 static void dropPointerConversion(StandardConversionSequence &SCS) {
5062 if (SCS.Second == ICK_Pointer_Conversion) {
5063 SCS.Second = ICK_Identity;
5064 SCS.Third = ICK_Identity;
5065 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5069 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5070 /// convert the expression From to an Objective-C pointer type.
5071 static ImplicitConversionSequence
5072 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5073 // Do an implicit conversion to 'id'.
5074 QualType Ty = S.Context.getObjCIdType();
5075 ImplicitConversionSequence ICS
5076 = TryImplicitConversion(S, From, Ty,
5077 // FIXME: Are these flags correct?
5078 /*SuppressUserConversions=*/false,
5079 /*AllowExplicit=*/true,
5080 /*InOverloadResolution=*/false,
5082 /*AllowObjCWritebackConversion=*/false);
5084 // Strip off any final conversions to 'id'.
5085 switch (ICS.getKind()) {
5086 case ImplicitConversionSequence::BadConversion:
5087 case ImplicitConversionSequence::AmbiguousConversion:
5088 case ImplicitConversionSequence::EllipsisConversion:
5091 case ImplicitConversionSequence::UserDefinedConversion:
5092 dropPointerConversion(ICS.UserDefined.After);
5095 case ImplicitConversionSequence::StandardConversion:
5096 dropPointerConversion(ICS.Standard);
5103 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5104 /// conversion of the expression From to an Objective-C pointer type.
5105 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5106 if (checkPlaceholderForOverload(*this, From))
5109 QualType Ty = Context.getObjCIdType();
5110 ImplicitConversionSequence ICS =
5111 TryContextuallyConvertToObjCPointer(*this, From);
5113 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5117 /// Determine whether the provided type is an integral type, or an enumeration
5118 /// type of a permitted flavor.
5119 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5120 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5121 : T->isIntegralOrUnscopedEnumerationType();
5124 /// \brief Attempt to convert the given expression to an integral or
5125 /// enumeration type.
5127 /// This routine will attempt to convert an expression of class type to an
5128 /// integral or enumeration type, if that class type only has a single
5129 /// conversion to an integral or enumeration type.
5131 /// \param Loc The source location of the construct that requires the
5134 /// \param From The expression we're converting from.
5136 /// \param Diagnoser Used to output any diagnostics.
5138 /// \param AllowScopedEnumerations Specifies whether conversions to scoped
5139 /// enumerations should be considered.
5141 /// \returns The expression, converted to an integral or enumeration type if
5144 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5145 ICEConvertDiagnoser &Diagnoser,
5146 bool AllowScopedEnumerations) {
5147 // We can't perform any more checking for type-dependent expressions.
5148 if (From->isTypeDependent())
5151 // Process placeholders immediately.
5152 if (From->hasPlaceholderType()) {
5153 ExprResult result = CheckPlaceholderExpr(From);
5154 if (result.isInvalid()) return result;
5155 From = result.take();
5158 // If the expression already has integral or enumeration type, we're golden.
5159 QualType T = From->getType();
5160 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5161 return DefaultLvalueConversion(From);
5163 // FIXME: Check for missing '()' if T is a function type?
5165 // If we don't have a class type in C++, there's no way we can get an
5166 // expression of integral or enumeration type.
5167 const RecordType *RecordTy = T->getAs<RecordType>();
5168 if (!RecordTy || !getLangOpts().CPlusPlus) {
5169 if (!Diagnoser.Suppress)
5170 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5174 // We must have a complete class type.
5175 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5176 ICEConvertDiagnoser &Diagnoser;
5179 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5180 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5182 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5183 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5185 } IncompleteDiagnoser(Diagnoser, From);
5187 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5190 // Look for a conversion to an integral or enumeration type.
5191 UnresolvedSet<4> ViableConversions;
5192 UnresolvedSet<4> ExplicitConversions;
5193 std::pair<CXXRecordDecl::conversion_iterator,
5194 CXXRecordDecl::conversion_iterator> Conversions
5195 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5197 bool HadMultipleCandidates
5198 = (std::distance(Conversions.first, Conversions.second) > 1);
5200 for (CXXRecordDecl::conversion_iterator
5201 I = Conversions.first, E = Conversions.second; I != E; ++I) {
5202 if (CXXConversionDecl *Conversion
5203 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5204 if (isIntegralOrEnumerationType(
5205 Conversion->getConversionType().getNonReferenceType(),
5206 AllowScopedEnumerations)) {
5207 if (Conversion->isExplicit())
5208 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5210 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5215 switch (ViableConversions.size()) {
5217 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5218 DeclAccessPair Found = ExplicitConversions[0];
5219 CXXConversionDecl *Conversion
5220 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5222 // The user probably meant to invoke the given explicit
5223 // conversion; use it.
5225 = Conversion->getConversionType().getNonReferenceType();
5226 std::string TypeStr;
5227 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5229 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5230 << FixItHint::CreateInsertion(From->getLocStart(),
5231 "static_cast<" + TypeStr + ">(")
5232 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5234 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5236 // If we aren't in a SFINAE context, build a call to the
5237 // explicit conversion function.
5238 if (isSFINAEContext())
5241 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5242 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5243 HadMultipleCandidates);
5244 if (Result.isInvalid())
5246 // Record usage of conversion in an implicit cast.
5247 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5248 CK_UserDefinedConversion,
5250 Result.get()->getValueKind());
5253 // We'll complain below about a non-integral condition type.
5257 // Apply this conversion.
5258 DeclAccessPair Found = ViableConversions[0];
5259 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5261 CXXConversionDecl *Conversion
5262 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5264 = Conversion->getConversionType().getNonReferenceType();
5265 if (!Diagnoser.SuppressConversion) {
5266 if (isSFINAEContext())
5269 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5270 << From->getSourceRange();
5273 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5274 HadMultipleCandidates);
5275 if (Result.isInvalid())
5277 // Record usage of conversion in an implicit cast.
5278 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5279 CK_UserDefinedConversion,
5281 Result.get()->getValueKind());
5286 if (Diagnoser.Suppress)
5289 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5290 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5291 CXXConversionDecl *Conv
5292 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5293 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5294 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5299 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5300 !Diagnoser.Suppress) {
5301 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5302 << From->getSourceRange();
5305 return DefaultLvalueConversion(From);
5308 /// AddOverloadCandidate - Adds the given function to the set of
5309 /// candidate functions, using the given function call arguments. If
5310 /// @p SuppressUserConversions, then don't allow user-defined
5311 /// conversions via constructors or conversion operators.
5313 /// \param PartialOverloading true if we are performing "partial" overloading
5314 /// based on an incomplete set of function arguments. This feature is used by
5315 /// code completion.
5317 Sema::AddOverloadCandidate(FunctionDecl *Function,
5318 DeclAccessPair FoundDecl,
5319 ArrayRef<Expr *> Args,
5320 OverloadCandidateSet& CandidateSet,
5321 bool SuppressUserConversions,
5322 bool PartialOverloading,
5323 bool AllowExplicit) {
5324 const FunctionProtoType* Proto
5325 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5326 assert(Proto && "Functions without a prototype cannot be overloaded");
5327 assert(!Function->getDescribedFunctionTemplate() &&
5328 "Use AddTemplateOverloadCandidate for function templates");
5330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5331 if (!isa<CXXConstructorDecl>(Method)) {
5332 // If we get here, it's because we're calling a member function
5333 // that is named without a member access expression (e.g.,
5334 // "this->f") that was either written explicitly or created
5335 // implicitly. This can happen with a qualified call to a member
5336 // function, e.g., X::f(). We use an empty type for the implied
5337 // object argument (C++ [over.call.func]p3), and the acting context
5339 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5340 QualType(), Expr::Classification::makeSimpleLValue(),
5341 Args, CandidateSet, SuppressUserConversions);
5344 // We treat a constructor like a non-member function, since its object
5345 // argument doesn't participate in overload resolution.
5348 if (!CandidateSet.isNewCandidate(Function))
5351 // Overload resolution is always an unevaluated context.
5352 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5354 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5355 // C++ [class.copy]p3:
5356 // A member function template is never instantiated to perform the copy
5357 // of a class object to an object of its class type.
5358 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5359 if (Args.size() == 1 &&
5360 Constructor->isSpecializationCopyingObject() &&
5361 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5362 IsDerivedFrom(Args[0]->getType(), ClassType)))
5366 // Add this candidate
5367 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5368 Candidate.FoundDecl = FoundDecl;
5369 Candidate.Function = Function;
5370 Candidate.Viable = true;
5371 Candidate.IsSurrogate = false;
5372 Candidate.IgnoreObjectArgument = false;
5373 Candidate.ExplicitCallArguments = Args.size();
5375 unsigned NumArgsInProto = Proto->getNumArgs();
5377 // (C++ 13.3.2p2): A candidate function having fewer than m
5378 // parameters is viable only if it has an ellipsis in its parameter
5380 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5381 !Proto->isVariadic()) {
5382 Candidate.Viable = false;
5383 Candidate.FailureKind = ovl_fail_too_many_arguments;
5387 // (C++ 13.3.2p2): A candidate function having more than m parameters
5388 // is viable only if the (m+1)st parameter has a default argument
5389 // (8.3.6). For the purposes of overload resolution, the
5390 // parameter list is truncated on the right, so that there are
5391 // exactly m parameters.
5392 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5393 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5394 // Not enough arguments.
5395 Candidate.Viable = false;
5396 Candidate.FailureKind = ovl_fail_too_few_arguments;
5400 // (CUDA B.1): Check for invalid calls between targets.
5401 if (getLangOpts().CUDA)
5402 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5403 if (CheckCUDATarget(Caller, Function)) {
5404 Candidate.Viable = false;
5405 Candidate.FailureKind = ovl_fail_bad_target;
5409 // Determine the implicit conversion sequences for each of the
5411 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5412 if (ArgIdx < NumArgsInProto) {
5413 // (C++ 13.3.2p3): for F to be a viable function, there shall
5414 // exist for each argument an implicit conversion sequence
5415 // (13.3.3.1) that converts that argument to the corresponding
5417 QualType ParamType = Proto->getArgType(ArgIdx);
5418 Candidate.Conversions[ArgIdx]
5419 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5420 SuppressUserConversions,
5421 /*InOverloadResolution=*/true,
5422 /*AllowObjCWritebackConversion=*/
5423 getLangOpts().ObjCAutoRefCount,
5425 if (Candidate.Conversions[ArgIdx].isBad()) {
5426 Candidate.Viable = false;
5427 Candidate.FailureKind = ovl_fail_bad_conversion;
5431 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5432 // argument for which there is no corresponding parameter is
5433 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5434 Candidate.Conversions[ArgIdx].setEllipsis();
5439 /// \brief Add all of the function declarations in the given function set to
5440 /// the overload canddiate set.
5441 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5442 ArrayRef<Expr *> Args,
5443 OverloadCandidateSet& CandidateSet,
5444 bool SuppressUserConversions,
5445 TemplateArgumentListInfo *ExplicitTemplateArgs) {
5446 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5447 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5448 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5449 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5450 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5451 cast<CXXMethodDecl>(FD)->getParent(),
5452 Args[0]->getType(), Args[0]->Classify(Context),
5453 Args.slice(1), CandidateSet,
5454 SuppressUserConversions);
5456 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5457 SuppressUserConversions);
5459 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5460 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5461 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5462 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5463 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5464 ExplicitTemplateArgs,
5466 Args[0]->Classify(Context), Args.slice(1),
5467 CandidateSet, SuppressUserConversions);
5469 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5470 ExplicitTemplateArgs, Args,
5471 CandidateSet, SuppressUserConversions);
5476 /// AddMethodCandidate - Adds a named decl (which is some kind of
5477 /// method) as a method candidate to the given overload set.
5478 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5479 QualType ObjectType,
5480 Expr::Classification ObjectClassification,
5481 ArrayRef<Expr *> Args,
5482 OverloadCandidateSet& CandidateSet,
5483 bool SuppressUserConversions) {
5484 NamedDecl *Decl = FoundDecl.getDecl();
5485 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5487 if (isa<UsingShadowDecl>(Decl))
5488 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5490 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5491 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5492 "Expected a member function template");
5493 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5495 ObjectType, ObjectClassification,
5497 SuppressUserConversions);
5499 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5500 ObjectType, ObjectClassification,
5502 CandidateSet, SuppressUserConversions);
5506 /// AddMethodCandidate - Adds the given C++ member function to the set
5507 /// of candidate functions, using the given function call arguments
5508 /// and the object argument (@c Object). For example, in a call
5509 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5510 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5511 /// allow user-defined conversions via constructors or conversion
5514 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5515 CXXRecordDecl *ActingContext, QualType ObjectType,
5516 Expr::Classification ObjectClassification,
5517 ArrayRef<Expr *> Args,
5518 OverloadCandidateSet& CandidateSet,
5519 bool SuppressUserConversions) {
5520 const FunctionProtoType* Proto
5521 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5522 assert(Proto && "Methods without a prototype cannot be overloaded");
5523 assert(!isa<CXXConstructorDecl>(Method) &&
5524 "Use AddOverloadCandidate for constructors");
5526 if (!CandidateSet.isNewCandidate(Method))
5529 // Overload resolution is always an unevaluated context.
5530 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5532 // Add this candidate
5533 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5534 Candidate.FoundDecl = FoundDecl;
5535 Candidate.Function = Method;
5536 Candidate.IsSurrogate = false;
5537 Candidate.IgnoreObjectArgument = false;
5538 Candidate.ExplicitCallArguments = Args.size();
5540 unsigned NumArgsInProto = Proto->getNumArgs();
5542 // (C++ 13.3.2p2): A candidate function having fewer than m
5543 // parameters is viable only if it has an ellipsis in its parameter
5545 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5546 Candidate.Viable = false;
5547 Candidate.FailureKind = ovl_fail_too_many_arguments;
5551 // (C++ 13.3.2p2): A candidate function having more than m parameters
5552 // is viable only if the (m+1)st parameter has a default argument
5553 // (8.3.6). For the purposes of overload resolution, the
5554 // parameter list is truncated on the right, so that there are
5555 // exactly m parameters.
5556 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5557 if (Args.size() < MinRequiredArgs) {
5558 // Not enough arguments.
5559 Candidate.Viable = false;
5560 Candidate.FailureKind = ovl_fail_too_few_arguments;
5564 Candidate.Viable = true;
5566 if (Method->isStatic() || ObjectType.isNull())
5567 // The implicit object argument is ignored.
5568 Candidate.IgnoreObjectArgument = true;
5570 // Determine the implicit conversion sequence for the object
5572 Candidate.Conversions[0]
5573 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5574 Method, ActingContext);
5575 if (Candidate.Conversions[0].isBad()) {
5576 Candidate.Viable = false;
5577 Candidate.FailureKind = ovl_fail_bad_conversion;
5582 // Determine the implicit conversion sequences for each of the
5584 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5585 if (ArgIdx < NumArgsInProto) {
5586 // (C++ 13.3.2p3): for F to be a viable function, there shall
5587 // exist for each argument an implicit conversion sequence
5588 // (13.3.3.1) that converts that argument to the corresponding
5590 QualType ParamType = Proto->getArgType(ArgIdx);
5591 Candidate.Conversions[ArgIdx + 1]
5592 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5593 SuppressUserConversions,
5594 /*InOverloadResolution=*/true,
5595 /*AllowObjCWritebackConversion=*/
5596 getLangOpts().ObjCAutoRefCount);
5597 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5598 Candidate.Viable = false;
5599 Candidate.FailureKind = ovl_fail_bad_conversion;
5603 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5604 // argument for which there is no corresponding parameter is
5605 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5606 Candidate.Conversions[ArgIdx + 1].setEllipsis();
5611 /// \brief Add a C++ member function template as a candidate to the candidate
5612 /// set, using template argument deduction to produce an appropriate member
5613 /// function template specialization.
5615 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5616 DeclAccessPair FoundDecl,
5617 CXXRecordDecl *ActingContext,
5618 TemplateArgumentListInfo *ExplicitTemplateArgs,
5619 QualType ObjectType,
5620 Expr::Classification ObjectClassification,
5621 ArrayRef<Expr *> Args,
5622 OverloadCandidateSet& CandidateSet,
5623 bool SuppressUserConversions) {
5624 if (!CandidateSet.isNewCandidate(MethodTmpl))
5627 // C++ [over.match.funcs]p7:
5628 // In each case where a candidate is a function template, candidate
5629 // function template specializations are generated using template argument
5630 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
5631 // candidate functions in the usual way.113) A given name can refer to one
5632 // or more function templates and also to a set of overloaded non-template
5633 // functions. In such a case, the candidate functions generated from each
5634 // function template are combined with the set of non-template candidate
5636 TemplateDeductionInfo Info(CandidateSet.getLocation());
5637 FunctionDecl *Specialization = 0;
5638 if (TemplateDeductionResult Result
5639 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5640 Specialization, Info)) {
5641 OverloadCandidate &Candidate = CandidateSet.addCandidate();
5642 Candidate.FoundDecl = FoundDecl;
5643 Candidate.Function = MethodTmpl->getTemplatedDecl();
5644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_bad_deduction;
5646 Candidate.IsSurrogate = false;
5647 Candidate.IgnoreObjectArgument = false;
5648 Candidate.ExplicitCallArguments = Args.size();
5649 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5654 // Add the function template specialization produced by template argument
5655 // deduction as a candidate.
5656 assert(Specialization && "Missing member function template specialization?");
5657 assert(isa<CXXMethodDecl>(Specialization) &&
5658 "Specialization is not a member function?");
5659 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5660 ActingContext, ObjectType, ObjectClassification, Args,
5661 CandidateSet, SuppressUserConversions);
5664 /// \brief Add a C++ function template specialization as a candidate
5665 /// in the candidate set, using template argument deduction to produce
5666 /// an appropriate function template specialization.
5668 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5669 DeclAccessPair FoundDecl,
5670 TemplateArgumentListInfo *ExplicitTemplateArgs,
5671 ArrayRef<Expr *> Args,
5672 OverloadCandidateSet& CandidateSet,
5673 bool SuppressUserConversions) {
5674 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5677 // C++ [over.match.funcs]p7:
5678 // In each case where a candidate is a function template, candidate
5679 // function template specializations are generated using template argument
5680 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
5681 // candidate functions in the usual way.113) A given name can refer to one
5682 // or more function templates and also to a set of overloaded non-template
5683 // functions. In such a case, the candidate functions generated from each
5684 // function template are combined with the set of non-template candidate
5686 TemplateDeductionInfo Info(CandidateSet.getLocation());
5687 FunctionDecl *Specialization = 0;
5688 if (TemplateDeductionResult Result
5689 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5690 Specialization, Info)) {
5691 OverloadCandidate &Candidate = CandidateSet.addCandidate();
5692 Candidate.FoundDecl = FoundDecl;
5693 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5694 Candidate.Viable = false;
5695 Candidate.FailureKind = ovl_fail_bad_deduction;
5696 Candidate.IsSurrogate = false;
5697 Candidate.IgnoreObjectArgument = false;
5698 Candidate.ExplicitCallArguments = Args.size();
5699 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5704 // Add the function template specialization produced by template argument
5705 // deduction as a candidate.
5706 assert(Specialization && "Missing function template specialization?");
5707 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5708 SuppressUserConversions);
5711 /// AddConversionCandidate - Add a C++ conversion function as a
5712 /// candidate in the candidate set (C++ [over.match.conv],
5713 /// C++ [over.match.copy]). From is the expression we're converting from,
5714 /// and ToType is the type that we're eventually trying to convert to
5715 /// (which may or may not be the same type as the type that the
5716 /// conversion function produces).
5718 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5719 DeclAccessPair FoundDecl,
5720 CXXRecordDecl *ActingContext,
5721 Expr *From, QualType ToType,
5722 OverloadCandidateSet& CandidateSet) {
5723 assert(!Conversion->getDescribedFunctionTemplate() &&
5724 "Conversion function templates use AddTemplateConversionCandidate");
5725 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5726 if (!CandidateSet.isNewCandidate(Conversion))
5729 // If the conversion function has an undeduced return type, trigger its
5731 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5732 if (DeduceReturnType(Conversion, From->getExprLoc()))
5734 ConvType = Conversion->getConversionType().getNonReferenceType();
5737 // Overload resolution is always an unevaluated context.
5738 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5740 // Add this candidate
5741 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5742 Candidate.FoundDecl = FoundDecl;
5743 Candidate.Function = Conversion;
5744 Candidate.IsSurrogate = false;
5745 Candidate.IgnoreObjectArgument = false;
5746 Candidate.FinalConversion.setAsIdentityConversion();
5747 Candidate.FinalConversion.setFromType(ConvType);
5748 Candidate.FinalConversion.setAllToTypes(ToType);
5749 Candidate.Viable = true;
5750 Candidate.ExplicitCallArguments = 1;
5752 // C++ [over.match.funcs]p4:
5753 // For conversion functions, the function is considered to be a member of
5754 // the class of the implicit implied object argument for the purpose of
5755 // defining the type of the implicit object parameter.
5757 // Determine the implicit conversion sequence for the implicit
5758 // object parameter.
5759 QualType ImplicitParamType = From->getType();
5760 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5761 ImplicitParamType = FromPtrType->getPointeeType();
5762 CXXRecordDecl *ConversionContext
5763 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5765 Candidate.Conversions[0]
5766 = TryObjectArgumentInitialization(*this, From->getType(),
5767 From->Classify(Context),
5768 Conversion, ConversionContext);
5770 if (Candidate.Conversions[0].isBad()) {
5771 Candidate.Viable = false;
5772 Candidate.FailureKind = ovl_fail_bad_conversion;
5776 // We won't go through a user-define type conversion function to convert a
5777 // derived to base as such conversions are given Conversion Rank. They only
5778 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5780 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5781 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5782 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5783 Candidate.Viable = false;
5784 Candidate.FailureKind = ovl_fail_trivial_conversion;
5788 // To determine what the conversion from the result of calling the
5789 // conversion function to the type we're eventually trying to
5790 // convert to (ToType), we need to synthesize a call to the
5791 // conversion function and attempt copy initialization from it. This
5792 // makes sure that we get the right semantics with respect to
5793 // lvalues/rvalues and the type. Fortunately, we can allocate this
5794 // call on the stack and we don't need its arguments to be
5796 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5797 VK_LValue, From->getLocStart());
5798 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5799 Context.getPointerType(Conversion->getType()),
5800 CK_FunctionToPointerDecay,
5801 &ConversionRef, VK_RValue);
5803 QualType ConversionType = Conversion->getConversionType();
5804 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5805 Candidate.Viable = false;
5806 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5810 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5812 // Note that it is safe to allocate CallExpr on the stack here because
5813 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5815 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5816 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
5817 From->getLocStart());
5818 ImplicitConversionSequence ICS =
5819 TryCopyInitialization(*this, &Call, ToType,
5820 /*SuppressUserConversions=*/true,
5821 /*InOverloadResolution=*/false,
5822 /*AllowObjCWritebackConversion=*/false);
5824 switch (ICS.getKind()) {
5825 case ImplicitConversionSequence::StandardConversion:
5826 Candidate.FinalConversion = ICS.Standard;
5828 // C++ [over.ics.user]p3:
5829 // If the user-defined conversion is specified by a specialization of a
5830 // conversion function template, the second standard conversion sequence
5831 // shall have exact match rank.
5832 if (Conversion->getPrimaryTemplate() &&
5833 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5834 Candidate.Viable = false;
5835 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5838 // C++0x [dcl.init.ref]p5:
5839 // In the second case, if the reference is an rvalue reference and
5840 // the second standard conversion sequence of the user-defined
5841 // conversion sequence includes an lvalue-to-rvalue conversion, the
5842 // program is ill-formed.
5843 if (ToType->isRValueReferenceType() &&
5844 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5845 Candidate.Viable = false;
5846 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5850 case ImplicitConversionSequence::BadConversion:
5851 Candidate.Viable = false;
5852 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5857 "Can only end up with a standard conversion sequence or failure");
5861 /// \brief Adds a conversion function template specialization
5862 /// candidate to the overload set, using template argument deduction
5863 /// to deduce the template arguments of the conversion function
5864 /// template from the type that we are converting to (C++
5865 /// [temp.deduct.conv]).
5867 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5868 DeclAccessPair FoundDecl,
5869 CXXRecordDecl *ActingDC,
5870 Expr *From, QualType ToType,
5871 OverloadCandidateSet &CandidateSet) {
5872 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5873 "Only conversion function templates permitted here");
5875 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5878 TemplateDeductionInfo Info(CandidateSet.getLocation());
5879 CXXConversionDecl *Specialization = 0;
5880 if (TemplateDeductionResult Result
5881 = DeduceTemplateArguments(FunctionTemplate, ToType,
5882 Specialization, Info)) {
5883 OverloadCandidate &Candidate = CandidateSet.addCandidate();
5884 Candidate.FoundDecl = FoundDecl;
5885 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5886 Candidate.Viable = false;
5887 Candidate.FailureKind = ovl_fail_bad_deduction;
5888 Candidate.IsSurrogate = false;
5889 Candidate.IgnoreObjectArgument = false;
5890 Candidate.ExplicitCallArguments = 1;
5891 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5896 // Add the conversion function template specialization produced by
5897 // template argument deduction as a candidate.
5898 assert(Specialization && "Missing function template specialization?");
5899 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5903 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5904 /// converts the given @c Object to a function pointer via the
5905 /// conversion function @c Conversion, and then attempts to call it
5906 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
5907 /// the type of function that we'll eventually be calling.
5908 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5909 DeclAccessPair FoundDecl,
5910 CXXRecordDecl *ActingContext,
5911 const FunctionProtoType *Proto,
5913 ArrayRef<Expr *> Args,
5914 OverloadCandidateSet& CandidateSet) {
5915 if (!CandidateSet.isNewCandidate(Conversion))
5918 // Overload resolution is always an unevaluated context.
5919 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5921 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5922 Candidate.FoundDecl = FoundDecl;
5923 Candidate.Function = 0;
5924 Candidate.Surrogate = Conversion;
5925 Candidate.Viable = true;
5926 Candidate.IsSurrogate = true;
5927 Candidate.IgnoreObjectArgument = false;
5928 Candidate.ExplicitCallArguments = Args.size();
5930 // Determine the implicit conversion sequence for the implicit
5931 // object parameter.
5932 ImplicitConversionSequence ObjectInit
5933 = TryObjectArgumentInitialization(*this, Object->getType(),
5934 Object->Classify(Context),
5935 Conversion, ActingContext);
5936 if (ObjectInit.isBad()) {
5937 Candidate.Viable = false;
5938 Candidate.FailureKind = ovl_fail_bad_conversion;
5939 Candidate.Conversions[0] = ObjectInit;
5943 // The first conversion is actually a user-defined conversion whose
5944 // first conversion is ObjectInit's standard conversion (which is
5945 // effectively a reference binding). Record it as such.
5946 Candidate.Conversions[0].setUserDefined();
5947 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5948 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5949 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5950 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5951 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5952 Candidate.Conversions[0].UserDefined.After
5953 = Candidate.Conversions[0].UserDefined.Before;
5954 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5957 unsigned NumArgsInProto = Proto->getNumArgs();
5959 // (C++ 13.3.2p2): A candidate function having fewer than m
5960 // parameters is viable only if it has an ellipsis in its parameter
5962 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5963 Candidate.Viable = false;
5964 Candidate.FailureKind = ovl_fail_too_many_arguments;
5968 // Function types don't have any default arguments, so just check if
5969 // we have enough arguments.
5970 if (Args.size() < NumArgsInProto) {
5971 // Not enough arguments.
5972 Candidate.Viable = false;
5973 Candidate.FailureKind = ovl_fail_too_few_arguments;
5977 // Determine the implicit conversion sequences for each of the
5979 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
5980 if (ArgIdx < NumArgsInProto) {
5981 // (C++ 13.3.2p3): for F to be a viable function, there shall
5982 // exist for each argument an implicit conversion sequence
5983 // (13.3.3.1) that converts that argument to the corresponding
5985 QualType ParamType = Proto->getArgType(ArgIdx);
5986 Candidate.Conversions[ArgIdx + 1]
5987 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5988 /*SuppressUserConversions=*/false,
5989 /*InOverloadResolution=*/false,
5990 /*AllowObjCWritebackConversion=*/
5991 getLangOpts().ObjCAutoRefCount);
5992 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5993 Candidate.Viable = false;
5994 Candidate.FailureKind = ovl_fail_bad_conversion;
5998 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5999 // argument for which there is no corresponding parameter is
6000 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6001 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6006 /// \brief Add overload candidates for overloaded operators that are
6007 /// member functions.
6009 /// Add the overloaded operator candidates that are member functions
6010 /// for the operator Op that was used in an operator expression such
6011 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6012 /// CandidateSet will store the added overload candidates. (C++
6013 /// [over.match.oper]).
6014 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6015 SourceLocation OpLoc,
6016 ArrayRef<Expr *> Args,
6017 OverloadCandidateSet& CandidateSet,
6018 SourceRange OpRange) {
6019 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6021 // C++ [over.match.oper]p3:
6022 // For a unary operator @ with an operand of a type whose
6023 // cv-unqualified version is T1, and for a binary operator @ with
6024 // a left operand of a type whose cv-unqualified version is T1 and
6025 // a right operand of a type whose cv-unqualified version is T2,
6026 // three sets of candidate functions, designated member
6027 // candidates, non-member candidates and built-in candidates, are
6028 // constructed as follows:
6029 QualType T1 = Args[0]->getType();
6031 // -- If T1 is a complete class type or a class currently being
6032 // defined, the set of member candidates is the result of the
6033 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6034 // the set of member candidates is empty.
6035 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6036 // Complete the type if it can be completed.
6037 RequireCompleteType(OpLoc, T1, 0);
6038 // If the type is neither complete nor being defined, bail out now.
6039 if (!T1Rec->getDecl()->getDefinition())
6042 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6043 LookupQualifiedName(Operators, T1Rec->getDecl());
6044 Operators.suppressDiagnostics();
6046 for (LookupResult::iterator Oper = Operators.begin(),
6047 OperEnd = Operators.end();
6050 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6051 Args[0]->Classify(Context),
6054 /* SuppressUserConversions = */ false);
6058 /// AddBuiltinCandidate - Add a candidate for a built-in
6059 /// operator. ResultTy and ParamTys are the result and parameter types
6060 /// of the built-in candidate, respectively. Args and NumArgs are the
6061 /// arguments being passed to the candidate. IsAssignmentOperator
6062 /// should be true when this built-in candidate is an assignment
6063 /// operator. NumContextualBoolArguments is the number of arguments
6064 /// (at the beginning of the argument list) that will be contextually
6065 /// converted to bool.
6066 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6067 ArrayRef<Expr *> Args,
6068 OverloadCandidateSet& CandidateSet,
6069 bool IsAssignmentOperator,
6070 unsigned NumContextualBoolArguments) {
6071 // Overload resolution is always an unevaluated context.
6072 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6074 // Add this candidate
6075 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6076 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6077 Candidate.Function = 0;
6078 Candidate.IsSurrogate = false;
6079 Candidate.IgnoreObjectArgument = false;
6080 Candidate.BuiltinTypes.ResultTy = ResultTy;
6081 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6082 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6084 // Determine the implicit conversion sequences for each of the
6086 Candidate.Viable = true;
6087 Candidate.ExplicitCallArguments = Args.size();
6088 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6089 // C++ [over.match.oper]p4:
6090 // For the built-in assignment operators, conversions of the
6091 // left operand are restricted as follows:
6092 // -- no temporaries are introduced to hold the left operand, and
6093 // -- no user-defined conversions are applied to the left
6094 // operand to achieve a type match with the left-most
6095 // parameter of a built-in candidate.
6097 // We block these conversions by turning off user-defined
6098 // conversions, since that is the only way that initialization of
6099 // a reference to a non-class type can occur from something that
6100 // is not of the same type.
6101 if (ArgIdx < NumContextualBoolArguments) {
6102 assert(ParamTys[ArgIdx] == Context.BoolTy &&
6103 "Contextual conversion to bool requires bool type");
6104 Candidate.Conversions[ArgIdx]
6105 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6107 Candidate.Conversions[ArgIdx]
6108 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6109 ArgIdx == 0 && IsAssignmentOperator,
6110 /*InOverloadResolution=*/false,
6111 /*AllowObjCWritebackConversion=*/
6112 getLangOpts().ObjCAutoRefCount);
6114 if (Candidate.Conversions[ArgIdx].isBad()) {
6115 Candidate.Viable = false;
6116 Candidate.FailureKind = ovl_fail_bad_conversion;
6122 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6123 /// candidate operator functions for built-in operators (C++
6124 /// [over.built]). The types are separated into pointer types and
6125 /// enumeration types.
6126 class BuiltinCandidateTypeSet {
6127 /// TypeSet - A set of types.
6128 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6130 /// PointerTypes - The set of pointer types that will be used in the
6131 /// built-in candidates.
6132 TypeSet PointerTypes;
6134 /// MemberPointerTypes - The set of member pointer types that will be
6135 /// used in the built-in candidates.
6136 TypeSet MemberPointerTypes;
6138 /// EnumerationTypes - The set of enumeration types that will be
6139 /// used in the built-in candidates.
6140 TypeSet EnumerationTypes;
6142 /// \brief The set of vector types that will be used in the built-in
6144 TypeSet VectorTypes;
6146 /// \brief A flag indicating non-record types are viable candidates
6147 bool HasNonRecordTypes;
6149 /// \brief A flag indicating whether either arithmetic or enumeration types
6150 /// were present in the candidate set.
6151 bool HasArithmeticOrEnumeralTypes;
6153 /// \brief A flag indicating whether the nullptr type was present in the
6155 bool HasNullPtrType;
6157 /// Sema - The semantic analysis instance where we are building the
6158 /// candidate type set.
6161 /// Context - The AST context in which we will build the type sets.
6162 ASTContext &Context;
6164 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6165 const Qualifiers &VisibleQuals);
6166 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6169 /// iterator - Iterates through the types that are part of the set.
6170 typedef TypeSet::iterator iterator;
6172 BuiltinCandidateTypeSet(Sema &SemaRef)
6173 : HasNonRecordTypes(false),
6174 HasArithmeticOrEnumeralTypes(false),
6175 HasNullPtrType(false),
6177 Context(SemaRef.Context) { }
6179 void AddTypesConvertedFrom(QualType Ty,
6181 bool AllowUserConversions,
6182 bool AllowExplicitConversions,
6183 const Qualifiers &VisibleTypeConversionsQuals);
6185 /// pointer_begin - First pointer type found;
6186 iterator pointer_begin() { return PointerTypes.begin(); }
6188 /// pointer_end - Past the last pointer type found;
6189 iterator pointer_end() { return PointerTypes.end(); }
6191 /// member_pointer_begin - First member pointer type found;
6192 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6194 /// member_pointer_end - Past the last member pointer type found;
6195 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6197 /// enumeration_begin - First enumeration type found;
6198 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6200 /// enumeration_end - Past the last enumeration type found;
6201 iterator enumeration_end() { return EnumerationTypes.end(); }
6203 iterator vector_begin() { return VectorTypes.begin(); }
6204 iterator vector_end() { return VectorTypes.end(); }
6206 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6207 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6208 bool hasNullPtrType() const { return HasNullPtrType; }
6211 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6212 /// the set of pointer types along with any more-qualified variants of
6213 /// that type. For example, if @p Ty is "int const *", this routine
6214 /// will add "int const *", "int const volatile *", "int const
6215 /// restrict *", and "int const volatile restrict *" to the set of
6216 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6217 /// false otherwise.
6219 /// FIXME: what to do about extended qualifiers?
6221 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6222 const Qualifiers &VisibleQuals) {
6224 // Insert this type.
6225 if (!PointerTypes.insert(Ty))
6229 const PointerType *PointerTy = Ty->getAs<PointerType>();
6230 bool buildObjCPtr = false;
6232 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6233 PointeeTy = PTy->getPointeeType();
6234 buildObjCPtr = true;
6236 PointeeTy = PointerTy->getPointeeType();
6239 // Don't add qualified variants of arrays. For one, they're not allowed
6240 // (the qualifier would sink to the element type), and for another, the
6241 // only overload situation where it matters is subscript or pointer +- int,
6242 // and those shouldn't have qualifier variants anyway.
6243 if (PointeeTy->isArrayType())
6246 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6247 bool hasVolatile = VisibleQuals.hasVolatile();
6248 bool hasRestrict = VisibleQuals.hasRestrict();
6250 // Iterate through all strict supersets of BaseCVR.
6251 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6252 if ((CVR | BaseCVR) != CVR) continue;
6253 // Skip over volatile if no volatile found anywhere in the types.
6254 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6256 // Skip over restrict if no restrict found anywhere in the types, or if
6257 // the type cannot be restrict-qualified.
6258 if ((CVR & Qualifiers::Restrict) &&
6260 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6263 // Build qualified pointee type.
6264 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6266 // Build qualified pointer type.
6267 QualType QPointerTy;
6269 QPointerTy = Context.getPointerType(QPointeeTy);
6271 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6273 // Insert qualified pointer type.
6274 PointerTypes.insert(QPointerTy);
6280 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6281 /// to the set of pointer types along with any more-qualified variants of
6282 /// that type. For example, if @p Ty is "int const *", this routine
6283 /// will add "int const *", "int const volatile *", "int const
6284 /// restrict *", and "int const volatile restrict *" to the set of
6285 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6286 /// false otherwise.
6288 /// FIXME: what to do about extended qualifiers?
6290 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6292 // Insert this type.
6293 if (!MemberPointerTypes.insert(Ty))
6296 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6297 assert(PointerTy && "type was not a member pointer type!");
6299 QualType PointeeTy = PointerTy->getPointeeType();
6300 // Don't add qualified variants of arrays. For one, they're not allowed
6301 // (the qualifier would sink to the element type), and for another, the
6302 // only overload situation where it matters is subscript or pointer +- int,
6303 // and those shouldn't have qualifier variants anyway.
6304 if (PointeeTy->isArrayType())
6306 const Type *ClassTy = PointerTy->getClass();
6308 // Iterate through all strict supersets of the pointee type's CVR
6310 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6311 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6312 if ((CVR | BaseCVR) != CVR) continue;
6314 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6315 MemberPointerTypes.insert(
6316 Context.getMemberPointerType(QPointeeTy, ClassTy));
6322 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6323 /// Ty can be implicit converted to the given set of @p Types. We're
6324 /// primarily interested in pointer types and enumeration types. We also
6325 /// take member pointer types, for the conditional operator.
6326 /// AllowUserConversions is true if we should look at the conversion
6327 /// functions of a class type, and AllowExplicitConversions if we
6328 /// should also include the explicit conversion functions of a class
6331 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6333 bool AllowUserConversions,
6334 bool AllowExplicitConversions,
6335 const Qualifiers &VisibleQuals) {
6336 // Only deal with canonical types.
6337 Ty = Context.getCanonicalType(Ty);
6339 // Look through reference types; they aren't part of the type of an
6340 // expression for the purposes of conversions.
6341 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6342 Ty = RefTy->getPointeeType();
6344 // If we're dealing with an array type, decay to the pointer.
6345 if (Ty->isArrayType())
6346 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6348 // Otherwise, we don't care about qualifiers on the type.
6349 Ty = Ty.getLocalUnqualifiedType();
6351 // Flag if we ever add a non-record type.
6352 const RecordType *TyRec = Ty->getAs<RecordType>();
6353 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6355 // Flag if we encounter an arithmetic type.
6356 HasArithmeticOrEnumeralTypes =
6357 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6359 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6360 PointerTypes.insert(Ty);
6361 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6362 // Insert our type, and its more-qualified variants, into the set
6364 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6366 } else if (Ty->isMemberPointerType()) {
6367 // Member pointers are far easier, since the pointee can't be converted.
6368 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6370 } else if (Ty->isEnumeralType()) {
6371 HasArithmeticOrEnumeralTypes = true;
6372 EnumerationTypes.insert(Ty);
6373 } else if (Ty->isVectorType()) {
6374 // We treat vector types as arithmetic types in many contexts as an
6376 HasArithmeticOrEnumeralTypes = true;
6377 VectorTypes.insert(Ty);
6378 } else if (Ty->isNullPtrType()) {
6379 HasNullPtrType = true;
6380 } else if (AllowUserConversions && TyRec) {
6381 // No conversion functions in incomplete types.
6382 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6385 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6386 std::pair<CXXRecordDecl::conversion_iterator,
6387 CXXRecordDecl::conversion_iterator>
6388 Conversions = ClassDecl->getVisibleConversionFunctions();
6389 for (CXXRecordDecl::conversion_iterator
6390 I = Conversions.first, E = Conversions.second; I != E; ++I) {
6391 NamedDecl *D = I.getDecl();
6392 if (isa<UsingShadowDecl>(D))
6393 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6395 // Skip conversion function templates; they don't tell us anything
6396 // about which builtin types we can convert to.
6397 if (isa<FunctionTemplateDecl>(D))
6400 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6401 if (AllowExplicitConversions || !Conv->isExplicit()) {
6402 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6409 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6410 /// the volatile- and non-volatile-qualified assignment operators for the
6411 /// given type to the candidate set.
6412 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6414 ArrayRef<Expr *> Args,
6415 OverloadCandidateSet &CandidateSet) {
6416 QualType ParamTypes[2];
6418 // T& operator=(T&, T)
6419 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6421 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6422 /*IsAssignmentOperator=*/true);
6424 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6425 // volatile T& operator=(volatile T&, T)
6427 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6429 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6430 /*IsAssignmentOperator=*/true);
6434 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6435 /// if any, found in visible type conversion functions found in ArgExpr's type.
6436 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6438 const RecordType *TyRec;
6439 if (const MemberPointerType *RHSMPType =
6440 ArgExpr->getType()->getAs<MemberPointerType>())
6441 TyRec = RHSMPType->getClass()->getAs<RecordType>();
6443 TyRec = ArgExpr->getType()->getAs<RecordType>();
6445 // Just to be safe, assume the worst case.
6446 VRQuals.addVolatile();
6447 VRQuals.addRestrict();
6451 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6452 if (!ClassDecl->hasDefinition())
6455 std::pair<CXXRecordDecl::conversion_iterator,
6456 CXXRecordDecl::conversion_iterator>
6457 Conversions = ClassDecl->getVisibleConversionFunctions();
6459 for (CXXRecordDecl::conversion_iterator
6460 I = Conversions.first, E = Conversions.second; I != E; ++I) {
6461 NamedDecl *D = I.getDecl();
6462 if (isa<UsingShadowDecl>(D))
6463 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6464 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6465 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6466 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6467 CanTy = ResTypeRef->getPointeeType();
6468 // Need to go down the pointer/mempointer chain and add qualifiers
6472 if (CanTy.isRestrictQualified())
6473 VRQuals.addRestrict();
6474 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6475 CanTy = ResTypePtr->getPointeeType();
6476 else if (const MemberPointerType *ResTypeMPtr =
6477 CanTy->getAs<MemberPointerType>())
6478 CanTy = ResTypeMPtr->getPointeeType();
6481 if (CanTy.isVolatileQualified())
6482 VRQuals.addVolatile();
6483 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6493 /// \brief Helper class to manage the addition of builtin operator overload
6494 /// candidates. It provides shared state and utility methods used throughout
6495 /// the process, as well as a helper method to add each group of builtin
6496 /// operator overloads from the standard to a candidate set.
6497 class BuiltinOperatorOverloadBuilder {
6498 // Common instance state available to all overload candidate addition methods.
6500 ArrayRef<Expr *> Args;
6501 Qualifiers VisibleTypeConversionsQuals;
6502 bool HasArithmeticOrEnumeralCandidateType;
6503 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6504 OverloadCandidateSet &CandidateSet;
6506 // Define some constants used to index and iterate over the arithemetic types
6507 // provided via the getArithmeticType() method below.
6508 // The "promoted arithmetic types" are the arithmetic
6509 // types are that preserved by promotion (C++ [over.built]p2).
6510 static const unsigned FirstIntegralType = 3;
6511 static const unsigned LastIntegralType = 20;
6512 static const unsigned FirstPromotedIntegralType = 3,
6513 LastPromotedIntegralType = 11;
6514 static const unsigned FirstPromotedArithmeticType = 0,
6515 LastPromotedArithmeticType = 11;
6516 static const unsigned NumArithmeticTypes = 20;
6518 /// \brief Get the canonical type for a given arithmetic type index.
6519 CanQualType getArithmeticType(unsigned index) {
6520 assert(index < NumArithmeticTypes);
6521 static CanQualType ASTContext::* const
6522 ArithmeticTypes[NumArithmeticTypes] = {
6523 // Start of promoted types.
6524 &ASTContext::FloatTy,
6525 &ASTContext::DoubleTy,
6526 &ASTContext::LongDoubleTy,
6528 // Start of integral types.
6530 &ASTContext::LongTy,
6531 &ASTContext::LongLongTy,
6532 &ASTContext::Int128Ty,
6533 &ASTContext::UnsignedIntTy,
6534 &ASTContext::UnsignedLongTy,
6535 &ASTContext::UnsignedLongLongTy,
6536 &ASTContext::UnsignedInt128Ty,
6537 // End of promoted types.
6539 &ASTContext::BoolTy,
6540 &ASTContext::CharTy,
6541 &ASTContext::WCharTy,
6542 &ASTContext::Char16Ty,
6543 &ASTContext::Char32Ty,
6544 &ASTContext::SignedCharTy,
6545 &ASTContext::ShortTy,
6546 &ASTContext::UnsignedCharTy,
6547 &ASTContext::UnsignedShortTy,
6548 // End of integral types.
6549 // FIXME: What about complex? What about half?
6551 return S.Context.*ArithmeticTypes[index];
6554 /// \brief Gets the canonical type resulting from the usual arithemetic
6555 /// converions for the given arithmetic types.
6556 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6557 // Accelerator table for performing the usual arithmetic conversions.
6558 // The rules are basically:
6559 // - if either is floating-point, use the wider floating-point
6560 // - if same signedness, use the higher rank
6561 // - if same size, use unsigned of the higher rank
6562 // - use the larger type
6563 // These rules, together with the axiom that higher ranks are
6564 // never smaller, are sufficient to precompute all of these results
6565 // *except* when dealing with signed types of higher rank.
6566 // (we could precompute SLL x UI for all known platforms, but it's
6567 // better not to make any assumptions).
6568 // We assume that int128 has a higher rank than long long on all platforms.
6571 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
6573 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6574 [LastPromotedArithmeticType] = {
6575 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6576 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6577 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6578 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6579 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6580 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6581 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6582 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6583 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6584 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6585 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6588 assert(L < LastPromotedArithmeticType);
6589 assert(R < LastPromotedArithmeticType);
6590 int Idx = ConversionsTable[L][R];
6592 // Fast path: the table gives us a concrete answer.
6593 if (Idx != Dep) return getArithmeticType(Idx);
6595 // Slow path: we need to compare widths.
6596 // An invariant is that the signed type has higher rank.
6597 CanQualType LT = getArithmeticType(L),
6598 RT = getArithmeticType(R);
6599 unsigned LW = S.Context.getIntWidth(LT),
6600 RW = S.Context.getIntWidth(RT);
6602 // If they're different widths, use the signed type.
6603 if (LW > RW) return LT;
6604 else if (LW < RW) return RT;
6606 // Otherwise, use the unsigned type of the signed type's rank.
6607 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6608 assert(L == SLL || R == SLL);
6609 return S.Context.UnsignedLongLongTy;
6612 /// \brief Helper method to factor out the common pattern of adding overloads
6613 /// for '++' and '--' builtin operators.
6614 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6617 QualType ParamTypes[2] = {
6618 S.Context.getLValueReferenceType(CandidateTy),
6622 // Non-volatile version.
6623 if (Args.size() == 1)
6624 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6626 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6628 // Use a heuristic to reduce number of builtin candidates in the set:
6629 // add volatile version only if there are conversions to a volatile type.
6632 S.Context.getLValueReferenceType(
6633 S.Context.getVolatileType(CandidateTy));
6634 if (Args.size() == 1)
6635 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6637 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6640 // Add restrict version only if there are conversions to a restrict type
6641 // and our candidate type is a non-restrict-qualified pointer.
6642 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6643 !CandidateTy.isRestrictQualified()) {
6645 = S.Context.getLValueReferenceType(
6646 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6647 if (Args.size() == 1)
6648 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6650 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6654 = S.Context.getLValueReferenceType(
6655 S.Context.getCVRQualifiedType(CandidateTy,
6656 (Qualifiers::Volatile |
6657 Qualifiers::Restrict)));
6658 if (Args.size() == 1)
6659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6661 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6668 BuiltinOperatorOverloadBuilder(
6669 Sema &S, ArrayRef<Expr *> Args,
6670 Qualifiers VisibleTypeConversionsQuals,
6671 bool HasArithmeticOrEnumeralCandidateType,
6672 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6673 OverloadCandidateSet &CandidateSet)
6675 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6676 HasArithmeticOrEnumeralCandidateType(
6677 HasArithmeticOrEnumeralCandidateType),
6678 CandidateTypes(CandidateTypes),
6679 CandidateSet(CandidateSet) {
6680 // Validate some of our static helper constants in debug builds.
6681 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6682 "Invalid first promoted integral type");
6683 assert(getArithmeticType(LastPromotedIntegralType - 1)
6684 == S.Context.UnsignedInt128Ty &&
6685 "Invalid last promoted integral type");
6686 assert(getArithmeticType(FirstPromotedArithmeticType)
6687 == S.Context.FloatTy &&
6688 "Invalid first promoted arithmetic type");
6689 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6690 == S.Context.UnsignedInt128Ty &&
6691 "Invalid last promoted arithmetic type");
6694 // C++ [over.built]p3:
6696 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6697 // is either volatile or empty, there exist candidate operator
6698 // functions of the form
6700 // VQ T& operator++(VQ T&);
6701 // T operator++(VQ T&, int);
6703 // C++ [over.built]p4:
6705 // For every pair (T, VQ), where T is an arithmetic type other
6706 // than bool, and VQ is either volatile or empty, there exist
6707 // candidate operator functions of the form
6709 // VQ T& operator--(VQ T&);
6710 // T operator--(VQ T&, int);
6711 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6712 if (!HasArithmeticOrEnumeralCandidateType)
6715 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6716 Arith < NumArithmeticTypes; ++Arith) {
6717 addPlusPlusMinusMinusStyleOverloads(
6718 getArithmeticType(Arith),
6719 VisibleTypeConversionsQuals.hasVolatile(),
6720 VisibleTypeConversionsQuals.hasRestrict());
6724 // C++ [over.built]p5:
6726 // For every pair (T, VQ), where T is a cv-qualified or
6727 // cv-unqualified object type, and VQ is either volatile or
6728 // empty, there exist candidate operator functions of the form
6730 // T*VQ& operator++(T*VQ&);
6731 // T*VQ& operator--(T*VQ&);
6732 // T* operator++(T*VQ&, int);
6733 // T* operator--(T*VQ&, int);
6734 void addPlusPlusMinusMinusPointerOverloads() {
6735 for (BuiltinCandidateTypeSet::iterator
6736 Ptr = CandidateTypes[0].pointer_begin(),
6737 PtrEnd = CandidateTypes[0].pointer_end();
6738 Ptr != PtrEnd; ++Ptr) {
6739 // Skip pointer types that aren't pointers to object types.
6740 if (!(*Ptr)->getPointeeType()->isObjectType())
6743 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6744 (!(*Ptr).isVolatileQualified() &&
6745 VisibleTypeConversionsQuals.hasVolatile()),
6746 (!(*Ptr).isRestrictQualified() &&
6747 VisibleTypeConversionsQuals.hasRestrict()));
6751 // C++ [over.built]p6:
6752 // For every cv-qualified or cv-unqualified object type T, there
6753 // exist candidate operator functions of the form
6755 // T& operator*(T*);
6757 // C++ [over.built]p7:
6758 // For every function type T that does not have cv-qualifiers or a
6759 // ref-qualifier, there exist candidate operator functions of the form
6760 // T& operator*(T*);
6761 void addUnaryStarPointerOverloads() {
6762 for (BuiltinCandidateTypeSet::iterator
6763 Ptr = CandidateTypes[0].pointer_begin(),
6764 PtrEnd = CandidateTypes[0].pointer_end();
6765 Ptr != PtrEnd; ++Ptr) {
6766 QualType ParamTy = *Ptr;
6767 QualType PointeeTy = ParamTy->getPointeeType();
6768 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6771 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6772 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6775 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6776 &ParamTy, Args, CandidateSet);
6780 // C++ [over.built]p9:
6781 // For every promoted arithmetic type T, there exist candidate
6782 // operator functions of the form
6786 void addUnaryPlusOrMinusArithmeticOverloads() {
6787 if (!HasArithmeticOrEnumeralCandidateType)
6790 for (unsigned Arith = FirstPromotedArithmeticType;
6791 Arith < LastPromotedArithmeticType; ++Arith) {
6792 QualType ArithTy = getArithmeticType(Arith);
6793 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
6796 // Extension: We also add these operators for vector types.
6797 for (BuiltinCandidateTypeSet::iterator
6798 Vec = CandidateTypes[0].vector_begin(),
6799 VecEnd = CandidateTypes[0].vector_end();
6800 Vec != VecEnd; ++Vec) {
6801 QualType VecTy = *Vec;
6802 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6806 // C++ [over.built]p8:
6807 // For every type T, there exist candidate operator functions of
6810 // T* operator+(T*);
6811 void addUnaryPlusPointerOverloads() {
6812 for (BuiltinCandidateTypeSet::iterator
6813 Ptr = CandidateTypes[0].pointer_begin(),
6814 PtrEnd = CandidateTypes[0].pointer_end();
6815 Ptr != PtrEnd; ++Ptr) {
6816 QualType ParamTy = *Ptr;
6817 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
6821 // C++ [over.built]p10:
6822 // For every promoted integral type T, there exist candidate
6823 // operator functions of the form
6826 void addUnaryTildePromotedIntegralOverloads() {
6827 if (!HasArithmeticOrEnumeralCandidateType)
6830 for (unsigned Int = FirstPromotedIntegralType;
6831 Int < LastPromotedIntegralType; ++Int) {
6832 QualType IntTy = getArithmeticType(Int);
6833 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
6836 // Extension: We also add this operator for vector types.
6837 for (BuiltinCandidateTypeSet::iterator
6838 Vec = CandidateTypes[0].vector_begin(),
6839 VecEnd = CandidateTypes[0].vector_end();
6840 Vec != VecEnd; ++Vec) {
6841 QualType VecTy = *Vec;
6842 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6846 // C++ [over.match.oper]p16:
6847 // For every pointer to member type T, there exist candidate operator
6848 // functions of the form
6850 // bool operator==(T,T);
6851 // bool operator!=(T,T);
6852 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6853 /// Set of (canonical) types that we've already handled.
6854 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6856 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6857 for (BuiltinCandidateTypeSet::iterator
6858 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6859 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6860 MemPtr != MemPtrEnd;
6862 // Don't add the same builtin candidate twice.
6863 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6866 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6867 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
6872 // C++ [over.built]p15:
6874 // For every T, where T is an enumeration type, a pointer type, or
6875 // std::nullptr_t, there exist candidate operator functions of the form
6877 // bool operator<(T, T);
6878 // bool operator>(T, T);
6879 // bool operator<=(T, T);
6880 // bool operator>=(T, T);
6881 // bool operator==(T, T);
6882 // bool operator!=(T, T);
6883 void addRelationalPointerOrEnumeralOverloads() {
6884 // C++ [over.match.oper]p3:
6885 // [...]the built-in candidates include all of the candidate operator
6886 // functions defined in 13.6 that, compared to the given operator, [...]
6887 // do not have the same parameter-type-list as any non-template non-member
6890 // Note that in practice, this only affects enumeration types because there
6891 // aren't any built-in candidates of record type, and a user-defined operator
6892 // must have an operand of record or enumeration type. Also, the only other
6893 // overloaded operator with enumeration arguments, operator=,
6894 // cannot be overloaded for enumeration types, so this is the only place
6895 // where we must suppress candidates like this.
6896 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6897 UserDefinedBinaryOperators;
6899 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6900 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6901 CandidateTypes[ArgIdx].enumeration_end()) {
6902 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6903 CEnd = CandidateSet.end();
6905 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6908 if (C->Function->isFunctionTemplateSpecialization())
6911 QualType FirstParamType =
6912 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6913 QualType SecondParamType =
6914 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6916 // Skip if either parameter isn't of enumeral type.
6917 if (!FirstParamType->isEnumeralType() ||
6918 !SecondParamType->isEnumeralType())
6921 // Add this operator to the set of known user-defined operators.
6922 UserDefinedBinaryOperators.insert(
6923 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6924 S.Context.getCanonicalType(SecondParamType)));
6929 /// Set of (canonical) types that we've already handled.
6930 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6932 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6933 for (BuiltinCandidateTypeSet::iterator
6934 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6935 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6936 Ptr != PtrEnd; ++Ptr) {
6937 // Don't add the same builtin candidate twice.
6938 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6941 QualType ParamTypes[2] = { *Ptr, *Ptr };
6942 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
6944 for (BuiltinCandidateTypeSet::iterator
6945 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6946 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6947 Enum != EnumEnd; ++Enum) {
6948 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6950 // Don't add the same builtin candidate twice, or if a user defined
6951 // candidate exists.
6952 if (!AddedTypes.insert(CanonType) ||
6953 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6957 QualType ParamTypes[2] = { *Enum, *Enum };
6958 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
6961 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6962 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6963 if (AddedTypes.insert(NullPtrTy) &&
6964 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6966 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6967 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
6974 // C++ [over.built]p13:
6976 // For every cv-qualified or cv-unqualified object type T
6977 // there exist candidate operator functions of the form
6979 // T* operator+(T*, ptrdiff_t);
6980 // T& operator[](T*, ptrdiff_t); [BELOW]
6981 // T* operator-(T*, ptrdiff_t);
6982 // T* operator+(ptrdiff_t, T*);
6983 // T& operator[](ptrdiff_t, T*); [BELOW]
6985 // C++ [over.built]p14:
6987 // For every T, where T is a pointer to object type, there
6988 // exist candidate operator functions of the form
6990 // ptrdiff_t operator-(T, T);
6991 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6992 /// Set of (canonical) types that we've already handled.
6993 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6995 for (int Arg = 0; Arg < 2; ++Arg) {
6996 QualType AsymetricParamTypes[2] = {
6997 S.Context.getPointerDiffType(),
6998 S.Context.getPointerDiffType(),
7000 for (BuiltinCandidateTypeSet::iterator
7001 Ptr = CandidateTypes[Arg].pointer_begin(),
7002 PtrEnd = CandidateTypes[Arg].pointer_end();
7003 Ptr != PtrEnd; ++Ptr) {
7004 QualType PointeeTy = (*Ptr)->getPointeeType();
7005 if (!PointeeTy->isObjectType())
7008 AsymetricParamTypes[Arg] = *Ptr;
7009 if (Arg == 0 || Op == OO_Plus) {
7010 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7011 // T* operator+(ptrdiff_t, T*);
7012 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7014 if (Op == OO_Minus) {
7015 // ptrdiff_t operator-(T, T);
7016 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7019 QualType ParamTypes[2] = { *Ptr, *Ptr };
7020 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7021 Args, CandidateSet);
7027 // C++ [over.built]p12:
7029 // For every pair of promoted arithmetic types L and R, there
7030 // exist candidate operator functions of the form
7032 // LR operator*(L, R);
7033 // LR operator/(L, R);
7034 // LR operator+(L, R);
7035 // LR operator-(L, R);
7036 // bool operator<(L, R);
7037 // bool operator>(L, R);
7038 // bool operator<=(L, R);
7039 // bool operator>=(L, R);
7040 // bool operator==(L, R);
7041 // bool operator!=(L, R);
7043 // where LR is the result of the usual arithmetic conversions
7044 // between types L and R.
7046 // C++ [over.built]p24:
7048 // For every pair of promoted arithmetic types L and R, there exist
7049 // candidate operator functions of the form
7051 // LR operator?(bool, L, R);
7053 // where LR is the result of the usual arithmetic conversions
7054 // between types L and R.
7055 // Our candidates ignore the first parameter.
7056 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7057 if (!HasArithmeticOrEnumeralCandidateType)
7060 for (unsigned Left = FirstPromotedArithmeticType;
7061 Left < LastPromotedArithmeticType; ++Left) {
7062 for (unsigned Right = FirstPromotedArithmeticType;
7063 Right < LastPromotedArithmeticType; ++Right) {
7064 QualType LandR[2] = { getArithmeticType(Left),
7065 getArithmeticType(Right) };
7067 isComparison ? S.Context.BoolTy
7068 : getUsualArithmeticConversions(Left, Right);
7069 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7073 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7074 // conditional operator for vector types.
7075 for (BuiltinCandidateTypeSet::iterator
7076 Vec1 = CandidateTypes[0].vector_begin(),
7077 Vec1End = CandidateTypes[0].vector_end();
7078 Vec1 != Vec1End; ++Vec1) {
7079 for (BuiltinCandidateTypeSet::iterator
7080 Vec2 = CandidateTypes[1].vector_begin(),
7081 Vec2End = CandidateTypes[1].vector_end();
7082 Vec2 != Vec2End; ++Vec2) {
7083 QualType LandR[2] = { *Vec1, *Vec2 };
7084 QualType Result = S.Context.BoolTy;
7085 if (!isComparison) {
7086 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7092 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7097 // C++ [over.built]p17:
7099 // For every pair of promoted integral types L and R, there
7100 // exist candidate operator functions of the form
7102 // LR operator%(L, R);
7103 // LR operator&(L, R);
7104 // LR operator^(L, R);
7105 // LR operator|(L, R);
7106 // L operator<<(L, R);
7107 // L operator>>(L, R);
7109 // where LR is the result of the usual arithmetic conversions
7110 // between types L and R.
7111 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7112 if (!HasArithmeticOrEnumeralCandidateType)
7115 for (unsigned Left = FirstPromotedIntegralType;
7116 Left < LastPromotedIntegralType; ++Left) {
7117 for (unsigned Right = FirstPromotedIntegralType;
7118 Right < LastPromotedIntegralType; ++Right) {
7119 QualType LandR[2] = { getArithmeticType(Left),
7120 getArithmeticType(Right) };
7121 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7123 : getUsualArithmeticConversions(Left, Right);
7124 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7129 // C++ [over.built]p20:
7131 // For every pair (T, VQ), where T is an enumeration or
7132 // pointer to member type and VQ is either volatile or
7133 // empty, there exist candidate operator functions of the form
7135 // VQ T& operator=(VQ T&, T);
7136 void addAssignmentMemberPointerOrEnumeralOverloads() {
7137 /// Set of (canonical) types that we've already handled.
7138 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7140 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7141 for (BuiltinCandidateTypeSet::iterator
7142 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7143 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7144 Enum != EnumEnd; ++Enum) {
7145 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7148 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7151 for (BuiltinCandidateTypeSet::iterator
7152 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7153 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7154 MemPtr != MemPtrEnd; ++MemPtr) {
7155 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7158 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7163 // C++ [over.built]p19:
7165 // For every pair (T, VQ), where T is any type and VQ is either
7166 // volatile or empty, there exist candidate operator functions
7169 // T*VQ& operator=(T*VQ&, T*);
7171 // C++ [over.built]p21:
7173 // For every pair (T, VQ), where T is a cv-qualified or
7174 // cv-unqualified object type and VQ is either volatile or
7175 // empty, there exist candidate operator functions of the form
7177 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7178 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7179 void addAssignmentPointerOverloads(bool isEqualOp) {
7180 /// Set of (canonical) types that we've already handled.
7181 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7183 for (BuiltinCandidateTypeSet::iterator
7184 Ptr = CandidateTypes[0].pointer_begin(),
7185 PtrEnd = CandidateTypes[0].pointer_end();
7186 Ptr != PtrEnd; ++Ptr) {
7187 // If this is operator=, keep track of the builtin candidates we added.
7189 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7190 else if (!(*Ptr)->getPointeeType()->isObjectType())
7193 // non-volatile version
7194 QualType ParamTypes[2] = {
7195 S.Context.getLValueReferenceType(*Ptr),
7196 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7199 /*IsAssigmentOperator=*/ isEqualOp);
7201 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7202 VisibleTypeConversionsQuals.hasVolatile();
7206 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7207 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7208 /*IsAssigmentOperator=*/isEqualOp);
7211 if (!(*Ptr).isRestrictQualified() &&
7212 VisibleTypeConversionsQuals.hasRestrict()) {
7215 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7217 /*IsAssigmentOperator=*/isEqualOp);
7220 // volatile restrict version
7222 = S.Context.getLValueReferenceType(
7223 S.Context.getCVRQualifiedType(*Ptr,
7224 (Qualifiers::Volatile |
7225 Qualifiers::Restrict)));
7226 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7227 /*IsAssigmentOperator=*/isEqualOp);
7233 for (BuiltinCandidateTypeSet::iterator
7234 Ptr = CandidateTypes[1].pointer_begin(),
7235 PtrEnd = CandidateTypes[1].pointer_end();
7236 Ptr != PtrEnd; ++Ptr) {
7237 // Make sure we don't add the same candidate twice.
7238 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7241 QualType ParamTypes[2] = {
7242 S.Context.getLValueReferenceType(*Ptr),
7246 // non-volatile version
7247 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7248 /*IsAssigmentOperator=*/true);
7250 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7251 VisibleTypeConversionsQuals.hasVolatile();
7255 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7256 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7257 /*IsAssigmentOperator=*/true);
7260 if (!(*Ptr).isRestrictQualified() &&
7261 VisibleTypeConversionsQuals.hasRestrict()) {
7264 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7265 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7266 /*IsAssigmentOperator=*/true);
7269 // volatile restrict version
7271 = S.Context.getLValueReferenceType(
7272 S.Context.getCVRQualifiedType(*Ptr,
7273 (Qualifiers::Volatile |
7274 Qualifiers::Restrict)));
7275 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7276 /*IsAssigmentOperator=*/true);
7283 // C++ [over.built]p18:
7285 // For every triple (L, VQ, R), where L is an arithmetic type,
7286 // VQ is either volatile or empty, and R is a promoted
7287 // arithmetic type, there exist candidate operator functions of
7290 // VQ L& operator=(VQ L&, R);
7291 // VQ L& operator*=(VQ L&, R);
7292 // VQ L& operator/=(VQ L&, R);
7293 // VQ L& operator+=(VQ L&, R);
7294 // VQ L& operator-=(VQ L&, R);
7295 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7296 if (!HasArithmeticOrEnumeralCandidateType)
7299 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7300 for (unsigned Right = FirstPromotedArithmeticType;
7301 Right < LastPromotedArithmeticType; ++Right) {
7302 QualType ParamTypes[2];
7303 ParamTypes[1] = getArithmeticType(Right);
7305 // Add this built-in operator as a candidate (VQ is empty).
7307 S.Context.getLValueReferenceType(getArithmeticType(Left));
7308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7309 /*IsAssigmentOperator=*/isEqualOp);
7311 // Add this built-in operator as a candidate (VQ is 'volatile').
7312 if (VisibleTypeConversionsQuals.hasVolatile()) {
7314 S.Context.getVolatileType(getArithmeticType(Left));
7315 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7317 /*IsAssigmentOperator=*/isEqualOp);
7322 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7323 for (BuiltinCandidateTypeSet::iterator
7324 Vec1 = CandidateTypes[0].vector_begin(),
7325 Vec1End = CandidateTypes[0].vector_end();
7326 Vec1 != Vec1End; ++Vec1) {
7327 for (BuiltinCandidateTypeSet::iterator
7328 Vec2 = CandidateTypes[1].vector_begin(),
7329 Vec2End = CandidateTypes[1].vector_end();
7330 Vec2 != Vec2End; ++Vec2) {
7331 QualType ParamTypes[2];
7332 ParamTypes[1] = *Vec2;
7333 // Add this built-in operator as a candidate (VQ is empty).
7334 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7335 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7336 /*IsAssigmentOperator=*/isEqualOp);
7338 // Add this built-in operator as a candidate (VQ is 'volatile').
7339 if (VisibleTypeConversionsQuals.hasVolatile()) {
7340 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7341 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7342 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7343 /*IsAssigmentOperator=*/isEqualOp);
7349 // C++ [over.built]p22:
7351 // For every triple (L, VQ, R), where L is an integral type, VQ
7352 // is either volatile or empty, and R is a promoted integral
7353 // type, there exist candidate operator functions of the form
7355 // VQ L& operator%=(VQ L&, R);
7356 // VQ L& operator<<=(VQ L&, R);
7357 // VQ L& operator>>=(VQ L&, R);
7358 // VQ L& operator&=(VQ L&, R);
7359 // VQ L& operator^=(VQ L&, R);
7360 // VQ L& operator|=(VQ L&, R);
7361 void addAssignmentIntegralOverloads() {
7362 if (!HasArithmeticOrEnumeralCandidateType)
7365 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7366 for (unsigned Right = FirstPromotedIntegralType;
7367 Right < LastPromotedIntegralType; ++Right) {
7368 QualType ParamTypes[2];
7369 ParamTypes[1] = getArithmeticType(Right);
7371 // Add this built-in operator as a candidate (VQ is empty).
7373 S.Context.getLValueReferenceType(getArithmeticType(Left));
7374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7375 if (VisibleTypeConversionsQuals.hasVolatile()) {
7376 // Add this built-in operator as a candidate (VQ is 'volatile').
7377 ParamTypes[0] = getArithmeticType(Left);
7378 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7379 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7380 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7386 // C++ [over.operator]p23:
7388 // There also exist candidate operator functions of the form
7390 // bool operator!(bool);
7391 // bool operator&&(bool, bool);
7392 // bool operator||(bool, bool);
7393 void addExclaimOverload() {
7394 QualType ParamTy = S.Context.BoolTy;
7395 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7396 /*IsAssignmentOperator=*/false,
7397 /*NumContextualBoolArguments=*/1);
7399 void addAmpAmpOrPipePipeOverload() {
7400 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7401 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7402 /*IsAssignmentOperator=*/false,
7403 /*NumContextualBoolArguments=*/2);
7406 // C++ [over.built]p13:
7408 // For every cv-qualified or cv-unqualified object type T there
7409 // exist candidate operator functions of the form
7411 // T* operator+(T*, ptrdiff_t); [ABOVE]
7412 // T& operator[](T*, ptrdiff_t);
7413 // T* operator-(T*, ptrdiff_t); [ABOVE]
7414 // T* operator+(ptrdiff_t, T*); [ABOVE]
7415 // T& operator[](ptrdiff_t, T*);
7416 void addSubscriptOverloads() {
7417 for (BuiltinCandidateTypeSet::iterator
7418 Ptr = CandidateTypes[0].pointer_begin(),
7419 PtrEnd = CandidateTypes[0].pointer_end();
7420 Ptr != PtrEnd; ++Ptr) {
7421 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7422 QualType PointeeType = (*Ptr)->getPointeeType();
7423 if (!PointeeType->isObjectType())
7426 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7428 // T& operator[](T*, ptrdiff_t)
7429 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7432 for (BuiltinCandidateTypeSet::iterator
7433 Ptr = CandidateTypes[1].pointer_begin(),
7434 PtrEnd = CandidateTypes[1].pointer_end();
7435 Ptr != PtrEnd; ++Ptr) {
7436 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7437 QualType PointeeType = (*Ptr)->getPointeeType();
7438 if (!PointeeType->isObjectType())
7441 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7443 // T& operator[](ptrdiff_t, T*)
7444 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7448 // C++ [over.built]p11:
7449 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7450 // C1 is the same type as C2 or is a derived class of C2, T is an object
7451 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7452 // there exist candidate operator functions of the form
7454 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7456 // where CV12 is the union of CV1 and CV2.
7457 void addArrowStarOverloads() {
7458 for (BuiltinCandidateTypeSet::iterator
7459 Ptr = CandidateTypes[0].pointer_begin(),
7460 PtrEnd = CandidateTypes[0].pointer_end();
7461 Ptr != PtrEnd; ++Ptr) {
7462 QualType C1Ty = (*Ptr);
7464 QualifierCollector Q1;
7465 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7466 if (!isa<RecordType>(C1))
7468 // heuristic to reduce number of builtin candidates in the set.
7469 // Add volatile/restrict version only if there are conversions to a
7470 // volatile/restrict type.
7471 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7473 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7475 for (BuiltinCandidateTypeSet::iterator
7476 MemPtr = CandidateTypes[1].member_pointer_begin(),
7477 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7478 MemPtr != MemPtrEnd; ++MemPtr) {
7479 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7480 QualType C2 = QualType(mptr->getClass(), 0);
7481 C2 = C2.getUnqualifiedType();
7482 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7484 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7486 QualType T = mptr->getPointeeType();
7487 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7488 T.isVolatileQualified())
7490 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7491 T.isRestrictQualified())
7493 T = Q1.apply(S.Context, T);
7494 QualType ResultTy = S.Context.getLValueReferenceType(T);
7495 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7500 // Note that we don't consider the first argument, since it has been
7501 // contextually converted to bool long ago. The candidates below are
7502 // therefore added as binary.
7504 // C++ [over.built]p25:
7505 // For every type T, where T is a pointer, pointer-to-member, or scoped
7506 // enumeration type, there exist candidate operator functions of the form
7508 // T operator?(bool, T, T);
7510 void addConditionalOperatorOverloads() {
7511 /// Set of (canonical) types that we've already handled.
7512 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7514 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7515 for (BuiltinCandidateTypeSet::iterator
7516 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7517 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7518 Ptr != PtrEnd; ++Ptr) {
7519 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7522 QualType ParamTypes[2] = { *Ptr, *Ptr };
7523 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7526 for (BuiltinCandidateTypeSet::iterator
7527 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7528 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7529 MemPtr != MemPtrEnd; ++MemPtr) {
7530 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7533 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7534 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7537 if (S.getLangOpts().CPlusPlus11) {
7538 for (BuiltinCandidateTypeSet::iterator
7539 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7540 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7541 Enum != EnumEnd; ++Enum) {
7542 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7545 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7548 QualType ParamTypes[2] = { *Enum, *Enum };
7549 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7556 } // end anonymous namespace
7558 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7559 /// operator overloads to the candidate set (C++ [over.built]), based
7560 /// on the operator @p Op and the arguments given. For example, if the
7561 /// operator is a binary '+', this routine might add "int
7562 /// operator+(int, int)" to cover integer addition.
7564 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7565 SourceLocation OpLoc,
7566 llvm::ArrayRef<Expr *> Args,
7567 OverloadCandidateSet& CandidateSet) {
7568 // Find all of the types that the arguments can convert to, but only
7569 // if the operator we're looking at has built-in operator candidates
7570 // that make use of these types. Also record whether we encounter non-record
7571 // candidate types or either arithmetic or enumeral candidate types.
7572 Qualifiers VisibleTypeConversionsQuals;
7573 VisibleTypeConversionsQuals.addConst();
7574 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7575 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7577 bool HasNonRecordCandidateType = false;
7578 bool HasArithmeticOrEnumeralCandidateType = false;
7579 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7580 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7581 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7582 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7585 (Op == OO_Exclaim ||
7588 VisibleTypeConversionsQuals);
7589 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7590 CandidateTypes[ArgIdx].hasNonRecordTypes();
7591 HasArithmeticOrEnumeralCandidateType =
7592 HasArithmeticOrEnumeralCandidateType ||
7593 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7596 // Exit early when no non-record types have been added to the candidate set
7597 // for any of the arguments to the operator.
7599 // We can't exit early for !, ||, or &&, since there we have always have
7600 // 'bool' overloads.
7601 if (!HasNonRecordCandidateType &&
7602 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7605 // Setup an object to manage the common state for building overloads.
7606 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7607 VisibleTypeConversionsQuals,
7608 HasArithmeticOrEnumeralCandidateType,
7609 CandidateTypes, CandidateSet);
7611 // Dispatch over the operation to add in only those overloads which apply.
7614 case NUM_OVERLOADED_OPERATORS:
7615 llvm_unreachable("Expected an overloaded operator");
7620 case OO_Array_Delete:
7623 "Special operators don't use AddBuiltinOperatorCandidates");
7627 // C++ [over.match.oper]p3:
7628 // -- For the operator ',', the unary operator '&', or the
7629 // operator '->', the built-in candidates set is empty.
7632 case OO_Plus: // '+' is either unary or binary
7633 if (Args.size() == 1)
7634 OpBuilder.addUnaryPlusPointerOverloads();
7637 case OO_Minus: // '-' is either unary or binary
7638 if (Args.size() == 1) {
7639 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7641 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7642 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7646 case OO_Star: // '*' is either unary or binary
7647 if (Args.size() == 1)
7648 OpBuilder.addUnaryStarPointerOverloads();
7650 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7654 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7659 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7660 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7664 case OO_ExclaimEqual:
7665 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7671 case OO_GreaterEqual:
7672 OpBuilder.addRelationalPointerOrEnumeralOverloads();
7673 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7680 case OO_GreaterGreater:
7681 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7684 case OO_Amp: // '&' is either unary or binary
7685 if (Args.size() == 1)
7686 // C++ [over.match.oper]p3:
7687 // -- For the operator ',', the unary operator '&', or the
7688 // operator '->', the built-in candidates set is empty.
7691 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7695 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7699 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7704 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7709 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7712 case OO_PercentEqual:
7713 case OO_LessLessEqual:
7714 case OO_GreaterGreaterEqual:
7718 OpBuilder.addAssignmentIntegralOverloads();
7722 OpBuilder.addExclaimOverload();
7727 OpBuilder.addAmpAmpOrPipePipeOverload();
7731 OpBuilder.addSubscriptOverloads();
7735 OpBuilder.addArrowStarOverloads();
7738 case OO_Conditional:
7739 OpBuilder.addConditionalOperatorOverloads();
7740 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7745 /// \brief Add function candidates found via argument-dependent lookup
7746 /// to the set of overloading candidates.
7748 /// This routine performs argument-dependent name lookup based on the
7749 /// given function name (which may also be an operator name) and adds
7750 /// all of the overload candidates found by ADL to the overload
7751 /// candidate set (C++ [basic.lookup.argdep]).
7753 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7754 bool Operator, SourceLocation Loc,
7755 ArrayRef<Expr *> Args,
7756 TemplateArgumentListInfo *ExplicitTemplateArgs,
7757 OverloadCandidateSet& CandidateSet,
7758 bool PartialOverloading) {
7761 // FIXME: This approach for uniquing ADL results (and removing
7762 // redundant candidates from the set) relies on pointer-equality,
7763 // which means we need to key off the canonical decl. However,
7764 // always going back to the canonical decl might not get us the
7765 // right set of default arguments. What default arguments are
7766 // we supposed to consider on ADL candidates, anyway?
7768 // FIXME: Pass in the explicit template arguments?
7769 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7771 // Erase all of the candidates we already knew about.
7772 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7773 CandEnd = CandidateSet.end();
7774 Cand != CandEnd; ++Cand)
7775 if (Cand->Function) {
7776 Fns.erase(Cand->Function);
7777 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7781 // For each of the ADL candidates we found, add it to the overload
7783 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7784 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7785 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7786 if (ExplicitTemplateArgs)
7789 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7790 PartialOverloading);
7792 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7793 FoundDecl, ExplicitTemplateArgs,
7794 Args, CandidateSet);
7798 /// isBetterOverloadCandidate - Determines whether the first overload
7799 /// candidate is a better candidate than the second (C++ 13.3.3p1).
7801 isBetterOverloadCandidate(Sema &S,
7802 const OverloadCandidate &Cand1,
7803 const OverloadCandidate &Cand2,
7805 bool UserDefinedConversion) {
7806 // Define viable functions to be better candidates than non-viable
7809 return Cand1.Viable;
7810 else if (!Cand1.Viable)
7813 // C++ [over.match.best]p1:
7815 // -- if F is a static member function, ICS1(F) is defined such
7816 // that ICS1(F) is neither better nor worse than ICS1(G) for
7817 // any function G, and, symmetrically, ICS1(G) is neither
7818 // better nor worse than ICS1(F).
7819 unsigned StartArg = 0;
7820 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7823 // C++ [over.match.best]p1:
7824 // A viable function F1 is defined to be a better function than another
7825 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
7826 // conversion sequence than ICSi(F2), and then...
7827 unsigned NumArgs = Cand1.NumConversions;
7828 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7829 bool HasBetterConversion = false;
7830 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7831 switch (CompareImplicitConversionSequences(S,
7832 Cand1.Conversions[ArgIdx],
7833 Cand2.Conversions[ArgIdx])) {
7834 case ImplicitConversionSequence::Better:
7835 // Cand1 has a better conversion sequence.
7836 HasBetterConversion = true;
7839 case ImplicitConversionSequence::Worse:
7840 // Cand1 can't be better than Cand2.
7843 case ImplicitConversionSequence::Indistinguishable:
7849 // -- for some argument j, ICSj(F1) is a better conversion sequence than
7850 // ICSj(F2), or, if not that,
7851 if (HasBetterConversion)
7854 // - F1 is a non-template function and F2 is a function template
7855 // specialization, or, if not that,
7856 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7857 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7860 // -- F1 and F2 are function template specializations, and the function
7861 // template for F1 is more specialized than the template for F2
7862 // according to the partial ordering rules described in 14.5.5.2, or,
7864 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7865 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7866 if (FunctionTemplateDecl *BetterTemplate
7867 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7868 Cand2.Function->getPrimaryTemplate(),
7870 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7872 Cand1.ExplicitCallArguments))
7873 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7876 // -- the context is an initialization by user-defined conversion
7877 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7878 // from the return type of F1 to the destination type (i.e.,
7879 // the type of the entity being initialized) is a better
7880 // conversion sequence than the standard conversion sequence
7881 // from the return type of F2 to the destination type.
7882 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7883 isa<CXXConversionDecl>(Cand1.Function) &&
7884 isa<CXXConversionDecl>(Cand2.Function)) {
7885 // First check whether we prefer one of the conversion functions over the
7886 // other. This only distinguishes the results in non-standard, extension
7887 // cases such as the conversion from a lambda closure type to a function
7888 // pointer or block.
7889 ImplicitConversionSequence::CompareKind FuncResult
7890 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7891 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7894 switch (CompareStandardConversionSequences(S,
7895 Cand1.FinalConversion,
7896 Cand2.FinalConversion)) {
7897 case ImplicitConversionSequence::Better:
7898 // Cand1 has a better conversion sequence.
7901 case ImplicitConversionSequence::Worse:
7902 // Cand1 can't be better than Cand2.
7905 case ImplicitConversionSequence::Indistinguishable:
7914 /// \brief Computes the best viable function (C++ 13.3.3)
7915 /// within an overload candidate set.
7917 /// \param Loc The location of the function name (or operator symbol) for
7918 /// which overload resolution occurs.
7920 /// \param Best If overload resolution was successful or found a deleted
7921 /// function, \p Best points to the candidate function found.
7923 /// \returns The result of overload resolution.
7925 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7927 bool UserDefinedConversion) {
7928 // Find the best viable function.
7930 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7932 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7933 UserDefinedConversion))
7937 // If we didn't find any viable functions, abort.
7939 return OR_No_Viable_Function;
7941 // Make sure that this function is better than every other viable
7942 // function. If not, we have an ambiguity.
7943 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7946 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7947 UserDefinedConversion)) {
7949 return OR_Ambiguous;
7953 // Best is the best viable function.
7954 if (Best->Function &&
7955 (Best->Function->isDeleted() ||
7956 S.isFunctionConsideredUnavailable(Best->Function)))
7964 enum OverloadCandidateKind {
7968 oc_function_template,
7970 oc_constructor_template,
7971 oc_implicit_default_constructor,
7972 oc_implicit_copy_constructor,
7973 oc_implicit_move_constructor,
7974 oc_implicit_copy_assignment,
7975 oc_implicit_move_assignment,
7976 oc_implicit_inherited_constructor
7979 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7981 std::string &Description) {
7982 bool isTemplate = false;
7984 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7986 Description = S.getTemplateArgumentBindingsText(
7987 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7990 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7991 if (!Ctor->isImplicit())
7992 return isTemplate ? oc_constructor_template : oc_constructor;
7994 if (Ctor->getInheritedConstructor())
7995 return oc_implicit_inherited_constructor;
7997 if (Ctor->isDefaultConstructor())
7998 return oc_implicit_default_constructor;
8000 if (Ctor->isMoveConstructor())
8001 return oc_implicit_move_constructor;
8003 assert(Ctor->isCopyConstructor() &&
8004 "unexpected sort of implicit constructor");
8005 return oc_implicit_copy_constructor;
8008 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8009 // This actually gets spelled 'candidate function' for now, but
8010 // it doesn't hurt to split it out.
8011 if (!Meth->isImplicit())
8012 return isTemplate ? oc_method_template : oc_method;
8014 if (Meth->isMoveAssignmentOperator())
8015 return oc_implicit_move_assignment;
8017 if (Meth->isCopyAssignmentOperator())
8018 return oc_implicit_copy_assignment;
8020 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8024 return isTemplate ? oc_function_template : oc_function;
8027 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8028 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8031 Ctor = Ctor->getInheritedConstructor();
8034 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8037 } // end anonymous namespace
8039 // Notes the location of an overload candidate.
8040 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8042 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8043 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8044 << (unsigned) K << FnDesc;
8045 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8046 Diag(Fn->getLocation(), PD);
8047 MaybeEmitInheritedConstructorNote(*this, Fn);
8050 //Notes the location of all overload candidates designated through
8052 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8053 assert(OverloadedExpr->getType() == Context.OverloadTy);
8055 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8056 OverloadExpr *OvlExpr = Ovl.Expression;
8058 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8059 IEnd = OvlExpr->decls_end();
8061 if (FunctionTemplateDecl *FunTmpl =
8062 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8063 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8064 } else if (FunctionDecl *Fun
8065 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8066 NoteOverloadCandidate(Fun, DestType);
8071 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
8072 /// "lead" diagnostic; it will be given two arguments, the source and
8073 /// target types of the conversion.
8074 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8076 SourceLocation CaretLoc,
8077 const PartialDiagnostic &PDiag) const {
8078 S.Diag(CaretLoc, PDiag)
8079 << Ambiguous.getFromType() << Ambiguous.getToType();
8080 // FIXME: The note limiting machinery is borrowed from
8081 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8082 // refactoring here.
8083 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8084 unsigned CandsShown = 0;
8085 AmbiguousConversionSequence::const_iterator I, E;
8086 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8087 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8090 S.NoteOverloadCandidate(*I);
8093 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8098 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8099 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8100 assert(Conv.isBad());
8101 assert(Cand->Function && "for now, candidate must be a function");
8102 FunctionDecl *Fn = Cand->Function;
8104 // There's a conversion slot for the object argument if this is a
8105 // non-constructor method. Note that 'I' corresponds the
8106 // conversion-slot index.
8107 bool isObjectArgument = false;
8108 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8110 isObjectArgument = true;
8116 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8118 Expr *FromExpr = Conv.Bad.FromExpr;
8119 QualType FromTy = Conv.Bad.getFromType();
8120 QualType ToTy = Conv.Bad.getToType();
8122 if (FromTy == S.Context.OverloadTy) {
8123 assert(FromExpr && "overload set argument came from implicit argument?");
8124 Expr *E = FromExpr->IgnoreParens();
8125 if (isa<UnaryOperator>(E))
8126 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8127 DeclarationName Name = cast<OverloadExpr>(E)->getName();
8129 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8130 << (unsigned) FnKind << FnDesc
8131 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8132 << ToTy << Name << I+1;
8133 MaybeEmitInheritedConstructorNote(S, Fn);
8137 // Do some hand-waving analysis to see if the non-viability is due
8138 // to a qualifier mismatch.
8139 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8140 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8141 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8142 CToTy = RT->getPointeeType();
8144 // TODO: detect and diagnose the full richness of const mismatches.
8145 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8146 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8147 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8150 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8151 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8152 Qualifiers FromQs = CFromTy.getQualifiers();
8153 Qualifiers ToQs = CToTy.getQualifiers();
8155 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8157 << (unsigned) FnKind << FnDesc
8158 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8160 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8161 << (unsigned) isObjectArgument << I+1;
8162 MaybeEmitInheritedConstructorNote(S, Fn);
8166 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8167 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8168 << (unsigned) FnKind << FnDesc
8169 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8171 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8172 << (unsigned) isObjectArgument << I+1;
8173 MaybeEmitInheritedConstructorNote(S, Fn);
8177 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8179 << (unsigned) FnKind << FnDesc
8180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8182 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8183 << (unsigned) isObjectArgument << I+1;
8184 MaybeEmitInheritedConstructorNote(S, Fn);
8188 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8189 assert(CVR && "unexpected qualifiers mismatch");
8191 if (isObjectArgument) {
8192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8193 << (unsigned) FnKind << FnDesc
8194 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8195 << FromTy << (CVR - 1);
8197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8198 << (unsigned) FnKind << FnDesc
8199 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8200 << FromTy << (CVR - 1) << I+1;
8202 MaybeEmitInheritedConstructorNote(S, Fn);
8206 // Special diagnostic for failure to convert an initializer list, since
8207 // telling the user that it has type void is not useful.
8208 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8209 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8210 << (unsigned) FnKind << FnDesc
8211 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8212 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8213 MaybeEmitInheritedConstructorNote(S, Fn);
8217 // Diagnose references or pointers to incomplete types differently,
8218 // since it's far from impossible that the incompleteness triggered
8220 QualType TempFromTy = FromTy.getNonReferenceType();
8221 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8222 TempFromTy = PTy->getPointeeType();
8223 if (TempFromTy->isIncompleteType()) {
8224 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8225 << (unsigned) FnKind << FnDesc
8226 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8227 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8228 MaybeEmitInheritedConstructorNote(S, Fn);
8232 // Diagnose base -> derived pointer conversions.
8233 unsigned BaseToDerivedConversion = 0;
8234 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8235 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8236 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8237 FromPtrTy->getPointeeType()) &&
8238 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8239 !ToPtrTy->getPointeeType()->isIncompleteType() &&
8240 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8241 FromPtrTy->getPointeeType()))
8242 BaseToDerivedConversion = 1;
8244 } else if (const ObjCObjectPointerType *FromPtrTy
8245 = FromTy->getAs<ObjCObjectPointerType>()) {
8246 if (const ObjCObjectPointerType *ToPtrTy
8247 = ToTy->getAs<ObjCObjectPointerType>())
8248 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8249 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8250 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8251 FromPtrTy->getPointeeType()) &&
8252 FromIface->isSuperClassOf(ToIface))
8253 BaseToDerivedConversion = 2;
8254 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8255 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8256 !FromTy->isIncompleteType() &&
8257 !ToRefTy->getPointeeType()->isIncompleteType() &&
8258 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8259 BaseToDerivedConversion = 3;
8260 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8261 ToTy.getNonReferenceType().getCanonicalType() ==
8262 FromTy.getNonReferenceType().getCanonicalType()) {
8263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8264 << (unsigned) FnKind << FnDesc
8265 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8266 << (unsigned) isObjectArgument << I + 1;
8267 MaybeEmitInheritedConstructorNote(S, Fn);
8272 if (BaseToDerivedConversion) {
8273 S.Diag(Fn->getLocation(),
8274 diag::note_ovl_candidate_bad_base_to_derived_conv)
8275 << (unsigned) FnKind << FnDesc
8276 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8277 << (BaseToDerivedConversion - 1)
8278 << FromTy << ToTy << I+1;
8279 MaybeEmitInheritedConstructorNote(S, Fn);
8283 if (isa<ObjCObjectPointerType>(CFromTy) &&
8284 isa<PointerType>(CToTy)) {
8285 Qualifiers FromQs = CFromTy.getQualifiers();
8286 Qualifiers ToQs = CToTy.getQualifiers();
8287 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8289 << (unsigned) FnKind << FnDesc
8290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8291 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8292 MaybeEmitInheritedConstructorNote(S, Fn);
8297 // Emit the generic diagnostic and, optionally, add the hints to it.
8298 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8299 FDiag << (unsigned) FnKind << FnDesc
8300 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8301 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8302 << (unsigned) (Cand->Fix.Kind);
8304 // If we can fix the conversion, suggest the FixIts.
8305 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8306 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8308 S.Diag(Fn->getLocation(), FDiag);
8310 MaybeEmitInheritedConstructorNote(S, Fn);
8313 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8314 unsigned NumFormalArgs) {
8315 // TODO: treat calls to a missing default constructor as a special case
8317 FunctionDecl *Fn = Cand->Function;
8318 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8320 unsigned MinParams = Fn->getMinRequiredArguments();
8322 // With invalid overloaded operators, it's possible that we think we
8323 // have an arity mismatch when it fact it looks like we have the
8324 // right number of arguments, because only overloaded operators have
8325 // the weird behavior of overloading member and non-member functions.
8326 // Just don't report anything.
8327 if (Fn->isInvalidDecl() &&
8328 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8331 // at least / at most / exactly
8332 unsigned mode, modeCount;
8333 if (NumFormalArgs < MinParams) {
8334 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8335 (Cand->FailureKind == ovl_fail_bad_deduction &&
8336 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8337 if (MinParams != FnTy->getNumArgs() ||
8338 FnTy->isVariadic() || FnTy->isTemplateVariadic())
8339 mode = 0; // "at least"
8341 mode = 2; // "exactly"
8342 modeCount = MinParams;
8344 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8345 (Cand->FailureKind == ovl_fail_bad_deduction &&
8346 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8347 if (MinParams != FnTy->getNumArgs())
8348 mode = 1; // "at most"
8350 mode = 2; // "exactly"
8351 modeCount = FnTy->getNumArgs();
8354 std::string Description;
8355 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8357 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8358 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8359 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8360 << Fn->getParamDecl(0) << NumFormalArgs;
8362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8363 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8364 << modeCount << NumFormalArgs;
8365 MaybeEmitInheritedConstructorNote(S, Fn);
8368 /// Diagnose a failed template-argument deduction.
8369 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8371 FunctionDecl *Fn = Cand->Function; // pattern
8373 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8375 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8376 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8377 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8378 switch (Cand->DeductionFailure.Result) {
8379 case Sema::TDK_Success:
8380 llvm_unreachable("TDK_success while diagnosing bad deduction");
8382 case Sema::TDK_Incomplete: {
8383 assert(ParamD && "no parameter found for incomplete deduction result");
8384 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8385 << ParamD->getDeclName();
8386 MaybeEmitInheritedConstructorNote(S, Fn);
8390 case Sema::TDK_Underqualified: {
8391 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8392 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8394 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8396 // Param will have been canonicalized, but it should just be a
8397 // qualified version of ParamD, so move the qualifiers to that.
8398 QualifierCollector Qs;
8400 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8401 assert(S.Context.hasSameType(Param, NonCanonParam));
8403 // Arg has also been canonicalized, but there's nothing we can do
8404 // about that. It also doesn't matter as much, because it won't
8405 // have any template parameters in it (because deduction isn't
8406 // done on dependent types).
8407 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8409 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8410 << ParamD->getDeclName() << Arg << NonCanonParam;
8411 MaybeEmitInheritedConstructorNote(S, Fn);
8415 case Sema::TDK_Inconsistent: {
8416 assert(ParamD && "no parameter found for inconsistent deduction result");
8418 if (isa<TemplateTypeParmDecl>(ParamD))
8420 else if (isa<NonTypeTemplateParmDecl>(ParamD))
8426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8427 << which << ParamD->getDeclName()
8428 << *Cand->DeductionFailure.getFirstArg()
8429 << *Cand->DeductionFailure.getSecondArg();
8430 MaybeEmitInheritedConstructorNote(S, Fn);
8434 case Sema::TDK_InvalidExplicitArguments:
8435 assert(ParamD && "no parameter found for invalid explicit arguments");
8436 if (ParamD->getDeclName())
8437 S.Diag(Fn->getLocation(),
8438 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8439 << ParamD->getDeclName();
8442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8443 index = TTP->getIndex();
8444 else if (NonTypeTemplateParmDecl *NTTP
8445 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8446 index = NTTP->getIndex();
8448 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8449 S.Diag(Fn->getLocation(),
8450 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8453 MaybeEmitInheritedConstructorNote(S, Fn);
8456 case Sema::TDK_TooManyArguments:
8457 case Sema::TDK_TooFewArguments:
8458 DiagnoseArityMismatch(S, Cand, NumArgs);
8461 case Sema::TDK_InstantiationDepth:
8462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8463 MaybeEmitInheritedConstructorNote(S, Fn);
8466 case Sema::TDK_SubstitutionFailure: {
8467 // Format the template argument list into the argument string.
8468 SmallString<128> TemplateArgString;
8469 if (TemplateArgumentList *Args =
8470 Cand->DeductionFailure.getTemplateArgumentList()) {
8471 TemplateArgString = " ";
8472 TemplateArgString += S.getTemplateArgumentBindingsText(
8473 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8476 // If this candidate was disabled by enable_if, say so.
8477 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8478 if (PDiag && PDiag->second.getDiagID() ==
8479 diag::err_typename_nested_not_found_enable_if) {
8480 // FIXME: Use the source range of the condition, and the fully-qualified
8481 // name of the enable_if template. These are both present in PDiag.
8482 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8483 << "'enable_if'" << TemplateArgString;
8487 // Format the SFINAE diagnostic into the argument string.
8488 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8489 // formatted message in another diagnostic.
8490 SmallString<128> SFINAEArgString;
8493 SFINAEArgString = ": ";
8494 R = SourceRange(PDiag->first, PDiag->first);
8495 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8499 << TemplateArgString << SFINAEArgString << R;
8500 MaybeEmitInheritedConstructorNote(S, Fn);
8504 case Sema::TDK_FailedOverloadResolution: {
8505 OverloadExpr::FindResult R =
8506 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8507 S.Diag(Fn->getLocation(),
8508 diag::note_ovl_candidate_failed_overload_resolution)
8509 << R.Expression->getName();
8513 case Sema::TDK_NonDeducedMismatch: {
8514 // FIXME: Provide a source location to indicate what we couldn't match.
8515 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8516 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8517 if (FirstTA.getKind() == TemplateArgument::Template &&
8518 SecondTA.getKind() == TemplateArgument::Template) {
8519 TemplateName FirstTN = FirstTA.getAsTemplate();
8520 TemplateName SecondTN = SecondTA.getAsTemplate();
8521 if (FirstTN.getKind() == TemplateName::Template &&
8522 SecondTN.getKind() == TemplateName::Template) {
8523 if (FirstTN.getAsTemplateDecl()->getName() ==
8524 SecondTN.getAsTemplateDecl()->getName()) {
8525 // FIXME: This fixes a bad diagnostic where both templates are named
8526 // the same. This particular case is a bit difficult since:
8527 // 1) It is passed as a string to the diagnostic printer.
8528 // 2) The diagnostic printer only attempts to find a better
8529 // name for types, not decls.
8530 // Ideally, this should folded into the diagnostic printer.
8531 S.Diag(Fn->getLocation(),
8532 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8533 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8539 << FirstTA << SecondTA;
8542 // TODO: diagnose these individually, then kill off
8543 // note_ovl_candidate_bad_deduction, which is uselessly vague.
8544 case Sema::TDK_MiscellaneousDeductionFailure:
8545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8546 MaybeEmitInheritedConstructorNote(S, Fn);
8551 /// CUDA: diagnose an invalid call across targets.
8552 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8553 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8554 FunctionDecl *Callee = Cand->Function;
8556 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8557 CalleeTarget = S.IdentifyCUDATarget(Callee);
8560 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8562 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8563 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8566 /// Generates a 'note' diagnostic for an overload candidate. We've
8567 /// already generated a primary error at the call site.
8569 /// It really does need to be a single diagnostic with its caret
8570 /// pointed at the candidate declaration. Yes, this creates some
8571 /// major challenges of technical writing. Yes, this makes pointing
8572 /// out problems with specific arguments quite awkward. It's still
8573 /// better than generating twenty screens of text for every failed
8576 /// It would be great to be able to express per-candidate problems
8577 /// more richly for those diagnostic clients that cared, but we'd
8578 /// still have to be just as careful with the default diagnostics.
8579 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8581 FunctionDecl *Fn = Cand->Function;
8583 // Note deleted candidates, but only if they're viable.
8584 if (Cand->Viable && (Fn->isDeleted() ||
8585 S.isFunctionConsideredUnavailable(Fn))) {
8587 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8591 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8592 MaybeEmitInheritedConstructorNote(S, Fn);
8596 // We don't really have anything else to say about viable candidates.
8598 S.NoteOverloadCandidate(Fn);
8602 switch (Cand->FailureKind) {
8603 case ovl_fail_too_many_arguments:
8604 case ovl_fail_too_few_arguments:
8605 return DiagnoseArityMismatch(S, Cand, NumArgs);
8607 case ovl_fail_bad_deduction:
8608 return DiagnoseBadDeduction(S, Cand, NumArgs);
8610 case ovl_fail_trivial_conversion:
8611 case ovl_fail_bad_final_conversion:
8612 case ovl_fail_final_conversion_not_exact:
8613 return S.NoteOverloadCandidate(Fn);
8615 case ovl_fail_bad_conversion: {
8616 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8617 for (unsigned N = Cand->NumConversions; I != N; ++I)
8618 if (Cand->Conversions[I].isBad())
8619 return DiagnoseBadConversion(S, Cand, I);
8621 // FIXME: this currently happens when we're called from SemaInit
8622 // when user-conversion overload fails. Figure out how to handle
8623 // those conditions and diagnose them well.
8624 return S.NoteOverloadCandidate(Fn);
8627 case ovl_fail_bad_target:
8628 return DiagnoseBadTarget(S, Cand);
8632 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8633 // Desugar the type of the surrogate down to a function type,
8634 // retaining as many typedefs as possible while still showing
8635 // the function type (and, therefore, its parameter types).
8636 QualType FnType = Cand->Surrogate->getConversionType();
8637 bool isLValueReference = false;
8638 bool isRValueReference = false;
8639 bool isPointer = false;
8640 if (const LValueReferenceType *FnTypeRef =
8641 FnType->getAs<LValueReferenceType>()) {
8642 FnType = FnTypeRef->getPointeeType();
8643 isLValueReference = true;
8644 } else if (const RValueReferenceType *FnTypeRef =
8645 FnType->getAs<RValueReferenceType>()) {
8646 FnType = FnTypeRef->getPointeeType();
8647 isRValueReference = true;
8649 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8650 FnType = FnTypePtr->getPointeeType();
8653 // Desugar down to a function type.
8654 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8655 // Reconstruct the pointer/reference as appropriate.
8656 if (isPointer) FnType = S.Context.getPointerType(FnType);
8657 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8658 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8660 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8662 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8665 void NoteBuiltinOperatorCandidate(Sema &S,
8667 SourceLocation OpLoc,
8668 OverloadCandidate *Cand) {
8669 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8670 std::string TypeStr("operator");
8673 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8674 if (Cand->NumConversions == 1) {
8676 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8679 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8681 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8685 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8686 OverloadCandidate *Cand) {
8687 unsigned NoOperands = Cand->NumConversions;
8688 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8689 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8690 if (ICS.isBad()) break; // all meaningless after first invalid
8691 if (!ICS.isAmbiguous()) continue;
8693 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8694 S.PDiag(diag::note_ambiguous_type_conversion));
8698 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8700 return Cand->Function->getLocation();
8701 if (Cand->IsSurrogate)
8702 return Cand->Surrogate->getLocation();
8703 return SourceLocation();
8707 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8708 switch ((Sema::TemplateDeductionResult)DFI.Result) {
8709 case Sema::TDK_Success:
8710 llvm_unreachable("TDK_success while diagnosing bad deduction");
8712 case Sema::TDK_Invalid:
8713 case Sema::TDK_Incomplete:
8716 case Sema::TDK_Underqualified:
8717 case Sema::TDK_Inconsistent:
8720 case Sema::TDK_SubstitutionFailure:
8721 case Sema::TDK_NonDeducedMismatch:
8722 case Sema::TDK_MiscellaneousDeductionFailure:
8725 case Sema::TDK_InstantiationDepth:
8726 case Sema::TDK_FailedOverloadResolution:
8729 case Sema::TDK_InvalidExplicitArguments:
8732 case Sema::TDK_TooManyArguments:
8733 case Sema::TDK_TooFewArguments:
8736 llvm_unreachable("Unhandled deduction result");
8739 struct CompareOverloadCandidatesForDisplay {
8741 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8743 bool operator()(const OverloadCandidate *L,
8744 const OverloadCandidate *R) {
8745 // Fast-path this check.
8746 if (L == R) return false;
8748 // Order first by viability.
8750 if (!R->Viable) return true;
8752 // TODO: introduce a tri-valued comparison for overload
8753 // candidates. Would be more worthwhile if we had a sort
8754 // that could exploit it.
8755 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8756 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8757 } else if (R->Viable)
8760 assert(L->Viable == R->Viable);
8762 // Criteria by which we can sort non-viable candidates:
8764 // 1. Arity mismatches come after other candidates.
8765 if (L->FailureKind == ovl_fail_too_many_arguments ||
8766 L->FailureKind == ovl_fail_too_few_arguments)
8768 if (R->FailureKind == ovl_fail_too_many_arguments ||
8769 R->FailureKind == ovl_fail_too_few_arguments)
8772 // 2. Bad conversions come first and are ordered by the number
8773 // of bad conversions and quality of good conversions.
8774 if (L->FailureKind == ovl_fail_bad_conversion) {
8775 if (R->FailureKind != ovl_fail_bad_conversion)
8778 // The conversion that can be fixed with a smaller number of changes,
8780 unsigned numLFixes = L->Fix.NumConversionsFixed;
8781 unsigned numRFixes = R->Fix.NumConversionsFixed;
8782 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8783 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8784 if (numLFixes != numRFixes) {
8785 if (numLFixes < numRFixes)
8791 // If there's any ordering between the defined conversions...
8792 // FIXME: this might not be transitive.
8793 assert(L->NumConversions == R->NumConversions);
8796 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8797 for (unsigned E = L->NumConversions; I != E; ++I) {
8798 switch (CompareImplicitConversionSequences(S,
8800 R->Conversions[I])) {
8801 case ImplicitConversionSequence::Better:
8805 case ImplicitConversionSequence::Worse:
8809 case ImplicitConversionSequence::Indistinguishable:
8813 if (leftBetter > 0) return true;
8814 if (leftBetter < 0) return false;
8816 } else if (R->FailureKind == ovl_fail_bad_conversion)
8819 if (L->FailureKind == ovl_fail_bad_deduction) {
8820 if (R->FailureKind != ovl_fail_bad_deduction)
8823 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8824 return RankDeductionFailure(L->DeductionFailure)
8825 < RankDeductionFailure(R->DeductionFailure);
8826 } else if (R->FailureKind == ovl_fail_bad_deduction)
8832 // Sort everything else by location.
8833 SourceLocation LLoc = GetLocationForCandidate(L);
8834 SourceLocation RLoc = GetLocationForCandidate(R);
8836 // Put candidates without locations (e.g. builtins) at the end.
8837 if (LLoc.isInvalid()) return false;
8838 if (RLoc.isInvalid()) return true;
8840 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8844 /// CompleteNonViableCandidate - Normally, overload resolution only
8845 /// computes up to the first. Produces the FixIt set if possible.
8846 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8847 ArrayRef<Expr *> Args) {
8848 assert(!Cand->Viable);
8850 // Don't do anything on failures other than bad conversion.
8851 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8853 // We only want the FixIts if all the arguments can be corrected.
8854 bool Unfixable = false;
8855 // Use a implicit copy initialization to check conversion fixes.
8856 Cand->Fix.setConversionChecker(TryCopyInitialization);
8858 // Skip forward to the first bad conversion.
8859 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8860 unsigned ConvCount = Cand->NumConversions;
8862 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8864 if (Cand->Conversions[ConvIdx - 1].isBad()) {
8865 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8870 if (ConvIdx == ConvCount)
8873 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8874 "remaining conversion is initialized?");
8876 // FIXME: this should probably be preserved from the overload
8877 // operation somehow.
8878 bool SuppressUserConversions = false;
8880 const FunctionProtoType* Proto;
8881 unsigned ArgIdx = ConvIdx;
8883 if (Cand->IsSurrogate) {
8885 = Cand->Surrogate->getConversionType().getNonReferenceType();
8886 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8887 ConvType = ConvPtrType->getPointeeType();
8888 Proto = ConvType->getAs<FunctionProtoType>();
8890 } else if (Cand->Function) {
8891 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8892 if (isa<CXXMethodDecl>(Cand->Function) &&
8893 !isa<CXXConstructorDecl>(Cand->Function))
8896 // Builtin binary operator with a bad first conversion.
8897 assert(ConvCount <= 3);
8898 for (; ConvIdx != ConvCount; ++ConvIdx)
8899 Cand->Conversions[ConvIdx]
8900 = TryCopyInitialization(S, Args[ConvIdx],
8901 Cand->BuiltinTypes.ParamTypes[ConvIdx],
8902 SuppressUserConversions,
8903 /*InOverloadResolution*/ true,
8904 /*AllowObjCWritebackConversion=*/
8905 S.getLangOpts().ObjCAutoRefCount);
8909 // Fill in the rest of the conversions.
8910 unsigned NumArgsInProto = Proto->getNumArgs();
8911 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8912 if (ArgIdx < NumArgsInProto) {
8913 Cand->Conversions[ConvIdx]
8914 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8915 SuppressUserConversions,
8916 /*InOverloadResolution=*/true,
8917 /*AllowObjCWritebackConversion=*/
8918 S.getLangOpts().ObjCAutoRefCount);
8919 // Store the FixIt in the candidate if it exists.
8920 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8921 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8924 Cand->Conversions[ConvIdx].setEllipsis();
8928 } // end anonymous namespace
8930 /// PrintOverloadCandidates - When overload resolution fails, prints
8931 /// diagnostic messages containing the candidates in the candidate
8933 void OverloadCandidateSet::NoteCandidates(Sema &S,
8934 OverloadCandidateDisplayKind OCD,
8935 ArrayRef<Expr *> Args,
8937 SourceLocation OpLoc) {
8938 // Sort the candidates by viability and position. Sorting directly would
8939 // be prohibitive, so we make a set of pointers and sort those.
8940 SmallVector<OverloadCandidate*, 32> Cands;
8941 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8942 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8944 Cands.push_back(Cand);
8945 else if (OCD == OCD_AllCandidates) {
8946 CompleteNonViableCandidate(S, Cand, Args);
8947 if (Cand->Function || Cand->IsSurrogate)
8948 Cands.push_back(Cand);
8949 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8950 // want to list every possible builtin candidate.
8954 std::sort(Cands.begin(), Cands.end(),
8955 CompareOverloadCandidatesForDisplay(S));
8957 bool ReportedAmbiguousConversions = false;
8959 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8960 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8961 unsigned CandsShown = 0;
8962 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8963 OverloadCandidate *Cand = *I;
8965 // Set an arbitrary limit on the number of candidate functions we'll spam
8966 // the user with. FIXME: This limit should depend on details of the
8968 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
8974 NoteFunctionCandidate(S, Cand, Args.size());
8975 else if (Cand->IsSurrogate)
8976 NoteSurrogateCandidate(S, Cand);
8978 assert(Cand->Viable &&
8979 "Non-viable built-in candidates are not added to Cands.");
8980 // Generally we only see ambiguities including viable builtin
8981 // operators if overload resolution got screwed up by an
8982 // ambiguous user-defined conversion.
8984 // FIXME: It's quite possible for different conversions to see
8985 // different ambiguities, though.
8986 if (!ReportedAmbiguousConversions) {
8987 NoteAmbiguousUserConversions(S, OpLoc, Cand);
8988 ReportedAmbiguousConversions = true;
8991 // If this is a viable builtin, print it.
8992 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8997 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9000 // [PossiblyAFunctionType] --> [Return]
9001 // NonFunctionType --> NonFunctionType
9003 // R (*)(A) --> R (A)
9004 // R (&)(A) --> R (A)
9005 // R (S::*)(A) --> R (A)
9006 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9007 QualType Ret = PossiblyAFunctionType;
9008 if (const PointerType *ToTypePtr =
9009 PossiblyAFunctionType->getAs<PointerType>())
9010 Ret = ToTypePtr->getPointeeType();
9011 else if (const ReferenceType *ToTypeRef =
9012 PossiblyAFunctionType->getAs<ReferenceType>())
9013 Ret = ToTypeRef->getPointeeType();
9014 else if (const MemberPointerType *MemTypePtr =
9015 PossiblyAFunctionType->getAs<MemberPointerType>())
9016 Ret = MemTypePtr->getPointeeType();
9018 Context.getCanonicalType(Ret).getUnqualifiedType();
9022 // A helper class to help with address of function resolution
9023 // - allows us to avoid passing around all those ugly parameters
9024 class AddressOfFunctionResolver
9028 const QualType& TargetType;
9029 QualType TargetFunctionType; // Extracted function type from target type
9032 //DeclAccessPair& ResultFunctionAccessPair;
9033 ASTContext& Context;
9035 bool TargetTypeIsNonStaticMemberFunction;
9036 bool FoundNonTemplateFunction;
9038 OverloadExpr::FindResult OvlExprInfo;
9039 OverloadExpr *OvlExpr;
9040 TemplateArgumentListInfo OvlExplicitTemplateArgs;
9041 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9044 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9045 const QualType& TargetType, bool Complain)
9046 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9047 Complain(Complain), Context(S.getASTContext()),
9048 TargetTypeIsNonStaticMemberFunction(
9049 !!TargetType->getAs<MemberPointerType>()),
9050 FoundNonTemplateFunction(false),
9051 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9052 OvlExpr(OvlExprInfo.Expression)
9054 ExtractUnqualifiedFunctionTypeFromTargetType();
9056 if (!TargetFunctionType->isFunctionType()) {
9057 if (OvlExpr->hasExplicitTemplateArgs()) {
9059 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
9060 OvlExpr, false, &dap) ) {
9062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9063 if (!Method->isStatic()) {
9064 // If the target type is a non-function type and the function
9065 // found is a non-static member function, pretend as if that was
9066 // the target, it's the only possible type to end up with.
9067 TargetTypeIsNonStaticMemberFunction = true;
9069 // And skip adding the function if its not in the proper form.
9070 // We'll diagnose this due to an empty set of functions.
9071 if (!OvlExprInfo.HasFormOfMemberPointer)
9076 Matches.push_back(std::make_pair(dap,Fn));
9082 if (OvlExpr->hasExplicitTemplateArgs())
9083 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9085 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9086 // C++ [over.over]p4:
9087 // If more than one function is selected, [...]
9088 if (Matches.size() > 1) {
9089 if (FoundNonTemplateFunction)
9090 EliminateAllTemplateMatches();
9092 EliminateAllExceptMostSpecializedTemplate();
9098 bool isTargetTypeAFunction() const {
9099 return TargetFunctionType->isFunctionType();
9102 // [ToType] [Return]
9104 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9105 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9106 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9107 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9108 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9111 // return true if any matching specializations were found
9112 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9113 const DeclAccessPair& CurAccessFunPair) {
9114 if (CXXMethodDecl *Method
9115 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9116 // Skip non-static function templates when converting to pointer, and
9117 // static when converting to member pointer.
9118 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9121 else if (TargetTypeIsNonStaticMemberFunction)
9124 // C++ [over.over]p2:
9125 // If the name is a function template, template argument deduction is
9126 // done (14.8.2.2), and if the argument deduction succeeds, the
9127 // resulting template argument list is used to generate a single
9128 // function template specialization, which is added to the set of
9129 // overloaded functions considered.
9130 FunctionDecl *Specialization = 0;
9131 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9132 if (Sema::TemplateDeductionResult Result
9133 = S.DeduceTemplateArguments(FunctionTemplate,
9134 &OvlExplicitTemplateArgs,
9135 TargetFunctionType, Specialization,
9136 Info, /*InOverloadResolution=*/true)) {
9137 // FIXME: make a note of the failed deduction for diagnostics.
9142 // Template argument deduction ensures that we have an exact match or
9143 // compatible pointer-to-function arguments that would be adjusted by ICS.
9144 // This function template specicalization works.
9145 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9146 assert(S.isSameOrCompatibleFunctionType(
9147 Context.getCanonicalType(Specialization->getType()),
9148 Context.getCanonicalType(TargetFunctionType)));
9149 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9153 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9154 const DeclAccessPair& CurAccessFunPair) {
9155 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9156 // Skip non-static functions when converting to pointer, and static
9157 // when converting to member pointer.
9158 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9161 else if (TargetTypeIsNonStaticMemberFunction)
9164 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9165 if (S.getLangOpts().CUDA)
9166 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9167 if (S.CheckCUDATarget(Caller, FunDecl))
9170 // If any candidate has a placeholder return type, trigger its deduction
9172 if (S.getLangOpts().CPlusPlus1y &&
9173 FunDecl->getResultType()->isUndeducedType() &&
9174 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9178 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9179 FunDecl->getType()) ||
9180 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9182 Matches.push_back(std::make_pair(CurAccessFunPair,
9183 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9184 FoundNonTemplateFunction = true;
9192 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9195 // If the overload expression doesn't have the form of a pointer to
9196 // member, don't try to convert it to a pointer-to-member type.
9197 if (IsInvalidFormOfPointerToMemberFunction())
9200 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9201 E = OvlExpr->decls_end();
9203 // Look through any using declarations to find the underlying function.
9204 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9206 // C++ [over.over]p3:
9207 // Non-member functions and static member functions match
9208 // targets of type "pointer-to-function" or "reference-to-function."
9209 // Nonstatic member functions match targets of
9210 // type "pointer-to-member-function."
9211 // Note that according to DR 247, the containing class does not matter.
9212 if (FunctionTemplateDecl *FunctionTemplate
9213 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9214 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9217 // If we have explicit template arguments supplied, skip non-templates.
9218 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9219 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9222 assert(Ret || Matches.empty());
9226 void EliminateAllExceptMostSpecializedTemplate() {
9227 // [...] and any given function template specialization F1 is
9228 // eliminated if the set contains a second function template
9229 // specialization whose function template is more specialized
9230 // than the function template of F1 according to the partial
9231 // ordering rules of 14.5.5.2.
9233 // The algorithm specified above is quadratic. We instead use a
9234 // two-pass algorithm (similar to the one used to identify the
9235 // best viable function in an overload set) that identifies the
9236 // best function template (if it exists).
9238 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9239 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9240 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9242 UnresolvedSetIterator Result =
9243 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9244 TPOC_Other, 0, SourceExpr->getLocStart(),
9246 S.PDiag(diag::err_addr_ovl_ambiguous)
9247 << Matches[0].second->getDeclName(),
9248 S.PDiag(diag::note_ovl_candidate)
9249 << (unsigned) oc_function_template,
9250 Complain, TargetFunctionType);
9252 if (Result != MatchesCopy.end()) {
9253 // Make it the first and only element
9254 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9255 Matches[0].second = cast<FunctionDecl>(*Result);
9260 void EliminateAllTemplateMatches() {
9261 // [...] any function template specializations in the set are
9262 // eliminated if the set also contains a non-template function, [...]
9263 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9264 if (Matches[I].second->getPrimaryTemplate() == 0)
9267 Matches[I] = Matches[--N];
9268 Matches.set_size(N);
9274 void ComplainNoMatchesFound() const {
9275 assert(Matches.empty());
9276 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9277 << OvlExpr->getName() << TargetFunctionType
9278 << OvlExpr->getSourceRange();
9279 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9282 bool IsInvalidFormOfPointerToMemberFunction() const {
9283 return TargetTypeIsNonStaticMemberFunction &&
9284 !OvlExprInfo.HasFormOfMemberPointer;
9287 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9288 // TODO: Should we condition this on whether any functions might
9289 // have matched, or is it more appropriate to do that in callers?
9290 // TODO: a fixit wouldn't hurt.
9291 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9292 << TargetType << OvlExpr->getSourceRange();
9295 void ComplainOfInvalidConversion() const {
9296 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9297 << OvlExpr->getName() << TargetType;
9300 void ComplainMultipleMatchesFound() const {
9301 assert(Matches.size() > 1);
9302 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9303 << OvlExpr->getName()
9304 << OvlExpr->getSourceRange();
9305 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9308 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9310 int getNumMatches() const { return Matches.size(); }
9312 FunctionDecl* getMatchingFunctionDecl() const {
9313 if (Matches.size() != 1) return 0;
9314 return Matches[0].second;
9317 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9318 if (Matches.size() != 1) return 0;
9319 return &Matches[0].first;
9323 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9324 /// an overloaded function (C++ [over.over]), where @p From is an
9325 /// expression with overloaded function type and @p ToType is the type
9326 /// we're trying to resolve to. For example:
9332 /// int (*pfd)(double) = f; // selects f(double)
9335 /// This routine returns the resulting FunctionDecl if it could be
9336 /// resolved, and NULL otherwise. When @p Complain is true, this
9337 /// routine will emit diagnostics if there is an error.
9339 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9340 QualType TargetType,
9342 DeclAccessPair &FoundResult,
9343 bool *pHadMultipleCandidates) {
9344 assert(AddressOfExpr->getType() == Context.OverloadTy);
9346 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9348 int NumMatches = Resolver.getNumMatches();
9349 FunctionDecl* Fn = 0;
9350 if (NumMatches == 0 && Complain) {
9351 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9352 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9354 Resolver.ComplainNoMatchesFound();
9356 else if (NumMatches > 1 && Complain)
9357 Resolver.ComplainMultipleMatchesFound();
9358 else if (NumMatches == 1) {
9359 Fn = Resolver.getMatchingFunctionDecl();
9361 FoundResult = *Resolver.getMatchingFunctionAccessPair();
9363 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9366 if (pHadMultipleCandidates)
9367 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9371 /// \brief Given an expression that refers to an overloaded function, try to
9372 /// resolve that overloaded function expression down to a single function.
9374 /// This routine can only resolve template-ids that refer to a single function
9375 /// template, where that template-id refers to a single template whose template
9376 /// arguments are either provided by the template-id or have defaults,
9377 /// as described in C++0x [temp.arg.explicit]p3.
9379 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9381 DeclAccessPair *FoundResult) {
9382 // C++ [over.over]p1:
9383 // [...] [Note: any redundant set of parentheses surrounding the
9384 // overloaded function name is ignored (5.1). ]
9385 // C++ [over.over]p1:
9386 // [...] The overloaded function name can be preceded by the &
9389 // If we didn't actually find any template-ids, we're done.
9390 if (!ovl->hasExplicitTemplateArgs())
9393 TemplateArgumentListInfo ExplicitTemplateArgs;
9394 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9396 // Look through all of the overloaded functions, searching for one
9397 // whose type matches exactly.
9398 FunctionDecl *Matched = 0;
9399 for (UnresolvedSetIterator I = ovl->decls_begin(),
9400 E = ovl->decls_end(); I != E; ++I) {
9401 // C++0x [temp.arg.explicit]p3:
9402 // [...] In contexts where deduction is done and fails, or in contexts
9403 // where deduction is not done, if a template argument list is
9404 // specified and it, along with any default template arguments,
9405 // identifies a single function template specialization, then the
9406 // template-id is an lvalue for the function template specialization.
9407 FunctionTemplateDecl *FunctionTemplate
9408 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9410 // C++ [over.over]p2:
9411 // If the name is a function template, template argument deduction is
9412 // done (14.8.2.2), and if the argument deduction succeeds, the
9413 // resulting template argument list is used to generate a single
9414 // function template specialization, which is added to the set of
9415 // overloaded functions considered.
9416 FunctionDecl *Specialization = 0;
9417 TemplateDeductionInfo Info(ovl->getNameLoc());
9418 if (TemplateDeductionResult Result
9419 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9420 Specialization, Info,
9421 /*InOverloadResolution=*/true)) {
9422 // FIXME: make a note of the failed deduction for diagnostics.
9427 assert(Specialization && "no specialization and no error?");
9429 // Multiple matches; we can't resolve to a single declaration.
9432 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9434 NoteAllOverloadCandidates(ovl);
9439 Matched = Specialization;
9440 if (FoundResult) *FoundResult = I.getPair();
9443 if (Matched && getLangOpts().CPlusPlus1y &&
9444 Matched->getResultType()->isUndeducedType() &&
9445 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9454 // Resolve and fix an overloaded expression that can be resolved
9455 // because it identifies a single function template specialization.
9457 // Last three arguments should only be supplied if Complain = true
9459 // Return true if it was logically possible to so resolve the
9460 // expression, regardless of whether or not it succeeded. Always
9461 // returns true if 'complain' is set.
9462 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9463 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9464 bool complain, const SourceRange& OpRangeForComplaining,
9465 QualType DestTypeForComplaining,
9466 unsigned DiagIDForComplaining) {
9467 assert(SrcExpr.get()->getType() == Context.OverloadTy);
9469 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9471 DeclAccessPair found;
9472 ExprResult SingleFunctionExpression;
9473 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9474 ovl.Expression, /*complain*/ false, &found)) {
9475 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9476 SrcExpr = ExprError();
9480 // It is only correct to resolve to an instance method if we're
9481 // resolving a form that's permitted to be a pointer to member.
9482 // Otherwise we'll end up making a bound member expression, which
9483 // is illegal in all the contexts we resolve like this.
9484 if (!ovl.HasFormOfMemberPointer &&
9485 isa<CXXMethodDecl>(fn) &&
9486 cast<CXXMethodDecl>(fn)->isInstance()) {
9487 if (!complain) return false;
9489 Diag(ovl.Expression->getExprLoc(),
9490 diag::err_bound_member_function)
9491 << 0 << ovl.Expression->getSourceRange();
9493 // TODO: I believe we only end up here if there's a mix of
9494 // static and non-static candidates (otherwise the expression
9495 // would have 'bound member' type, not 'overload' type).
9496 // Ideally we would note which candidate was chosen and why
9497 // the static candidates were rejected.
9498 SrcExpr = ExprError();
9502 // Fix the expression to refer to 'fn'.
9503 SingleFunctionExpression =
9504 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9506 // If desired, do function-to-pointer decay.
9507 if (doFunctionPointerConverion) {
9508 SingleFunctionExpression =
9509 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9510 if (SingleFunctionExpression.isInvalid()) {
9511 SrcExpr = ExprError();
9517 if (!SingleFunctionExpression.isUsable()) {
9519 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9520 << ovl.Expression->getName()
9521 << DestTypeForComplaining
9522 << OpRangeForComplaining
9523 << ovl.Expression->getQualifierLoc().getSourceRange();
9524 NoteAllOverloadCandidates(SrcExpr.get());
9526 SrcExpr = ExprError();
9533 SrcExpr = SingleFunctionExpression;
9537 /// \brief Add a single candidate to the overload set.
9538 static void AddOverloadedCallCandidate(Sema &S,
9539 DeclAccessPair FoundDecl,
9540 TemplateArgumentListInfo *ExplicitTemplateArgs,
9541 ArrayRef<Expr *> Args,
9542 OverloadCandidateSet &CandidateSet,
9543 bool PartialOverloading,
9545 NamedDecl *Callee = FoundDecl.getDecl();
9546 if (isa<UsingShadowDecl>(Callee))
9547 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9549 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9550 if (ExplicitTemplateArgs) {
9551 assert(!KnownValid && "Explicit template arguments?");
9554 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9555 PartialOverloading);
9559 if (FunctionTemplateDecl *FuncTemplate
9560 = dyn_cast<FunctionTemplateDecl>(Callee)) {
9561 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9562 ExplicitTemplateArgs, Args, CandidateSet);
9566 assert(!KnownValid && "unhandled case in overloaded call candidate");
9569 /// \brief Add the overload candidates named by callee and/or found by argument
9570 /// dependent lookup to the given overload set.
9571 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9572 ArrayRef<Expr *> Args,
9573 OverloadCandidateSet &CandidateSet,
9574 bool PartialOverloading) {
9577 // Verify that ArgumentDependentLookup is consistent with the rules
9578 // in C++0x [basic.lookup.argdep]p3:
9580 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9581 // and let Y be the lookup set produced by argument dependent
9582 // lookup (defined as follows). If X contains
9584 // -- a declaration of a class member, or
9586 // -- a block-scope function declaration that is not a
9587 // using-declaration, or
9589 // -- a declaration that is neither a function or a function
9594 if (ULE->requiresADL()) {
9595 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9596 E = ULE->decls_end(); I != E; ++I) {
9597 assert(!(*I)->getDeclContext()->isRecord());
9598 assert(isa<UsingShadowDecl>(*I) ||
9599 !(*I)->getDeclContext()->isFunctionOrMethod());
9600 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9605 // It would be nice to avoid this copy.
9606 TemplateArgumentListInfo TABuffer;
9607 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9608 if (ULE->hasExplicitTemplateArgs()) {
9609 ULE->copyTemplateArgumentsInto(TABuffer);
9610 ExplicitTemplateArgs = &TABuffer;
9613 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9614 E = ULE->decls_end(); I != E; ++I)
9615 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9616 CandidateSet, PartialOverloading,
9617 /*KnownValid*/ true);
9619 if (ULE->requiresADL())
9620 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9622 Args, ExplicitTemplateArgs,
9623 CandidateSet, PartialOverloading);
9626 /// Attempt to recover from an ill-formed use of a non-dependent name in a
9627 /// template, where the non-dependent name was declared after the template
9628 /// was defined. This is common in code written for a compilers which do not
9629 /// correctly implement two-stage name lookup.
9631 /// Returns true if a viable candidate was found and a diagnostic was issued.
9633 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9634 const CXXScopeSpec &SS, LookupResult &R,
9635 TemplateArgumentListInfo *ExplicitTemplateArgs,
9636 ArrayRef<Expr *> Args) {
9637 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9640 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9641 if (DC->isTransparentContext())
9644 SemaRef.LookupQualifiedName(R, DC);
9647 R.suppressDiagnostics();
9649 if (isa<CXXRecordDecl>(DC)) {
9650 // Don't diagnose names we find in classes; we get much better
9651 // diagnostics for these from DiagnoseEmptyLookup.
9656 OverloadCandidateSet Candidates(FnLoc);
9657 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9658 AddOverloadedCallCandidate(SemaRef, I.getPair(),
9659 ExplicitTemplateArgs, Args,
9660 Candidates, false, /*KnownValid*/ false);
9662 OverloadCandidateSet::iterator Best;
9663 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9664 // No viable functions. Don't bother the user with notes for functions
9665 // which don't work and shouldn't be found anyway.
9670 // Find the namespaces where ADL would have looked, and suggest
9671 // declaring the function there instead.
9672 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9673 Sema::AssociatedClassSet AssociatedClasses;
9674 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9675 AssociatedNamespaces,
9677 Sema::AssociatedNamespaceSet SuggestedNamespaces;
9678 DeclContext *Std = SemaRef.getStdNamespace();
9679 for (Sema::AssociatedNamespaceSet::iterator
9680 it = AssociatedNamespaces.begin(),
9681 end = AssociatedNamespaces.end(); it != end; ++it) {
9682 // Never suggest declaring a function within namespace 'std'.
9683 if (Std && Std->Encloses(*it))
9686 // Never suggest declaring a function within a namespace with a reserved
9687 // name, like __gnu_cxx.
9688 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9690 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9693 SuggestedNamespaces.insert(*it);
9696 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9697 << R.getLookupName();
9698 if (SuggestedNamespaces.empty()) {
9699 SemaRef.Diag(Best->Function->getLocation(),
9700 diag::note_not_found_by_two_phase_lookup)
9701 << R.getLookupName() << 0;
9702 } else if (SuggestedNamespaces.size() == 1) {
9703 SemaRef.Diag(Best->Function->getLocation(),
9704 diag::note_not_found_by_two_phase_lookup)
9705 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9707 // FIXME: It would be useful to list the associated namespaces here,
9708 // but the diagnostics infrastructure doesn't provide a way to produce
9709 // a localized representation of a list of items.
9710 SemaRef.Diag(Best->Function->getLocation(),
9711 diag::note_not_found_by_two_phase_lookup)
9712 << R.getLookupName() << 2;
9715 // Try to recover by calling this function.
9725 /// Attempt to recover from ill-formed use of a non-dependent operator in a
9726 /// template, where the non-dependent operator was declared after the template
9729 /// Returns true if a viable candidate was found and a diagnostic was issued.
9731 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9732 SourceLocation OpLoc,
9733 ArrayRef<Expr *> Args) {
9734 DeclarationName OpName =
9735 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9736 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9737 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9738 /*ExplicitTemplateArgs=*/0, Args);
9742 // Callback to limit the allowed keywords and to only accept typo corrections
9743 // that are keywords or whose decls refer to functions (or template functions)
9744 // that accept the given number of arguments.
9745 class RecoveryCallCCC : public CorrectionCandidateCallback {
9747 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9748 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9749 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9750 WantRemainingKeywords = false;
9753 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9754 if (!candidate.getCorrectionDecl())
9755 return candidate.isKeyword();
9757 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9758 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9759 FunctionDecl *FD = 0;
9760 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9761 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9762 FD = FTD->getTemplatedDecl();
9763 if (!HasExplicitTemplateArgs && !FD) {
9764 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9765 // If the Decl is neither a function nor a template function,
9766 // determine if it is a pointer or reference to a function. If so,
9767 // check against the number of arguments expected for the pointee.
9768 QualType ValType = cast<ValueDecl>(ND)->getType();
9769 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9770 ValType = ValType->getPointeeType();
9771 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9772 if (FPT->getNumArgs() == NumArgs)
9776 if (FD && FD->getNumParams() >= NumArgs &&
9777 FD->getMinRequiredArguments() <= NumArgs)
9785 bool HasExplicitTemplateArgs;
9788 // Callback that effectively disabled typo correction
9789 class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9791 NoTypoCorrectionCCC() {
9792 WantTypeSpecifiers = false;
9793 WantExpressionKeywords = false;
9794 WantCXXNamedCasts = false;
9795 WantRemainingKeywords = false;
9798 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9803 class BuildRecoveryCallExprRAII {
9806 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9807 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9808 SemaRef.IsBuildingRecoveryCallExpr = true;
9811 ~BuildRecoveryCallExprRAII() {
9812 SemaRef.IsBuildingRecoveryCallExpr = false;
9818 /// Attempts to recover from a call where no functions were found.
9820 /// Returns true if new candidates were found.
9822 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9823 UnresolvedLookupExpr *ULE,
9824 SourceLocation LParenLoc,
9825 llvm::MutableArrayRef<Expr *> Args,
9826 SourceLocation RParenLoc,
9827 bool EmptyLookup, bool AllowTypoCorrection) {
9828 // Do not try to recover if it is already building a recovery call.
9829 // This stops infinite loops for template instantiations like
9831 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9832 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9834 if (SemaRef.IsBuildingRecoveryCallExpr)
9836 BuildRecoveryCallExprRAII RCE(SemaRef);
9839 SS.Adopt(ULE->getQualifierLoc());
9840 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9842 TemplateArgumentListInfo TABuffer;
9843 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9844 if (ULE->hasExplicitTemplateArgs()) {
9845 ULE->copyTemplateArgumentsInto(TABuffer);
9846 ExplicitTemplateArgs = &TABuffer;
9849 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9850 Sema::LookupOrdinaryName);
9851 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9852 NoTypoCorrectionCCC RejectAll;
9853 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9854 (CorrectionCandidateCallback*)&Validator :
9855 (CorrectionCandidateCallback*)&RejectAll;
9856 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9857 ExplicitTemplateArgs, Args) &&
9859 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9860 ExplicitTemplateArgs, Args)))
9863 assert(!R.empty() && "lookup results empty despite recovery");
9865 // Build an implicit member call if appropriate. Just drop the
9866 // casts and such from the call, we don't really care.
9867 ExprResult NewFn = ExprError();
9868 if ((*R.begin())->isCXXClassMember())
9869 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9870 R, ExplicitTemplateArgs);
9871 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9872 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9873 ExplicitTemplateArgs);
9875 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9877 if (NewFn.isInvalid())
9880 // This shouldn't cause an infinite loop because we're giving it
9881 // an expression with viable lookup results, which should never
9883 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9884 MultiExprArg(Args.data(), Args.size()),
9888 /// \brief Constructs and populates an OverloadedCandidateSet from
9889 /// the given function.
9890 /// \returns true when an the ExprResult output parameter has been set.
9891 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9892 UnresolvedLookupExpr *ULE,
9893 Expr **Args, unsigned NumArgs,
9894 SourceLocation RParenLoc,
9895 OverloadCandidateSet *CandidateSet,
9896 ExprResult *Result) {
9898 if (ULE->requiresADL()) {
9899 // To do ADL, we must have found an unqualified name.
9900 assert(!ULE->getQualifier() && "qualified name with ADL");
9902 // We don't perform ADL for implicit declarations of builtins.
9903 // Verify that this was correctly set up.
9905 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9906 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9907 F->getBuiltinID() && F->isImplicit())
9908 llvm_unreachable("performing ADL for builtin");
9910 // We don't perform ADL in C.
9911 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9915 UnbridgedCastsSet UnbridgedCasts;
9916 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9917 *Result = ExprError();
9921 // Add the functions denoted by the callee to the set of candidate
9922 // functions, including those from argument-dependent lookup.
9923 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9926 // If we found nothing, try to recover.
9927 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9929 if (CandidateSet->empty()) {
9930 // In Microsoft mode, if we are inside a template class member function then
9931 // create a type dependent CallExpr. The goal is to postpone name lookup
9932 // to instantiation time to be able to search into type dependent base
9934 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9935 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9936 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9937 llvm::makeArrayRef(Args, NumArgs),
9938 Context.DependentTy, VK_RValue,
9940 CE->setTypeDependent(true);
9941 *Result = Owned(CE);
9947 UnbridgedCasts.restore();
9951 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9952 /// the completed call expression. If overload resolution fails, emits
9953 /// diagnostics and returns ExprError()
9954 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9955 UnresolvedLookupExpr *ULE,
9956 SourceLocation LParenLoc,
9957 Expr **Args, unsigned NumArgs,
9958 SourceLocation RParenLoc,
9960 OverloadCandidateSet *CandidateSet,
9961 OverloadCandidateSet::iterator *Best,
9962 OverloadingResult OverloadResult,
9963 bool AllowTypoCorrection) {
9964 if (CandidateSet->empty())
9965 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9966 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9967 RParenLoc, /*EmptyLookup=*/true,
9968 AllowTypoCorrection);
9970 switch (OverloadResult) {
9972 FunctionDecl *FDecl = (*Best)->Function;
9973 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9974 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
9976 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9977 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9978 RParenLoc, ExecConfig);
9981 case OR_No_Viable_Function: {
9982 // Try to recover by looking for viable functions which the user might
9983 // have meant to call.
9984 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9985 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9987 /*EmptyLookup=*/false,
9988 AllowTypoCorrection);
9989 if (!Recovery.isInvalid())
9992 SemaRef.Diag(Fn->getLocStart(),
9993 diag::err_ovl_no_viable_function_in_call)
9994 << ULE->getName() << Fn->getSourceRange();
9995 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9996 llvm::makeArrayRef(Args, NumArgs));
10001 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10002 << ULE->getName() << Fn->getSourceRange();
10003 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
10004 llvm::makeArrayRef(Args, NumArgs));
10008 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10009 << (*Best)->Function->isDeleted()
10011 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10012 << Fn->getSourceRange();
10013 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
10014 llvm::makeArrayRef(Args, NumArgs));
10016 // We emitted an error for the unvailable/deleted function call but keep
10017 // the call in the AST.
10018 FunctionDecl *FDecl = (*Best)->Function;
10019 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10020 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
10021 RParenLoc, ExecConfig);
10025 // Overload resolution failed.
10026 return ExprError();
10029 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10030 /// (which eventually refers to the declaration Func) and the call
10031 /// arguments Args/NumArgs, attempt to resolve the function call down
10032 /// to a specific function. If overload resolution succeeds, returns
10033 /// the call expression produced by overload resolution.
10034 /// Otherwise, emits diagnostics and returns ExprError.
10035 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10036 UnresolvedLookupExpr *ULE,
10037 SourceLocation LParenLoc,
10038 Expr **Args, unsigned NumArgs,
10039 SourceLocation RParenLoc,
10041 bool AllowTypoCorrection) {
10042 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10045 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
10046 &CandidateSet, &result))
10049 OverloadCandidateSet::iterator Best;
10050 OverloadingResult OverloadResult =
10051 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10053 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
10054 RParenLoc, ExecConfig, &CandidateSet,
10055 &Best, OverloadResult,
10056 AllowTypoCorrection);
10059 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10060 return Functions.size() > 1 ||
10061 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10064 /// \brief Create a unary operation that may resolve to an overloaded
10067 /// \param OpLoc The location of the operator itself (e.g., '*').
10069 /// \param OpcIn The UnaryOperator::Opcode that describes this
10072 /// \param Fns The set of non-member functions that will be
10073 /// considered by overload resolution. The caller needs to build this
10074 /// set based on the context using, e.g.,
10075 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10076 /// set should not contain any member functions; those will be added
10077 /// by CreateOverloadedUnaryOp().
10079 /// \param Input The input argument.
10081 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10082 const UnresolvedSetImpl &Fns,
10084 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10086 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10087 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10088 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10089 // TODO: provide better source location info.
10090 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10092 if (checkPlaceholderForOverload(*this, Input))
10093 return ExprError();
10095 Expr *Args[2] = { Input, 0 };
10096 unsigned NumArgs = 1;
10098 // For post-increment and post-decrement, add the implicit '0' as
10099 // the second argument, so that we know this is a post-increment or
10101 if (Opc == UO_PostInc || Opc == UO_PostDec) {
10102 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10103 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10108 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10110 if (Input->isTypeDependent()) {
10112 return Owned(new (Context) UnaryOperator(Input,
10114 Context.DependentTy,
10115 VK_RValue, OK_Ordinary,
10118 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10119 UnresolvedLookupExpr *Fn
10120 = UnresolvedLookupExpr::Create(Context, NamingClass,
10121 NestedNameSpecifierLoc(), OpNameInfo,
10122 /*ADL*/ true, IsOverloaded(Fns),
10123 Fns.begin(), Fns.end());
10124 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
10125 Context.DependentTy,
10130 // Build an empty overload set.
10131 OverloadCandidateSet CandidateSet(OpLoc);
10133 // Add the candidates from the given function set.
10134 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10136 // Add operator candidates that are member functions.
10137 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10139 // Add candidates from ADL.
10140 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10141 ArgsArray, /*ExplicitTemplateArgs*/ 0,
10144 // Add builtin operator candidates.
10145 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10147 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10149 // Perform overload resolution.
10150 OverloadCandidateSet::iterator Best;
10151 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10153 // We found a built-in operator or an overloaded operator.
10154 FunctionDecl *FnDecl = Best->Function;
10157 // We matched an overloaded operator. Build a call to that
10160 // Convert the arguments.
10161 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10162 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10164 ExprResult InputRes =
10165 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10166 Best->FoundDecl, Method);
10167 if (InputRes.isInvalid())
10168 return ExprError();
10169 Input = InputRes.take();
10171 // Convert the arguments.
10172 ExprResult InputInit
10173 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10175 FnDecl->getParamDecl(0)),
10178 if (InputInit.isInvalid())
10179 return ExprError();
10180 Input = InputInit.take();
10183 // Determine the result type.
10184 QualType ResultTy = FnDecl->getResultType();
10185 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10186 ResultTy = ResultTy.getNonLValueExprType(Context);
10188 // Build the actual expression node.
10189 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10190 HadMultipleCandidates, OpLoc);
10191 if (FnExpr.isInvalid())
10192 return ExprError();
10195 CallExpr *TheCall =
10196 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10197 ResultTy, VK, OpLoc, false);
10199 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10201 return ExprError();
10203 return MaybeBindToTemporary(TheCall);
10205 // We matched a built-in operator. Convert the arguments, then
10206 // break out so that we will build the appropriate built-in
10208 ExprResult InputRes =
10209 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10210 Best->Conversions[0], AA_Passing);
10211 if (InputRes.isInvalid())
10212 return ExprError();
10213 Input = InputRes.take();
10218 case OR_No_Viable_Function:
10219 // This is an erroneous use of an operator which can be overloaded by
10220 // a non-member function. Check for non-member operators which were
10221 // defined too late to be candidates.
10222 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10223 // FIXME: Recover by calling the found function.
10224 return ExprError();
10226 // No viable function; fall through to handling this as a
10227 // built-in operator, which will produce an error message for us.
10231 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10232 << UnaryOperator::getOpcodeStr(Opc)
10233 << Input->getType()
10234 << Input->getSourceRange();
10235 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10236 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10237 return ExprError();
10240 Diag(OpLoc, diag::err_ovl_deleted_oper)
10241 << Best->Function->isDeleted()
10242 << UnaryOperator::getOpcodeStr(Opc)
10243 << getDeletedOrUnavailableSuffix(Best->Function)
10244 << Input->getSourceRange();
10245 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10246 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10247 return ExprError();
10250 // Either we found no viable overloaded operator or we matched a
10251 // built-in operator. In either case, fall through to trying to
10252 // build a built-in operation.
10253 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10256 /// \brief Create a binary operation that may resolve to an overloaded
10259 /// \param OpLoc The location of the operator itself (e.g., '+').
10261 /// \param OpcIn The BinaryOperator::Opcode that describes this
10264 /// \param Fns The set of non-member functions that will be
10265 /// considered by overload resolution. The caller needs to build this
10266 /// set based on the context using, e.g.,
10267 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10268 /// set should not contain any member functions; those will be added
10269 /// by CreateOverloadedBinOp().
10271 /// \param LHS Left-hand argument.
10272 /// \param RHS Right-hand argument.
10274 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10276 const UnresolvedSetImpl &Fns,
10277 Expr *LHS, Expr *RHS) {
10278 Expr *Args[2] = { LHS, RHS };
10279 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10281 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10282 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10283 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10285 // If either side is type-dependent, create an appropriate dependent
10287 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10289 // If there are no functions to store, just build a dependent
10290 // BinaryOperator or CompoundAssignment.
10291 if (Opc <= BO_Assign || Opc > BO_OrAssign)
10292 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10293 Context.DependentTy,
10294 VK_RValue, OK_Ordinary,
10296 FPFeatures.fp_contract));
10298 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10299 Context.DependentTy,
10302 Context.DependentTy,
10303 Context.DependentTy,
10305 FPFeatures.fp_contract));
10308 // FIXME: save results of ADL from here?
10309 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10310 // TODO: provide better source location info in DNLoc component.
10311 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10312 UnresolvedLookupExpr *Fn
10313 = UnresolvedLookupExpr::Create(Context, NamingClass,
10314 NestedNameSpecifierLoc(), OpNameInfo,
10315 /*ADL*/ true, IsOverloaded(Fns),
10316 Fns.begin(), Fns.end());
10317 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10318 Context.DependentTy, VK_RValue,
10319 OpLoc, FPFeatures.fp_contract));
10322 // Always do placeholder-like conversions on the RHS.
10323 if (checkPlaceholderForOverload(*this, Args[1]))
10324 return ExprError();
10326 // Do placeholder-like conversion on the LHS; note that we should
10327 // not get here with a PseudoObject LHS.
10328 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10329 if (checkPlaceholderForOverload(*this, Args[0]))
10330 return ExprError();
10332 // If this is the assignment operator, we only perform overload resolution
10333 // if the left-hand side is a class or enumeration type. This is actually
10334 // a hack. The standard requires that we do overload resolution between the
10335 // various built-in candidates, but as DR507 points out, this can lead to
10336 // problems. So we do it this way, which pretty much follows what GCC does.
10337 // Note that we go the traditional code path for compound assignment forms.
10338 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10339 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10341 // If this is the .* operator, which is not overloadable, just
10342 // create a built-in binary operator.
10343 if (Opc == BO_PtrMemD)
10344 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10346 // Build an empty overload set.
10347 OverloadCandidateSet CandidateSet(OpLoc);
10349 // Add the candidates from the given function set.
10350 AddFunctionCandidates(Fns, Args, CandidateSet, false);
10352 // Add operator candidates that are member functions.
10353 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10355 // Add candidates from ADL.
10356 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10358 /*ExplicitTemplateArgs*/ 0,
10361 // Add builtin operator candidates.
10362 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10364 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10366 // Perform overload resolution.
10367 OverloadCandidateSet::iterator Best;
10368 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10370 // We found a built-in operator or an overloaded operator.
10371 FunctionDecl *FnDecl = Best->Function;
10374 // We matched an overloaded operator. Build a call to that
10377 // Convert the arguments.
10378 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10379 // Best->Access is only meaningful for class members.
10380 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10383 PerformCopyInitialization(
10384 InitializedEntity::InitializeParameter(Context,
10385 FnDecl->getParamDecl(0)),
10386 SourceLocation(), Owned(Args[1]));
10387 if (Arg1.isInvalid())
10388 return ExprError();
10391 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10392 Best->FoundDecl, Method);
10393 if (Arg0.isInvalid())
10394 return ExprError();
10395 Args[0] = Arg0.takeAs<Expr>();
10396 Args[1] = RHS = Arg1.takeAs<Expr>();
10398 // Convert the arguments.
10399 ExprResult Arg0 = PerformCopyInitialization(
10400 InitializedEntity::InitializeParameter(Context,
10401 FnDecl->getParamDecl(0)),
10402 SourceLocation(), Owned(Args[0]));
10403 if (Arg0.isInvalid())
10404 return ExprError();
10407 PerformCopyInitialization(
10408 InitializedEntity::InitializeParameter(Context,
10409 FnDecl->getParamDecl(1)),
10410 SourceLocation(), Owned(Args[1]));
10411 if (Arg1.isInvalid())
10412 return ExprError();
10413 Args[0] = LHS = Arg0.takeAs<Expr>();
10414 Args[1] = RHS = Arg1.takeAs<Expr>();
10417 // Determine the result type.
10418 QualType ResultTy = FnDecl->getResultType();
10419 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10420 ResultTy = ResultTy.getNonLValueExprType(Context);
10422 // Build the actual expression node.
10423 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10425 HadMultipleCandidates, OpLoc);
10426 if (FnExpr.isInvalid())
10427 return ExprError();
10429 CXXOperatorCallExpr *TheCall =
10430 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10431 Args, ResultTy, VK, OpLoc,
10432 FPFeatures.fp_contract);
10434 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10436 return ExprError();
10438 ArrayRef<const Expr *> ArgsArray(Args, 2);
10439 // Cut off the implicit 'this'.
10440 if (isa<CXXMethodDecl>(FnDecl))
10441 ArgsArray = ArgsArray.slice(1);
10442 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10443 TheCall->getSourceRange(), VariadicDoesNotApply);
10445 return MaybeBindToTemporary(TheCall);
10447 // We matched a built-in operator. Convert the arguments, then
10448 // break out so that we will build the appropriate built-in
10450 ExprResult ArgsRes0 =
10451 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10452 Best->Conversions[0], AA_Passing);
10453 if (ArgsRes0.isInvalid())
10454 return ExprError();
10455 Args[0] = ArgsRes0.take();
10457 ExprResult ArgsRes1 =
10458 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10459 Best->Conversions[1], AA_Passing);
10460 if (ArgsRes1.isInvalid())
10461 return ExprError();
10462 Args[1] = ArgsRes1.take();
10467 case OR_No_Viable_Function: {
10468 // C++ [over.match.oper]p9:
10469 // If the operator is the operator , [...] and there are no
10470 // viable functions, then the operator is assumed to be the
10471 // built-in operator and interpreted according to clause 5.
10472 if (Opc == BO_Comma)
10475 // For class as left operand for assignment or compound assigment
10476 // operator do not fall through to handling in built-in, but report that
10477 // no overloaded assignment operator found
10478 ExprResult Result = ExprError();
10479 if (Args[0]->getType()->isRecordType() &&
10480 Opc >= BO_Assign && Opc <= BO_OrAssign) {
10481 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10482 << BinaryOperator::getOpcodeStr(Opc)
10483 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10485 // This is an erroneous use of an operator which can be overloaded by
10486 // a non-member function. Check for non-member operators which were
10487 // defined too late to be candidates.
10488 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10489 // FIXME: Recover by calling the found function.
10490 return ExprError();
10492 // No viable function; try to create a built-in operation, which will
10493 // produce an error. Then, show the non-viable candidates.
10494 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10496 assert(Result.isInvalid() &&
10497 "C++ binary operator overloading is missing candidates!");
10498 if (Result.isInvalid())
10499 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10500 BinaryOperator::getOpcodeStr(Opc), OpLoc);
10505 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
10506 << BinaryOperator::getOpcodeStr(Opc)
10507 << Args[0]->getType() << Args[1]->getType()
10508 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10509 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10510 BinaryOperator::getOpcodeStr(Opc), OpLoc);
10511 return ExprError();
10514 if (isImplicitlyDeleted(Best->Function)) {
10515 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10516 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10517 << Context.getRecordType(Method->getParent())
10518 << getSpecialMember(Method);
10520 // The user probably meant to call this special member. Just
10521 // explain why it's deleted.
10522 NoteDeletedFunction(Method);
10523 return ExprError();
10525 Diag(OpLoc, diag::err_ovl_deleted_oper)
10526 << Best->Function->isDeleted()
10527 << BinaryOperator::getOpcodeStr(Opc)
10528 << getDeletedOrUnavailableSuffix(Best->Function)
10529 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10531 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10532 BinaryOperator::getOpcodeStr(Opc), OpLoc);
10533 return ExprError();
10536 // We matched a built-in operator; build it.
10537 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10541 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10542 SourceLocation RLoc,
10543 Expr *Base, Expr *Idx) {
10544 Expr *Args[2] = { Base, Idx };
10545 DeclarationName OpName =
10546 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10548 // If either side is type-dependent, create an appropriate dependent
10550 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10552 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10553 // CHECKME: no 'operator' keyword?
10554 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10555 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10556 UnresolvedLookupExpr *Fn
10557 = UnresolvedLookupExpr::Create(Context, NamingClass,
10558 NestedNameSpecifierLoc(), OpNameInfo,
10559 /*ADL*/ true, /*Overloaded*/ false,
10560 UnresolvedSetIterator(),
10561 UnresolvedSetIterator());
10562 // Can't add any actual overloads yet
10564 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10566 Context.DependentTy,
10571 // Handle placeholders on both operands.
10572 if (checkPlaceholderForOverload(*this, Args[0]))
10573 return ExprError();
10574 if (checkPlaceholderForOverload(*this, Args[1]))
10575 return ExprError();
10577 // Build an empty overload set.
10578 OverloadCandidateSet CandidateSet(LLoc);
10580 // Subscript can only be overloaded as a member function.
10582 // Add operator candidates that are member functions.
10583 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10585 // Add builtin operator candidates.
10586 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10588 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10590 // Perform overload resolution.
10591 OverloadCandidateSet::iterator Best;
10592 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10594 // We found a built-in operator or an overloaded operator.
10595 FunctionDecl *FnDecl = Best->Function;
10598 // We matched an overloaded operator. Build a call to that
10601 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10603 // Convert the arguments.
10604 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10606 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10607 Best->FoundDecl, Method);
10608 if (Arg0.isInvalid())
10609 return ExprError();
10610 Args[0] = Arg0.take();
10612 // Convert the arguments.
10613 ExprResult InputInit
10614 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10616 FnDecl->getParamDecl(0)),
10619 if (InputInit.isInvalid())
10620 return ExprError();
10622 Args[1] = InputInit.takeAs<Expr>();
10624 // Determine the result type
10625 QualType ResultTy = FnDecl->getResultType();
10626 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10627 ResultTy = ResultTy.getNonLValueExprType(Context);
10629 // Build the actual expression node.
10630 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10631 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10632 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10634 HadMultipleCandidates,
10635 OpLocInfo.getLoc(),
10636 OpLocInfo.getInfo());
10637 if (FnExpr.isInvalid())
10638 return ExprError();
10640 CXXOperatorCallExpr *TheCall =
10641 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10642 FnExpr.take(), Args,
10643 ResultTy, VK, RLoc,
10646 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10648 return ExprError();
10650 return MaybeBindToTemporary(TheCall);
10652 // We matched a built-in operator. Convert the arguments, then
10653 // break out so that we will build the appropriate built-in
10655 ExprResult ArgsRes0 =
10656 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10657 Best->Conversions[0], AA_Passing);
10658 if (ArgsRes0.isInvalid())
10659 return ExprError();
10660 Args[0] = ArgsRes0.take();
10662 ExprResult ArgsRes1 =
10663 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10664 Best->Conversions[1], AA_Passing);
10665 if (ArgsRes1.isInvalid())
10666 return ExprError();
10667 Args[1] = ArgsRes1.take();
10673 case OR_No_Viable_Function: {
10674 if (CandidateSet.empty())
10675 Diag(LLoc, diag::err_ovl_no_oper)
10676 << Args[0]->getType() << /*subscript*/ 0
10677 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10679 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10680 << Args[0]->getType()
10681 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10682 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10684 return ExprError();
10688 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
10690 << Args[0]->getType() << Args[1]->getType()
10691 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10692 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10694 return ExprError();
10697 Diag(LLoc, diag::err_ovl_deleted_oper)
10698 << Best->Function->isDeleted() << "[]"
10699 << getDeletedOrUnavailableSuffix(Best->Function)
10700 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10701 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10703 return ExprError();
10706 // We matched a built-in operator; build it.
10707 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10710 /// BuildCallToMemberFunction - Build a call to a member
10711 /// function. MemExpr is the expression that refers to the member
10712 /// function (and includes the object parameter), Args/NumArgs are the
10713 /// arguments to the function call (not including the object
10714 /// parameter). The caller needs to validate that the member
10715 /// expression refers to a non-static member function or an overloaded
10716 /// member function.
10718 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10719 SourceLocation LParenLoc, Expr **Args,
10720 unsigned NumArgs, SourceLocation RParenLoc) {
10721 assert(MemExprE->getType() == Context.BoundMemberTy ||
10722 MemExprE->getType() == Context.OverloadTy);
10724 // Dig out the member expression. This holds both the object
10725 // argument and the member function we're referring to.
10726 Expr *NakedMemExpr = MemExprE->IgnoreParens();
10728 // Determine whether this is a call to a pointer-to-member function.
10729 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10730 assert(op->getType() == Context.BoundMemberTy);
10731 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10734 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10736 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10737 QualType resultType = proto->getCallResultType(Context);
10738 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10740 // Check that the object type isn't more qualified than the
10741 // member function we're calling.
10742 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10744 QualType objectType = op->getLHS()->getType();
10745 if (op->getOpcode() == BO_PtrMemI)
10746 objectType = objectType->castAs<PointerType>()->getPointeeType();
10747 Qualifiers objectQuals = objectType.getQualifiers();
10749 Qualifiers difference = objectQuals - funcQuals;
10750 difference.removeObjCGCAttr();
10751 difference.removeAddressSpace();
10753 std::string qualsString = difference.getAsString();
10754 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10755 << fnType.getUnqualifiedType()
10757 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10760 CXXMemberCallExpr *call
10761 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10762 llvm::makeArrayRef(Args, NumArgs),
10763 resultType, valueKind, RParenLoc);
10765 if (CheckCallReturnType(proto->getResultType(),
10766 op->getRHS()->getLocStart(),
10768 return ExprError();
10770 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10771 return ExprError();
10773 return MaybeBindToTemporary(call);
10776 UnbridgedCastsSet UnbridgedCasts;
10777 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10778 return ExprError();
10780 MemberExpr *MemExpr;
10781 CXXMethodDecl *Method = 0;
10782 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10783 NestedNameSpecifier *Qualifier = 0;
10784 if (isa<MemberExpr>(NakedMemExpr)) {
10785 MemExpr = cast<MemberExpr>(NakedMemExpr);
10786 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10787 FoundDecl = MemExpr->getFoundDecl();
10788 Qualifier = MemExpr->getQualifier();
10789 UnbridgedCasts.restore();
10791 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10792 Qualifier = UnresExpr->getQualifier();
10794 QualType ObjectType = UnresExpr->getBaseType();
10795 Expr::Classification ObjectClassification
10796 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10797 : UnresExpr->getBase()->Classify(Context);
10799 // Add overload candidates
10800 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10802 // FIXME: avoid copy.
10803 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10804 if (UnresExpr->hasExplicitTemplateArgs()) {
10805 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10806 TemplateArgs = &TemplateArgsBuffer;
10809 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10810 E = UnresExpr->decls_end(); I != E; ++I) {
10812 NamedDecl *Func = *I;
10813 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10814 if (isa<UsingShadowDecl>(Func))
10815 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10818 // Microsoft supports direct constructor calls.
10819 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10820 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10821 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10822 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10823 // If explicit template arguments were provided, we can't call a
10824 // non-template member function.
10828 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10829 ObjectClassification,
10830 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10831 /*SuppressUserConversions=*/false);
10833 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10834 I.getPair(), ActingDC, TemplateArgs,
10835 ObjectType, ObjectClassification,
10836 llvm::makeArrayRef(Args, NumArgs),
10838 /*SuppressUsedConversions=*/false);
10842 DeclarationName DeclName = UnresExpr->getMemberName();
10844 UnbridgedCasts.restore();
10846 OverloadCandidateSet::iterator Best;
10847 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10850 Method = cast<CXXMethodDecl>(Best->Function);
10851 FoundDecl = Best->FoundDecl;
10852 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10853 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10854 return ExprError();
10857 case OR_No_Viable_Function:
10858 Diag(UnresExpr->getMemberLoc(),
10859 diag::err_ovl_no_viable_member_function_in_call)
10860 << DeclName << MemExprE->getSourceRange();
10861 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10862 llvm::makeArrayRef(Args, NumArgs));
10863 // FIXME: Leaking incoming expressions!
10864 return ExprError();
10867 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10868 << DeclName << MemExprE->getSourceRange();
10869 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10870 llvm::makeArrayRef(Args, NumArgs));
10871 // FIXME: Leaking incoming expressions!
10872 return ExprError();
10875 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10876 << Best->Function->isDeleted()
10878 << getDeletedOrUnavailableSuffix(Best->Function)
10879 << MemExprE->getSourceRange();
10880 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10881 llvm::makeArrayRef(Args, NumArgs));
10882 // FIXME: Leaking incoming expressions!
10883 return ExprError();
10886 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10888 // If overload resolution picked a static member, build a
10889 // non-member call based on that function.
10890 if (Method->isStatic()) {
10891 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10892 Args, NumArgs, RParenLoc);
10895 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10898 QualType ResultType = Method->getResultType();
10899 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10900 ResultType = ResultType.getNonLValueExprType(Context);
10902 assert(Method && "Member call to something that isn't a method?");
10903 CXXMemberCallExpr *TheCall =
10904 new (Context) CXXMemberCallExpr(Context, MemExprE,
10905 llvm::makeArrayRef(Args, NumArgs),
10906 ResultType, VK, RParenLoc);
10908 // Check for a valid return type.
10909 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10911 return ExprError();
10913 // Convert the object argument (for a non-static member function call).
10914 // We only need to do this if there was actually an overload; otherwise
10915 // it was done at lookup.
10916 if (!Method->isStatic()) {
10917 ExprResult ObjectArg =
10918 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10919 FoundDecl, Method);
10920 if (ObjectArg.isInvalid())
10921 return ExprError();
10922 MemExpr->setBase(ObjectArg.take());
10925 // Convert the rest of the arguments
10926 const FunctionProtoType *Proto =
10927 Method->getType()->getAs<FunctionProtoType>();
10928 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10930 return ExprError();
10932 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10934 if (CheckFunctionCall(Method, TheCall, Proto))
10935 return ExprError();
10937 if ((isa<CXXConstructorDecl>(CurContext) ||
10938 isa<CXXDestructorDecl>(CurContext)) &&
10939 TheCall->getMethodDecl()->isPure()) {
10940 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10942 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10943 Diag(MemExpr->getLocStart(),
10944 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10945 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10946 << MD->getParent()->getDeclName();
10948 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10951 return MaybeBindToTemporary(TheCall);
10954 /// BuildCallToObjectOfClassType - Build a call to an object of class
10955 /// type (C++ [over.call.object]), which can end up invoking an
10956 /// overloaded function call operator (@c operator()) or performing a
10957 /// user-defined conversion on the object argument.
10959 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10960 SourceLocation LParenLoc,
10961 Expr **Args, unsigned NumArgs,
10962 SourceLocation RParenLoc) {
10963 if (checkPlaceholderForOverload(*this, Obj))
10964 return ExprError();
10965 ExprResult Object = Owned(Obj);
10967 UnbridgedCastsSet UnbridgedCasts;
10968 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10969 return ExprError();
10971 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10972 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10974 // C++ [over.call.object]p1:
10975 // If the primary-expression E in the function call syntax
10976 // evaluates to a class object of type "cv T", then the set of
10977 // candidate functions includes at least the function call
10978 // operators of T. The function call operators of T are obtained by
10979 // ordinary lookup of the name operator() in the context of
10981 OverloadCandidateSet CandidateSet(LParenLoc);
10982 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10984 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10985 diag::err_incomplete_object_call, Object.get()))
10988 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10989 LookupQualifiedName(R, Record->getDecl());
10990 R.suppressDiagnostics();
10992 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10993 Oper != OperEnd; ++Oper) {
10994 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10995 Object.get()->Classify(Context),
10996 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10997 /*SuppressUserConversions=*/ false);
11000 // C++ [over.call.object]p2:
11001 // In addition, for each (non-explicit in C++0x) conversion function
11002 // declared in T of the form
11004 // operator conversion-type-id () cv-qualifier;
11006 // where cv-qualifier is the same cv-qualification as, or a
11007 // greater cv-qualification than, cv, and where conversion-type-id
11008 // denotes the type "pointer to function of (P1,...,Pn) returning
11009 // R", or the type "reference to pointer to function of
11010 // (P1,...,Pn) returning R", or the type "reference to function
11011 // of (P1,...,Pn) returning R", a surrogate call function [...]
11012 // is also considered as a candidate function. Similarly,
11013 // surrogate call functions are added to the set of candidate
11014 // functions for each conversion function declared in an
11015 // accessible base class provided the function is not hidden
11016 // within T by another intervening declaration.
11017 std::pair<CXXRecordDecl::conversion_iterator,
11018 CXXRecordDecl::conversion_iterator> Conversions
11019 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11020 for (CXXRecordDecl::conversion_iterator
11021 I = Conversions.first, E = Conversions.second; I != E; ++I) {
11023 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11024 if (isa<UsingShadowDecl>(D))
11025 D = cast<UsingShadowDecl>(D)->getTargetDecl();
11027 // Skip over templated conversion functions; they aren't
11029 if (isa<FunctionTemplateDecl>(D))
11032 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11033 if (!Conv->isExplicit()) {
11034 // Strip the reference type (if any) and then the pointer type (if
11035 // any) to get down to what might be a function type.
11036 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11037 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11038 ConvType = ConvPtrType->getPointeeType();
11040 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11042 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11043 Object.get(), llvm::makeArrayRef(Args, NumArgs),
11049 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11051 // Perform overload resolution.
11052 OverloadCandidateSet::iterator Best;
11053 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11056 // Overload resolution succeeded; we'll build the appropriate call
11060 case OR_No_Viable_Function:
11061 if (CandidateSet.empty())
11062 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11063 << Object.get()->getType() << /*call*/ 1
11064 << Object.get()->getSourceRange();
11066 Diag(Object.get()->getLocStart(),
11067 diag::err_ovl_no_viable_object_call)
11068 << Object.get()->getType() << Object.get()->getSourceRange();
11069 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11070 llvm::makeArrayRef(Args, NumArgs));
11074 Diag(Object.get()->getLocStart(),
11075 diag::err_ovl_ambiguous_object_call)
11076 << Object.get()->getType() << Object.get()->getSourceRange();
11077 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11078 llvm::makeArrayRef(Args, NumArgs));
11082 Diag(Object.get()->getLocStart(),
11083 diag::err_ovl_deleted_object_call)
11084 << Best->Function->isDeleted()
11085 << Object.get()->getType()
11086 << getDeletedOrUnavailableSuffix(Best->Function)
11087 << Object.get()->getSourceRange();
11088 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11089 llvm::makeArrayRef(Args, NumArgs));
11093 if (Best == CandidateSet.end())
11096 UnbridgedCasts.restore();
11098 if (Best->Function == 0) {
11099 // Since there is no function declaration, this is one of the
11100 // surrogate candidates. Dig out the conversion function.
11101 CXXConversionDecl *Conv
11102 = cast<CXXConversionDecl>(
11103 Best->Conversions[0].UserDefined.ConversionFunction);
11105 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11106 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11107 return ExprError();
11109 // We selected one of the surrogate functions that converts the
11110 // object parameter to a function pointer. Perform the conversion
11111 // on the object argument, then let ActOnCallExpr finish the job.
11113 // Create an implicit member expr to refer to the conversion operator.
11114 // and then call it.
11115 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11116 Conv, HadMultipleCandidates);
11117 if (Call.isInvalid())
11118 return ExprError();
11119 // Record usage of conversion in an implicit cast.
11120 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11121 CK_UserDefinedConversion,
11122 Call.get(), 0, VK_RValue));
11124 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
11128 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11130 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11131 // that calls this method, using Object for the implicit object
11132 // parameter and passing along the remaining arguments.
11133 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11135 // An error diagnostic has already been printed when parsing the declaration.
11136 if (Method->isInvalidDecl())
11137 return ExprError();
11139 const FunctionProtoType *Proto =
11140 Method->getType()->getAs<FunctionProtoType>();
11142 unsigned NumArgsInProto = Proto->getNumArgs();
11143 unsigned NumArgsToCheck = NumArgs;
11145 // Build the full argument list for the method call (the
11146 // implicit object parameter is placed at the beginning of the
11149 if (NumArgs < NumArgsInProto) {
11150 NumArgsToCheck = NumArgsInProto;
11151 MethodArgs = new Expr*[NumArgsInProto + 1];
11153 MethodArgs = new Expr*[NumArgs + 1];
11155 MethodArgs[0] = Object.get();
11156 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11157 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11159 DeclarationNameInfo OpLocInfo(
11160 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11161 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11162 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11163 HadMultipleCandidates,
11164 OpLocInfo.getLoc(),
11165 OpLocInfo.getInfo());
11166 if (NewFn.isInvalid())
11169 // Once we've built TheCall, all of the expressions are properly
11171 QualType ResultTy = Method->getResultType();
11172 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11173 ResultTy = ResultTy.getNonLValueExprType(Context);
11175 CXXOperatorCallExpr *TheCall =
11176 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11177 llvm::makeArrayRef(MethodArgs, NumArgs+1),
11178 ResultTy, VK, RParenLoc, false);
11179 delete [] MethodArgs;
11181 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11185 // We may have default arguments. If so, we need to allocate more
11186 // slots in the call for them.
11187 if (NumArgs < NumArgsInProto)
11188 TheCall->setNumArgs(Context, NumArgsInProto + 1);
11189 else if (NumArgs > NumArgsInProto)
11190 NumArgsToCheck = NumArgsInProto;
11192 bool IsError = false;
11194 // Initialize the implicit object parameter.
11195 ExprResult ObjRes =
11196 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11197 Best->FoundDecl, Method);
11198 if (ObjRes.isInvalid())
11202 TheCall->setArg(0, Object.take());
11204 // Check the argument types.
11205 for (unsigned i = 0; i != NumArgsToCheck; i++) {
11210 // Pass the argument.
11212 ExprResult InputInit
11213 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11215 Method->getParamDecl(i)),
11216 SourceLocation(), Arg);
11218 IsError |= InputInit.isInvalid();
11219 Arg = InputInit.takeAs<Expr>();
11222 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11223 if (DefArg.isInvalid()) {
11228 Arg = DefArg.takeAs<Expr>();
11231 TheCall->setArg(i + 1, Arg);
11234 // If this is a variadic call, handle args passed through "...".
11235 if (Proto->isVariadic()) {
11236 // Promote the arguments (C99 6.5.2.2p7).
11237 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11238 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11239 IsError |= Arg.isInvalid();
11240 TheCall->setArg(i + 1, Arg.take());
11244 if (IsError) return true;
11246 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11248 if (CheckFunctionCall(Method, TheCall, Proto))
11251 return MaybeBindToTemporary(TheCall);
11254 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11255 /// (if one exists), where @c Base is an expression of class type and
11256 /// @c Member is the name of the member we're trying to find.
11258 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11259 assert(Base->getType()->isRecordType() &&
11260 "left-hand side must have class type");
11262 if (checkPlaceholderForOverload(*this, Base))
11263 return ExprError();
11265 SourceLocation Loc = Base->getExprLoc();
11267 // C++ [over.ref]p1:
11269 // [...] An expression x->m is interpreted as (x.operator->())->m
11270 // for a class object x of type T if T::operator->() exists and if
11271 // the operator is selected as the best match function by the
11272 // overload resolution mechanism (13.3).
11273 DeclarationName OpName =
11274 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11275 OverloadCandidateSet CandidateSet(Loc);
11276 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11278 if (RequireCompleteType(Loc, Base->getType(),
11279 diag::err_typecheck_incomplete_tag, Base))
11280 return ExprError();
11282 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11283 LookupQualifiedName(R, BaseRecord->getDecl());
11284 R.suppressDiagnostics();
11286 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11287 Oper != OperEnd; ++Oper) {
11288 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11289 None, CandidateSet, /*SuppressUserConversions=*/false);
11292 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11294 // Perform overload resolution.
11295 OverloadCandidateSet::iterator Best;
11296 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11298 // Overload resolution succeeded; we'll build the call below.
11301 case OR_No_Viable_Function:
11302 if (CandidateSet.empty())
11303 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11304 << Base->getType() << Base->getSourceRange();
11306 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11307 << "operator->" << Base->getSourceRange();
11308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11309 return ExprError();
11312 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11313 << "->" << Base->getType() << Base->getSourceRange();
11314 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11315 return ExprError();
11318 Diag(OpLoc, diag::err_ovl_deleted_oper)
11319 << Best->Function->isDeleted()
11321 << getDeletedOrUnavailableSuffix(Best->Function)
11322 << Base->getSourceRange();
11323 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11324 return ExprError();
11327 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11329 // Convert the object parameter.
11330 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11331 ExprResult BaseResult =
11332 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11333 Best->FoundDecl, Method);
11334 if (BaseResult.isInvalid())
11335 return ExprError();
11336 Base = BaseResult.take();
11338 // Build the operator call.
11339 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11340 HadMultipleCandidates, OpLoc);
11341 if (FnExpr.isInvalid())
11342 return ExprError();
11344 QualType ResultTy = Method->getResultType();
11345 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11346 ResultTy = ResultTy.getNonLValueExprType(Context);
11347 CXXOperatorCallExpr *TheCall =
11348 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11349 Base, ResultTy, VK, OpLoc, false);
11351 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11353 return ExprError();
11355 return MaybeBindToTemporary(TheCall);
11358 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11359 /// a literal operator described by the provided lookup results.
11360 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11361 DeclarationNameInfo &SuffixInfo,
11362 ArrayRef<Expr*> Args,
11363 SourceLocation LitEndLoc,
11364 TemplateArgumentListInfo *TemplateArgs) {
11365 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11367 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11368 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11371 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11373 // Perform overload resolution. This will usually be trivial, but might need
11374 // to perform substitutions for a literal operator template.
11375 OverloadCandidateSet::iterator Best;
11376 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11381 case OR_No_Viable_Function:
11382 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11383 << R.getLookupName();
11384 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11385 return ExprError();
11388 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11389 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11390 return ExprError();
11393 FunctionDecl *FD = Best->Function;
11394 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11395 HadMultipleCandidates,
11396 SuffixInfo.getLoc(),
11397 SuffixInfo.getInfo());
11398 if (Fn.isInvalid())
11401 // Check the argument types. This should almost always be a no-op, except
11402 // that array-to-pointer decay is applied to string literals.
11404 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11405 ExprResult InputInit = PerformCopyInitialization(
11406 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11407 SourceLocation(), Args[ArgIdx]);
11408 if (InputInit.isInvalid())
11410 ConvArgs[ArgIdx] = InputInit.take();
11413 QualType ResultTy = FD->getResultType();
11414 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11415 ResultTy = ResultTy.getNonLValueExprType(Context);
11417 UserDefinedLiteral *UDL =
11418 new (Context) UserDefinedLiteral(Context, Fn.take(),
11419 llvm::makeArrayRef(ConvArgs, Args.size()),
11420 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11422 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11423 return ExprError();
11425 if (CheckFunctionCall(FD, UDL, NULL))
11426 return ExprError();
11428 return MaybeBindToTemporary(UDL);
11431 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11432 /// given LookupResult is non-empty, it is assumed to describe a member which
11433 /// will be invoked. Otherwise, the function will be found via argument
11434 /// dependent lookup.
11435 /// CallExpr is set to a valid expression and FRS_Success returned on success,
11436 /// otherwise CallExpr is set to ExprError() and some non-success value
11438 Sema::ForRangeStatus
11439 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11440 SourceLocation RangeLoc, VarDecl *Decl,
11441 BeginEndFunction BEF,
11442 const DeclarationNameInfo &NameInfo,
11443 LookupResult &MemberLookup,
11444 OverloadCandidateSet *CandidateSet,
11445 Expr *Range, ExprResult *CallExpr) {
11446 CandidateSet->clear();
11447 if (!MemberLookup.empty()) {
11448 ExprResult MemberRef =
11449 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11450 /*IsPtr=*/false, CXXScopeSpec(),
11451 /*TemplateKWLoc=*/SourceLocation(),
11452 /*FirstQualifierInScope=*/0,
11454 /*TemplateArgs=*/0);
11455 if (MemberRef.isInvalid()) {
11456 *CallExpr = ExprError();
11457 Diag(Range->getLocStart(), diag::note_in_for_range)
11458 << RangeLoc << BEF << Range->getType();
11459 return FRS_DiagnosticIssued;
11461 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11462 if (CallExpr->isInvalid()) {
11463 *CallExpr = ExprError();
11464 Diag(Range->getLocStart(), diag::note_in_for_range)
11465 << RangeLoc << BEF << Range->getType();
11466 return FRS_DiagnosticIssued;
11469 UnresolvedSet<0> FoundNames;
11470 UnresolvedLookupExpr *Fn =
11471 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11472 NestedNameSpecifierLoc(), NameInfo,
11473 /*NeedsADL=*/true, /*Overloaded=*/false,
11474 FoundNames.begin(), FoundNames.end());
11476 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11477 CandidateSet, CallExpr);
11478 if (CandidateSet->empty() || CandidateSetError) {
11479 *CallExpr = ExprError();
11480 return FRS_NoViableFunction;
11482 OverloadCandidateSet::iterator Best;
11483 OverloadingResult OverloadResult =
11484 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11486 if (OverloadResult == OR_No_Viable_Function) {
11487 *CallExpr = ExprError();
11488 return FRS_NoViableFunction;
11490 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11491 Loc, 0, CandidateSet, &Best,
11493 /*AllowTypoCorrection=*/false);
11494 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11495 *CallExpr = ExprError();
11496 Diag(Range->getLocStart(), diag::note_in_for_range)
11497 << RangeLoc << BEF << Range->getType();
11498 return FRS_DiagnosticIssued;
11501 return FRS_Success;
11505 /// FixOverloadedFunctionReference - E is an expression that refers to
11506 /// a C++ overloaded function (possibly with some parentheses and
11507 /// perhaps a '&' around it). We have resolved the overloaded function
11508 /// to the function declaration Fn, so patch up the expression E to
11509 /// refer (possibly indirectly) to Fn. Returns the new expr.
11510 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11511 FunctionDecl *Fn) {
11512 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11513 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11515 if (SubExpr == PE->getSubExpr())
11518 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11521 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11522 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11524 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11525 SubExpr->getType()) &&
11526 "Implicit cast type cannot be determined from overload");
11527 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11528 if (SubExpr == ICE->getSubExpr())
11531 return ImplicitCastExpr::Create(Context, ICE->getType(),
11532 ICE->getCastKind(),
11534 ICE->getValueKind());
11537 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11538 assert(UnOp->getOpcode() == UO_AddrOf &&
11539 "Can only take the address of an overloaded function");
11540 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11541 if (Method->isStatic()) {
11542 // Do nothing: static member functions aren't any different
11543 // from non-member functions.
11545 // Fix the sub expression, which really has to be an
11546 // UnresolvedLookupExpr holding an overloaded member function
11548 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11550 if (SubExpr == UnOp->getSubExpr())
11553 assert(isa<DeclRefExpr>(SubExpr)
11554 && "fixed to something other than a decl ref");
11555 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11556 && "fixed to a member ref with no nested name qualifier");
11558 // We have taken the address of a pointer to member
11559 // function. Perform the computation here so that we get the
11560 // appropriate pointer to member type.
11562 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11563 QualType MemPtrType
11564 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11566 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11567 VK_RValue, OK_Ordinary,
11568 UnOp->getOperatorLoc());
11571 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11573 if (SubExpr == UnOp->getSubExpr())
11576 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11577 Context.getPointerType(SubExpr->getType()),
11578 VK_RValue, OK_Ordinary,
11579 UnOp->getOperatorLoc());
11582 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11583 // FIXME: avoid copy.
11584 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11585 if (ULE->hasExplicitTemplateArgs()) {
11586 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11587 TemplateArgs = &TemplateArgsBuffer;
11590 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11591 ULE->getQualifierLoc(),
11592 ULE->getTemplateKeywordLoc(),
11594 /*enclosing*/ false, // FIXME?
11600 MarkDeclRefReferenced(DRE);
11601 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11605 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11606 // FIXME: avoid copy.
11607 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11608 if (MemExpr->hasExplicitTemplateArgs()) {
11609 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11610 TemplateArgs = &TemplateArgsBuffer;
11615 // If we're filling in a static method where we used to have an
11616 // implicit member access, rewrite to a simple decl ref.
11617 if (MemExpr->isImplicitAccess()) {
11618 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11619 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11620 MemExpr->getQualifierLoc(),
11621 MemExpr->getTemplateKeywordLoc(),
11623 /*enclosing*/ false,
11624 MemExpr->getMemberLoc(),
11629 MarkDeclRefReferenced(DRE);
11630 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11633 SourceLocation Loc = MemExpr->getMemberLoc();
11634 if (MemExpr->getQualifier())
11635 Loc = MemExpr->getQualifierLoc().getBeginLoc();
11636 CheckCXXThisCapture(Loc);
11637 Base = new (Context) CXXThisExpr(Loc,
11638 MemExpr->getBaseType(),
11639 /*isImplicit=*/true);
11642 Base = MemExpr->getBase();
11644 ExprValueKind valueKind;
11646 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11647 valueKind = VK_LValue;
11648 type = Fn->getType();
11650 valueKind = VK_RValue;
11651 type = Context.BoundMemberTy;
11654 MemberExpr *ME = MemberExpr::Create(Context, Base,
11655 MemExpr->isArrow(),
11656 MemExpr->getQualifierLoc(),
11657 MemExpr->getTemplateKeywordLoc(),
11660 MemExpr->getMemberNameInfo(),
11662 type, valueKind, OK_Ordinary);
11663 ME->setHadMultipleCandidates(true);
11664 MarkMemberReferenced(ME);
11668 llvm_unreachable("Invalid reference to overloaded function");
11671 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11672 DeclAccessPair Found,
11673 FunctionDecl *Fn) {
11674 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11677 } // end namespace clang