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/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
38 using namespace clang;
41 /// A convenience routine for creating a decayed reference to a function.
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
45 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
62 S.MarkDeclRefReferenced(DRE);
65 E = S.DefaultFunctionArrayConversion(E.get());
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
73 StandardConversionSequence &SCS,
75 bool AllowObjCWritebackConversion);
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
87 bool AllowObjCConversionOnExplicit);
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
105 /// GetConversionRank - Retrieve the implicit conversion rank
106 /// corresponding to the given implicit conversion kind.
107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
130 ICR_Complex_Real_Conversion,
133 ICR_Writeback_Conversion
135 return Rank[(int)Kind];
138 /// GetImplicitConversionName - Return the name of this kind of
139 /// implicit conversion.
140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
145 "Function-to-pointer",
146 "Noreturn adjustment",
148 "Integral promotion",
149 "Floating point promotion",
151 "Integral conversion",
152 "Floating conversion",
153 "Complex conversion",
154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
157 "Boolean conversion",
158 "Compatible-types conversion",
159 "Derived-to-base conversion",
162 "Complex-real conversion",
163 "Block Pointer conversion",
164 "Transparent Union Conversion",
165 "Writeback conversion"
170 /// StandardConversionSequence - Set the standard conversion
171 /// sequence to the identity conversion.
172 void StandardConversionSequence::setAsIdentityConversion() {
173 First = ICK_Identity;
174 Second = ICK_Identity;
175 Third = ICK_Identity;
176 DeprecatedStringLiteralToCharPtr = false;
177 QualificationIncludesObjCLifetime = false;
178 ReferenceBinding = false;
179 DirectBinding = false;
180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
184 ObjCLifetimeConversionBinding = false;
185 CopyConstructor = nullptr;
188 /// getRank - Retrieve the rank of this standard conversion sequence
189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190 /// implicit conversions.
191 ImplicitConversionRank StandardConversionSequence::getRank() const {
192 ImplicitConversionRank Rank = ICR_Exact_Match;
193 if (GetConversionRank(First) > Rank)
194 Rank = GetConversionRank(First);
195 if (GetConversionRank(Second) > Rank)
196 Rank = GetConversionRank(Second);
197 if (GetConversionRank(Third) > Rank)
198 Rank = GetConversionRank(Third);
202 /// isPointerConversionToBool - Determines whether this conversion is
203 /// a conversion of a pointer or pointer-to-member to bool. This is
204 /// used as part of the ranking of standard conversion sequences
205 /// (C++ 13.3.3.2p4).
206 bool StandardConversionSequence::isPointerConversionToBool() const {
207 // Note that FromType has not necessarily been transformed by the
208 // array-to-pointer or function-to-pointer implicit conversions, so
209 // check for their presence as well as checking whether FromType is
211 if (getToType(1)->isBooleanType() &&
212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
215 getFromType()->isNullPtrType() ||
216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 /// isPointerConversionToVoidPointer - Determines whether this
223 /// conversion is a conversion of a pointer to a void pointer. This is
224 /// used as part of the ranking of standard conversion sequences (C++
227 StandardConversionSequence::
228 isPointerConversionToVoidPointer(ASTContext& Context) const {
229 QualType FromType = getFromType();
230 QualType ToType = getToType(1);
232 // Note that FromType has not necessarily been transformed by the
233 // array-to-pointer implicit conversion, so check for its presence
234 // and redo the conversion to get a pointer.
235 if (First == ICK_Array_To_Pointer)
236 FromType = Context.getArrayDecayedType(FromType);
238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
240 return ToPtrType->getPointeeType()->isVoidType();
245 /// Skip any implicit casts which could be either part of a narrowing conversion
246 /// or after one in an implicit conversion.
247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249 switch (ICE->getCastKind()) {
251 case CK_IntegralCast:
252 case CK_IntegralToBoolean:
253 case CK_IntegralToFloating:
254 case CK_FloatingToIntegral:
255 case CK_FloatingToBoolean:
256 case CK_FloatingCast:
257 Converted = ICE->getSubExpr();
268 /// Check if this standard conversion sequence represents a narrowing
269 /// conversion, according to C++11 [dcl.init.list]p7.
271 /// \param Ctx The AST context.
272 /// \param Converted The result of applying this standard conversion sequence.
273 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
274 /// value of the expression prior to the narrowing conversion.
275 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
276 /// type of the expression prior to the narrowing conversion.
278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
280 APValue &ConstantValue,
281 QualType &ConstantType) const {
282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
284 // C++11 [dcl.init.list]p7:
285 // A narrowing conversion is an implicit conversion ...
286 QualType FromType = getToType(0);
287 QualType ToType = getToType(1);
289 // 'bool' is an integral type; dispatch to the right place to handle it.
290 case ICK_Boolean_Conversion:
291 if (FromType->isRealFloatingType())
292 goto FloatingIntegralConversion;
293 if (FromType->isIntegralOrUnscopedEnumerationType())
294 goto IntegralConversion;
295 // Boolean conversions can be from pointers and pointers to members
296 // [conv.bool], and those aren't considered narrowing conversions.
297 return NK_Not_Narrowing;
299 // -- from a floating-point type to an integer type, or
301 // -- from an integer type or unscoped enumeration type to a floating-point
302 // type, except where the source is a constant expression and the actual
303 // value after conversion will fit into the target type and will produce
304 // the original value when converted back to the original type, or
305 case ICK_Floating_Integral:
306 FloatingIntegralConversion:
307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308 return NK_Type_Narrowing;
309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310 llvm::APSInt IntConstantValue;
311 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314 // Convert the integer to the floating type.
315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317 llvm::APFloat::rmNearestTiesToEven);
319 llvm::APSInt ConvertedValue = IntConstantValue;
321 Result.convertToInteger(ConvertedValue,
322 llvm::APFloat::rmTowardZero, &ignored);
323 // If the resulting value is different, this was a narrowing conversion.
324 if (IntConstantValue != ConvertedValue) {
325 ConstantValue = APValue(IntConstantValue);
326 ConstantType = Initializer->getType();
327 return NK_Constant_Narrowing;
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
334 return NK_Not_Narrowing;
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
358 return NK_Constant_Narrowing;
361 return NK_Variable_Narrowing;
364 return NK_Not_Narrowing;
366 // -- from an integer type or unscoped enumeration type to an integer type
367 // that cannot represent all the values of the original type, except where
368 // the source is a constant expression and the actual value after
369 // conversion will fit into the target type and will produce the original
370 // value when converted back to the original type.
371 case ICK_Integral_Conversion:
372 IntegralConversion: {
373 assert(FromType->isIntegralOrUnscopedEnumerationType());
374 assert(ToType->isIntegralOrUnscopedEnumerationType());
375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376 const unsigned FromWidth = Ctx.getIntWidth(FromType);
377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378 const unsigned ToWidth = Ctx.getIntWidth(ToType);
380 if (FromWidth > ToWidth ||
381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
383 // Not all values of FromType can be represented in ToType.
384 llvm::APSInt InitializerValue;
385 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387 // Such conversions on variables are always narrowing.
388 return NK_Variable_Narrowing;
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
397 // Add a bit to the InitializerValue so we don't have to worry about
398 // signed vs. unsigned comparisons.
399 InitializerValue = InitializerValue.extend(
400 InitializerValue.getBitWidth() + 1);
401 // Convert the initializer to and from the target width and signed-ness.
402 llvm::APSInt ConvertedValue = InitializerValue;
403 ConvertedValue = ConvertedValue.trunc(ToWidth);
404 ConvertedValue.setIsSigned(ToSigned);
405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406 ConvertedValue.setIsSigned(InitializerValue.isSigned());
407 // If the result is different, this was a narrowing conversion.
408 if (ConvertedValue != InitializerValue)
412 ConstantType = Initializer->getType();
413 ConstantValue = APValue(InitializerValue);
414 return NK_Constant_Narrowing;
417 return NK_Not_Narrowing;
421 // Other kinds of conversions are not narrowings.
422 return NK_Not_Narrowing;
426 /// dump - Print this standard conversion sequence to standard
427 /// error. Useful for debugging overloading issues.
428 void StandardConversionSequence::dump() const {
429 raw_ostream &OS = llvm::errs();
430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
432 OS << GetImplicitConversionName(First);
433 PrintedSomething = true;
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
440 OS << GetImplicitConversionName(Second);
442 if (CopyConstructor) {
443 OS << " (by copy constructor)";
444 } else if (DirectBinding) {
445 OS << " (direct reference binding)";
446 } else if (ReferenceBinding) {
447 OS << " (reference binding)";
449 PrintedSomething = true;
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
456 OS << GetImplicitConversionName(Third);
457 PrintedSomething = true;
460 if (!PrintedSomething) {
461 OS << "No conversions required";
465 /// dump - Print this user-defined conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 void UserDefinedConversionSequence::dump() const {
468 raw_ostream &OS = llvm::errs();
469 if (Before.First || Before.Second || Before.Third) {
473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
476 OS << "aggregate initialization";
477 if (After.First || After.Second || After.Third) {
483 /// dump - Print this implicit conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 void ImplicitConversionSequence::dump() const {
486 raw_ostream &OS = llvm::errs();
487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
489 switch (ConversionKind) {
490 case StandardConversion:
491 OS << "Standard conversion: ";
494 case UserDefinedConversion:
495 OS << "User-defined conversion: ";
498 case EllipsisConversion:
499 OS << "Ellipsis conversion";
501 case AmbiguousConversion:
502 OS << "Ambiguous conversion";
505 OS << "Bad conversion";
512 void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
516 void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
528 // Structure used by DeductionFailureInfo to store
529 // template argument information.
530 struct DFIArguments {
531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
534 // Structure used by DeductionFailureInfo to store
535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
541 /// \brief Convert from Sema's representation of template deduction information
542 /// to the form used in overload-candidate information.
544 clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
547 DeductionFailureInfo Result;
548 Result.Result = static_cast<unsigned>(TDK);
549 Result.HasDiagnostic = false;
550 Result.Data = nullptr;
552 case Sema::TDK_Success:
553 case Sema::TDK_Invalid:
554 case Sema::TDK_InstantiationDepth:
555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
559 case Sema::TDK_Incomplete:
560 case Sema::TDK_InvalidExplicitArguments:
561 Result.Data = Info.Param.getOpaqueValue();
564 case Sema::TDK_NonDeducedMismatch: {
565 // FIXME: Should allocate from normal heap so that we can free this later.
566 DFIArguments *Saved = new (Context) DFIArguments;
567 Saved->FirstArg = Info.FirstArg;
568 Saved->SecondArg = Info.SecondArg;
573 case Sema::TDK_Inconsistent:
574 case Sema::TDK_Underqualified: {
575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
577 Saved->Param = Info.Param;
578 Saved->FirstArg = Info.FirstArg;
579 Saved->SecondArg = Info.SecondArg;
584 case Sema::TDK_SubstitutionFailure:
585 Result.Data = Info.take();
586 if (Info.hasSFINAEDiagnostic()) {
587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588 SourceLocation(), PartialDiagnostic::NullDiagnostic());
589 Info.takeSFINAEDiagnostic(*Diag);
590 Result.HasDiagnostic = true;
594 case Sema::TDK_FailedOverloadResolution:
595 Result.Data = Info.Expression;
598 case Sema::TDK_MiscellaneousDeductionFailure:
605 void DeductionFailureInfo::Destroy() {
606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
608 case Sema::TDK_Invalid:
609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
613 case Sema::TDK_InvalidExplicitArguments:
614 case Sema::TDK_FailedOverloadResolution:
617 case Sema::TDK_Inconsistent:
618 case Sema::TDK_Underqualified:
619 case Sema::TDK_NonDeducedMismatch:
620 // FIXME: Destroy the data?
624 case Sema::TDK_SubstitutionFailure:
625 // FIXME: Destroy the template argument list?
627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
634 case Sema::TDK_MiscellaneousDeductionFailure:
639 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
645 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
648 case Sema::TDK_Invalid:
649 case Sema::TDK_InstantiationDepth:
650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
652 case Sema::TDK_SubstitutionFailure:
653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
655 return TemplateParameter();
657 case Sema::TDK_Incomplete:
658 case Sema::TDK_InvalidExplicitArguments:
659 return TemplateParameter::getFromOpaqueValue(Data);
661 case Sema::TDK_Inconsistent:
662 case Sema::TDK_Underqualified:
663 return static_cast<DFIParamWithArguments*>(Data)->Param;
666 case Sema::TDK_MiscellaneousDeductionFailure:
670 return TemplateParameter();
673 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
675 case Sema::TDK_Success:
676 case Sema::TDK_Invalid:
677 case Sema::TDK_InstantiationDepth:
678 case Sema::TDK_TooManyArguments:
679 case Sema::TDK_TooFewArguments:
680 case Sema::TDK_Incomplete:
681 case Sema::TDK_InvalidExplicitArguments:
682 case Sema::TDK_Inconsistent:
683 case Sema::TDK_Underqualified:
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
692 case Sema::TDK_MiscellaneousDeductionFailure:
699 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_SubstitutionFailure:
709 case Sema::TDK_FailedOverloadResolution:
712 case Sema::TDK_Inconsistent:
713 case Sema::TDK_Underqualified:
714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
718 case Sema::TDK_MiscellaneousDeductionFailure:
725 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
728 case Sema::TDK_Invalid:
729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
733 case Sema::TDK_InvalidExplicitArguments:
734 case Sema::TDK_SubstitutionFailure:
735 case Sema::TDK_FailedOverloadResolution:
738 case Sema::TDK_Inconsistent:
739 case Sema::TDK_Underqualified:
740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
744 case Sema::TDK_MiscellaneousDeductionFailure:
751 Expr *DeductionFailureInfo::getExpr() {
752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
759 void OverloadCandidateSet::destroyCandidates() {
760 for (iterator i = begin(), e = end(); i != e; ++i) {
761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
768 void OverloadCandidateSet::clear() {
770 NumInlineSequences = 0;
776 class UnbridgedCastsSet {
781 SmallVector<Entry, 2> Entries;
784 void save(Sema &S, Expr *&E) {
785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786 Entry entry = { &E, E };
787 Entries.push_back(entry);
788 E = S.stripARCUnbridgedCast(E);
792 for (SmallVectorImpl<Entry>::iterator
793 i = Entries.begin(), e = Entries.end(); i != e; ++i)
799 /// checkPlaceholderForOverload - Do any interesting placeholder-like
800 /// preprocessing on the given expression.
802 /// \param unbridgedCasts a collection to which to add unbridged casts;
803 /// without this, they will be immediately diagnosed as errors
805 /// Return true on unrecoverable error.
807 checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
810 // We can't handle overloaded expressions here because overload
811 // resolution might reasonably tweak them.
812 if (placeholder->getKind() == BuiltinType::Overload) return false;
814 // If the context potentially accepts unbridged ARC casts, strip
815 // the unbridged cast and add it to the collection for later restoration.
816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
818 unbridgedCasts->save(S, E);
822 // Go ahead and check everything else.
823 ExprResult result = S.CheckPlaceholderExpr(E);
824 if (result.isInvalid())
835 /// checkArgPlaceholdersForOverload - Check a set of call operands for
837 static bool checkArgPlaceholdersForOverload(Sema &S,
839 UnbridgedCastsSet &unbridged) {
840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
847 // IsOverload - Determine whether the given New declaration is an
848 // overload of the declarations in Old. This routine returns false if
849 // New and Old cannot be overloaded, e.g., if New has the same
850 // signature as some function in Old (C++ 1.3.10) or if the Old
851 // declarations aren't functions (or function templates) at all. When
852 // it does return false, MatchedDecl will point to the decl that New
853 // cannot be overloaded with. This decl may be a UsingShadowDecl on
854 // top of the underlying declaration.
856 // Example: Given the following input:
858 // void f(int, float); // #1
859 // void f(int, int); // #2
860 // int f(int, int); // #3
862 // When we process #1, there is no previous declaration of "f",
863 // so IsOverload will not be used.
865 // When we process #2, Old contains only the FunctionDecl for #1. By
866 // comparing the parameter types, we see that #1 and #2 are overloaded
867 // (since they have different signatures), so this routine returns
868 // false; MatchedDecl is unchanged.
870 // When we process #3, Old is an overload set containing #1 and #2. We
871 // compare the signatures of #3 to #1 (they're overloaded, so we do
872 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873 // identical (return types of functions are not part of the
874 // signature), IsOverload returns false and MatchedDecl will be set to
875 // point to the FunctionDecl for #2.
877 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878 // into a class by a using declaration. The rules for whether to hide
879 // shadow declarations ignore some properties which otherwise figure
880 // into a function template's signature.
882 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
886 NamedDecl *OldD = *I;
888 bool OldIsUsingDecl = false;
889 if (isa<UsingShadowDecl>(OldD)) {
890 OldIsUsingDecl = true;
892 // We can always introduce two using declarations into the same
893 // context, even if they have identical signatures.
894 if (NewIsUsingDecl) continue;
896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
899 // If either declaration was introduced by a using declaration,
900 // we'll need to use slightly different rules for matching.
901 // Essentially, these rules are the normal rules, except that
902 // function templates hide function templates with different
903 // return types or template parameter lists.
904 bool UseMemberUsingDeclRules =
905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906 !New->getFriendObjectKind();
908 if (FunctionDecl *OldF = OldD->getAsFunction()) {
909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
910 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
915 if (!isa<FunctionTemplateDecl>(OldD) &&
916 !shouldLinkPossiblyHiddenDecl(*I, New))
922 } else if (isa<UsingDecl>(OldD)) {
923 // We can overload with these, which can show up when doing
924 // redeclaration checks for UsingDecls.
925 assert(Old.getLookupKind() == LookupUsingDeclName);
926 } else if (isa<TagDecl>(OldD)) {
927 // We can always overload with tags by hiding them.
928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
929 // Optimistically assume that an unresolved using decl will
930 // overload; if it doesn't, we'll have to diagnose during
931 // template instantiation.
934 // Only function declarations can be overloaded; object and type
935 // declarations cannot be overloaded.
937 return Ovl_NonFunction;
944 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
945 bool UseUsingDeclRules) {
946 // C++ [basic.start.main]p2: This function shall not be overloaded.
950 // MSVCRT user defined entry points cannot be overloaded.
951 if (New->isMSVCRTEntryPoint())
954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
958 // A function template can be overloaded with other function templates
959 // and with normal (non-template) functions.
960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
963 // Is the function New an overload of the function Old?
964 QualType OldQType = Context.getCanonicalType(Old->getType());
965 QualType NewQType = Context.getCanonicalType(New->getType());
967 // Compare the signatures (C++ 1.3.10) of the two functions to
968 // determine whether they are overloads. If we find any mismatch
969 // in the signature, they are overloads.
971 // If either of these functions is a K&R-style function (no
972 // prototype), then we consider them to have matching signatures.
973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
974 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
980 // The signature of a function includes the types of its
981 // parameters (C++ 1.3.10), which includes the presence or absence
982 // of the ellipsis; see C++ DR 357).
983 if (OldQType != NewQType &&
984 (OldType->getNumParams() != NewType->getNumParams() ||
985 OldType->isVariadic() != NewType->isVariadic() ||
986 !FunctionParamTypesAreEqual(OldType, NewType)))
989 // C++ [temp.over.link]p4:
990 // The signature of a function template consists of its function
991 // signature, its return type and its template parameter list. The names
992 // of the template parameters are significant only for establishing the
993 // relationship between the template parameters and the rest of the
996 // We check the return type and template parameter lists for function
997 // templates first; the remaining checks follow.
999 // However, we don't consider either of these when deciding whether
1000 // a member introduced by a shadow declaration is hidden.
1001 if (!UseUsingDeclRules && NewTemplate &&
1002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003 OldTemplate->getTemplateParameters(),
1004 false, TPL_TemplateMatch) ||
1005 OldType->getReturnType() != NewType->getReturnType()))
1008 // If the function is a class member, its signature includes the
1009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1011 // As part of this, also check whether one of the member functions
1012 // is static, in which case they are not overloads (C++
1013 // 13.1p2). While not part of the definition of the signature,
1014 // this check is important to determine whether these functions
1015 // can be overloaded.
1016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1018 if (OldMethod && NewMethod &&
1019 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1021 if (!UseUsingDeclRules &&
1022 (OldMethod->getRefQualifier() == RQ_None ||
1023 NewMethod->getRefQualifier() == RQ_None)) {
1024 // C++0x [over.load]p2:
1025 // - Member function declarations with the same name and the same
1026 // parameter-type-list as well as member function template
1027 // declarations with the same name, the same parameter-type-list, and
1028 // the same template parameter lists cannot be overloaded if any of
1029 // them, but not all, have a ref-qualifier (8.3.5).
1030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1032 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1037 // We may not have applied the implicit const for a constexpr member
1038 // function yet (because we haven't yet resolved whether this is a static
1039 // or non-static member function). Add it now, on the assumption that this
1040 // is a redeclaration of OldMethod.
1041 unsigned OldQuals = OldMethod->getTypeQualifiers();
1042 unsigned NewQuals = NewMethod->getTypeQualifiers();
1043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1044 !isa<CXXConstructorDecl>(NewMethod))
1045 NewQuals |= Qualifiers::Const;
1047 // We do not allow overloading based off of '__restrict'.
1048 OldQuals &= ~Qualifiers::Restrict;
1049 NewQuals &= ~Qualifiers::Restrict;
1050 if (OldQuals != NewQuals)
1054 // enable_if attributes are an order-sensitive part of the signature.
1055 for (specific_attr_iterator<EnableIfAttr>
1056 NewI = New->specific_attr_begin<EnableIfAttr>(),
1057 NewE = New->specific_attr_end<EnableIfAttr>(),
1058 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1059 OldE = Old->specific_attr_end<EnableIfAttr>();
1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1061 if (NewI == NewE || OldI == OldE)
1063 llvm::FoldingSetNodeID NewID, OldID;
1064 NewI->getCond()->Profile(NewID, Context, true);
1065 OldI->getCond()->Profile(OldID, Context, true);
1070 // The signatures match; this is not an overload.
1074 /// \brief Checks availability of the function depending on the current
1075 /// function context. Inside an unavailable function, unavailability is ignored.
1077 /// \returns true if \arg FD is unavailable and current context is inside
1078 /// an available function, false otherwise.
1079 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1083 /// \brief Tries a user-defined conversion from From to ToType.
1085 /// Produces an implicit conversion sequence for when a standard conversion
1086 /// is not an option. See TryImplicitConversion for more information.
1087 static ImplicitConversionSequence
1088 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1089 bool SuppressUserConversions,
1091 bool InOverloadResolution,
1093 bool AllowObjCWritebackConversion,
1094 bool AllowObjCConversionOnExplicit) {
1095 ImplicitConversionSequence ICS;
1097 if (SuppressUserConversions) {
1098 // We're not in the case above, so there is no conversion that
1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1104 // Attempt user-defined conversion.
1105 OverloadCandidateSet Conversions(From->getExprLoc(),
1106 OverloadCandidateSet::CSK_Normal);
1107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108 Conversions, AllowExplicit,
1109 AllowObjCConversionOnExplicit)) {
1112 ICS.setUserDefined();
1113 ICS.UserDefined.Before.setAsIdentityConversion();
1114 // C++ [over.ics.user]p4:
1115 // A conversion of an expression of class type to the same class
1116 // type is given Exact Match rank, and a conversion of an
1117 // expression of class type to a base class of that type is
1118 // given Conversion rank, in spite of the fact that a copy
1119 // constructor (i.e., a user-defined conversion function) is
1120 // called for those cases.
1121 if (CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1127 if (Constructor->isCopyConstructor() &&
1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1129 // Turn this into a "standard" conversion sequence, so that it
1130 // gets ranked with standard conversion sequences.
1132 ICS.Standard.setAsIdentityConversion();
1133 ICS.Standard.setFromType(From->getType());
1134 ICS.Standard.setAllToTypes(ToType);
1135 ICS.Standard.CopyConstructor = Constructor;
1136 if (ToCanon != FromCanon)
1137 ICS.Standard.Second = ICK_Derived_To_Base;
1144 ICS.Ambiguous.setFromType(From->getType());
1145 ICS.Ambiguous.setToType(ToType);
1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1147 Cand != Conversions.end(); ++Cand)
1149 ICS.Ambiguous.addConversion(Cand->Function);
1153 case OR_No_Viable_Function:
1154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1161 /// TryImplicitConversion - Attempt to perform an implicit conversion
1162 /// from the given expression (Expr) to the given type (ToType). This
1163 /// function returns an implicit conversion sequence that can be used
1164 /// to perform the initialization. Given
1166 /// void f(float f);
1167 /// void g(int i) { f(i); }
1169 /// this routine would produce an implicit conversion sequence to
1170 /// describe the initialization of f from i, which will be a standard
1171 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1172 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1174 /// Note that this routine only determines how the conversion can be
1175 /// performed; it does not actually perform the conversion. As such,
1176 /// it will not produce any diagnostics if no conversion is available,
1177 /// but will instead return an implicit conversion sequence of kind
1178 /// "BadConversion".
1180 /// If @p SuppressUserConversions, then user-defined conversions are
1182 /// If @p AllowExplicit, then explicit user-defined conversions are
1185 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1186 /// writeback conversion, which allows __autoreleasing id* parameters to
1187 /// be initialized with __strong id* or __weak id* arguments.
1188 static ImplicitConversionSequence
1189 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
1192 bool InOverloadResolution,
1194 bool AllowObjCWritebackConversion,
1195 bool AllowObjCConversionOnExplicit) {
1196 ImplicitConversionSequence ICS;
1197 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1203 if (!S.getLangOpts().CPlusPlus) {
1204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1208 // C++ [over.ics.user]p4:
1209 // A conversion of an expression of class type to the same class
1210 // type is given Exact Match rank, and a conversion of an
1211 // expression of class type to a base class of that type is
1212 // given Conversion rank, in spite of the fact that a copy/move
1213 // constructor (i.e., a user-defined conversion function) is
1214 // called for those cases.
1215 QualType FromType = From->getType();
1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1217 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218 S.IsDerivedFrom(FromType, ToType))) {
1220 ICS.Standard.setAsIdentityConversion();
1221 ICS.Standard.setFromType(FromType);
1222 ICS.Standard.setAllToTypes(ToType);
1224 // We don't actually check at this point whether there is a valid
1225 // copy/move constructor, since overloading just assumes that it
1226 // exists. When we actually perform initialization, we'll find the
1227 // appropriate constructor to copy the returned object, if needed.
1228 ICS.Standard.CopyConstructor = nullptr;
1230 // Determine whether this is considered a derived-to-base conversion.
1231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1232 ICS.Standard.Second = ICK_Derived_To_Base;
1237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238 AllowExplicit, InOverloadResolution, CStyle,
1239 AllowObjCWritebackConversion,
1240 AllowObjCConversionOnExplicit);
1243 ImplicitConversionSequence
1244 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1245 bool SuppressUserConversions,
1247 bool InOverloadResolution,
1249 bool AllowObjCWritebackConversion) {
1250 return ::TryImplicitConversion(*this, From, ToType,
1251 SuppressUserConversions, AllowExplicit,
1252 InOverloadResolution, CStyle,
1253 AllowObjCWritebackConversion,
1254 /*AllowObjCConversionOnExplicit=*/false);
1257 /// PerformImplicitConversion - Perform an implicit conversion of the
1258 /// expression From to the type ToType. Returns the
1259 /// converted expression. Flavor is the kind of conversion we're
1260 /// performing, used in the error message. If @p AllowExplicit,
1261 /// explicit user-defined conversions are permitted.
1263 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1264 AssignmentAction Action, bool AllowExplicit) {
1265 ImplicitConversionSequence ICS;
1266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1270 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1271 AssignmentAction Action, bool AllowExplicit,
1272 ImplicitConversionSequence& ICS) {
1273 if (checkPlaceholderForOverload(*this, From))
1276 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277 bool AllowObjCWritebackConversion
1278 = getLangOpts().ObjCAutoRefCount &&
1279 (Action == AA_Passing || Action == AA_Sending);
1280 if (getLangOpts().ObjC1)
1281 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282 ToType, From->getType(), From);
1283 ICS = ::TryImplicitConversion(*this, From, ToType,
1284 /*SuppressUserConversions=*/false,
1286 /*InOverloadResolution=*/false,
1288 AllowObjCWritebackConversion,
1289 /*AllowObjCConversionOnExplicit=*/false);
1290 return PerformImplicitConversion(From, ToType, ICS, Action);
1293 /// \brief Determine whether the conversion from FromType to ToType is a valid
1294 /// conversion that strips "noreturn" off the nested function type.
1295 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296 QualType &ResultTy) {
1297 if (Context.hasSameUnqualifiedType(FromType, ToType))
1300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1301 // where F adds one of the following at most once:
1303 // - a member pointer
1304 // - a block pointer
1305 CanQualType CanTo = Context.getCanonicalType(ToType);
1306 CanQualType CanFrom = Context.getCanonicalType(FromType);
1307 Type::TypeClass TyClass = CanTo->getTypeClass();
1308 if (TyClass != CanFrom->getTypeClass()) return false;
1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1310 if (TyClass == Type::Pointer) {
1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1313 } else if (TyClass == Type::BlockPointer) {
1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1316 } else if (TyClass == Type::MemberPointer) {
1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1323 TyClass = CanTo->getTypeClass();
1324 if (TyClass != CanFrom->getTypeClass()) return false;
1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1331 if (!EInfo.getNoReturn()) return false;
1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1334 assert(QualType(FromFn, 0).isCanonical());
1335 if (QualType(FromFn, 0) != CanTo) return false;
1341 /// \brief Determine whether the conversion from FromType to ToType is a valid
1342 /// vector conversion.
1344 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1346 static bool IsVectorConversion(Sema &S, QualType FromType,
1347 QualType ToType, ImplicitConversionKind &ICK) {
1348 // We need at least one of these types to be a vector type to have a vector
1350 if (!ToType->isVectorType() && !FromType->isVectorType())
1353 // Identical types require no conversions.
1354 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1357 // There are no conversions between extended vector types, only identity.
1358 if (ToType->isExtVectorType()) {
1359 // There are no conversions between extended vector types other than the
1360 // identity conversion.
1361 if (FromType->isExtVectorType())
1364 // Vector splat from any arithmetic type to a vector.
1365 if (FromType->isArithmeticType()) {
1366 ICK = ICK_Vector_Splat;
1371 // We can perform the conversion between vector types in the following cases:
1372 // 1)vector types are equivalent AltiVec and GCC vector types
1373 // 2)lax vector conversions are permitted and the vector types are of the
1375 if (ToType->isVectorType() && FromType->isVectorType()) {
1376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377 S.isLaxVectorConversion(FromType, ToType)) {
1378 ICK = ICK_Vector_Conversion;
1386 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387 bool InOverloadResolution,
1388 StandardConversionSequence &SCS,
1391 /// IsStandardConversion - Determines whether there is a standard
1392 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1393 /// expression From to the type ToType. Standard conversion sequences
1394 /// only consider non-class types; for conversions that involve class
1395 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1396 /// contain the standard conversion sequence required to perform this
1397 /// conversion and this routine will return true. Otherwise, this
1398 /// routine will return false and the value of SCS is unspecified.
1399 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400 bool InOverloadResolution,
1401 StandardConversionSequence &SCS,
1403 bool AllowObjCWritebackConversion) {
1404 QualType FromType = From->getType();
1406 // Standard conversions (C++ [conv])
1407 SCS.setAsIdentityConversion();
1408 SCS.IncompatibleObjC = false;
1409 SCS.setFromType(FromType);
1410 SCS.CopyConstructor = nullptr;
1412 // There are no standard conversions for class types in C++, so
1413 // abort early. When overloading in C, however, we do permit
1414 if (FromType->isRecordType() || ToType->isRecordType()) {
1415 if (S.getLangOpts().CPlusPlus)
1418 // When we're overloading in C, we allow, as standard conversions,
1421 // The first conversion can be an lvalue-to-rvalue conversion,
1422 // array-to-pointer conversion, or function-to-pointer conversion
1425 if (FromType == S.Context.OverloadTy) {
1426 DeclAccessPair AccessPair;
1427 if (FunctionDecl *Fn
1428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1430 // We were able to resolve the address of the overloaded function,
1431 // so we can convert to the type of that function.
1432 FromType = Fn->getType();
1433 SCS.setFromType(FromType);
1435 // we can sometimes resolve &foo<int> regardless of ToType, so check
1436 // if the type matches (identity) or we are converting to bool
1437 if (!S.Context.hasSameUnqualifiedType(
1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1440 // if the function type matches except for [[noreturn]], it's ok
1441 if (!S.IsNoReturnConversion(FromType,
1442 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1443 // otherwise, only a boolean conversion is standard
1444 if (!ToType->isBooleanType())
1448 // Check if the "from" expression is taking the address of an overloaded
1449 // function and recompute the FromType accordingly. Take advantage of the
1450 // fact that non-static member functions *must* have such an address-of
1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1453 if (Method && !Method->isStatic()) {
1454 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1455 "Non-unary operator on non-static member address");
1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1458 "Non-address-of operator on non-static member address");
1459 const Type *ClassType
1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1461 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1462 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1465 "Non-address-of operator for overloaded function expression");
1466 FromType = S.Context.getPointerType(FromType);
1469 // Check that we've computed the proper type after overload resolution.
1470 assert(S.Context.hasSameType(
1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1477 // Lvalue-to-rvalue conversion (C++11 4.1):
1478 // A glvalue (3.10) of a non-function, non-array type T can
1479 // be converted to a prvalue.
1480 bool argIsLValue = From->isGLValue();
1482 !FromType->isFunctionType() && !FromType->isArrayType() &&
1483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1484 SCS.First = ICK_Lvalue_To_Rvalue;
1487 // ... if the lvalue has atomic type, the value has the non-atomic version
1488 // of the type of the lvalue ...
1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1490 FromType = Atomic->getValueType();
1492 // If T is a non-class type, the type of the rvalue is the
1493 // cv-unqualified version of T. Otherwise, the type of the rvalue
1494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1495 // just strip the qualifiers because they don't matter.
1496 FromType = FromType.getUnqualifiedType();
1497 } else if (FromType->isArrayType()) {
1498 // Array-to-pointer conversion (C++ 4.2)
1499 SCS.First = ICK_Array_To_Pointer;
1501 // An lvalue or rvalue of type "array of N T" or "array of unknown
1502 // bound of T" can be converted to an rvalue of type "pointer to
1504 FromType = S.Context.getArrayDecayedType(FromType);
1506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1507 // This conversion is deprecated in C++03 (D.4)
1508 SCS.DeprecatedStringLiteralToCharPtr = true;
1510 // For the purpose of ranking in overload resolution
1511 // (13.3.3.1.1), this conversion is considered an
1512 // array-to-pointer conversion followed by a qualification
1513 // conversion (4.4). (C++ 4.2p2)
1514 SCS.Second = ICK_Identity;
1515 SCS.Third = ICK_Qualification;
1516 SCS.QualificationIncludesObjCLifetime = false;
1517 SCS.setAllToTypes(FromType);
1520 } else if (FromType->isFunctionType() && argIsLValue) {
1521 // Function-to-pointer conversion (C++ 4.3).
1522 SCS.First = ICK_Function_To_Pointer;
1524 // An lvalue of function type T can be converted to an rvalue of
1525 // type "pointer to T." The result is a pointer to the
1526 // function. (C++ 4.3p1).
1527 FromType = S.Context.getPointerType(FromType);
1529 // We don't require any conversions for the first step.
1530 SCS.First = ICK_Identity;
1532 SCS.setToType(0, FromType);
1534 // The second conversion can be an integral promotion, floating
1535 // point promotion, integral conversion, floating point conversion,
1536 // floating-integral conversion, pointer conversion,
1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1538 // For overloading in C, this can also be a "compatible-type"
1540 bool IncompatibleObjC = false;
1541 ImplicitConversionKind SecondICK = ICK_Identity;
1542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1543 // The unqualified versions of the types are the same: there's no
1544 // conversion to do.
1545 SCS.Second = ICK_Identity;
1546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1547 // Integral promotion (C++ 4.5).
1548 SCS.Second = ICK_Integral_Promotion;
1549 FromType = ToType.getUnqualifiedType();
1550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1551 // Floating point promotion (C++ 4.6).
1552 SCS.Second = ICK_Floating_Promotion;
1553 FromType = ToType.getUnqualifiedType();
1554 } else if (S.IsComplexPromotion(FromType, ToType)) {
1555 // Complex promotion (Clang extension)
1556 SCS.Second = ICK_Complex_Promotion;
1557 FromType = ToType.getUnqualifiedType();
1558 } else if (ToType->isBooleanType() &&
1559 (FromType->isArithmeticType() ||
1560 FromType->isAnyPointerType() ||
1561 FromType->isBlockPointerType() ||
1562 FromType->isMemberPointerType() ||
1563 FromType->isNullPtrType())) {
1564 // Boolean conversions (C++ 4.12).
1565 SCS.Second = ICK_Boolean_Conversion;
1566 FromType = S.Context.BoolTy;
1567 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1568 ToType->isIntegralType(S.Context)) {
1569 // Integral conversions (C++ 4.7).
1570 SCS.Second = ICK_Integral_Conversion;
1571 FromType = ToType.getUnqualifiedType();
1572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1573 // Complex conversions (C99 6.3.1.6)
1574 SCS.Second = ICK_Complex_Conversion;
1575 FromType = ToType.getUnqualifiedType();
1576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1578 // Complex-real conversions (C99 6.3.1.7)
1579 SCS.Second = ICK_Complex_Real;
1580 FromType = ToType.getUnqualifiedType();
1581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1582 // Floating point conversions (C++ 4.8).
1583 SCS.Second = ICK_Floating_Conversion;
1584 FromType = ToType.getUnqualifiedType();
1585 } else if ((FromType->isRealFloatingType() &&
1586 ToType->isIntegralType(S.Context)) ||
1587 (FromType->isIntegralOrUnscopedEnumerationType() &&
1588 ToType->isRealFloatingType())) {
1589 // Floating-integral conversions (C++ 4.9).
1590 SCS.Second = ICK_Floating_Integral;
1591 FromType = ToType.getUnqualifiedType();
1592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1593 SCS.Second = ICK_Block_Pointer_Conversion;
1594 } else if (AllowObjCWritebackConversion &&
1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1596 SCS.Second = ICK_Writeback_Conversion;
1597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598 FromType, IncompatibleObjC)) {
1599 // Pointer conversions (C++ 4.10).
1600 SCS.Second = ICK_Pointer_Conversion;
1601 SCS.IncompatibleObjC = IncompatibleObjC;
1602 FromType = FromType.getUnqualifiedType();
1603 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1604 InOverloadResolution, FromType)) {
1605 // Pointer to member conversions (4.11).
1606 SCS.Second = ICK_Pointer_Member;
1607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1608 SCS.Second = SecondICK;
1609 FromType = ToType.getUnqualifiedType();
1610 } else if (!S.getLangOpts().CPlusPlus &&
1611 S.Context.typesAreCompatible(ToType, FromType)) {
1612 // Compatible conversions (Clang extension for C function overloading)
1613 SCS.Second = ICK_Compatible_Conversion;
1614 FromType = ToType.getUnqualifiedType();
1615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1616 // Treat a conversion that strips "noreturn" as an identity conversion.
1617 SCS.Second = ICK_NoReturn_Adjustment;
1618 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1619 InOverloadResolution,
1621 SCS.Second = ICK_TransparentUnionConversion;
1623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1625 // tryAtomicConversion has updated the standard conversion sequence
1628 } else if (ToType->isEventT() &&
1629 From->isIntegerConstantExpr(S.getASTContext()) &&
1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1631 SCS.Second = ICK_Zero_Event_Conversion;
1634 // No second conversion required.
1635 SCS.Second = ICK_Identity;
1637 SCS.setToType(1, FromType);
1641 // The third conversion can be a qualification conversion (C++ 4p1).
1642 bool ObjCLifetimeConversion;
1643 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644 ObjCLifetimeConversion)) {
1645 SCS.Third = ICK_Qualification;
1646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1648 CanonFrom = S.Context.getCanonicalType(FromType);
1649 CanonTo = S.Context.getCanonicalType(ToType);
1651 // No conversion required
1652 SCS.Third = ICK_Identity;
1654 // C++ [over.best.ics]p6:
1655 // [...] Any difference in top-level cv-qualification is
1656 // subsumed by the initialization itself and does not constitute
1657 // a conversion. [...]
1658 CanonFrom = S.Context.getCanonicalType(FromType);
1659 CanonTo = S.Context.getCanonicalType(ToType);
1660 if (CanonFrom.getLocalUnqualifiedType()
1661 == CanonTo.getLocalUnqualifiedType() &&
1662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1664 CanonFrom = CanonTo;
1667 SCS.setToType(2, FromType);
1669 // If we have not converted the argument type to the parameter type,
1670 // this is a bad conversion sequence.
1671 if (CanonFrom != CanonTo)
1678 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1680 bool InOverloadResolution,
1681 StandardConversionSequence &SCS,
1684 const RecordType *UT = ToType->getAsUnionType();
1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1687 // The field to initialize within the transparent union.
1688 RecordDecl *UD = UT->getDecl();
1689 // It's compatible if the expression matches any of the fields.
1690 for (const auto *it : UD->fields()) {
1691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692 CStyle, /*ObjCWritebackConversion=*/false)) {
1693 ToType = it->getType();
1700 /// IsIntegralPromotion - Determines whether the conversion from the
1701 /// expression From (whose potentially-adjusted type is FromType) to
1702 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1703 /// sets PromotedType to the promoted type.
1704 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1705 const BuiltinType *To = ToType->getAs<BuiltinType>();
1706 // All integers are built-in.
1711 // An rvalue of type char, signed char, unsigned char, short int, or
1712 // unsigned short int can be converted to an rvalue of type int if
1713 // int can represent all the values of the source type; otherwise,
1714 // the source rvalue can be converted to an rvalue of type unsigned
1716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717 !FromType->isEnumeralType()) {
1718 if (// We can promote any signed, promotable integer type to an int
1719 (FromType->isSignedIntegerType() ||
1720 // We can promote any unsigned integer type whose size is
1721 // less than int to an int.
1722 (!FromType->isSignedIntegerType() &&
1723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1724 return To->getKind() == BuiltinType::Int;
1727 return To->getKind() == BuiltinType::UInt;
1730 // C++11 [conv.prom]p3:
1731 // A prvalue of an unscoped enumeration type whose underlying type is not
1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1733 // following types that can represent all the values of the enumeration
1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1735 // unsigned int, long int, unsigned long int, long long int, or unsigned
1736 // long long int. If none of the types in that list can represent all the
1737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1738 // type can be converted to an rvalue a prvalue of the extended integer type
1739 // with lowest integer conversion rank (4.13) greater than the rank of long
1740 // long in which all the values of the enumeration can be represented. If
1741 // there are two such extended types, the signed one is chosen.
1742 // C++11 [conv.prom]p4:
1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1744 // can be converted to a prvalue of its underlying type. Moreover, if
1745 // integral promotion can be applied to its underlying type, a prvalue of an
1746 // unscoped enumeration type whose underlying type is fixed can also be
1747 // converted to a prvalue of the promoted underlying type.
1748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1750 // provided for a scoped enumeration.
1751 if (FromEnumType->getDecl()->isScoped())
1754 // We can perform an integral promotion to the underlying type of the enum,
1755 // even if that's not the promoted type. Note that the check for promoting
1756 // the underlying type is based on the type alone, and does not consider
1757 // the bitfield-ness of the actual source expression.
1758 if (FromEnumType->getDecl()->isFixed()) {
1759 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1760 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1761 IsIntegralPromotion(nullptr, Underlying, ToType);
1764 // We have already pre-calculated the promotion type, so this is trivial.
1765 if (ToType->isIntegerType() &&
1766 !RequireCompleteType(From->getLocStart(), FromType, 0))
1767 return Context.hasSameUnqualifiedType(
1768 ToType, FromEnumType->getDecl()->getPromotionType());
1771 // C++0x [conv.prom]p2:
1772 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1773 // to an rvalue a prvalue of the first of the following types that can
1774 // represent all the values of its underlying type: int, unsigned int,
1775 // long int, unsigned long int, long long int, or unsigned long long int.
1776 // If none of the types in that list can represent all the values of its
1777 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1778 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1780 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1781 ToType->isIntegerType()) {
1782 // Determine whether the type we're converting from is signed or
1784 bool FromIsSigned = FromType->isSignedIntegerType();
1785 uint64_t FromSize = Context.getTypeSize(FromType);
1787 // The types we'll try to promote to, in the appropriate
1788 // order. Try each of these types.
1789 QualType PromoteTypes[6] = {
1790 Context.IntTy, Context.UnsignedIntTy,
1791 Context.LongTy, Context.UnsignedLongTy ,
1792 Context.LongLongTy, Context.UnsignedLongLongTy
1794 for (int Idx = 0; Idx < 6; ++Idx) {
1795 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1796 if (FromSize < ToSize ||
1797 (FromSize == ToSize &&
1798 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1799 // We found the type that we can promote to. If this is the
1800 // type we wanted, we have a promotion. Otherwise, no
1802 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1807 // An rvalue for an integral bit-field (9.6) can be converted to an
1808 // rvalue of type int if int can represent all the values of the
1809 // bit-field; otherwise, it can be converted to unsigned int if
1810 // unsigned int can represent all the values of the bit-field. If
1811 // the bit-field is larger yet, no integral promotion applies to
1812 // it. If the bit-field has an enumerated type, it is treated as any
1813 // other value of that type for promotion purposes (C++ 4.5p3).
1814 // FIXME: We should delay checking of bit-fields until we actually perform the
1817 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1818 llvm::APSInt BitWidth;
1819 if (FromType->isIntegralType(Context) &&
1820 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1821 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1822 ToSize = Context.getTypeSize(ToType);
1824 // Are we promoting to an int from a bitfield that fits in an int?
1825 if (BitWidth < ToSize ||
1826 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1827 return To->getKind() == BuiltinType::Int;
1830 // Are we promoting to an unsigned int from an unsigned bitfield
1831 // that fits into an unsigned int?
1832 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1833 return To->getKind() == BuiltinType::UInt;
1841 // An rvalue of type bool can be converted to an rvalue of type int,
1842 // with false becoming zero and true becoming one (C++ 4.5p4).
1843 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1850 /// IsFloatingPointPromotion - Determines whether the conversion from
1851 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1852 /// returns true and sets PromotedType to the promoted type.
1853 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1854 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1855 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1856 /// An rvalue of type float can be converted to an rvalue of type
1857 /// double. (C++ 4.6p1).
1858 if (FromBuiltin->getKind() == BuiltinType::Float &&
1859 ToBuiltin->getKind() == BuiltinType::Double)
1863 // When a float is promoted to double or long double, or a
1864 // double is promoted to long double [...].
1865 if (!getLangOpts().CPlusPlus &&
1866 (FromBuiltin->getKind() == BuiltinType::Float ||
1867 FromBuiltin->getKind() == BuiltinType::Double) &&
1868 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1871 // Half can be promoted to float.
1872 if (!getLangOpts().NativeHalfType &&
1873 FromBuiltin->getKind() == BuiltinType::Half &&
1874 ToBuiltin->getKind() == BuiltinType::Float)
1881 /// \brief Determine if a conversion is a complex promotion.
1883 /// A complex promotion is defined as a complex -> complex conversion
1884 /// where the conversion between the underlying real types is a
1885 /// floating-point or integral promotion.
1886 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1887 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1891 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1895 return IsFloatingPointPromotion(FromComplex->getElementType(),
1896 ToComplex->getElementType()) ||
1897 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1898 ToComplex->getElementType());
1901 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1902 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1903 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1904 /// if non-empty, will be a pointer to ToType that may or may not have
1905 /// the right set of qualifiers on its pointee.
1908 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1909 QualType ToPointee, QualType ToType,
1910 ASTContext &Context,
1911 bool StripObjCLifetime = false) {
1912 assert((FromPtr->getTypeClass() == Type::Pointer ||
1913 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1914 "Invalid similarly-qualified pointer type");
1916 /// Conversions to 'id' subsume cv-qualifier conversions.
1917 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1918 return ToType.getUnqualifiedType();
1920 QualType CanonFromPointee
1921 = Context.getCanonicalType(FromPtr->getPointeeType());
1922 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1923 Qualifiers Quals = CanonFromPointee.getQualifiers();
1925 if (StripObjCLifetime)
1926 Quals.removeObjCLifetime();
1928 // Exact qualifier match -> return the pointer type we're converting to.
1929 if (CanonToPointee.getLocalQualifiers() == Quals) {
1930 // ToType is exactly what we need. Return it.
1931 if (!ToType.isNull())
1932 return ToType.getUnqualifiedType();
1934 // Build a pointer to ToPointee. It has the right qualifiers
1936 if (isa<ObjCObjectPointerType>(ToType))
1937 return Context.getObjCObjectPointerType(ToPointee);
1938 return Context.getPointerType(ToPointee);
1941 // Just build a canonical type that has the right qualifiers.
1942 QualType QualifiedCanonToPointee
1943 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1945 if (isa<ObjCObjectPointerType>(ToType))
1946 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1947 return Context.getPointerType(QualifiedCanonToPointee);
1950 static bool isNullPointerConstantForConversion(Expr *Expr,
1951 bool InOverloadResolution,
1952 ASTContext &Context) {
1953 // Handle value-dependent integral null pointer constants correctly.
1954 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1955 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1956 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1957 return !InOverloadResolution;
1959 return Expr->isNullPointerConstant(Context,
1960 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1961 : Expr::NPC_ValueDependentIsNull);
1964 /// IsPointerConversion - Determines whether the conversion of the
1965 /// expression From, which has the (possibly adjusted) type FromType,
1966 /// can be converted to the type ToType via a pointer conversion (C++
1967 /// 4.10). If so, returns true and places the converted type (that
1968 /// might differ from ToType in its cv-qualifiers at some level) into
1971 /// This routine also supports conversions to and from block pointers
1972 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1973 /// pointers to interfaces. FIXME: Once we've determined the
1974 /// appropriate overloading rules for Objective-C, we may want to
1975 /// split the Objective-C checks into a different routine; however,
1976 /// GCC seems to consider all of these conversions to be pointer
1977 /// conversions, so for now they live here. IncompatibleObjC will be
1978 /// set if the conversion is an allowed Objective-C conversion that
1979 /// should result in a warning.
1980 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1981 bool InOverloadResolution,
1982 QualType& ConvertedType,
1983 bool &IncompatibleObjC) {
1984 IncompatibleObjC = false;
1985 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1989 // Conversion from a null pointer constant to any Objective-C pointer type.
1990 if (ToType->isObjCObjectPointerType() &&
1991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1992 ConvertedType = ToType;
1996 // Blocks: Block pointers can be converted to void*.
1997 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1998 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1999 ConvertedType = ToType;
2002 // Blocks: A null pointer constant can be converted to a block
2004 if (ToType->isBlockPointerType() &&
2005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2006 ConvertedType = ToType;
2010 // If the left-hand-side is nullptr_t, the right side can be a null
2011 // pointer constant.
2012 if (ToType->isNullPtrType() &&
2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2014 ConvertedType = ToType;
2018 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2022 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2023 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2024 ConvertedType = ToType;
2028 // Beyond this point, both types need to be pointers
2029 // , including objective-c pointers.
2030 QualType ToPointeeType = ToTypePtr->getPointeeType();
2031 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2032 !getLangOpts().ObjCAutoRefCount) {
2033 ConvertedType = BuildSimilarlyQualifiedPointerType(
2034 FromType->getAs<ObjCObjectPointerType>(),
2039 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2043 QualType FromPointeeType = FromTypePtr->getPointeeType();
2045 // If the unqualified pointee types are the same, this can't be a
2046 // pointer conversion, so don't do all of the work below.
2047 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2050 // An rvalue of type "pointer to cv T," where T is an object type,
2051 // can be converted to an rvalue of type "pointer to cv void" (C++
2053 if (FromPointeeType->isIncompleteOrObjectType() &&
2054 ToPointeeType->isVoidType()) {
2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2058 /*StripObjCLifetime=*/true);
2062 // MSVC allows implicit function to void* type conversion.
2063 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2064 ToPointeeType->isVoidType()) {
2065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2071 // When we're overloading in C, we allow a special kind of pointer
2072 // conversion for compatible-but-not-identical pointee types.
2073 if (!getLangOpts().CPlusPlus &&
2074 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2081 // C++ [conv.ptr]p3:
2083 // An rvalue of type "pointer to cv D," where D is a class type,
2084 // can be converted to an rvalue of type "pointer to cv B," where
2085 // B is a base class (clause 10) of D. If B is an inaccessible
2086 // (clause 11) or ambiguous (10.2) base class of D, a program that
2087 // necessitates this conversion is ill-formed. The result of the
2088 // conversion is a pointer to the base class sub-object of the
2089 // derived class object. The null pointer value is converted to
2090 // the null pointer value of the destination type.
2092 // Note that we do not check for ambiguity or inaccessibility
2093 // here. That is handled by CheckPointerConversion.
2094 if (getLangOpts().CPlusPlus &&
2095 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2096 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2097 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2098 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2105 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2106 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2116 /// \brief Adopt the given qualifiers for the given type.
2117 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2118 Qualifiers TQs = T.getQualifiers();
2120 // Check whether qualifiers already match.
2124 if (Qs.compatiblyIncludes(TQs))
2125 return Context.getQualifiedType(T, Qs);
2127 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2130 /// isObjCPointerConversion - Determines whether this is an
2131 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2132 /// with the same arguments and return values.
2133 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2134 QualType& ConvertedType,
2135 bool &IncompatibleObjC) {
2136 if (!getLangOpts().ObjC1)
2139 // The set of qualifiers on the type we're converting from.
2140 Qualifiers FromQualifiers = FromType.getQualifiers();
2142 // First, we handle all conversions on ObjC object pointer types.
2143 const ObjCObjectPointerType* ToObjCPtr =
2144 ToType->getAs<ObjCObjectPointerType>();
2145 const ObjCObjectPointerType *FromObjCPtr =
2146 FromType->getAs<ObjCObjectPointerType>();
2148 if (ToObjCPtr && FromObjCPtr) {
2149 // If the pointee types are the same (ignoring qualifications),
2150 // then this is not a pointer conversion.
2151 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2152 FromObjCPtr->getPointeeType()))
2155 // Check for compatible
2156 // Objective C++: We're able to convert between "id" or "Class" and a
2157 // pointer to any interface (in both directions).
2158 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2159 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2162 // Conversions with Objective-C's id<...>.
2163 if ((FromObjCPtr->isObjCQualifiedIdType() ||
2164 ToObjCPtr->isObjCQualifiedIdType()) &&
2165 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2166 /*compare=*/false)) {
2167 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2170 // Objective C++: We're able to convert from a pointer to an
2171 // interface to a pointer to a different interface.
2172 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2173 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2174 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2175 if (getLangOpts().CPlusPlus && LHS && RHS &&
2176 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2177 FromObjCPtr->getPointeeType()))
2179 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2180 ToObjCPtr->getPointeeType(),
2182 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2186 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2187 // Okay: this is some kind of implicit downcast of Objective-C
2188 // interfaces, which is permitted. However, we're going to
2189 // complain about it.
2190 IncompatibleObjC = true;
2191 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2192 ToObjCPtr->getPointeeType(),
2194 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2198 // Beyond this point, both types need to be C pointers or block pointers.
2199 QualType ToPointeeType;
2200 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2201 ToPointeeType = ToCPtr->getPointeeType();
2202 else if (const BlockPointerType *ToBlockPtr =
2203 ToType->getAs<BlockPointerType>()) {
2204 // Objective C++: We're able to convert from a pointer to any object
2205 // to a block pointer type.
2206 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2207 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2210 ToPointeeType = ToBlockPtr->getPointeeType();
2212 else if (FromType->getAs<BlockPointerType>() &&
2213 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2214 // Objective C++: We're able to convert from a block pointer type to a
2215 // pointer to any object.
2216 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2222 QualType FromPointeeType;
2223 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2224 FromPointeeType = FromCPtr->getPointeeType();
2225 else if (const BlockPointerType *FromBlockPtr =
2226 FromType->getAs<BlockPointerType>())
2227 FromPointeeType = FromBlockPtr->getPointeeType();
2231 // If we have pointers to pointers, recursively check whether this
2232 // is an Objective-C conversion.
2233 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2234 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2235 IncompatibleObjC)) {
2236 // We always complain about this conversion.
2237 IncompatibleObjC = true;
2238 ConvertedType = Context.getPointerType(ConvertedType);
2239 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2242 // Allow conversion of pointee being objective-c pointer to another one;
2244 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2245 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2246 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2247 IncompatibleObjC)) {
2249 ConvertedType = Context.getPointerType(ConvertedType);
2250 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2254 // If we have pointers to functions or blocks, check whether the only
2255 // differences in the argument and result types are in Objective-C
2256 // pointer conversions. If so, we permit the conversion (but
2257 // complain about it).
2258 const FunctionProtoType *FromFunctionType
2259 = FromPointeeType->getAs<FunctionProtoType>();
2260 const FunctionProtoType *ToFunctionType
2261 = ToPointeeType->getAs<FunctionProtoType>();
2262 if (FromFunctionType && ToFunctionType) {
2263 // If the function types are exactly the same, this isn't an
2264 // Objective-C pointer conversion.
2265 if (Context.getCanonicalType(FromPointeeType)
2266 == Context.getCanonicalType(ToPointeeType))
2269 // Perform the quick checks that will tell us whether these
2270 // function types are obviously different.
2271 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2272 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2273 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2276 bool HasObjCConversion = false;
2277 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2278 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2279 // Okay, the types match exactly. Nothing to do.
2280 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2281 ToFunctionType->getReturnType(),
2282 ConvertedType, IncompatibleObjC)) {
2283 // Okay, we have an Objective-C pointer conversion.
2284 HasObjCConversion = true;
2286 // Function types are too different. Abort.
2290 // Check argument types.
2291 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2292 ArgIdx != NumArgs; ++ArgIdx) {
2293 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2294 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2295 if (Context.getCanonicalType(FromArgType)
2296 == Context.getCanonicalType(ToArgType)) {
2297 // Okay, the types match exactly. Nothing to do.
2298 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2299 ConvertedType, IncompatibleObjC)) {
2300 // Okay, we have an Objective-C pointer conversion.
2301 HasObjCConversion = true;
2303 // Argument types are too different. Abort.
2308 if (HasObjCConversion) {
2309 // We had an Objective-C conversion. Allow this pointer
2310 // conversion, but complain about it.
2311 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2312 IncompatibleObjC = true;
2320 /// \brief Determine whether this is an Objective-C writeback conversion,
2321 /// used for parameter passing when performing automatic reference counting.
2323 /// \param FromType The type we're converting form.
2325 /// \param ToType The type we're converting to.
2327 /// \param ConvertedType The type that will be produced after applying
2328 /// this conversion.
2329 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2330 QualType &ConvertedType) {
2331 if (!getLangOpts().ObjCAutoRefCount ||
2332 Context.hasSameUnqualifiedType(FromType, ToType))
2335 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2337 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2338 ToPointee = ToPointer->getPointeeType();
2342 Qualifiers ToQuals = ToPointee.getQualifiers();
2343 if (!ToPointee->isObjCLifetimeType() ||
2344 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2345 !ToQuals.withoutObjCLifetime().empty())
2348 // Argument must be a pointer to __strong to __weak.
2349 QualType FromPointee;
2350 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2351 FromPointee = FromPointer->getPointeeType();
2355 Qualifiers FromQuals = FromPointee.getQualifiers();
2356 if (!FromPointee->isObjCLifetimeType() ||
2357 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2358 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2361 // Make sure that we have compatible qualifiers.
2362 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2363 if (!ToQuals.compatiblyIncludes(FromQuals))
2366 // Remove qualifiers from the pointee type we're converting from; they
2367 // aren't used in the compatibility check belong, and we'll be adding back
2368 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2369 FromPointee = FromPointee.getUnqualifiedType();
2371 // The unqualified form of the pointee types must be compatible.
2372 ToPointee = ToPointee.getUnqualifiedType();
2373 bool IncompatibleObjC;
2374 if (Context.typesAreCompatible(FromPointee, ToPointee))
2375 FromPointee = ToPointee;
2376 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2380 /// \brief Construct the type we're converting to, which is a pointer to
2381 /// __autoreleasing pointee.
2382 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2383 ConvertedType = Context.getPointerType(FromPointee);
2387 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2388 QualType& ConvertedType) {
2389 QualType ToPointeeType;
2390 if (const BlockPointerType *ToBlockPtr =
2391 ToType->getAs<BlockPointerType>())
2392 ToPointeeType = ToBlockPtr->getPointeeType();
2396 QualType FromPointeeType;
2397 if (const BlockPointerType *FromBlockPtr =
2398 FromType->getAs<BlockPointerType>())
2399 FromPointeeType = FromBlockPtr->getPointeeType();
2402 // We have pointer to blocks, check whether the only
2403 // differences in the argument and result types are in Objective-C
2404 // pointer conversions. If so, we permit the conversion.
2406 const FunctionProtoType *FromFunctionType
2407 = FromPointeeType->getAs<FunctionProtoType>();
2408 const FunctionProtoType *ToFunctionType
2409 = ToPointeeType->getAs<FunctionProtoType>();
2411 if (!FromFunctionType || !ToFunctionType)
2414 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2417 // Perform the quick checks that will tell us whether these
2418 // function types are obviously different.
2419 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2420 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2423 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2424 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2425 if (FromEInfo != ToEInfo)
2428 bool IncompatibleObjC = false;
2429 if (Context.hasSameType(FromFunctionType->getReturnType(),
2430 ToFunctionType->getReturnType())) {
2431 // Okay, the types match exactly. Nothing to do.
2433 QualType RHS = FromFunctionType->getReturnType();
2434 QualType LHS = ToFunctionType->getReturnType();
2435 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2436 !RHS.hasQualifiers() && LHS.hasQualifiers())
2437 LHS = LHS.getUnqualifiedType();
2439 if (Context.hasSameType(RHS,LHS)) {
2441 } else if (isObjCPointerConversion(RHS, LHS,
2442 ConvertedType, IncompatibleObjC)) {
2443 if (IncompatibleObjC)
2445 // Okay, we have an Objective-C pointer conversion.
2451 // Check argument types.
2452 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2453 ArgIdx != NumArgs; ++ArgIdx) {
2454 IncompatibleObjC = false;
2455 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2456 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2457 if (Context.hasSameType(FromArgType, ToArgType)) {
2458 // Okay, the types match exactly. Nothing to do.
2459 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2460 ConvertedType, IncompatibleObjC)) {
2461 if (IncompatibleObjC)
2463 // Okay, we have an Objective-C pointer conversion.
2465 // Argument types are too different. Abort.
2468 if (LangOpts.ObjCAutoRefCount &&
2469 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2473 ConvertedType = ToType;
2481 ft_parameter_mismatch,
2483 ft_qualifer_mismatch
2486 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2487 /// function types. Catches different number of parameter, mismatch in
2488 /// parameter types, and different return types.
2489 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2490 QualType FromType, QualType ToType) {
2491 // If either type is not valid, include no extra info.
2492 if (FromType.isNull() || ToType.isNull()) {
2493 PDiag << ft_default;
2497 // Get the function type from the pointers.
2498 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2499 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2500 *ToMember = ToType->getAs<MemberPointerType>();
2501 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2502 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2503 << QualType(FromMember->getClass(), 0);
2506 FromType = FromMember->getPointeeType();
2507 ToType = ToMember->getPointeeType();
2510 if (FromType->isPointerType())
2511 FromType = FromType->getPointeeType();
2512 if (ToType->isPointerType())
2513 ToType = ToType->getPointeeType();
2515 // Remove references.
2516 FromType = FromType.getNonReferenceType();
2517 ToType = ToType.getNonReferenceType();
2519 // Don't print extra info for non-specialized template functions.
2520 if (FromType->isInstantiationDependentType() &&
2521 !FromType->getAs<TemplateSpecializationType>()) {
2522 PDiag << ft_default;
2526 // No extra info for same types.
2527 if (Context.hasSameType(FromType, ToType)) {
2528 PDiag << ft_default;
2532 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2533 *ToFunction = ToType->getAs<FunctionProtoType>();
2535 // Both types need to be function types.
2536 if (!FromFunction || !ToFunction) {
2537 PDiag << ft_default;
2541 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2542 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2543 << FromFunction->getNumParams();
2547 // Handle different parameter types.
2549 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2550 PDiag << ft_parameter_mismatch << ArgPos + 1
2551 << ToFunction->getParamType(ArgPos)
2552 << FromFunction->getParamType(ArgPos);
2556 // Handle different return type.
2557 if (!Context.hasSameType(FromFunction->getReturnType(),
2558 ToFunction->getReturnType())) {
2559 PDiag << ft_return_type << ToFunction->getReturnType()
2560 << FromFunction->getReturnType();
2564 unsigned FromQuals = FromFunction->getTypeQuals(),
2565 ToQuals = ToFunction->getTypeQuals();
2566 if (FromQuals != ToQuals) {
2567 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2571 // Unable to find a difference, so add no extra info.
2572 PDiag << ft_default;
2575 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2576 /// for equality of their argument types. Caller has already checked that
2577 /// they have same number of arguments. If the parameters are different,
2578 /// ArgPos will have the parameter index of the first different parameter.
2579 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2580 const FunctionProtoType *NewType,
2582 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2583 N = NewType->param_type_begin(),
2584 E = OldType->param_type_end();
2585 O && (O != E); ++O, ++N) {
2586 if (!Context.hasSameType(O->getUnqualifiedType(),
2587 N->getUnqualifiedType())) {
2589 *ArgPos = O - OldType->param_type_begin();
2596 /// CheckPointerConversion - Check the pointer conversion from the
2597 /// expression From to the type ToType. This routine checks for
2598 /// ambiguous or inaccessible derived-to-base pointer
2599 /// conversions for which IsPointerConversion has already returned
2600 /// true. It returns true and produces a diagnostic if there was an
2601 /// error, or returns false otherwise.
2602 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2604 CXXCastPath& BasePath,
2605 bool IgnoreBaseAccess) {
2606 QualType FromType = From->getType();
2607 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2611 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2612 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2613 Expr::NPCK_ZeroExpression) {
2614 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2615 DiagRuntimeBehavior(From->getExprLoc(), From,
2616 PDiag(diag::warn_impcast_bool_to_null_pointer)
2617 << ToType << From->getSourceRange());
2618 else if (!isUnevaluatedContext())
2619 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2620 << ToType << From->getSourceRange();
2622 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2623 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2624 QualType FromPointeeType = FromPtrType->getPointeeType(),
2625 ToPointeeType = ToPtrType->getPointeeType();
2627 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2628 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2629 // We must have a derived-to-base conversion. Check an
2630 // ambiguous or inaccessible conversion.
2631 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2633 From->getSourceRange(), &BasePath,
2637 // The conversion was successful.
2638 Kind = CK_DerivedToBase;
2641 } else if (const ObjCObjectPointerType *ToPtrType =
2642 ToType->getAs<ObjCObjectPointerType>()) {
2643 if (const ObjCObjectPointerType *FromPtrType =
2644 FromType->getAs<ObjCObjectPointerType>()) {
2645 // Objective-C++ conversions are always okay.
2646 // FIXME: We should have a different class of conversions for the
2647 // Objective-C++ implicit conversions.
2648 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2650 } else if (FromType->isBlockPointerType()) {
2651 Kind = CK_BlockPointerToObjCPointerCast;
2653 Kind = CK_CPointerToObjCPointerCast;
2655 } else if (ToType->isBlockPointerType()) {
2656 if (!FromType->isBlockPointerType())
2657 Kind = CK_AnyPointerToBlockPointerCast;
2660 // We shouldn't fall into this case unless it's valid for other
2662 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2663 Kind = CK_NullToPointer;
2668 /// IsMemberPointerConversion - Determines whether the conversion of the
2669 /// expression From, which has the (possibly adjusted) type FromType, can be
2670 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2671 /// If so, returns true and places the converted type (that might differ from
2672 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2673 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2675 bool InOverloadResolution,
2676 QualType &ConvertedType) {
2677 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2681 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2682 if (From->isNullPointerConstant(Context,
2683 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2684 : Expr::NPC_ValueDependentIsNull)) {
2685 ConvertedType = ToType;
2689 // Otherwise, both types have to be member pointers.
2690 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2694 // A pointer to member of B can be converted to a pointer to member of D,
2695 // where D is derived from B (C++ 4.11p2).
2696 QualType FromClass(FromTypePtr->getClass(), 0);
2697 QualType ToClass(ToTypePtr->getClass(), 0);
2699 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2700 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2701 IsDerivedFrom(ToClass, FromClass)) {
2702 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2703 ToClass.getTypePtr());
2710 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2711 /// expression From to the type ToType. This routine checks for ambiguous or
2712 /// virtual or inaccessible base-to-derived member pointer conversions
2713 /// for which IsMemberPointerConversion has already returned true. It returns
2714 /// true and produces a diagnostic if there was an error, or returns false
2716 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2718 CXXCastPath &BasePath,
2719 bool IgnoreBaseAccess) {
2720 QualType FromType = From->getType();
2721 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2723 // This must be a null pointer to member pointer conversion
2724 assert(From->isNullPointerConstant(Context,
2725 Expr::NPC_ValueDependentIsNull) &&
2726 "Expr must be null pointer constant!");
2727 Kind = CK_NullToMemberPointer;
2731 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2732 assert(ToPtrType && "No member pointer cast has a target type "
2733 "that is not a member pointer.");
2735 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2736 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2738 // FIXME: What about dependent types?
2739 assert(FromClass->isRecordType() && "Pointer into non-class.");
2740 assert(ToClass->isRecordType() && "Pointer into non-class.");
2742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2743 /*DetectVirtual=*/true);
2744 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2745 assert(DerivationOkay &&
2746 "Should not have been called if derivation isn't OK.");
2747 (void)DerivationOkay;
2749 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2750 getUnqualifiedType())) {
2751 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2752 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2753 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2757 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2758 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2759 << FromClass << ToClass << QualType(VBase, 0)
2760 << From->getSourceRange();
2764 if (!IgnoreBaseAccess)
2765 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2767 diag::err_downcast_from_inaccessible_base);
2769 // Must be a base to derived member conversion.
2770 BuildBasePathArray(Paths, BasePath);
2771 Kind = CK_BaseToDerivedMemberPointer;
2775 /// Determine whether the lifetime conversion between the two given
2776 /// qualifiers sets is nontrivial.
2777 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2778 Qualifiers ToQuals) {
2779 // Converting anything to const __unsafe_unretained is trivial.
2780 if (ToQuals.hasConst() &&
2781 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2787 /// IsQualificationConversion - Determines whether the conversion from
2788 /// an rvalue of type FromType to ToType is a qualification conversion
2791 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2792 /// when the qualification conversion involves a change in the Objective-C
2793 /// object lifetime.
2795 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2796 bool CStyle, bool &ObjCLifetimeConversion) {
2797 FromType = Context.getCanonicalType(FromType);
2798 ToType = Context.getCanonicalType(ToType);
2799 ObjCLifetimeConversion = false;
2801 // If FromType and ToType are the same type, this is not a
2802 // qualification conversion.
2803 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2807 // A conversion can add cv-qualifiers at levels other than the first
2808 // in multi-level pointers, subject to the following rules: [...]
2809 bool PreviousToQualsIncludeConst = true;
2810 bool UnwrappedAnyPointer = false;
2811 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2812 // Within each iteration of the loop, we check the qualifiers to
2813 // determine if this still looks like a qualification
2814 // conversion. Then, if all is well, we unwrap one more level of
2815 // pointers or pointers-to-members and do it all again
2816 // until there are no more pointers or pointers-to-members left to
2818 UnwrappedAnyPointer = true;
2820 Qualifiers FromQuals = FromType.getQualifiers();
2821 Qualifiers ToQuals = ToType.getQualifiers();
2824 // Check Objective-C lifetime conversions.
2825 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2826 UnwrappedAnyPointer) {
2827 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2828 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2829 ObjCLifetimeConversion = true;
2830 FromQuals.removeObjCLifetime();
2831 ToQuals.removeObjCLifetime();
2833 // Qualification conversions cannot cast between different
2834 // Objective-C lifetime qualifiers.
2839 // Allow addition/removal of GC attributes but not changing GC attributes.
2840 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2841 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2842 FromQuals.removeObjCGCAttr();
2843 ToQuals.removeObjCGCAttr();
2846 // -- for every j > 0, if const is in cv 1,j then const is in cv
2847 // 2,j, and similarly for volatile.
2848 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2851 // -- if the cv 1,j and cv 2,j are different, then const is in
2852 // every cv for 0 < k < j.
2853 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2854 && !PreviousToQualsIncludeConst)
2857 // Keep track of whether all prior cv-qualifiers in the "to" type
2859 PreviousToQualsIncludeConst
2860 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2863 // We are left with FromType and ToType being the pointee types
2864 // after unwrapping the original FromType and ToType the same number
2865 // of types. If we unwrapped any pointers, and if FromType and
2866 // ToType have the same unqualified type (since we checked
2867 // qualifiers above), then this is a qualification conversion.
2868 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2871 /// \brief - Determine whether this is a conversion from a scalar type to an
2874 /// If successful, updates \c SCS's second and third steps in the conversion
2875 /// sequence to finish the conversion.
2876 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2877 bool InOverloadResolution,
2878 StandardConversionSequence &SCS,
2880 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2884 StandardConversionSequence InnerSCS;
2885 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2886 InOverloadResolution, InnerSCS,
2887 CStyle, /*AllowObjCWritebackConversion=*/false))
2890 SCS.Second = InnerSCS.Second;
2891 SCS.setToType(1, InnerSCS.getToType(1));
2892 SCS.Third = InnerSCS.Third;
2893 SCS.QualificationIncludesObjCLifetime
2894 = InnerSCS.QualificationIncludesObjCLifetime;
2895 SCS.setToType(2, InnerSCS.getToType(2));
2899 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2900 CXXConstructorDecl *Constructor,
2902 const FunctionProtoType *CtorType =
2903 Constructor->getType()->getAs<FunctionProtoType>();
2904 if (CtorType->getNumParams() > 0) {
2905 QualType FirstArg = CtorType->getParamType(0);
2906 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2912 static OverloadingResult
2913 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2915 UserDefinedConversionSequence &User,
2916 OverloadCandidateSet &CandidateSet,
2917 bool AllowExplicit) {
2918 DeclContext::lookup_result R = S.LookupConstructors(To);
2919 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2920 Con != ConEnd; ++Con) {
2921 NamedDecl *D = *Con;
2922 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2924 // Find the constructor (which may be a template).
2925 CXXConstructorDecl *Constructor = nullptr;
2926 FunctionTemplateDecl *ConstructorTmpl
2927 = dyn_cast<FunctionTemplateDecl>(D);
2928 if (ConstructorTmpl)
2930 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2932 Constructor = cast<CXXConstructorDecl>(D);
2934 bool Usable = !Constructor->isInvalidDecl() &&
2935 S.isInitListConstructor(Constructor) &&
2936 (AllowExplicit || !Constructor->isExplicit());
2938 // If the first argument is (a reference to) the target type,
2939 // suppress conversions.
2940 bool SuppressUserConversions =
2941 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2942 if (ConstructorTmpl)
2943 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2944 /*ExplicitArgs*/ nullptr,
2946 SuppressUserConversions);
2948 S.AddOverloadCandidate(Constructor, FoundDecl,
2950 SuppressUserConversions);
2954 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2956 OverloadCandidateSet::iterator Best;
2957 switch (auto Result =
2958 CandidateSet.BestViableFunction(S, From->getLocStart(),
2962 // Record the standard conversion we used and the conversion function.
2963 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2964 QualType ThisType = Constructor->getThisType(S.Context);
2965 // Initializer lists don't have conversions as such.
2966 User.Before.setAsIdentityConversion();
2967 User.HadMultipleCandidates = HadMultipleCandidates;
2968 User.ConversionFunction = Constructor;
2969 User.FoundConversionFunction = Best->FoundDecl;
2970 User.After.setAsIdentityConversion();
2971 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2972 User.After.setAllToTypes(ToType);
2976 case OR_No_Viable_Function:
2977 return OR_No_Viable_Function;
2979 return OR_Ambiguous;
2982 llvm_unreachable("Invalid OverloadResult!");
2985 /// Determines whether there is a user-defined conversion sequence
2986 /// (C++ [over.ics.user]) that converts expression From to the type
2987 /// ToType. If such a conversion exists, User will contain the
2988 /// user-defined conversion sequence that performs such a conversion
2989 /// and this routine will return true. Otherwise, this routine returns
2990 /// false and User is unspecified.
2992 /// \param AllowExplicit true if the conversion should consider C++0x
2993 /// "explicit" conversion functions as well as non-explicit conversion
2994 /// functions (C++0x [class.conv.fct]p2).
2996 /// \param AllowObjCConversionOnExplicit true if the conversion should
2997 /// allow an extra Objective-C pointer conversion on uses of explicit
2998 /// constructors. Requires \c AllowExplicit to also be set.
2999 static OverloadingResult
3000 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3001 UserDefinedConversionSequence &User,
3002 OverloadCandidateSet &CandidateSet,
3004 bool AllowObjCConversionOnExplicit) {
3005 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3007 // Whether we will only visit constructors.
3008 bool ConstructorsOnly = false;
3010 // If the type we are conversion to is a class type, enumerate its
3012 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3013 // C++ [over.match.ctor]p1:
3014 // When objects of class type are direct-initialized (8.5), or
3015 // copy-initialized from an expression of the same or a
3016 // derived class type (8.5), overload resolution selects the
3017 // constructor. [...] For copy-initialization, the candidate
3018 // functions are all the converting constructors (12.3.1) of
3019 // that class. The argument list is the expression-list within
3020 // the parentheses of the initializer.
3021 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3022 (From->getType()->getAs<RecordType>() &&
3023 S.IsDerivedFrom(From->getType(), ToType)))
3024 ConstructorsOnly = true;
3026 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3027 // RequireCompleteType may have returned true due to some invalid decl
3028 // during template instantiation, but ToType may be complete enough now
3029 // to try to recover.
3030 if (ToType->isIncompleteType()) {
3031 // We're not going to find any constructors.
3032 } else if (CXXRecordDecl *ToRecordDecl
3033 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3035 Expr **Args = &From;
3036 unsigned NumArgs = 1;
3037 bool ListInitializing = false;
3038 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3039 // But first, see if there is an init-list-constructor that will work.
3040 OverloadingResult Result = IsInitializerListConstructorConversion(
3041 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3042 if (Result != OR_No_Viable_Function)
3045 CandidateSet.clear();
3047 // If we're list-initializing, we pass the individual elements as
3048 // arguments, not the entire list.
3049 Args = InitList->getInits();
3050 NumArgs = InitList->getNumInits();
3051 ListInitializing = true;
3054 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3055 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3056 Con != ConEnd; ++Con) {
3057 NamedDecl *D = *Con;
3058 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3060 // Find the constructor (which may be a template).
3061 CXXConstructorDecl *Constructor = nullptr;
3062 FunctionTemplateDecl *ConstructorTmpl
3063 = dyn_cast<FunctionTemplateDecl>(D);
3064 if (ConstructorTmpl)
3066 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3068 Constructor = cast<CXXConstructorDecl>(D);
3070 bool Usable = !Constructor->isInvalidDecl();
3071 if (ListInitializing)
3072 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3074 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3076 bool SuppressUserConversions = !ConstructorsOnly;
3077 if (SuppressUserConversions && ListInitializing) {
3078 SuppressUserConversions = false;
3080 // If the first argument is (a reference to) the target type,
3081 // suppress conversions.
3082 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3083 S.Context, Constructor, ToType);
3086 if (ConstructorTmpl)
3087 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3088 /*ExplicitArgs*/ nullptr,
3089 llvm::makeArrayRef(Args, NumArgs),
3090 CandidateSet, SuppressUserConversions);
3092 // Allow one user-defined conversion when user specifies a
3093 // From->ToType conversion via an static cast (c-style, etc).
3094 S.AddOverloadCandidate(Constructor, FoundDecl,
3095 llvm::makeArrayRef(Args, NumArgs),
3096 CandidateSet, SuppressUserConversions);
3102 // Enumerate conversion functions, if we're allowed to.
3103 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3104 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3105 // No conversion functions from incomplete types.
3106 } else if (const RecordType *FromRecordType
3107 = From->getType()->getAs<RecordType>()) {
3108 if (CXXRecordDecl *FromRecordDecl
3109 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3110 // Add all of the conversion functions as candidates.
3111 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3112 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3113 DeclAccessPair FoundDecl = I.getPair();
3114 NamedDecl *D = FoundDecl.getDecl();
3115 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3116 if (isa<UsingShadowDecl>(D))
3117 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3119 CXXConversionDecl *Conv;
3120 FunctionTemplateDecl *ConvTemplate;
3121 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3122 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3124 Conv = cast<CXXConversionDecl>(D);
3126 if (AllowExplicit || !Conv->isExplicit()) {
3128 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3129 ActingContext, From, ToType,
3131 AllowObjCConversionOnExplicit);
3133 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3134 From, ToType, CandidateSet,
3135 AllowObjCConversionOnExplicit);
3141 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3143 OverloadCandidateSet::iterator Best;
3144 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3148 // Record the standard conversion we used and the conversion function.
3149 if (CXXConstructorDecl *Constructor
3150 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3151 // C++ [over.ics.user]p1:
3152 // If the user-defined conversion is specified by a
3153 // constructor (12.3.1), the initial standard conversion
3154 // sequence converts the source type to the type required by
3155 // the argument of the constructor.
3157 QualType ThisType = Constructor->getThisType(S.Context);
3158 if (isa<InitListExpr>(From)) {
3159 // Initializer lists don't have conversions as such.
3160 User.Before.setAsIdentityConversion();
3162 if (Best->Conversions[0].isEllipsis())
3163 User.EllipsisConversion = true;
3165 User.Before = Best->Conversions[0].Standard;
3166 User.EllipsisConversion = false;
3169 User.HadMultipleCandidates = HadMultipleCandidates;
3170 User.ConversionFunction = Constructor;
3171 User.FoundConversionFunction = Best->FoundDecl;
3172 User.After.setAsIdentityConversion();
3173 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3174 User.After.setAllToTypes(ToType);
3177 if (CXXConversionDecl *Conversion
3178 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3179 // C++ [over.ics.user]p1:
3181 // [...] If the user-defined conversion is specified by a
3182 // conversion function (12.3.2), the initial standard
3183 // conversion sequence converts the source type to the
3184 // implicit object parameter of the conversion function.
3185 User.Before = Best->Conversions[0].Standard;
3186 User.HadMultipleCandidates = HadMultipleCandidates;
3187 User.ConversionFunction = Conversion;
3188 User.FoundConversionFunction = Best->FoundDecl;
3189 User.EllipsisConversion = false;
3191 // C++ [over.ics.user]p2:
3192 // The second standard conversion sequence converts the
3193 // result of the user-defined conversion to the target type
3194 // for the sequence. Since an implicit conversion sequence
3195 // is an initialization, the special rules for
3196 // initialization by user-defined conversion apply when
3197 // selecting the best user-defined conversion for a
3198 // user-defined conversion sequence (see 13.3.3 and
3200 User.After = Best->FinalConversion;
3203 llvm_unreachable("Not a constructor or conversion function?");
3205 case OR_No_Viable_Function:
3206 return OR_No_Viable_Function;
3209 return OR_Ambiguous;
3212 llvm_unreachable("Invalid OverloadResult!");
3216 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3217 ImplicitConversionSequence ICS;
3218 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3219 OverloadCandidateSet::CSK_Normal);
3220 OverloadingResult OvResult =
3221 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3222 CandidateSet, false, false);
3223 if (OvResult == OR_Ambiguous)
3224 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3225 << From->getType() << ToType << From->getSourceRange();
3226 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3227 if (!RequireCompleteType(From->getLocStart(), ToType,
3228 diag::err_typecheck_nonviable_condition_incomplete,
3229 From->getType(), From->getSourceRange()))
3230 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3231 << From->getType() << From->getSourceRange() << ToType;
3234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3238 /// \brief Compare the user-defined conversion functions or constructors
3239 /// of two user-defined conversion sequences to determine whether any ordering
3241 static ImplicitConversionSequence::CompareKind
3242 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3243 FunctionDecl *Function2) {
3244 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3245 return ImplicitConversionSequence::Indistinguishable;
3248 // If both conversion functions are implicitly-declared conversions from
3249 // a lambda closure type to a function pointer and a block pointer,
3250 // respectively, always prefer the conversion to a function pointer,
3251 // because the function pointer is more lightweight and is more likely
3252 // to keep code working.
3253 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3255 return ImplicitConversionSequence::Indistinguishable;
3257 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3259 return ImplicitConversionSequence::Indistinguishable;
3261 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3262 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3263 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3264 if (Block1 != Block2)
3265 return Block1 ? ImplicitConversionSequence::Worse
3266 : ImplicitConversionSequence::Better;
3269 return ImplicitConversionSequence::Indistinguishable;
3272 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3273 const ImplicitConversionSequence &ICS) {
3274 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3275 (ICS.isUserDefined() &&
3276 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3279 /// CompareImplicitConversionSequences - Compare two implicit
3280 /// conversion sequences to determine whether one is better than the
3281 /// other or if they are indistinguishable (C++ 13.3.3.2).
3282 static ImplicitConversionSequence::CompareKind
3283 CompareImplicitConversionSequences(Sema &S,
3284 const ImplicitConversionSequence& ICS1,
3285 const ImplicitConversionSequence& ICS2)
3287 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3288 // conversion sequences (as defined in 13.3.3.1)
3289 // -- a standard conversion sequence (13.3.3.1.1) is a better
3290 // conversion sequence than a user-defined conversion sequence or
3291 // an ellipsis conversion sequence, and
3292 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3293 // conversion sequence than an ellipsis conversion sequence
3296 // C++0x [over.best.ics]p10:
3297 // For the purpose of ranking implicit conversion sequences as
3298 // described in 13.3.3.2, the ambiguous conversion sequence is
3299 // treated as a user-defined sequence that is indistinguishable
3300 // from any other user-defined conversion sequence.
3302 // String literal to 'char *' conversion has been deprecated in C++03. It has
3303 // been removed from C++11. We still accept this conversion, if it happens at
3304 // the best viable function. Otherwise, this conversion is considered worse
3305 // than ellipsis conversion. Consider this as an extension; this is not in the
3306 // standard. For example:
3308 // int &f(...); // #1
3309 // void f(char*); // #2
3310 // void g() { int &r = f("foo"); }
3312 // In C++03, we pick #2 as the best viable function.
3313 // In C++11, we pick #1 as the best viable function, because ellipsis
3314 // conversion is better than string-literal to char* conversion (since there
3315 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3316 // convert arguments, #2 would be the best viable function in C++11.
3317 // If the best viable function has this conversion, a warning will be issued
3318 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3320 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3321 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3322 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3323 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3324 ? ImplicitConversionSequence::Worse
3325 : ImplicitConversionSequence::Better;
3327 if (ICS1.getKindRank() < ICS2.getKindRank())
3328 return ImplicitConversionSequence::Better;
3329 if (ICS2.getKindRank() < ICS1.getKindRank())
3330 return ImplicitConversionSequence::Worse;
3332 // The following checks require both conversion sequences to be of
3334 if (ICS1.getKind() != ICS2.getKind())
3335 return ImplicitConversionSequence::Indistinguishable;
3337 ImplicitConversionSequence::CompareKind Result =
3338 ImplicitConversionSequence::Indistinguishable;
3340 // Two implicit conversion sequences of the same form are
3341 // indistinguishable conversion sequences unless one of the
3342 // following rules apply: (C++ 13.3.3.2p3):
3344 // List-initialization sequence L1 is a better conversion sequence than
3345 // list-initialization sequence L2 if:
3346 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3348 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3349 // and N1 is smaller than N2.,
3350 // even if one of the other rules in this paragraph would otherwise apply.
3351 if (!ICS1.isBad()) {
3352 if (ICS1.isStdInitializerListElement() &&
3353 !ICS2.isStdInitializerListElement())
3354 return ImplicitConversionSequence::Better;
3355 if (!ICS1.isStdInitializerListElement() &&
3356 ICS2.isStdInitializerListElement())
3357 return ImplicitConversionSequence::Worse;
3360 if (ICS1.isStandard())
3361 // Standard conversion sequence S1 is a better conversion sequence than
3362 // standard conversion sequence S2 if [...]
3363 Result = CompareStandardConversionSequences(S,
3364 ICS1.Standard, ICS2.Standard);
3365 else if (ICS1.isUserDefined()) {
3366 // User-defined conversion sequence U1 is a better conversion
3367 // sequence than another user-defined conversion sequence U2 if
3368 // they contain the same user-defined conversion function or
3369 // constructor and if the second standard conversion sequence of
3370 // U1 is better than the second standard conversion sequence of
3371 // U2 (C++ 13.3.3.2p3).
3372 if (ICS1.UserDefined.ConversionFunction ==
3373 ICS2.UserDefined.ConversionFunction)
3374 Result = CompareStandardConversionSequences(S,
3375 ICS1.UserDefined.After,
3376 ICS2.UserDefined.After);
3378 Result = compareConversionFunctions(S,
3379 ICS1.UserDefined.ConversionFunction,
3380 ICS2.UserDefined.ConversionFunction);
3386 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3387 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3389 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3390 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3393 return Context.hasSameUnqualifiedType(T1, T2);
3396 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3397 // determine if one is a proper subset of the other.
3398 static ImplicitConversionSequence::CompareKind
3399 compareStandardConversionSubsets(ASTContext &Context,
3400 const StandardConversionSequence& SCS1,
3401 const StandardConversionSequence& SCS2) {
3402 ImplicitConversionSequence::CompareKind Result
3403 = ImplicitConversionSequence::Indistinguishable;
3405 // the identity conversion sequence is considered to be a subsequence of
3406 // any non-identity conversion sequence
3407 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3408 return ImplicitConversionSequence::Better;
3409 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3410 return ImplicitConversionSequence::Worse;
3412 if (SCS1.Second != SCS2.Second) {
3413 if (SCS1.Second == ICK_Identity)
3414 Result = ImplicitConversionSequence::Better;
3415 else if (SCS2.Second == ICK_Identity)
3416 Result = ImplicitConversionSequence::Worse;
3418 return ImplicitConversionSequence::Indistinguishable;
3419 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3420 return ImplicitConversionSequence::Indistinguishable;
3422 if (SCS1.Third == SCS2.Third) {
3423 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3424 : ImplicitConversionSequence::Indistinguishable;
3427 if (SCS1.Third == ICK_Identity)
3428 return Result == ImplicitConversionSequence::Worse
3429 ? ImplicitConversionSequence::Indistinguishable
3430 : ImplicitConversionSequence::Better;
3432 if (SCS2.Third == ICK_Identity)
3433 return Result == ImplicitConversionSequence::Better
3434 ? ImplicitConversionSequence::Indistinguishable
3435 : ImplicitConversionSequence::Worse;
3437 return ImplicitConversionSequence::Indistinguishable;
3440 /// \brief Determine whether one of the given reference bindings is better
3441 /// than the other based on what kind of bindings they are.
3443 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3444 const StandardConversionSequence &SCS2) {
3445 // C++0x [over.ics.rank]p3b4:
3446 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3447 // implicit object parameter of a non-static member function declared
3448 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3449 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3450 // lvalue reference to a function lvalue and S2 binds an rvalue
3453 // FIXME: Rvalue references. We're going rogue with the above edits,
3454 // because the semantics in the current C++0x working paper (N3225 at the
3455 // time of this writing) break the standard definition of std::forward
3456 // and std::reference_wrapper when dealing with references to functions.
3457 // Proposed wording changes submitted to CWG for consideration.
3458 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3459 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3462 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3463 SCS2.IsLvalueReference) ||
3464 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3465 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3468 /// CompareStandardConversionSequences - Compare two standard
3469 /// conversion sequences to determine whether one is better than the
3470 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3471 static ImplicitConversionSequence::CompareKind
3472 CompareStandardConversionSequences(Sema &S,
3473 const StandardConversionSequence& SCS1,
3474 const StandardConversionSequence& SCS2)
3476 // Standard conversion sequence S1 is a better conversion sequence
3477 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3479 // -- S1 is a proper subsequence of S2 (comparing the conversion
3480 // sequences in the canonical form defined by 13.3.3.1.1,
3481 // excluding any Lvalue Transformation; the identity conversion
3482 // sequence is considered to be a subsequence of any
3483 // non-identity conversion sequence) or, if not that,
3484 if (ImplicitConversionSequence::CompareKind CK
3485 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3488 // -- the rank of S1 is better than the rank of S2 (by the rules
3489 // defined below), or, if not that,
3490 ImplicitConversionRank Rank1 = SCS1.getRank();
3491 ImplicitConversionRank Rank2 = SCS2.getRank();
3493 return ImplicitConversionSequence::Better;
3494 else if (Rank2 < Rank1)
3495 return ImplicitConversionSequence::Worse;
3497 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3498 // are indistinguishable unless one of the following rules
3501 // A conversion that is not a conversion of a pointer, or
3502 // pointer to member, to bool is better than another conversion
3503 // that is such a conversion.
3504 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3505 return SCS2.isPointerConversionToBool()
3506 ? ImplicitConversionSequence::Better
3507 : ImplicitConversionSequence::Worse;
3509 // C++ [over.ics.rank]p4b2:
3511 // If class B is derived directly or indirectly from class A,
3512 // conversion of B* to A* is better than conversion of B* to
3513 // void*, and conversion of A* to void* is better than conversion
3515 bool SCS1ConvertsToVoid
3516 = SCS1.isPointerConversionToVoidPointer(S.Context);
3517 bool SCS2ConvertsToVoid
3518 = SCS2.isPointerConversionToVoidPointer(S.Context);
3519 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3520 // Exactly one of the conversion sequences is a conversion to
3521 // a void pointer; it's the worse conversion.
3522 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3523 : ImplicitConversionSequence::Worse;
3524 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3525 // Neither conversion sequence converts to a void pointer; compare
3526 // their derived-to-base conversions.
3527 if (ImplicitConversionSequence::CompareKind DerivedCK
3528 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3530 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3531 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3532 // Both conversion sequences are conversions to void
3533 // pointers. Compare the source types to determine if there's an
3534 // inheritance relationship in their sources.
3535 QualType FromType1 = SCS1.getFromType();
3536 QualType FromType2 = SCS2.getFromType();
3538 // Adjust the types we're converting from via the array-to-pointer
3539 // conversion, if we need to.
3540 if (SCS1.First == ICK_Array_To_Pointer)
3541 FromType1 = S.Context.getArrayDecayedType(FromType1);
3542 if (SCS2.First == ICK_Array_To_Pointer)
3543 FromType2 = S.Context.getArrayDecayedType(FromType2);
3545 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3546 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3548 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3549 return ImplicitConversionSequence::Better;
3550 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3551 return ImplicitConversionSequence::Worse;
3553 // Objective-C++: If one interface is more specific than the
3554 // other, it is the better one.
3555 const ObjCObjectPointerType* FromObjCPtr1
3556 = FromType1->getAs<ObjCObjectPointerType>();
3557 const ObjCObjectPointerType* FromObjCPtr2
3558 = FromType2->getAs<ObjCObjectPointerType>();
3559 if (FromObjCPtr1 && FromObjCPtr2) {
3560 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3562 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3564 if (AssignLeft != AssignRight) {
3565 return AssignLeft? ImplicitConversionSequence::Better
3566 : ImplicitConversionSequence::Worse;
3571 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3573 if (ImplicitConversionSequence::CompareKind QualCK
3574 = CompareQualificationConversions(S, SCS1, SCS2))
3577 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3578 // Check for a better reference binding based on the kind of bindings.
3579 if (isBetterReferenceBindingKind(SCS1, SCS2))
3580 return ImplicitConversionSequence::Better;
3581 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3582 return ImplicitConversionSequence::Worse;
3584 // C++ [over.ics.rank]p3b4:
3585 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3586 // which the references refer are the same type except for
3587 // top-level cv-qualifiers, and the type to which the reference
3588 // initialized by S2 refers is more cv-qualified than the type
3589 // to which the reference initialized by S1 refers.
3590 QualType T1 = SCS1.getToType(2);
3591 QualType T2 = SCS2.getToType(2);
3592 T1 = S.Context.getCanonicalType(T1);
3593 T2 = S.Context.getCanonicalType(T2);
3594 Qualifiers T1Quals, T2Quals;
3595 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3596 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3597 if (UnqualT1 == UnqualT2) {
3598 // Objective-C++ ARC: If the references refer to objects with different
3599 // lifetimes, prefer bindings that don't change lifetime.
3600 if (SCS1.ObjCLifetimeConversionBinding !=
3601 SCS2.ObjCLifetimeConversionBinding) {
3602 return SCS1.ObjCLifetimeConversionBinding
3603 ? ImplicitConversionSequence::Worse
3604 : ImplicitConversionSequence::Better;
3607 // If the type is an array type, promote the element qualifiers to the
3608 // type for comparison.
3609 if (isa<ArrayType>(T1) && T1Quals)
3610 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3611 if (isa<ArrayType>(T2) && T2Quals)
3612 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3613 if (T2.isMoreQualifiedThan(T1))
3614 return ImplicitConversionSequence::Better;
3615 else if (T1.isMoreQualifiedThan(T2))
3616 return ImplicitConversionSequence::Worse;
3620 // In Microsoft mode, prefer an integral conversion to a
3621 // floating-to-integral conversion if the integral conversion
3622 // is between types of the same size.
3630 // Here, MSVC will call f(int) instead of generating a compile error
3631 // as clang will do in standard mode.
3632 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3633 SCS2.Second == ICK_Floating_Integral &&
3634 S.Context.getTypeSize(SCS1.getFromType()) ==
3635 S.Context.getTypeSize(SCS1.getToType(2)))
3636 return ImplicitConversionSequence::Better;
3638 return ImplicitConversionSequence::Indistinguishable;
3641 /// CompareQualificationConversions - Compares two standard conversion
3642 /// sequences to determine whether they can be ranked based on their
3643 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3644 static ImplicitConversionSequence::CompareKind
3645 CompareQualificationConversions(Sema &S,
3646 const StandardConversionSequence& SCS1,
3647 const StandardConversionSequence& SCS2) {
3649 // -- S1 and S2 differ only in their qualification conversion and
3650 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3651 // cv-qualification signature of type T1 is a proper subset of
3652 // the cv-qualification signature of type T2, and S1 is not the
3653 // deprecated string literal array-to-pointer conversion (4.2).
3654 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3655 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3656 return ImplicitConversionSequence::Indistinguishable;
3658 // FIXME: the example in the standard doesn't use a qualification
3660 QualType T1 = SCS1.getToType(2);
3661 QualType T2 = SCS2.getToType(2);
3662 T1 = S.Context.getCanonicalType(T1);
3663 T2 = S.Context.getCanonicalType(T2);
3664 Qualifiers T1Quals, T2Quals;
3665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3668 // If the types are the same, we won't learn anything by unwrapped
3670 if (UnqualT1 == UnqualT2)
3671 return ImplicitConversionSequence::Indistinguishable;
3673 // If the type is an array type, promote the element qualifiers to the type
3675 if (isa<ArrayType>(T1) && T1Quals)
3676 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3677 if (isa<ArrayType>(T2) && T2Quals)
3678 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3680 ImplicitConversionSequence::CompareKind Result
3681 = ImplicitConversionSequence::Indistinguishable;
3683 // Objective-C++ ARC:
3684 // Prefer qualification conversions not involving a change in lifetime
3685 // to qualification conversions that do not change lifetime.
3686 if (SCS1.QualificationIncludesObjCLifetime !=
3687 SCS2.QualificationIncludesObjCLifetime) {
3688 Result = SCS1.QualificationIncludesObjCLifetime
3689 ? ImplicitConversionSequence::Worse
3690 : ImplicitConversionSequence::Better;
3693 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3694 // Within each iteration of the loop, we check the qualifiers to
3695 // determine if this still looks like a qualification
3696 // conversion. Then, if all is well, we unwrap one more level of
3697 // pointers or pointers-to-members and do it all again
3698 // until there are no more pointers or pointers-to-members left
3699 // to unwrap. This essentially mimics what
3700 // IsQualificationConversion does, but here we're checking for a
3701 // strict subset of qualifiers.
3702 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3703 // The qualifiers are the same, so this doesn't tell us anything
3704 // about how the sequences rank.
3706 else if (T2.isMoreQualifiedThan(T1)) {
3707 // T1 has fewer qualifiers, so it could be the better sequence.
3708 if (Result == ImplicitConversionSequence::Worse)
3709 // Neither has qualifiers that are a subset of the other's
3711 return ImplicitConversionSequence::Indistinguishable;
3713 Result = ImplicitConversionSequence::Better;
3714 } else if (T1.isMoreQualifiedThan(T2)) {
3715 // T2 has fewer qualifiers, so it could be the better sequence.
3716 if (Result == ImplicitConversionSequence::Better)
3717 // Neither has qualifiers that are a subset of the other's
3719 return ImplicitConversionSequence::Indistinguishable;
3721 Result = ImplicitConversionSequence::Worse;
3723 // Qualifiers are disjoint.
3724 return ImplicitConversionSequence::Indistinguishable;
3727 // If the types after this point are equivalent, we're done.
3728 if (S.Context.hasSameUnqualifiedType(T1, T2))
3732 // Check that the winning standard conversion sequence isn't using
3733 // the deprecated string literal array to pointer conversion.
3735 case ImplicitConversionSequence::Better:
3736 if (SCS1.DeprecatedStringLiteralToCharPtr)
3737 Result = ImplicitConversionSequence::Indistinguishable;
3740 case ImplicitConversionSequence::Indistinguishable:
3743 case ImplicitConversionSequence::Worse:
3744 if (SCS2.DeprecatedStringLiteralToCharPtr)
3745 Result = ImplicitConversionSequence::Indistinguishable;
3752 /// CompareDerivedToBaseConversions - Compares two standard conversion
3753 /// sequences to determine whether they can be ranked based on their
3754 /// various kinds of derived-to-base conversions (C++
3755 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3756 /// conversions between Objective-C interface types.
3757 static ImplicitConversionSequence::CompareKind
3758 CompareDerivedToBaseConversions(Sema &S,
3759 const StandardConversionSequence& SCS1,
3760 const StandardConversionSequence& SCS2) {
3761 QualType FromType1 = SCS1.getFromType();
3762 QualType ToType1 = SCS1.getToType(1);
3763 QualType FromType2 = SCS2.getFromType();
3764 QualType ToType2 = SCS2.getToType(1);
3766 // Adjust the types we're converting from via the array-to-pointer
3767 // conversion, if we need to.
3768 if (SCS1.First == ICK_Array_To_Pointer)
3769 FromType1 = S.Context.getArrayDecayedType(FromType1);
3770 if (SCS2.First == ICK_Array_To_Pointer)
3771 FromType2 = S.Context.getArrayDecayedType(FromType2);
3773 // Canonicalize all of the types.
3774 FromType1 = S.Context.getCanonicalType(FromType1);
3775 ToType1 = S.Context.getCanonicalType(ToType1);
3776 FromType2 = S.Context.getCanonicalType(FromType2);
3777 ToType2 = S.Context.getCanonicalType(ToType2);
3779 // C++ [over.ics.rank]p4b3:
3781 // If class B is derived directly or indirectly from class A and
3782 // class C is derived directly or indirectly from B,
3784 // Compare based on pointer conversions.
3785 if (SCS1.Second == ICK_Pointer_Conversion &&
3786 SCS2.Second == ICK_Pointer_Conversion &&
3787 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3788 FromType1->isPointerType() && FromType2->isPointerType() &&
3789 ToType1->isPointerType() && ToType2->isPointerType()) {
3790 QualType FromPointee1
3791 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3793 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3794 QualType FromPointee2
3795 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3797 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3799 // -- conversion of C* to B* is better than conversion of C* to A*,
3800 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3801 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3802 return ImplicitConversionSequence::Better;
3803 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3804 return ImplicitConversionSequence::Worse;
3807 // -- conversion of B* to A* is better than conversion of C* to A*,
3808 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3809 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3810 return ImplicitConversionSequence::Better;
3811 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3812 return ImplicitConversionSequence::Worse;
3814 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3815 SCS2.Second == ICK_Pointer_Conversion) {
3816 const ObjCObjectPointerType *FromPtr1
3817 = FromType1->getAs<ObjCObjectPointerType>();
3818 const ObjCObjectPointerType *FromPtr2
3819 = FromType2->getAs<ObjCObjectPointerType>();
3820 const ObjCObjectPointerType *ToPtr1
3821 = ToType1->getAs<ObjCObjectPointerType>();
3822 const ObjCObjectPointerType *ToPtr2
3823 = ToType2->getAs<ObjCObjectPointerType>();
3825 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3826 // Apply the same conversion ranking rules for Objective-C pointer types
3827 // that we do for C++ pointers to class types. However, we employ the
3828 // Objective-C pseudo-subtyping relationship used for assignment of
3829 // Objective-C pointer types.
3831 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3832 bool FromAssignRight
3833 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3835 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3837 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3839 // A conversion to an a non-id object pointer type or qualified 'id'
3840 // type is better than a conversion to 'id'.
3841 if (ToPtr1->isObjCIdType() &&
3842 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3843 return ImplicitConversionSequence::Worse;
3844 if (ToPtr2->isObjCIdType() &&
3845 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3846 return ImplicitConversionSequence::Better;
3848 // A conversion to a non-id object pointer type is better than a
3849 // conversion to a qualified 'id' type
3850 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3851 return ImplicitConversionSequence::Worse;
3852 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3853 return ImplicitConversionSequence::Better;
3855 // A conversion to an a non-Class object pointer type or qualified 'Class'
3856 // type is better than a conversion to 'Class'.
3857 if (ToPtr1->isObjCClassType() &&
3858 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3859 return ImplicitConversionSequence::Worse;
3860 if (ToPtr2->isObjCClassType() &&
3861 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3862 return ImplicitConversionSequence::Better;
3864 // A conversion to a non-Class object pointer type is better than a
3865 // conversion to a qualified 'Class' type.
3866 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3867 return ImplicitConversionSequence::Worse;
3868 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3869 return ImplicitConversionSequence::Better;
3871 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3872 if (S.Context.hasSameType(FromType1, FromType2) &&
3873 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3874 (ToAssignLeft != ToAssignRight))
3875 return ToAssignLeft? ImplicitConversionSequence::Worse
3876 : ImplicitConversionSequence::Better;
3878 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3879 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3880 (FromAssignLeft != FromAssignRight))
3881 return FromAssignLeft? ImplicitConversionSequence::Better
3882 : ImplicitConversionSequence::Worse;
3886 // Ranking of member-pointer types.
3887 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3888 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3889 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3890 const MemberPointerType * FromMemPointer1 =
3891 FromType1->getAs<MemberPointerType>();
3892 const MemberPointerType * ToMemPointer1 =
3893 ToType1->getAs<MemberPointerType>();
3894 const MemberPointerType * FromMemPointer2 =
3895 FromType2->getAs<MemberPointerType>();
3896 const MemberPointerType * ToMemPointer2 =
3897 ToType2->getAs<MemberPointerType>();
3898 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3899 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3900 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3901 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3902 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3903 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3904 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3905 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3906 // conversion of A::* to B::* is better than conversion of A::* to C::*,
3907 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3908 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3909 return ImplicitConversionSequence::Worse;
3910 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3911 return ImplicitConversionSequence::Better;
3913 // conversion of B::* to C::* is better than conversion of A::* to C::*
3914 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3915 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3916 return ImplicitConversionSequence::Better;
3917 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3918 return ImplicitConversionSequence::Worse;
3922 if (SCS1.Second == ICK_Derived_To_Base) {
3923 // -- conversion of C to B is better than conversion of C to A,
3924 // -- binding of an expression of type C to a reference of type
3925 // B& is better than binding an expression of type C to a
3926 // reference of type A&,
3927 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3928 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3929 if (S.IsDerivedFrom(ToType1, ToType2))
3930 return ImplicitConversionSequence::Better;
3931 else if (S.IsDerivedFrom(ToType2, ToType1))
3932 return ImplicitConversionSequence::Worse;
3935 // -- conversion of B to A is better than conversion of C to A.
3936 // -- binding of an expression of type B to a reference of type
3937 // A& is better than binding an expression of type C to a
3938 // reference of type A&,
3939 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3940 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3941 if (S.IsDerivedFrom(FromType2, FromType1))
3942 return ImplicitConversionSequence::Better;
3943 else if (S.IsDerivedFrom(FromType1, FromType2))
3944 return ImplicitConversionSequence::Worse;
3948 return ImplicitConversionSequence::Indistinguishable;
3951 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3953 static bool isTypeValid(QualType T) {
3954 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3955 return !Record->isInvalidDecl();
3960 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3961 /// determine whether they are reference-related,
3962 /// reference-compatible, reference-compatible with added
3963 /// qualification, or incompatible, for use in C++ initialization by
3964 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3965 /// type, and the first type (T1) is the pointee type of the reference
3966 /// type being initialized.
3967 Sema::ReferenceCompareResult
3968 Sema::CompareReferenceRelationship(SourceLocation Loc,
3969 QualType OrigT1, QualType OrigT2,
3970 bool &DerivedToBase,
3971 bool &ObjCConversion,
3972 bool &ObjCLifetimeConversion) {
3973 assert(!OrigT1->isReferenceType() &&
3974 "T1 must be the pointee type of the reference type");
3975 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3977 QualType T1 = Context.getCanonicalType(OrigT1);
3978 QualType T2 = Context.getCanonicalType(OrigT2);
3979 Qualifiers T1Quals, T2Quals;
3980 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3981 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3983 // C++ [dcl.init.ref]p4:
3984 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3985 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3986 // T1 is a base class of T2.
3987 DerivedToBase = false;
3988 ObjCConversion = false;
3989 ObjCLifetimeConversion = false;
3990 if (UnqualT1 == UnqualT2) {
3992 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3993 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3994 IsDerivedFrom(UnqualT2, UnqualT1))
3995 DerivedToBase = true;
3996 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3997 UnqualT2->isObjCObjectOrInterfaceType() &&
3998 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3999 ObjCConversion = true;
4001 return Ref_Incompatible;
4003 // At this point, we know that T1 and T2 are reference-related (at
4006 // If the type is an array type, promote the element qualifiers to the type
4008 if (isa<ArrayType>(T1) && T1Quals)
4009 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4010 if (isa<ArrayType>(T2) && T2Quals)
4011 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4013 // C++ [dcl.init.ref]p4:
4014 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4015 // reference-related to T2 and cv1 is the same cv-qualification
4016 // as, or greater cv-qualification than, cv2. For purposes of
4017 // overload resolution, cases for which cv1 is greater
4018 // cv-qualification than cv2 are identified as
4019 // reference-compatible with added qualification (see 13.3.3.2).
4021 // Note that we also require equivalence of Objective-C GC and address-space
4022 // qualifiers when performing these computations, so that e.g., an int in
4023 // address space 1 is not reference-compatible with an int in address
4025 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4026 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4027 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4028 ObjCLifetimeConversion = true;
4030 T1Quals.removeObjCLifetime();
4031 T2Quals.removeObjCLifetime();
4034 if (T1Quals == T2Quals)
4035 return Ref_Compatible;
4036 else if (T1Quals.compatiblyIncludes(T2Quals))
4037 return Ref_Compatible_With_Added_Qualification;
4042 /// \brief Look for a user-defined conversion to an value reference-compatible
4043 /// with DeclType. Return true if something definite is found.
4045 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4046 QualType DeclType, SourceLocation DeclLoc,
4047 Expr *Init, QualType T2, bool AllowRvalues,
4048 bool AllowExplicit) {
4049 assert(T2->isRecordType() && "Can only find conversions of record types.");
4050 CXXRecordDecl *T2RecordDecl
4051 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4053 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4054 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4055 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4057 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4058 if (isa<UsingShadowDecl>(D))
4059 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4061 FunctionTemplateDecl *ConvTemplate
4062 = dyn_cast<FunctionTemplateDecl>(D);
4063 CXXConversionDecl *Conv;
4065 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4067 Conv = cast<CXXConversionDecl>(D);
4069 // If this is an explicit conversion, and we're not allowed to consider
4070 // explicit conversions, skip it.
4071 if (!AllowExplicit && Conv->isExplicit())
4075 bool DerivedToBase = false;
4076 bool ObjCConversion = false;
4077 bool ObjCLifetimeConversion = false;
4079 // If we are initializing an rvalue reference, don't permit conversion
4080 // functions that return lvalues.
4081 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4082 const ReferenceType *RefType
4083 = Conv->getConversionType()->getAs<LValueReferenceType>();
4084 if (RefType && !RefType->getPointeeType()->isFunctionType())
4088 if (!ConvTemplate &&
4089 S.CompareReferenceRelationship(
4091 Conv->getConversionType().getNonReferenceType()
4092 .getUnqualifiedType(),
4093 DeclType.getNonReferenceType().getUnqualifiedType(),
4094 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4095 Sema::Ref_Incompatible)
4098 // If the conversion function doesn't return a reference type,
4099 // it can't be considered for this conversion. An rvalue reference
4100 // is only acceptable if its referencee is a function type.
4102 const ReferenceType *RefType =
4103 Conv->getConversionType()->getAs<ReferenceType>();
4105 (!RefType->isLValueReferenceType() &&
4106 !RefType->getPointeeType()->isFunctionType()))
4111 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4112 Init, DeclType, CandidateSet,
4113 /*AllowObjCConversionOnExplicit=*/false);
4115 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4116 DeclType, CandidateSet,
4117 /*AllowObjCConversionOnExplicit=*/false);
4120 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4122 OverloadCandidateSet::iterator Best;
4123 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4125 // C++ [over.ics.ref]p1:
4127 // [...] If the parameter binds directly to the result of
4128 // applying a conversion function to the argument
4129 // expression, the implicit conversion sequence is a
4130 // user-defined conversion sequence (13.3.3.1.2), with the
4131 // second standard conversion sequence either an identity
4132 // conversion or, if the conversion function returns an
4133 // entity of a type that is a derived class of the parameter
4134 // type, a derived-to-base Conversion.
4135 if (!Best->FinalConversion.DirectBinding)
4138 ICS.setUserDefined();
4139 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4140 ICS.UserDefined.After = Best->FinalConversion;
4141 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4142 ICS.UserDefined.ConversionFunction = Best->Function;
4143 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4144 ICS.UserDefined.EllipsisConversion = false;
4145 assert(ICS.UserDefined.After.ReferenceBinding &&
4146 ICS.UserDefined.After.DirectBinding &&
4147 "Expected a direct reference binding!");
4152 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4153 Cand != CandidateSet.end(); ++Cand)
4155 ICS.Ambiguous.addConversion(Cand->Function);
4158 case OR_No_Viable_Function:
4160 // There was no suitable conversion, or we found a deleted
4161 // conversion; continue with other checks.
4165 llvm_unreachable("Invalid OverloadResult!");
4168 /// \brief Compute an implicit conversion sequence for reference
4170 static ImplicitConversionSequence
4171 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4172 SourceLocation DeclLoc,
4173 bool SuppressUserConversions,
4174 bool AllowExplicit) {
4175 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4177 // Most paths end in a failed conversion.
4178 ImplicitConversionSequence ICS;
4179 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4181 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4182 QualType T2 = Init->getType();
4184 // If the initializer is the address of an overloaded function, try
4185 // to resolve the overloaded function. If all goes well, T2 is the
4186 // type of the resulting function.
4187 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4188 DeclAccessPair Found;
4189 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4194 // Compute some basic properties of the types and the initializer.
4195 bool isRValRef = DeclType->isRValueReferenceType();
4196 bool DerivedToBase = false;
4197 bool ObjCConversion = false;
4198 bool ObjCLifetimeConversion = false;
4199 Expr::Classification InitCategory = Init->Classify(S.Context);
4200 Sema::ReferenceCompareResult RefRelationship
4201 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4202 ObjCConversion, ObjCLifetimeConversion);
4205 // C++0x [dcl.init.ref]p5:
4206 // A reference to type "cv1 T1" is initialized by an expression
4207 // of type "cv2 T2" as follows:
4209 // -- If reference is an lvalue reference and the initializer expression
4211 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4212 // reference-compatible with "cv2 T2," or
4214 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4215 if (InitCategory.isLValue() &&
4216 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4217 // C++ [over.ics.ref]p1:
4218 // When a parameter of reference type binds directly (8.5.3)
4219 // to an argument expression, the implicit conversion sequence
4220 // is the identity conversion, unless the argument expression
4221 // has a type that is a derived class of the parameter type,
4222 // in which case the implicit conversion sequence is a
4223 // derived-to-base Conversion (13.3.3.1).
4225 ICS.Standard.First = ICK_Identity;
4226 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4227 : ObjCConversion? ICK_Compatible_Conversion
4229 ICS.Standard.Third = ICK_Identity;
4230 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4231 ICS.Standard.setToType(0, T2);
4232 ICS.Standard.setToType(1, T1);
4233 ICS.Standard.setToType(2, T1);
4234 ICS.Standard.ReferenceBinding = true;
4235 ICS.Standard.DirectBinding = true;
4236 ICS.Standard.IsLvalueReference = !isRValRef;
4237 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4238 ICS.Standard.BindsToRvalue = false;
4239 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4240 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4241 ICS.Standard.CopyConstructor = nullptr;
4242 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4244 // Nothing more to do: the inaccessibility/ambiguity check for
4245 // derived-to-base conversions is suppressed when we're
4246 // computing the implicit conversion sequence (C++
4247 // [over.best.ics]p2).
4251 // -- has a class type (i.e., T2 is a class type), where T1 is
4252 // not reference-related to T2, and can be implicitly
4253 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4254 // is reference-compatible with "cv3 T3" 92) (this
4255 // conversion is selected by enumerating the applicable
4256 // conversion functions (13.3.1.6) and choosing the best
4257 // one through overload resolution (13.3)),
4258 if (!SuppressUserConversions && T2->isRecordType() &&
4259 !S.RequireCompleteType(DeclLoc, T2, 0) &&
4260 RefRelationship == Sema::Ref_Incompatible) {
4261 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4262 Init, T2, /*AllowRvalues=*/false,
4268 // -- Otherwise, the reference shall be an lvalue reference to a
4269 // non-volatile const type (i.e., cv1 shall be const), or the reference
4270 // shall be an rvalue reference.
4271 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4274 // -- If the initializer expression
4276 // -- is an xvalue, class prvalue, array prvalue or function
4277 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4278 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4279 (InitCategory.isXValue() ||
4280 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4281 (InitCategory.isLValue() && T2->isFunctionType()))) {
4283 ICS.Standard.First = ICK_Identity;
4284 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4285 : ObjCConversion? ICK_Compatible_Conversion
4287 ICS.Standard.Third = ICK_Identity;
4288 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4289 ICS.Standard.setToType(0, T2);
4290 ICS.Standard.setToType(1, T1);
4291 ICS.Standard.setToType(2, T1);
4292 ICS.Standard.ReferenceBinding = true;
4293 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4294 // binding unless we're binding to a class prvalue.
4295 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4296 // allow the use of rvalue references in C++98/03 for the benefit of
4297 // standard library implementors; therefore, we need the xvalue check here.
4298 ICS.Standard.DirectBinding =
4299 S.getLangOpts().CPlusPlus11 ||
4300 !(InitCategory.isPRValue() || T2->isRecordType());
4301 ICS.Standard.IsLvalueReference = !isRValRef;
4302 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4303 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4304 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4305 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4306 ICS.Standard.CopyConstructor = nullptr;
4307 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4311 // -- has a class type (i.e., T2 is a class type), where T1 is not
4312 // reference-related to T2, and can be implicitly converted to
4313 // an xvalue, class prvalue, or function lvalue of type
4314 // "cv3 T3", where "cv1 T1" is reference-compatible with
4317 // then the reference is bound to the value of the initializer
4318 // expression in the first case and to the result of the conversion
4319 // in the second case (or, in either case, to an appropriate base
4320 // class subobject).
4321 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4322 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4323 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4324 Init, T2, /*AllowRvalues=*/true,
4326 // In the second case, if the reference is an rvalue reference
4327 // and the second standard conversion sequence of the
4328 // user-defined conversion sequence includes an lvalue-to-rvalue
4329 // conversion, the program is ill-formed.
4330 if (ICS.isUserDefined() && isRValRef &&
4331 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4332 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4337 // A temporary of function type cannot be created; don't even try.
4338 if (T1->isFunctionType())
4341 // -- Otherwise, a temporary of type "cv1 T1" is created and
4342 // initialized from the initializer expression using the
4343 // rules for a non-reference copy initialization (8.5). The
4344 // reference is then bound to the temporary. If T1 is
4345 // reference-related to T2, cv1 must be the same
4346 // cv-qualification as, or greater cv-qualification than,
4347 // cv2; otherwise, the program is ill-formed.
4348 if (RefRelationship == Sema::Ref_Related) {
4349 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4350 // we would be reference-compatible or reference-compatible with
4351 // added qualification. But that wasn't the case, so the reference
4352 // initialization fails.
4354 // Note that we only want to check address spaces and cvr-qualifiers here.
4355 // ObjC GC and lifetime qualifiers aren't important.
4356 Qualifiers T1Quals = T1.getQualifiers();
4357 Qualifiers T2Quals = T2.getQualifiers();
4358 T1Quals.removeObjCGCAttr();
4359 T1Quals.removeObjCLifetime();
4360 T2Quals.removeObjCGCAttr();
4361 T2Quals.removeObjCLifetime();
4362 if (!T1Quals.compatiblyIncludes(T2Quals))
4366 // If at least one of the types is a class type, the types are not
4367 // related, and we aren't allowed any user conversions, the
4368 // reference binding fails. This case is important for breaking
4369 // recursion, since TryImplicitConversion below will attempt to
4370 // create a temporary through the use of a copy constructor.
4371 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4372 (T1->isRecordType() || T2->isRecordType()))
4375 // If T1 is reference-related to T2 and the reference is an rvalue
4376 // reference, the initializer expression shall not be an lvalue.
4377 if (RefRelationship >= Sema::Ref_Related &&
4378 isRValRef && Init->Classify(S.Context).isLValue())
4381 // C++ [over.ics.ref]p2:
4382 // When a parameter of reference type is not bound directly to
4383 // an argument expression, the conversion sequence is the one
4384 // required to convert the argument expression to the
4385 // underlying type of the reference according to
4386 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4387 // to copy-initializing a temporary of the underlying type with
4388 // the argument expression. Any difference in top-level
4389 // cv-qualification is subsumed by the initialization itself
4390 // and does not constitute a conversion.
4391 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4392 /*AllowExplicit=*/false,
4393 /*InOverloadResolution=*/false,
4395 /*AllowObjCWritebackConversion=*/false,
4396 /*AllowObjCConversionOnExplicit=*/false);
4398 // Of course, that's still a reference binding.
4399 if (ICS.isStandard()) {
4400 ICS.Standard.ReferenceBinding = true;
4401 ICS.Standard.IsLvalueReference = !isRValRef;
4402 ICS.Standard.BindsToFunctionLvalue = false;
4403 ICS.Standard.BindsToRvalue = true;
4404 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4405 ICS.Standard.ObjCLifetimeConversionBinding = false;
4406 } else if (ICS.isUserDefined()) {
4407 const ReferenceType *LValRefType =
4408 ICS.UserDefined.ConversionFunction->getReturnType()
4409 ->getAs<LValueReferenceType>();
4411 // C++ [over.ics.ref]p3:
4412 // Except for an implicit object parameter, for which see 13.3.1, a
4413 // standard conversion sequence cannot be formed if it requires [...]
4414 // binding an rvalue reference to an lvalue other than a function
4416 // Note that the function case is not possible here.
4417 if (DeclType->isRValueReferenceType() && LValRefType) {
4418 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4419 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4420 // reference to an rvalue!
4421 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4425 ICS.UserDefined.Before.setAsIdentityConversion();
4426 ICS.UserDefined.After.ReferenceBinding = true;
4427 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4428 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4429 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4430 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4431 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4437 static ImplicitConversionSequence
4438 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4439 bool SuppressUserConversions,
4440 bool InOverloadResolution,
4441 bool AllowObjCWritebackConversion,
4442 bool AllowExplicit = false);
4444 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4445 /// initializer list From.
4446 static ImplicitConversionSequence
4447 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4448 bool SuppressUserConversions,
4449 bool InOverloadResolution,
4450 bool AllowObjCWritebackConversion) {
4451 // C++11 [over.ics.list]p1:
4452 // When an argument is an initializer list, it is not an expression and
4453 // special rules apply for converting it to a parameter type.
4455 ImplicitConversionSequence Result;
4456 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4458 // We need a complete type for what follows. Incomplete types can never be
4459 // initialized from init lists.
4460 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4464 // If the parameter type is a class X and the initializer list has a single
4465 // element of type cv U, where U is X or a class derived from X, the
4466 // implicit conversion sequence is the one required to convert the element
4467 // to the parameter type.
4469 // Otherwise, if the parameter type is a character array [... ]
4470 // and the initializer list has a single element that is an
4471 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4472 // implicit conversion sequence is the identity conversion.
4473 if (From->getNumInits() == 1) {
4474 if (ToType->isRecordType()) {
4475 QualType InitType = From->getInit(0)->getType();
4476 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4477 S.IsDerivedFrom(InitType, ToType))
4478 return TryCopyInitialization(S, From->getInit(0), ToType,
4479 SuppressUserConversions,
4480 InOverloadResolution,
4481 AllowObjCWritebackConversion);
4483 // FIXME: Check the other conditions here: array of character type,
4484 // initializer is a string literal.
4485 if (ToType->isArrayType()) {
4486 InitializedEntity Entity =
4487 InitializedEntity::InitializeParameter(S.Context, ToType,
4488 /*Consumed=*/false);
4489 if (S.CanPerformCopyInitialization(Entity, From)) {
4490 Result.setStandard();
4491 Result.Standard.setAsIdentityConversion();
4492 Result.Standard.setFromType(ToType);
4493 Result.Standard.setAllToTypes(ToType);
4499 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4500 // C++11 [over.ics.list]p2:
4501 // If the parameter type is std::initializer_list<X> or "array of X" and
4502 // all the elements can be implicitly converted to X, the implicit
4503 // conversion sequence is the worst conversion necessary to convert an
4504 // element of the list to X.
4506 // C++14 [over.ics.list]p3:
4507 // Otherwise, if the parameter type is "array of N X", if the initializer
4508 // list has exactly N elements or if it has fewer than N elements and X is
4509 // default-constructible, and if all the elements of the initializer list
4510 // can be implicitly converted to X, the implicit conversion sequence is
4511 // the worst conversion necessary to convert an element of the list to X.
4513 // FIXME: We're missing a lot of these checks.
4514 bool toStdInitializerList = false;
4516 if (ToType->isArrayType())
4517 X = S.Context.getAsArrayType(ToType)->getElementType();
4519 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4521 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4522 Expr *Init = From->getInit(i);
4523 ImplicitConversionSequence ICS =
4524 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4525 InOverloadResolution,
4526 AllowObjCWritebackConversion);
4527 // If a single element isn't convertible, fail.
4532 // Otherwise, look for the worst conversion.
4533 if (Result.isBad() ||
4534 CompareImplicitConversionSequences(S, ICS, Result) ==
4535 ImplicitConversionSequence::Worse)
4539 // For an empty list, we won't have computed any conversion sequence.
4540 // Introduce the identity conversion sequence.
4541 if (From->getNumInits() == 0) {
4542 Result.setStandard();
4543 Result.Standard.setAsIdentityConversion();
4544 Result.Standard.setFromType(ToType);
4545 Result.Standard.setAllToTypes(ToType);
4548 Result.setStdInitializerListElement(toStdInitializerList);
4552 // C++14 [over.ics.list]p4:
4553 // C++11 [over.ics.list]p3:
4554 // Otherwise, if the parameter is a non-aggregate class X and overload
4555 // resolution chooses a single best constructor [...] the implicit
4556 // conversion sequence is a user-defined conversion sequence. If multiple
4557 // constructors are viable but none is better than the others, the
4558 // implicit conversion sequence is a user-defined conversion sequence.
4559 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4560 // This function can deal with initializer lists.
4561 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4562 /*AllowExplicit=*/false,
4563 InOverloadResolution, /*CStyle=*/false,
4564 AllowObjCWritebackConversion,
4565 /*AllowObjCConversionOnExplicit=*/false);
4568 // C++14 [over.ics.list]p5:
4569 // C++11 [over.ics.list]p4:
4570 // Otherwise, if the parameter has an aggregate type which can be
4571 // initialized from the initializer list [...] the implicit conversion
4572 // sequence is a user-defined conversion sequence.
4573 if (ToType->isAggregateType()) {
4574 // Type is an aggregate, argument is an init list. At this point it comes
4575 // down to checking whether the initialization works.
4576 // FIXME: Find out whether this parameter is consumed or not.
4577 InitializedEntity Entity =
4578 InitializedEntity::InitializeParameter(S.Context, ToType,
4579 /*Consumed=*/false);
4580 if (S.CanPerformCopyInitialization(Entity, From)) {
4581 Result.setUserDefined();
4582 Result.UserDefined.Before.setAsIdentityConversion();
4583 // Initializer lists don't have a type.
4584 Result.UserDefined.Before.setFromType(QualType());
4585 Result.UserDefined.Before.setAllToTypes(QualType());
4587 Result.UserDefined.After.setAsIdentityConversion();
4588 Result.UserDefined.After.setFromType(ToType);
4589 Result.UserDefined.After.setAllToTypes(ToType);
4590 Result.UserDefined.ConversionFunction = nullptr;
4595 // C++14 [over.ics.list]p6:
4596 // C++11 [over.ics.list]p5:
4597 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4598 if (ToType->isReferenceType()) {
4599 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4600 // mention initializer lists in any way. So we go by what list-
4601 // initialization would do and try to extrapolate from that.
4603 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4605 // If the initializer list has a single element that is reference-related
4606 // to the parameter type, we initialize the reference from that.
4607 if (From->getNumInits() == 1) {
4608 Expr *Init = From->getInit(0);
4610 QualType T2 = Init->getType();
4612 // If the initializer is the address of an overloaded function, try
4613 // to resolve the overloaded function. If all goes well, T2 is the
4614 // type of the resulting function.
4615 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4616 DeclAccessPair Found;
4617 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4618 Init, ToType, false, Found))
4622 // Compute some basic properties of the types and the initializer.
4623 bool dummy1 = false;
4624 bool dummy2 = false;
4625 bool dummy3 = false;
4626 Sema::ReferenceCompareResult RefRelationship
4627 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4630 if (RefRelationship >= Sema::Ref_Related) {
4631 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4632 SuppressUserConversions,
4633 /*AllowExplicit=*/false);
4637 // Otherwise, we bind the reference to a temporary created from the
4638 // initializer list.
4639 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4640 InOverloadResolution,
4641 AllowObjCWritebackConversion);
4642 if (Result.isFailure())
4644 assert(!Result.isEllipsis() &&
4645 "Sub-initialization cannot result in ellipsis conversion.");
4647 // Can we even bind to a temporary?
4648 if (ToType->isRValueReferenceType() ||
4649 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4650 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4651 Result.UserDefined.After;
4652 SCS.ReferenceBinding = true;
4653 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4654 SCS.BindsToRvalue = true;
4655 SCS.BindsToFunctionLvalue = false;
4656 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4657 SCS.ObjCLifetimeConversionBinding = false;
4659 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4664 // C++14 [over.ics.list]p7:
4665 // C++11 [over.ics.list]p6:
4666 // Otherwise, if the parameter type is not a class:
4667 if (!ToType->isRecordType()) {
4668 // - if the initializer list has one element that is not itself an
4669 // initializer list, the implicit conversion sequence is the one
4670 // required to convert the element to the parameter type.
4671 unsigned NumInits = From->getNumInits();
4672 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4673 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4674 SuppressUserConversions,
4675 InOverloadResolution,
4676 AllowObjCWritebackConversion);
4677 // - if the initializer list has no elements, the implicit conversion
4678 // sequence is the identity conversion.
4679 else if (NumInits == 0) {
4680 Result.setStandard();
4681 Result.Standard.setAsIdentityConversion();
4682 Result.Standard.setFromType(ToType);
4683 Result.Standard.setAllToTypes(ToType);
4688 // C++14 [over.ics.list]p8:
4689 // C++11 [over.ics.list]p7:
4690 // In all cases other than those enumerated above, no conversion is possible
4694 /// TryCopyInitialization - Try to copy-initialize a value of type
4695 /// ToType from the expression From. Return the implicit conversion
4696 /// sequence required to pass this argument, which may be a bad
4697 /// conversion sequence (meaning that the argument cannot be passed to
4698 /// a parameter of this type). If @p SuppressUserConversions, then we
4699 /// do not permit any user-defined conversion sequences.
4700 static ImplicitConversionSequence
4701 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4702 bool SuppressUserConversions,
4703 bool InOverloadResolution,
4704 bool AllowObjCWritebackConversion,
4705 bool AllowExplicit) {
4706 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4707 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4708 InOverloadResolution,AllowObjCWritebackConversion);
4710 if (ToType->isReferenceType())
4711 return TryReferenceInit(S, From, ToType,
4712 /*FIXME:*/From->getLocStart(),
4713 SuppressUserConversions,
4716 return TryImplicitConversion(S, From, ToType,
4717 SuppressUserConversions,
4718 /*AllowExplicit=*/false,
4719 InOverloadResolution,
4721 AllowObjCWritebackConversion,
4722 /*AllowObjCConversionOnExplicit=*/false);
4725 static bool TryCopyInitialization(const CanQualType FromQTy,
4726 const CanQualType ToQTy,
4729 ExprValueKind FromVK) {
4730 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4731 ImplicitConversionSequence ICS =
4732 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4734 return !ICS.isBad();
4737 /// TryObjectArgumentInitialization - Try to initialize the object
4738 /// parameter of the given member function (@c Method) from the
4739 /// expression @p From.
4740 static ImplicitConversionSequence
4741 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4742 Expr::Classification FromClassification,
4743 CXXMethodDecl *Method,
4744 CXXRecordDecl *ActingContext) {
4745 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4746 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4747 // const volatile object.
4748 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4749 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4750 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4752 // Set up the conversion sequence as a "bad" conversion, to allow us
4754 ImplicitConversionSequence ICS;
4756 // We need to have an object of class type.
4757 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4758 FromType = PT->getPointeeType();
4760 // When we had a pointer, it's implicitly dereferenced, so we
4761 // better have an lvalue.
4762 assert(FromClassification.isLValue());
4765 assert(FromType->isRecordType());
4767 // C++0x [over.match.funcs]p4:
4768 // For non-static member functions, the type of the implicit object
4771 // - "lvalue reference to cv X" for functions declared without a
4772 // ref-qualifier or with the & ref-qualifier
4773 // - "rvalue reference to cv X" for functions declared with the &&
4776 // where X is the class of which the function is a member and cv is the
4777 // cv-qualification on the member function declaration.
4779 // However, when finding an implicit conversion sequence for the argument, we
4780 // are not allowed to create temporaries or perform user-defined conversions
4781 // (C++ [over.match.funcs]p5). We perform a simplified version of
4782 // reference binding here, that allows class rvalues to bind to
4783 // non-constant references.
4785 // First check the qualifiers.
4786 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4787 if (ImplicitParamType.getCVRQualifiers()
4788 != FromTypeCanon.getLocalCVRQualifiers() &&
4789 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4790 ICS.setBad(BadConversionSequence::bad_qualifiers,
4791 FromType, ImplicitParamType);
4795 // Check that we have either the same type or a derived type. It
4796 // affects the conversion rank.
4797 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4798 ImplicitConversionKind SecondKind;
4799 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4800 SecondKind = ICK_Identity;
4801 } else if (S.IsDerivedFrom(FromType, ClassType))
4802 SecondKind = ICK_Derived_To_Base;
4804 ICS.setBad(BadConversionSequence::unrelated_class,
4805 FromType, ImplicitParamType);
4809 // Check the ref-qualifier.
4810 switch (Method->getRefQualifier()) {
4812 // Do nothing; we don't care about lvalueness or rvalueness.
4816 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4817 // non-const lvalue reference cannot bind to an rvalue
4818 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4825 if (!FromClassification.isRValue()) {
4826 // rvalue reference cannot bind to an lvalue
4827 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4834 // Success. Mark this as a reference binding.
4836 ICS.Standard.setAsIdentityConversion();
4837 ICS.Standard.Second = SecondKind;
4838 ICS.Standard.setFromType(FromType);
4839 ICS.Standard.setAllToTypes(ImplicitParamType);
4840 ICS.Standard.ReferenceBinding = true;
4841 ICS.Standard.DirectBinding = true;
4842 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4843 ICS.Standard.BindsToFunctionLvalue = false;
4844 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4845 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4846 = (Method->getRefQualifier() == RQ_None);
4850 /// PerformObjectArgumentInitialization - Perform initialization of
4851 /// the implicit object parameter for the given Method with the given
4854 Sema::PerformObjectArgumentInitialization(Expr *From,
4855 NestedNameSpecifier *Qualifier,
4856 NamedDecl *FoundDecl,
4857 CXXMethodDecl *Method) {
4858 QualType FromRecordType, DestType;
4859 QualType ImplicitParamRecordType =
4860 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4862 Expr::Classification FromClassification;
4863 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4864 FromRecordType = PT->getPointeeType();
4865 DestType = Method->getThisType(Context);
4866 FromClassification = Expr::Classification::makeSimpleLValue();
4868 FromRecordType = From->getType();
4869 DestType = ImplicitParamRecordType;
4870 FromClassification = From->Classify(Context);
4873 // Note that we always use the true parent context when performing
4874 // the actual argument initialization.
4875 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4876 *this, From->getType(), FromClassification, Method, Method->getParent());
4878 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4879 Qualifiers FromQs = FromRecordType.getQualifiers();
4880 Qualifiers ToQs = DestType.getQualifiers();
4881 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4883 Diag(From->getLocStart(),
4884 diag::err_member_function_call_bad_cvr)
4885 << Method->getDeclName() << FromRecordType << (CVR - 1)
4886 << From->getSourceRange();
4887 Diag(Method->getLocation(), diag::note_previous_decl)
4888 << Method->getDeclName();
4893 return Diag(From->getLocStart(),
4894 diag::err_implicit_object_parameter_init)
4895 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4898 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4899 ExprResult FromRes =
4900 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4901 if (FromRes.isInvalid())
4903 From = FromRes.get();
4906 if (!Context.hasSameType(From->getType(), DestType))
4907 From = ImpCastExprToType(From, DestType, CK_NoOp,
4908 From->getValueKind()).get();
4912 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4913 /// expression From to bool (C++0x [conv]p3).
4914 static ImplicitConversionSequence
4915 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4916 return TryImplicitConversion(S, From, S.Context.BoolTy,
4917 /*SuppressUserConversions=*/false,
4918 /*AllowExplicit=*/true,
4919 /*InOverloadResolution=*/false,
4921 /*AllowObjCWritebackConversion=*/false,
4922 /*AllowObjCConversionOnExplicit=*/false);
4925 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4926 /// of the expression From to bool (C++0x [conv]p3).
4927 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4928 if (checkPlaceholderForOverload(*this, From))
4931 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4933 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4935 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4936 return Diag(From->getLocStart(),
4937 diag::err_typecheck_bool_condition)
4938 << From->getType() << From->getSourceRange();
4942 /// Check that the specified conversion is permitted in a converted constant
4943 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4945 static bool CheckConvertedConstantConversions(Sema &S,
4946 StandardConversionSequence &SCS) {
4947 // Since we know that the target type is an integral or unscoped enumeration
4948 // type, most conversion kinds are impossible. All possible First and Third
4949 // conversions are fine.
4950 switch (SCS.Second) {
4952 case ICK_NoReturn_Adjustment:
4953 case ICK_Integral_Promotion:
4954 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4957 case ICK_Boolean_Conversion:
4958 // Conversion from an integral or unscoped enumeration type to bool is
4959 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4960 // conversion, so we allow it in a converted constant expression.
4962 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4963 // a lot of popular code. We should at least add a warning for this
4964 // (non-conforming) extension.
4965 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4966 SCS.getToType(2)->isBooleanType();
4968 case ICK_Pointer_Conversion:
4969 case ICK_Pointer_Member:
4970 // C++1z: null pointer conversions and null member pointer conversions are
4971 // only permitted if the source type is std::nullptr_t.
4972 return SCS.getFromType()->isNullPtrType();
4974 case ICK_Floating_Promotion:
4975 case ICK_Complex_Promotion:
4976 case ICK_Floating_Conversion:
4977 case ICK_Complex_Conversion:
4978 case ICK_Floating_Integral:
4979 case ICK_Compatible_Conversion:
4980 case ICK_Derived_To_Base:
4981 case ICK_Vector_Conversion:
4982 case ICK_Vector_Splat:
4983 case ICK_Complex_Real:
4984 case ICK_Block_Pointer_Conversion:
4985 case ICK_TransparentUnionConversion:
4986 case ICK_Writeback_Conversion:
4987 case ICK_Zero_Event_Conversion:
4990 case ICK_Lvalue_To_Rvalue:
4991 case ICK_Array_To_Pointer:
4992 case ICK_Function_To_Pointer:
4993 llvm_unreachable("found a first conversion kind in Second");
4995 case ICK_Qualification:
4996 llvm_unreachable("found a third conversion kind in Second");
4998 case ICK_Num_Conversion_Kinds:
5002 llvm_unreachable("unknown conversion kind");
5005 /// CheckConvertedConstantExpression - Check that the expression From is a
5006 /// converted constant expression of type T, perform the conversion and produce
5007 /// the converted expression, per C++11 [expr.const]p3.
5008 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5009 QualType T, APValue &Value,
5012 assert(S.getLangOpts().CPlusPlus11 &&
5013 "converted constant expression outside C++11");
5015 if (checkPlaceholderForOverload(S, From))
5018 // C++1z [expr.const]p3:
5019 // A converted constant expression of type T is an expression,
5020 // implicitly converted to type T, where the converted
5021 // expression is a constant expression and the implicit conversion
5022 // sequence contains only [... list of conversions ...].
5023 ImplicitConversionSequence ICS =
5024 TryCopyInitialization(S, From, T,
5025 /*SuppressUserConversions=*/false,
5026 /*InOverloadResolution=*/false,
5027 /*AllowObjcWritebackConversion=*/false,
5028 /*AllowExplicit=*/false);
5029 StandardConversionSequence *SCS = nullptr;
5030 switch (ICS.getKind()) {
5031 case ImplicitConversionSequence::StandardConversion:
5032 SCS = &ICS.Standard;
5034 case ImplicitConversionSequence::UserDefinedConversion:
5035 // We are converting to a non-class type, so the Before sequence
5037 SCS = &ICS.UserDefined.After;
5039 case ImplicitConversionSequence::AmbiguousConversion:
5040 case ImplicitConversionSequence::BadConversion:
5041 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5042 return S.Diag(From->getLocStart(),
5043 diag::err_typecheck_converted_constant_expression)
5044 << From->getType() << From->getSourceRange() << T;
5047 case ImplicitConversionSequence::EllipsisConversion:
5048 llvm_unreachable("ellipsis conversion in converted constant expression");
5051 // Check that we would only use permitted conversions.
5052 if (!CheckConvertedConstantConversions(S, *SCS)) {
5053 return S.Diag(From->getLocStart(),
5054 diag::err_typecheck_converted_constant_expression_disallowed)
5055 << From->getType() << From->getSourceRange() << T;
5057 // [...] and where the reference binding (if any) binds directly.
5058 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5059 return S.Diag(From->getLocStart(),
5060 diag::err_typecheck_converted_constant_expression_indirect)
5061 << From->getType() << From->getSourceRange() << T;
5065 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5066 if (Result.isInvalid())
5069 // Check for a narrowing implicit conversion.
5070 APValue PreNarrowingValue;
5071 QualType PreNarrowingType;
5072 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5073 PreNarrowingType)) {
5074 case NK_Variable_Narrowing:
5075 // Implicit conversion to a narrower type, and the value is not a constant
5076 // expression. We'll diagnose this in a moment.
5077 case NK_Not_Narrowing:
5080 case NK_Constant_Narrowing:
5081 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5082 << CCE << /*Constant*/1
5083 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5086 case NK_Type_Narrowing:
5087 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5088 << CCE << /*Constant*/0 << From->getType() << T;
5092 // Check the expression is a constant expression.
5093 SmallVector<PartialDiagnosticAt, 8> Notes;
5094 Expr::EvalResult Eval;
5097 if ((T->isReferenceType()
5098 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5099 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5100 (RequireInt && !Eval.Val.isInt())) {
5101 // The expression can't be folded, so we can't keep it at this position in
5103 Result = ExprError();
5107 if (Notes.empty()) {
5108 // It's a constant expression.
5113 // It's not a constant expression. Produce an appropriate diagnostic.
5114 if (Notes.size() == 1 &&
5115 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5116 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5118 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5119 << CCE << From->getSourceRange();
5120 for (unsigned I = 0; I < Notes.size(); ++I)
5121 S.Diag(Notes[I].first, Notes[I].second);
5126 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5127 APValue &Value, CCEKind CCE) {
5128 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5131 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5132 llvm::APSInt &Value,
5134 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5137 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5144 /// dropPointerConversions - If the given standard conversion sequence
5145 /// involves any pointer conversions, remove them. This may change
5146 /// the result type of the conversion sequence.
5147 static void dropPointerConversion(StandardConversionSequence &SCS) {
5148 if (SCS.Second == ICK_Pointer_Conversion) {
5149 SCS.Second = ICK_Identity;
5150 SCS.Third = ICK_Identity;
5151 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5155 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5156 /// convert the expression From to an Objective-C pointer type.
5157 static ImplicitConversionSequence
5158 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5159 // Do an implicit conversion to 'id'.
5160 QualType Ty = S.Context.getObjCIdType();
5161 ImplicitConversionSequence ICS
5162 = TryImplicitConversion(S, From, Ty,
5163 // FIXME: Are these flags correct?
5164 /*SuppressUserConversions=*/false,
5165 /*AllowExplicit=*/true,
5166 /*InOverloadResolution=*/false,
5168 /*AllowObjCWritebackConversion=*/false,
5169 /*AllowObjCConversionOnExplicit=*/true);
5171 // Strip off any final conversions to 'id'.
5172 switch (ICS.getKind()) {
5173 case ImplicitConversionSequence::BadConversion:
5174 case ImplicitConversionSequence::AmbiguousConversion:
5175 case ImplicitConversionSequence::EllipsisConversion:
5178 case ImplicitConversionSequence::UserDefinedConversion:
5179 dropPointerConversion(ICS.UserDefined.After);
5182 case ImplicitConversionSequence::StandardConversion:
5183 dropPointerConversion(ICS.Standard);
5190 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5191 /// conversion of the expression From to an Objective-C pointer type.
5192 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5193 if (checkPlaceholderForOverload(*this, From))
5196 QualType Ty = Context.getObjCIdType();
5197 ImplicitConversionSequence ICS =
5198 TryContextuallyConvertToObjCPointer(*this, From);
5200 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5204 /// Determine whether the provided type is an integral type, or an enumeration
5205 /// type of a permitted flavor.
5206 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5207 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5208 : T->isIntegralOrUnscopedEnumerationType();
5212 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5213 Sema::ContextualImplicitConverter &Converter,
5214 QualType T, UnresolvedSetImpl &ViableConversions) {
5216 if (Converter.Suppress)
5219 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5220 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5221 CXXConversionDecl *Conv =
5222 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5223 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5224 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5230 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5231 Sema::ContextualImplicitConverter &Converter,
5232 QualType T, bool HadMultipleCandidates,
5233 UnresolvedSetImpl &ExplicitConversions) {
5234 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5235 DeclAccessPair Found = ExplicitConversions[0];
5236 CXXConversionDecl *Conversion =
5237 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5239 // The user probably meant to invoke the given explicit
5240 // conversion; use it.
5241 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5242 std::string TypeStr;
5243 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5245 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5246 << FixItHint::CreateInsertion(From->getLocStart(),
5247 "static_cast<" + TypeStr + ">(")
5248 << FixItHint::CreateInsertion(
5249 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5250 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5252 // If we aren't in a SFINAE context, build a call to the
5253 // explicit conversion function.
5254 if (SemaRef.isSFINAEContext())
5257 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5258 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5259 HadMultipleCandidates);
5260 if (Result.isInvalid())
5262 // Record usage of conversion in an implicit cast.
5263 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5264 CK_UserDefinedConversion, Result.get(),
5265 nullptr, Result.get()->getValueKind());
5270 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5271 Sema::ContextualImplicitConverter &Converter,
5272 QualType T, bool HadMultipleCandidates,
5273 DeclAccessPair &Found) {
5274 CXXConversionDecl *Conversion =
5275 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5276 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5278 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5279 if (!Converter.SuppressConversion) {
5280 if (SemaRef.isSFINAEContext())
5283 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5284 << From->getSourceRange();
5287 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5288 HadMultipleCandidates);
5289 if (Result.isInvalid())
5291 // Record usage of conversion in an implicit cast.
5292 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5293 CK_UserDefinedConversion, Result.get(),
5294 nullptr, Result.get()->getValueKind());
5298 static ExprResult finishContextualImplicitConversion(
5299 Sema &SemaRef, SourceLocation Loc, Expr *From,
5300 Sema::ContextualImplicitConverter &Converter) {
5301 if (!Converter.match(From->getType()) && !Converter.Suppress)
5302 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5303 << From->getSourceRange();
5305 return SemaRef.DefaultLvalueConversion(From);
5309 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5310 UnresolvedSetImpl &ViableConversions,
5311 OverloadCandidateSet &CandidateSet) {
5312 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5313 DeclAccessPair FoundDecl = ViableConversions[I];
5314 NamedDecl *D = FoundDecl.getDecl();
5315 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5316 if (isa<UsingShadowDecl>(D))
5317 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5319 CXXConversionDecl *Conv;
5320 FunctionTemplateDecl *ConvTemplate;
5321 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5322 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5324 Conv = cast<CXXConversionDecl>(D);
5327 SemaRef.AddTemplateConversionCandidate(
5328 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5329 /*AllowObjCConversionOnExplicit=*/false);
5331 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5332 ToType, CandidateSet,
5333 /*AllowObjCConversionOnExplicit=*/false);
5337 /// \brief Attempt to convert the given expression to a type which is accepted
5338 /// by the given converter.
5340 /// This routine will attempt to convert an expression of class type to a
5341 /// type accepted by the specified converter. In C++11 and before, the class
5342 /// must have a single non-explicit conversion function converting to a matching
5343 /// type. In C++1y, there can be multiple such conversion functions, but only
5344 /// one target type.
5346 /// \param Loc The source location of the construct that requires the
5349 /// \param From The expression we're converting from.
5351 /// \param Converter Used to control and diagnose the conversion process.
5353 /// \returns The expression, converted to an integral or enumeration type if
5355 ExprResult Sema::PerformContextualImplicitConversion(
5356 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5357 // We can't perform any more checking for type-dependent expressions.
5358 if (From->isTypeDependent())
5361 // Process placeholders immediately.
5362 if (From->hasPlaceholderType()) {
5363 ExprResult result = CheckPlaceholderExpr(From);
5364 if (result.isInvalid())
5366 From = result.get();
5369 // If the expression already has a matching type, we're golden.
5370 QualType T = From->getType();
5371 if (Converter.match(T))
5372 return DefaultLvalueConversion(From);
5374 // FIXME: Check for missing '()' if T is a function type?
5376 // We can only perform contextual implicit conversions on objects of class
5378 const RecordType *RecordTy = T->getAs<RecordType>();
5379 if (!RecordTy || !getLangOpts().CPlusPlus) {
5380 if (!Converter.Suppress)
5381 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5385 // We must have a complete class type.
5386 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5387 ContextualImplicitConverter &Converter;
5390 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5391 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5393 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5394 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5396 } IncompleteDiagnoser(Converter, From);
5398 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5401 // Look for a conversion to an integral or enumeration type.
5403 ViableConversions; // These are *potentially* viable in C++1y.
5404 UnresolvedSet<4> ExplicitConversions;
5405 const auto &Conversions =
5406 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5408 bool HadMultipleCandidates =
5409 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5411 // To check that there is only one target type, in C++1y:
5413 bool HasUniqueTargetType = true;
5415 // Collect explicit or viable (potentially in C++1y) conversions.
5416 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5417 NamedDecl *D = (*I)->getUnderlyingDecl();
5418 CXXConversionDecl *Conversion;
5419 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5421 if (getLangOpts().CPlusPlus14)
5422 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5424 continue; // C++11 does not consider conversion operator templates(?).
5426 Conversion = cast<CXXConversionDecl>(D);
5428 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5429 "Conversion operator templates are considered potentially "
5432 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5433 if (Converter.match(CurToType) || ConvTemplate) {
5435 if (Conversion->isExplicit()) {
5436 // FIXME: For C++1y, do we need this restriction?
5437 // cf. diagnoseNoViableConversion()
5439 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5441 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5442 if (ToType.isNull())
5443 ToType = CurToType.getUnqualifiedType();
5444 else if (HasUniqueTargetType &&
5445 (CurToType.getUnqualifiedType() != ToType))
5446 HasUniqueTargetType = false;
5448 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5453 if (getLangOpts().CPlusPlus14) {
5455 // ... An expression e of class type E appearing in such a context
5456 // is said to be contextually implicitly converted to a specified
5457 // type T and is well-formed if and only if e can be implicitly
5458 // converted to a type T that is determined as follows: E is searched
5459 // for conversion functions whose return type is cv T or reference to
5460 // cv T such that T is allowed by the context. There shall be
5461 // exactly one such T.
5463 // If no unique T is found:
5464 if (ToType.isNull()) {
5465 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5466 HadMultipleCandidates,
5467 ExplicitConversions))
5469 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5472 // If more than one unique Ts are found:
5473 if (!HasUniqueTargetType)
5474 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5477 // If one unique T is found:
5478 // First, build a candidate set from the previously recorded
5479 // potentially viable conversions.
5480 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5481 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5484 // Then, perform overload resolution over the candidate set.
5485 OverloadCandidateSet::iterator Best;
5486 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5488 // Apply this conversion.
5489 DeclAccessPair Found =
5490 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5491 if (recordConversion(*this, Loc, From, Converter, T,
5492 HadMultipleCandidates, Found))
5497 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5499 case OR_No_Viable_Function:
5500 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5501 HadMultipleCandidates,
5502 ExplicitConversions))
5504 // fall through 'OR_Deleted' case.
5506 // We'll complain below about a non-integral condition type.
5510 switch (ViableConversions.size()) {
5512 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5513 HadMultipleCandidates,
5514 ExplicitConversions))
5517 // We'll complain below about a non-integral condition type.
5521 // Apply this conversion.
5522 DeclAccessPair Found = ViableConversions[0];
5523 if (recordConversion(*this, Loc, From, Converter, T,
5524 HadMultipleCandidates, Found))
5529 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5534 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5537 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5538 /// an acceptable non-member overloaded operator for a call whose
5539 /// arguments have types T1 (and, if non-empty, T2). This routine
5540 /// implements the check in C++ [over.match.oper]p3b2 concerning
5541 /// enumeration types.
5542 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5544 ArrayRef<Expr *> Args) {
5545 QualType T1 = Args[0]->getType();
5546 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5548 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5551 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5554 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5555 if (Proto->getNumParams() < 1)
5558 if (T1->isEnumeralType()) {
5559 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5560 if (Context.hasSameUnqualifiedType(T1, ArgType))
5564 if (Proto->getNumParams() < 2)
5567 if (!T2.isNull() && T2->isEnumeralType()) {
5568 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5569 if (Context.hasSameUnqualifiedType(T2, ArgType))
5576 /// AddOverloadCandidate - Adds the given function to the set of
5577 /// candidate functions, using the given function call arguments. If
5578 /// @p SuppressUserConversions, then don't allow user-defined
5579 /// conversions via constructors or conversion operators.
5581 /// \param PartialOverloading true if we are performing "partial" overloading
5582 /// based on an incomplete set of function arguments. This feature is used by
5583 /// code completion.
5585 Sema::AddOverloadCandidate(FunctionDecl *Function,
5586 DeclAccessPair FoundDecl,
5587 ArrayRef<Expr *> Args,
5588 OverloadCandidateSet &CandidateSet,
5589 bool SuppressUserConversions,
5590 bool PartialOverloading,
5591 bool AllowExplicit) {
5592 const FunctionProtoType *Proto
5593 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5594 assert(Proto && "Functions without a prototype cannot be overloaded");
5595 assert(!Function->getDescribedFunctionTemplate() &&
5596 "Use AddTemplateOverloadCandidate for function templates");
5598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5599 if (!isa<CXXConstructorDecl>(Method)) {
5600 // If we get here, it's because we're calling a member function
5601 // that is named without a member access expression (e.g.,
5602 // "this->f") that was either written explicitly or created
5603 // implicitly. This can happen with a qualified call to a member
5604 // function, e.g., X::f(). We use an empty type for the implied
5605 // object argument (C++ [over.call.func]p3), and the acting context
5607 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5608 QualType(), Expr::Classification::makeSimpleLValue(),
5609 Args, CandidateSet, SuppressUserConversions,
5610 PartialOverloading);
5613 // We treat a constructor like a non-member function, since its object
5614 // argument doesn't participate in overload resolution.
5617 if (!CandidateSet.isNewCandidate(Function))
5620 // C++ [over.match.oper]p3:
5621 // if no operand has a class type, only those non-member functions in the
5622 // lookup set that have a first parameter of type T1 or "reference to
5623 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5624 // is a right operand) a second parameter of type T2 or "reference to
5625 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5626 // candidate functions.
5627 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5628 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5631 // C++11 [class.copy]p11: [DR1402]
5632 // A defaulted move constructor that is defined as deleted is ignored by
5633 // overload resolution.
5634 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5635 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5636 Constructor->isMoveConstructor())
5639 // Overload resolution is always an unevaluated context.
5640 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5642 // Add this candidate
5643 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5644 Candidate.FoundDecl = FoundDecl;
5645 Candidate.Function = Function;
5646 Candidate.Viable = true;
5647 Candidate.IsSurrogate = false;
5648 Candidate.IgnoreObjectArgument = false;
5649 Candidate.ExplicitCallArguments = Args.size();
5652 // C++ [class.copy]p3:
5653 // A member function template is never instantiated to perform the copy
5654 // of a class object to an object of its class type.
5655 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5656 if (Args.size() == 1 &&
5657 Constructor->isSpecializationCopyingObject() &&
5658 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5659 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5660 Candidate.Viable = false;
5661 Candidate.FailureKind = ovl_fail_illegal_constructor;
5666 unsigned NumParams = Proto->getNumParams();
5668 // (C++ 13.3.2p2): A candidate function having fewer than m
5669 // parameters is viable only if it has an ellipsis in its parameter
5671 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5672 !Proto->isVariadic()) {
5673 Candidate.Viable = false;
5674 Candidate.FailureKind = ovl_fail_too_many_arguments;
5678 // (C++ 13.3.2p2): A candidate function having more than m parameters
5679 // is viable only if the (m+1)st parameter has a default argument
5680 // (8.3.6). For the purposes of overload resolution, the
5681 // parameter list is truncated on the right, so that there are
5682 // exactly m parameters.
5683 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5684 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5685 // Not enough arguments.
5686 Candidate.Viable = false;
5687 Candidate.FailureKind = ovl_fail_too_few_arguments;
5691 // (CUDA B.1): Check for invalid calls between targets.
5692 if (getLangOpts().CUDA)
5693 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5694 // Skip the check for callers that are implicit members, because in this
5695 // case we may not yet know what the member's target is; the target is
5696 // inferred for the member automatically, based on the bases and fields of
5698 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5699 Candidate.Viable = false;
5700 Candidate.FailureKind = ovl_fail_bad_target;
5704 // Determine the implicit conversion sequences for each of the
5706 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5707 if (ArgIdx < NumParams) {
5708 // (C++ 13.3.2p3): for F to be a viable function, there shall
5709 // exist for each argument an implicit conversion sequence
5710 // (13.3.3.1) that converts that argument to the corresponding
5712 QualType ParamType = Proto->getParamType(ArgIdx);
5713 Candidate.Conversions[ArgIdx]
5714 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5715 SuppressUserConversions,
5716 /*InOverloadResolution=*/true,
5717 /*AllowObjCWritebackConversion=*/
5718 getLangOpts().ObjCAutoRefCount,
5720 if (Candidate.Conversions[ArgIdx].isBad()) {
5721 Candidate.Viable = false;
5722 Candidate.FailureKind = ovl_fail_bad_conversion;
5726 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5727 // argument for which there is no corresponding parameter is
5728 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5729 Candidate.Conversions[ArgIdx].setEllipsis();
5733 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5734 Candidate.Viable = false;
5735 Candidate.FailureKind = ovl_fail_enable_if;
5736 Candidate.DeductionFailure.Data = FailedAttr;
5741 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5743 SmallVector<ObjCMethodDecl*, 4> Methods;
5744 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5747 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5749 ObjCMethodDecl *Method = Methods[b];
5750 unsigned NumNamedArgs = Sel.getNumArgs();
5751 // Method might have more arguments than selector indicates. This is due
5752 // to addition of c-style arguments in method.
5753 if (Method->param_size() > NumNamedArgs)
5754 NumNamedArgs = Method->param_size();
5755 if (Args.size() < NumNamedArgs)
5758 for (unsigned i = 0; i < NumNamedArgs; i++) {
5759 // We can't do any type-checking on a type-dependent argument.
5760 if (Args[i]->isTypeDependent()) {
5765 ParmVarDecl *param = Method->parameters()[i];
5766 Expr *argExpr = Args[i];
5767 assert(argExpr && "SelectBestMethod(): missing expression");
5769 // Strip the unbridged-cast placeholder expression off unless it's
5770 // a consumed argument.
5771 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5772 !param->hasAttr<CFConsumedAttr>())
5773 argExpr = stripARCUnbridgedCast(argExpr);
5775 // If the parameter is __unknown_anytype, move on to the next method.
5776 if (param->getType() == Context.UnknownAnyTy) {
5781 ImplicitConversionSequence ConversionState
5782 = TryCopyInitialization(*this, argExpr, param->getType(),
5783 /*SuppressUserConversions*/false,
5784 /*InOverloadResolution=*/true,
5785 /*AllowObjCWritebackConversion=*/
5786 getLangOpts().ObjCAutoRefCount,
5787 /*AllowExplicit*/false);
5788 if (ConversionState.isBad()) {
5793 // Promote additional arguments to variadic methods.
5794 if (Match && Method->isVariadic()) {
5795 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5796 if (Args[i]->isTypeDependent()) {
5800 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5802 if (Arg.isInvalid()) {
5808 // Check for extra arguments to non-variadic methods.
5809 if (Args.size() != NumNamedArgs)
5811 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5812 // Special case when selectors have no argument. In this case, select
5813 // one with the most general result type of 'id'.
5814 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5815 QualType ReturnT = Methods[b]->getReturnType();
5816 if (ReturnT->isObjCIdType())
5828 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5830 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5831 bool MissingImplicitThis) {
5832 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5833 // we need to find the first failing one.
5834 if (!Function->hasAttrs())
5836 AttrVec Attrs = Function->getAttrs();
5837 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5839 if (Attrs.begin() == E)
5841 std::reverse(Attrs.begin(), E);
5843 SFINAETrap Trap(*this);
5845 // Convert the arguments.
5846 SmallVector<Expr *, 16> ConvertedArgs;
5847 bool InitializationFailed = false;
5848 bool ContainsValueDependentExpr = false;
5849 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5850 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5851 !cast<CXXMethodDecl>(Function)->isStatic() &&
5852 !isa<CXXConstructorDecl>(Function)) {
5853 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5855 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5857 if (R.isInvalid()) {
5858 InitializationFailed = true;
5861 ContainsValueDependentExpr |= R.get()->isValueDependent();
5862 ConvertedArgs.push_back(R.get());
5865 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5867 Function->getParamDecl(i)),
5870 if (R.isInvalid()) {
5871 InitializationFailed = true;
5874 ContainsValueDependentExpr |= R.get()->isValueDependent();
5875 ConvertedArgs.push_back(R.get());
5879 if (InitializationFailed || Trap.hasErrorOccurred())
5880 return cast<EnableIfAttr>(Attrs[0]);
5882 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5884 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5885 if (EIA->getCond()->isValueDependent()) {
5886 // Don't even try now, we'll examine it after instantiation.
5890 if (!EIA->getCond()->EvaluateWithSubstitution(
5891 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5892 if (!ContainsValueDependentExpr)
5894 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5901 /// \brief Add all of the function declarations in the given function set to
5902 /// the overload candidate set.
5903 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5904 ArrayRef<Expr *> Args,
5905 OverloadCandidateSet& CandidateSet,
5906 TemplateArgumentListInfo *ExplicitTemplateArgs,
5907 bool SuppressUserConversions,
5908 bool PartialOverloading) {
5909 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5910 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5911 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5912 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5913 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5914 cast<CXXMethodDecl>(FD)->getParent(),
5915 Args[0]->getType(), Args[0]->Classify(Context),
5916 Args.slice(1), CandidateSet,
5917 SuppressUserConversions, PartialOverloading);
5919 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5920 SuppressUserConversions, PartialOverloading);
5922 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5923 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5924 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5925 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5926 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5927 ExplicitTemplateArgs,
5929 Args[0]->Classify(Context), Args.slice(1),
5930 CandidateSet, SuppressUserConversions,
5931 PartialOverloading);
5933 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5934 ExplicitTemplateArgs, Args,
5935 CandidateSet, SuppressUserConversions,
5936 PartialOverloading);
5941 /// AddMethodCandidate - Adds a named decl (which is some kind of
5942 /// method) as a method candidate to the given overload set.
5943 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5944 QualType ObjectType,
5945 Expr::Classification ObjectClassification,
5946 ArrayRef<Expr *> Args,
5947 OverloadCandidateSet& CandidateSet,
5948 bool SuppressUserConversions) {
5949 NamedDecl *Decl = FoundDecl.getDecl();
5950 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5952 if (isa<UsingShadowDecl>(Decl))
5953 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5955 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5956 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5957 "Expected a member function template");
5958 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5959 /*ExplicitArgs*/ nullptr,
5960 ObjectType, ObjectClassification,
5962 SuppressUserConversions);
5964 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5965 ObjectType, ObjectClassification,
5967 CandidateSet, SuppressUserConversions);
5971 /// AddMethodCandidate - Adds the given C++ member function to the set
5972 /// of candidate functions, using the given function call arguments
5973 /// and the object argument (@c Object). For example, in a call
5974 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5975 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5976 /// allow user-defined conversions via constructors or conversion
5979 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5980 CXXRecordDecl *ActingContext, QualType ObjectType,
5981 Expr::Classification ObjectClassification,
5982 ArrayRef<Expr *> Args,
5983 OverloadCandidateSet &CandidateSet,
5984 bool SuppressUserConversions,
5985 bool PartialOverloading) {
5986 const FunctionProtoType *Proto
5987 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5988 assert(Proto && "Methods without a prototype cannot be overloaded");
5989 assert(!isa<CXXConstructorDecl>(Method) &&
5990 "Use AddOverloadCandidate for constructors");
5992 if (!CandidateSet.isNewCandidate(Method))
5995 // C++11 [class.copy]p23: [DR1402]
5996 // A defaulted move assignment operator that is defined as deleted is
5997 // ignored by overload resolution.
5998 if (Method->isDefaulted() && Method->isDeleted() &&
5999 Method->isMoveAssignmentOperator())
6002 // Overload resolution is always an unevaluated context.
6003 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6005 // Add this candidate
6006 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6007 Candidate.FoundDecl = FoundDecl;
6008 Candidate.Function = Method;
6009 Candidate.IsSurrogate = false;
6010 Candidate.IgnoreObjectArgument = false;
6011 Candidate.ExplicitCallArguments = Args.size();
6013 unsigned NumParams = Proto->getNumParams();
6015 // (C++ 13.3.2p2): A candidate function having fewer than m
6016 // parameters is viable only if it has an ellipsis in its parameter
6018 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6019 !Proto->isVariadic()) {
6020 Candidate.Viable = false;
6021 Candidate.FailureKind = ovl_fail_too_many_arguments;
6025 // (C++ 13.3.2p2): A candidate function having more than m parameters
6026 // is viable only if the (m+1)st parameter has a default argument
6027 // (8.3.6). For the purposes of overload resolution, the
6028 // parameter list is truncated on the right, so that there are
6029 // exactly m parameters.
6030 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6031 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6032 // Not enough arguments.
6033 Candidate.Viable = false;
6034 Candidate.FailureKind = ovl_fail_too_few_arguments;
6038 Candidate.Viable = true;
6040 if (Method->isStatic() || ObjectType.isNull())
6041 // The implicit object argument is ignored.
6042 Candidate.IgnoreObjectArgument = true;
6044 // Determine the implicit conversion sequence for the object
6046 Candidate.Conversions[0]
6047 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6048 Method, ActingContext);
6049 if (Candidate.Conversions[0].isBad()) {
6050 Candidate.Viable = false;
6051 Candidate.FailureKind = ovl_fail_bad_conversion;
6056 // (CUDA B.1): Check for invalid calls between targets.
6057 if (getLangOpts().CUDA)
6058 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6059 if (CheckCUDATarget(Caller, Method)) {
6060 Candidate.Viable = false;
6061 Candidate.FailureKind = ovl_fail_bad_target;
6065 // Determine the implicit conversion sequences for each of the
6067 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6068 if (ArgIdx < NumParams) {
6069 // (C++ 13.3.2p3): for F to be a viable function, there shall
6070 // exist for each argument an implicit conversion sequence
6071 // (13.3.3.1) that converts that argument to the corresponding
6073 QualType ParamType = Proto->getParamType(ArgIdx);
6074 Candidate.Conversions[ArgIdx + 1]
6075 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6076 SuppressUserConversions,
6077 /*InOverloadResolution=*/true,
6078 /*AllowObjCWritebackConversion=*/
6079 getLangOpts().ObjCAutoRefCount);
6080 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6081 Candidate.Viable = false;
6082 Candidate.FailureKind = ovl_fail_bad_conversion;
6086 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6087 // argument for which there is no corresponding parameter is
6088 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6089 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6093 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6094 Candidate.Viable = false;
6095 Candidate.FailureKind = ovl_fail_enable_if;
6096 Candidate.DeductionFailure.Data = FailedAttr;
6101 /// \brief Add a C++ member function template as a candidate to the candidate
6102 /// set, using template argument deduction to produce an appropriate member
6103 /// function template specialization.
6105 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6106 DeclAccessPair FoundDecl,
6107 CXXRecordDecl *ActingContext,
6108 TemplateArgumentListInfo *ExplicitTemplateArgs,
6109 QualType ObjectType,
6110 Expr::Classification ObjectClassification,
6111 ArrayRef<Expr *> Args,
6112 OverloadCandidateSet& CandidateSet,
6113 bool SuppressUserConversions,
6114 bool PartialOverloading) {
6115 if (!CandidateSet.isNewCandidate(MethodTmpl))
6118 // C++ [over.match.funcs]p7:
6119 // In each case where a candidate is a function template, candidate
6120 // function template specializations are generated using template argument
6121 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6122 // candidate functions in the usual way.113) A given name can refer to one
6123 // or more function templates and also to a set of overloaded non-template
6124 // functions. In such a case, the candidate functions generated from each
6125 // function template are combined with the set of non-template candidate
6127 TemplateDeductionInfo Info(CandidateSet.getLocation());
6128 FunctionDecl *Specialization = nullptr;
6129 if (TemplateDeductionResult Result
6130 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6131 Specialization, Info, PartialOverloading)) {
6132 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6133 Candidate.FoundDecl = FoundDecl;
6134 Candidate.Function = MethodTmpl->getTemplatedDecl();
6135 Candidate.Viable = false;
6136 Candidate.FailureKind = ovl_fail_bad_deduction;
6137 Candidate.IsSurrogate = false;
6138 Candidate.IgnoreObjectArgument = false;
6139 Candidate.ExplicitCallArguments = Args.size();
6140 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6145 // Add the function template specialization produced by template argument
6146 // deduction as a candidate.
6147 assert(Specialization && "Missing member function template specialization?");
6148 assert(isa<CXXMethodDecl>(Specialization) &&
6149 "Specialization is not a member function?");
6150 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6151 ActingContext, ObjectType, ObjectClassification, Args,
6152 CandidateSet, SuppressUserConversions, PartialOverloading);
6155 /// \brief Add a C++ function template specialization as a candidate
6156 /// in the candidate set, using template argument deduction to produce
6157 /// an appropriate function template specialization.
6159 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6160 DeclAccessPair FoundDecl,
6161 TemplateArgumentListInfo *ExplicitTemplateArgs,
6162 ArrayRef<Expr *> Args,
6163 OverloadCandidateSet& CandidateSet,
6164 bool SuppressUserConversions,
6165 bool PartialOverloading) {
6166 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6169 // C++ [over.match.funcs]p7:
6170 // In each case where a candidate is a function template, candidate
6171 // function template specializations are generated using template argument
6172 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6173 // candidate functions in the usual way.113) A given name can refer to one
6174 // or more function templates and also to a set of overloaded non-template
6175 // functions. In such a case, the candidate functions generated from each
6176 // function template are combined with the set of non-template candidate
6178 TemplateDeductionInfo Info(CandidateSet.getLocation());
6179 FunctionDecl *Specialization = nullptr;
6180 if (TemplateDeductionResult Result
6181 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6182 Specialization, Info, PartialOverloading)) {
6183 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6184 Candidate.FoundDecl = FoundDecl;
6185 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6186 Candidate.Viable = false;
6187 Candidate.FailureKind = ovl_fail_bad_deduction;
6188 Candidate.IsSurrogate = false;
6189 Candidate.IgnoreObjectArgument = false;
6190 Candidate.ExplicitCallArguments = Args.size();
6191 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6196 // Add the function template specialization produced by template argument
6197 // deduction as a candidate.
6198 assert(Specialization && "Missing function template specialization?");
6199 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6200 SuppressUserConversions, PartialOverloading);
6203 /// Determine whether this is an allowable conversion from the result
6204 /// of an explicit conversion operator to the expected type, per C++
6205 /// [over.match.conv]p1 and [over.match.ref]p1.
6207 /// \param ConvType The return type of the conversion function.
6209 /// \param ToType The type we are converting to.
6211 /// \param AllowObjCPointerConversion Allow a conversion from one
6212 /// Objective-C pointer to another.
6214 /// \returns true if the conversion is allowable, false otherwise.
6215 static bool isAllowableExplicitConversion(Sema &S,
6216 QualType ConvType, QualType ToType,
6217 bool AllowObjCPointerConversion) {
6218 QualType ToNonRefType = ToType.getNonReferenceType();
6220 // Easy case: the types are the same.
6221 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6224 // Allow qualification conversions.
6225 bool ObjCLifetimeConversion;
6226 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6227 ObjCLifetimeConversion))
6230 // If we're not allowed to consider Objective-C pointer conversions,
6232 if (!AllowObjCPointerConversion)
6235 // Is this an Objective-C pointer conversion?
6236 bool IncompatibleObjC = false;
6237 QualType ConvertedType;
6238 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6242 /// AddConversionCandidate - Add a C++ conversion function as a
6243 /// candidate in the candidate set (C++ [over.match.conv],
6244 /// C++ [over.match.copy]). From is the expression we're converting from,
6245 /// and ToType is the type that we're eventually trying to convert to
6246 /// (which may or may not be the same type as the type that the
6247 /// conversion function produces).
6249 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6250 DeclAccessPair FoundDecl,
6251 CXXRecordDecl *ActingContext,
6252 Expr *From, QualType ToType,
6253 OverloadCandidateSet& CandidateSet,
6254 bool AllowObjCConversionOnExplicit) {
6255 assert(!Conversion->getDescribedFunctionTemplate() &&
6256 "Conversion function templates use AddTemplateConversionCandidate");
6257 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6258 if (!CandidateSet.isNewCandidate(Conversion))
6261 // If the conversion function has an undeduced return type, trigger its
6263 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6264 if (DeduceReturnType(Conversion, From->getExprLoc()))
6266 ConvType = Conversion->getConversionType().getNonReferenceType();
6269 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6270 // operator is only a candidate if its return type is the target type or
6271 // can be converted to the target type with a qualification conversion.
6272 if (Conversion->isExplicit() &&
6273 !isAllowableExplicitConversion(*this, ConvType, ToType,
6274 AllowObjCConversionOnExplicit))
6277 // Overload resolution is always an unevaluated context.
6278 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6280 // Add this candidate
6281 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6282 Candidate.FoundDecl = FoundDecl;
6283 Candidate.Function = Conversion;
6284 Candidate.IsSurrogate = false;
6285 Candidate.IgnoreObjectArgument = false;
6286 Candidate.FinalConversion.setAsIdentityConversion();
6287 Candidate.FinalConversion.setFromType(ConvType);
6288 Candidate.FinalConversion.setAllToTypes(ToType);
6289 Candidate.Viable = true;
6290 Candidate.ExplicitCallArguments = 1;
6292 // C++ [over.match.funcs]p4:
6293 // For conversion functions, the function is considered to be a member of
6294 // the class of the implicit implied object argument for the purpose of
6295 // defining the type of the implicit object parameter.
6297 // Determine the implicit conversion sequence for the implicit
6298 // object parameter.
6299 QualType ImplicitParamType = From->getType();
6300 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6301 ImplicitParamType = FromPtrType->getPointeeType();
6302 CXXRecordDecl *ConversionContext
6303 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6305 Candidate.Conversions[0]
6306 = TryObjectArgumentInitialization(*this, From->getType(),
6307 From->Classify(Context),
6308 Conversion, ConversionContext);
6310 if (Candidate.Conversions[0].isBad()) {
6311 Candidate.Viable = false;
6312 Candidate.FailureKind = ovl_fail_bad_conversion;
6316 // We won't go through a user-defined type conversion function to convert a
6317 // derived to base as such conversions are given Conversion Rank. They only
6318 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6320 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6321 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6322 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6323 Candidate.Viable = false;
6324 Candidate.FailureKind = ovl_fail_trivial_conversion;
6328 // To determine what the conversion from the result of calling the
6329 // conversion function to the type we're eventually trying to
6330 // convert to (ToType), we need to synthesize a call to the
6331 // conversion function and attempt copy initialization from it. This
6332 // makes sure that we get the right semantics with respect to
6333 // lvalues/rvalues and the type. Fortunately, we can allocate this
6334 // call on the stack and we don't need its arguments to be
6336 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6337 VK_LValue, From->getLocStart());
6338 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6339 Context.getPointerType(Conversion->getType()),
6340 CK_FunctionToPointerDecay,
6341 &ConversionRef, VK_RValue);
6343 QualType ConversionType = Conversion->getConversionType();
6344 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6345 Candidate.Viable = false;
6346 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6350 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6352 // Note that it is safe to allocate CallExpr on the stack here because
6353 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6355 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6356 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6357 From->getLocStart());
6358 ImplicitConversionSequence ICS =
6359 TryCopyInitialization(*this, &Call, ToType,
6360 /*SuppressUserConversions=*/true,
6361 /*InOverloadResolution=*/false,
6362 /*AllowObjCWritebackConversion=*/false);
6364 switch (ICS.getKind()) {
6365 case ImplicitConversionSequence::StandardConversion:
6366 Candidate.FinalConversion = ICS.Standard;
6368 // C++ [over.ics.user]p3:
6369 // If the user-defined conversion is specified by a specialization of a
6370 // conversion function template, the second standard conversion sequence
6371 // shall have exact match rank.
6372 if (Conversion->getPrimaryTemplate() &&
6373 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6374 Candidate.Viable = false;
6375 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6379 // C++0x [dcl.init.ref]p5:
6380 // In the second case, if the reference is an rvalue reference and
6381 // the second standard conversion sequence of the user-defined
6382 // conversion sequence includes an lvalue-to-rvalue conversion, the
6383 // program is ill-formed.
6384 if (ToType->isRValueReferenceType() &&
6385 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6386 Candidate.Viable = false;
6387 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6392 case ImplicitConversionSequence::BadConversion:
6393 Candidate.Viable = false;
6394 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6399 "Can only end up with a standard conversion sequence or failure");
6402 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6403 Candidate.Viable = false;
6404 Candidate.FailureKind = ovl_fail_enable_if;
6405 Candidate.DeductionFailure.Data = FailedAttr;
6410 /// \brief Adds a conversion function template specialization
6411 /// candidate to the overload set, using template argument deduction
6412 /// to deduce the template arguments of the conversion function
6413 /// template from the type that we are converting to (C++
6414 /// [temp.deduct.conv]).
6416 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6417 DeclAccessPair FoundDecl,
6418 CXXRecordDecl *ActingDC,
6419 Expr *From, QualType ToType,
6420 OverloadCandidateSet &CandidateSet,
6421 bool AllowObjCConversionOnExplicit) {
6422 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6423 "Only conversion function templates permitted here");
6425 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6428 TemplateDeductionInfo Info(CandidateSet.getLocation());
6429 CXXConversionDecl *Specialization = nullptr;
6430 if (TemplateDeductionResult Result
6431 = DeduceTemplateArguments(FunctionTemplate, ToType,
6432 Specialization, Info)) {
6433 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6434 Candidate.FoundDecl = FoundDecl;
6435 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6436 Candidate.Viable = false;
6437 Candidate.FailureKind = ovl_fail_bad_deduction;
6438 Candidate.IsSurrogate = false;
6439 Candidate.IgnoreObjectArgument = false;
6440 Candidate.ExplicitCallArguments = 1;
6441 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6446 // Add the conversion function template specialization produced by
6447 // template argument deduction as a candidate.
6448 assert(Specialization && "Missing function template specialization?");
6449 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6450 CandidateSet, AllowObjCConversionOnExplicit);
6453 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6454 /// converts the given @c Object to a function pointer via the
6455 /// conversion function @c Conversion, and then attempts to call it
6456 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6457 /// the type of function that we'll eventually be calling.
6458 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6459 DeclAccessPair FoundDecl,
6460 CXXRecordDecl *ActingContext,
6461 const FunctionProtoType *Proto,
6463 ArrayRef<Expr *> Args,
6464 OverloadCandidateSet& CandidateSet) {
6465 if (!CandidateSet.isNewCandidate(Conversion))
6468 // Overload resolution is always an unevaluated context.
6469 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6471 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6472 Candidate.FoundDecl = FoundDecl;
6473 Candidate.Function = nullptr;
6474 Candidate.Surrogate = Conversion;
6475 Candidate.Viable = true;
6476 Candidate.IsSurrogate = true;
6477 Candidate.IgnoreObjectArgument = false;
6478 Candidate.ExplicitCallArguments = Args.size();
6480 // Determine the implicit conversion sequence for the implicit
6481 // object parameter.
6482 ImplicitConversionSequence ObjectInit
6483 = TryObjectArgumentInitialization(*this, Object->getType(),
6484 Object->Classify(Context),
6485 Conversion, ActingContext);
6486 if (ObjectInit.isBad()) {
6487 Candidate.Viable = false;
6488 Candidate.FailureKind = ovl_fail_bad_conversion;
6489 Candidate.Conversions[0] = ObjectInit;
6493 // The first conversion is actually a user-defined conversion whose
6494 // first conversion is ObjectInit's standard conversion (which is
6495 // effectively a reference binding). Record it as such.
6496 Candidate.Conversions[0].setUserDefined();
6497 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6498 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6499 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6500 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6501 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6502 Candidate.Conversions[0].UserDefined.After
6503 = Candidate.Conversions[0].UserDefined.Before;
6504 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6507 unsigned NumParams = Proto->getNumParams();
6509 // (C++ 13.3.2p2): A candidate function having fewer than m
6510 // parameters is viable only if it has an ellipsis in its parameter
6512 if (Args.size() > NumParams && !Proto->isVariadic()) {
6513 Candidate.Viable = false;
6514 Candidate.FailureKind = ovl_fail_too_many_arguments;
6518 // Function types don't have any default arguments, so just check if
6519 // we have enough arguments.
6520 if (Args.size() < NumParams) {
6521 // Not enough arguments.
6522 Candidate.Viable = false;
6523 Candidate.FailureKind = ovl_fail_too_few_arguments;
6527 // Determine the implicit conversion sequences for each of the
6529 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6530 if (ArgIdx < NumParams) {
6531 // (C++ 13.3.2p3): for F to be a viable function, there shall
6532 // exist for each argument an implicit conversion sequence
6533 // (13.3.3.1) that converts that argument to the corresponding
6535 QualType ParamType = Proto->getParamType(ArgIdx);
6536 Candidate.Conversions[ArgIdx + 1]
6537 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6538 /*SuppressUserConversions=*/false,
6539 /*InOverloadResolution=*/false,
6540 /*AllowObjCWritebackConversion=*/
6541 getLangOpts().ObjCAutoRefCount);
6542 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6543 Candidate.Viable = false;
6544 Candidate.FailureKind = ovl_fail_bad_conversion;
6548 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6549 // argument for which there is no corresponding parameter is
6550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6551 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6555 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6556 Candidate.Viable = false;
6557 Candidate.FailureKind = ovl_fail_enable_if;
6558 Candidate.DeductionFailure.Data = FailedAttr;
6563 /// \brief Add overload candidates for overloaded operators that are
6564 /// member functions.
6566 /// Add the overloaded operator candidates that are member functions
6567 /// for the operator Op that was used in an operator expression such
6568 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6569 /// CandidateSet will store the added overload candidates. (C++
6570 /// [over.match.oper]).
6571 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6572 SourceLocation OpLoc,
6573 ArrayRef<Expr *> Args,
6574 OverloadCandidateSet& CandidateSet,
6575 SourceRange OpRange) {
6576 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6578 // C++ [over.match.oper]p3:
6579 // For a unary operator @ with an operand of a type whose
6580 // cv-unqualified version is T1, and for a binary operator @ with
6581 // a left operand of a type whose cv-unqualified version is T1 and
6582 // a right operand of a type whose cv-unqualified version is T2,
6583 // three sets of candidate functions, designated member
6584 // candidates, non-member candidates and built-in candidates, are
6585 // constructed as follows:
6586 QualType T1 = Args[0]->getType();
6588 // -- If T1 is a complete class type or a class currently being
6589 // defined, the set of member candidates is the result of the
6590 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6591 // the set of member candidates is empty.
6592 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6593 // Complete the type if it can be completed.
6594 RequireCompleteType(OpLoc, T1, 0);
6595 // If the type is neither complete nor being defined, bail out now.
6596 if (!T1Rec->getDecl()->getDefinition())
6599 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6600 LookupQualifiedName(Operators, T1Rec->getDecl());
6601 Operators.suppressDiagnostics();
6603 for (LookupResult::iterator Oper = Operators.begin(),
6604 OperEnd = Operators.end();
6607 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6608 Args[0]->Classify(Context),
6611 /* SuppressUserConversions = */ false);
6615 /// AddBuiltinCandidate - Add a candidate for a built-in
6616 /// operator. ResultTy and ParamTys are the result and parameter types
6617 /// of the built-in candidate, respectively. Args and NumArgs are the
6618 /// arguments being passed to the candidate. IsAssignmentOperator
6619 /// should be true when this built-in candidate is an assignment
6620 /// operator. NumContextualBoolArguments is the number of arguments
6621 /// (at the beginning of the argument list) that will be contextually
6622 /// converted to bool.
6623 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6624 ArrayRef<Expr *> Args,
6625 OverloadCandidateSet& CandidateSet,
6626 bool IsAssignmentOperator,
6627 unsigned NumContextualBoolArguments) {
6628 // Overload resolution is always an unevaluated context.
6629 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6631 // Add this candidate
6632 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6633 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6634 Candidate.Function = nullptr;
6635 Candidate.IsSurrogate = false;
6636 Candidate.IgnoreObjectArgument = false;
6637 Candidate.BuiltinTypes.ResultTy = ResultTy;
6638 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6639 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6641 // Determine the implicit conversion sequences for each of the
6643 Candidate.Viable = true;
6644 Candidate.ExplicitCallArguments = Args.size();
6645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6646 // C++ [over.match.oper]p4:
6647 // For the built-in assignment operators, conversions of the
6648 // left operand are restricted as follows:
6649 // -- no temporaries are introduced to hold the left operand, and
6650 // -- no user-defined conversions are applied to the left
6651 // operand to achieve a type match with the left-most
6652 // parameter of a built-in candidate.
6654 // We block these conversions by turning off user-defined
6655 // conversions, since that is the only way that initialization of
6656 // a reference to a non-class type can occur from something that
6657 // is not of the same type.
6658 if (ArgIdx < NumContextualBoolArguments) {
6659 assert(ParamTys[ArgIdx] == Context.BoolTy &&
6660 "Contextual conversion to bool requires bool type");
6661 Candidate.Conversions[ArgIdx]
6662 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6664 Candidate.Conversions[ArgIdx]
6665 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6666 ArgIdx == 0 && IsAssignmentOperator,
6667 /*InOverloadResolution=*/false,
6668 /*AllowObjCWritebackConversion=*/
6669 getLangOpts().ObjCAutoRefCount);
6671 if (Candidate.Conversions[ArgIdx].isBad()) {
6672 Candidate.Viable = false;
6673 Candidate.FailureKind = ovl_fail_bad_conversion;
6681 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6682 /// candidate operator functions for built-in operators (C++
6683 /// [over.built]). The types are separated into pointer types and
6684 /// enumeration types.
6685 class BuiltinCandidateTypeSet {
6686 /// TypeSet - A set of types.
6687 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6689 /// PointerTypes - The set of pointer types that will be used in the
6690 /// built-in candidates.
6691 TypeSet PointerTypes;
6693 /// MemberPointerTypes - The set of member pointer types that will be
6694 /// used in the built-in candidates.
6695 TypeSet MemberPointerTypes;
6697 /// EnumerationTypes - The set of enumeration types that will be
6698 /// used in the built-in candidates.
6699 TypeSet EnumerationTypes;
6701 /// \brief The set of vector types that will be used in the built-in
6703 TypeSet VectorTypes;
6705 /// \brief A flag indicating non-record types are viable candidates
6706 bool HasNonRecordTypes;
6708 /// \brief A flag indicating whether either arithmetic or enumeration types
6709 /// were present in the candidate set.
6710 bool HasArithmeticOrEnumeralTypes;
6712 /// \brief A flag indicating whether the nullptr type was present in the
6714 bool HasNullPtrType;
6716 /// Sema - The semantic analysis instance where we are building the
6717 /// candidate type set.
6720 /// Context - The AST context in which we will build the type sets.
6721 ASTContext &Context;
6723 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6724 const Qualifiers &VisibleQuals);
6725 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6728 /// iterator - Iterates through the types that are part of the set.
6729 typedef TypeSet::iterator iterator;
6731 BuiltinCandidateTypeSet(Sema &SemaRef)
6732 : HasNonRecordTypes(false),
6733 HasArithmeticOrEnumeralTypes(false),
6734 HasNullPtrType(false),
6736 Context(SemaRef.Context) { }
6738 void AddTypesConvertedFrom(QualType Ty,
6740 bool AllowUserConversions,
6741 bool AllowExplicitConversions,
6742 const Qualifiers &VisibleTypeConversionsQuals);
6744 /// pointer_begin - First pointer type found;
6745 iterator pointer_begin() { return PointerTypes.begin(); }
6747 /// pointer_end - Past the last pointer type found;
6748 iterator pointer_end() { return PointerTypes.end(); }
6750 /// member_pointer_begin - First member pointer type found;
6751 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6753 /// member_pointer_end - Past the last member pointer type found;
6754 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6756 /// enumeration_begin - First enumeration type found;
6757 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6759 /// enumeration_end - Past the last enumeration type found;
6760 iterator enumeration_end() { return EnumerationTypes.end(); }
6762 iterator vector_begin() { return VectorTypes.begin(); }
6763 iterator vector_end() { return VectorTypes.end(); }
6765 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6766 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6767 bool hasNullPtrType() const { return HasNullPtrType; }
6770 } // end anonymous namespace
6772 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6773 /// the set of pointer types along with any more-qualified variants of
6774 /// that type. For example, if @p Ty is "int const *", this routine
6775 /// will add "int const *", "int const volatile *", "int const
6776 /// restrict *", and "int const volatile restrict *" to the set of
6777 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6778 /// false otherwise.
6780 /// FIXME: what to do about extended qualifiers?
6782 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6783 const Qualifiers &VisibleQuals) {
6785 // Insert this type.
6786 if (!PointerTypes.insert(Ty).second)
6790 const PointerType *PointerTy = Ty->getAs<PointerType>();
6791 bool buildObjCPtr = false;
6793 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6794 PointeeTy = PTy->getPointeeType();
6795 buildObjCPtr = true;
6797 PointeeTy = PointerTy->getPointeeType();
6800 // Don't add qualified variants of arrays. For one, they're not allowed
6801 // (the qualifier would sink to the element type), and for another, the
6802 // only overload situation where it matters is subscript or pointer +- int,
6803 // and those shouldn't have qualifier variants anyway.
6804 if (PointeeTy->isArrayType())
6807 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6808 bool hasVolatile = VisibleQuals.hasVolatile();
6809 bool hasRestrict = VisibleQuals.hasRestrict();
6811 // Iterate through all strict supersets of BaseCVR.
6812 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6813 if ((CVR | BaseCVR) != CVR) continue;
6814 // Skip over volatile if no volatile found anywhere in the types.
6815 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6817 // Skip over restrict if no restrict found anywhere in the types, or if
6818 // the type cannot be restrict-qualified.
6819 if ((CVR & Qualifiers::Restrict) &&
6821 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6824 // Build qualified pointee type.
6825 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6827 // Build qualified pointer type.
6828 QualType QPointerTy;
6830 QPointerTy = Context.getPointerType(QPointeeTy);
6832 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6834 // Insert qualified pointer type.
6835 PointerTypes.insert(QPointerTy);
6841 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6842 /// to the set of pointer types along with any more-qualified variants of
6843 /// that type. For example, if @p Ty is "int const *", this routine
6844 /// will add "int const *", "int const volatile *", "int const
6845 /// restrict *", and "int const volatile restrict *" to the set of
6846 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6847 /// false otherwise.
6849 /// FIXME: what to do about extended qualifiers?
6851 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6853 // Insert this type.
6854 if (!MemberPointerTypes.insert(Ty).second)
6857 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6858 assert(PointerTy && "type was not a member pointer type!");
6860 QualType PointeeTy = PointerTy->getPointeeType();
6861 // Don't add qualified variants of arrays. For one, they're not allowed
6862 // (the qualifier would sink to the element type), and for another, the
6863 // only overload situation where it matters is subscript or pointer +- int,
6864 // and those shouldn't have qualifier variants anyway.
6865 if (PointeeTy->isArrayType())
6867 const Type *ClassTy = PointerTy->getClass();
6869 // Iterate through all strict supersets of the pointee type's CVR
6871 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6872 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6873 if ((CVR | BaseCVR) != CVR) continue;
6875 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6876 MemberPointerTypes.insert(
6877 Context.getMemberPointerType(QPointeeTy, ClassTy));
6883 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6884 /// Ty can be implicit converted to the given set of @p Types. We're
6885 /// primarily interested in pointer types and enumeration types. We also
6886 /// take member pointer types, for the conditional operator.
6887 /// AllowUserConversions is true if we should look at the conversion
6888 /// functions of a class type, and AllowExplicitConversions if we
6889 /// should also include the explicit conversion functions of a class
6892 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6894 bool AllowUserConversions,
6895 bool AllowExplicitConversions,
6896 const Qualifiers &VisibleQuals) {
6897 // Only deal with canonical types.
6898 Ty = Context.getCanonicalType(Ty);
6900 // Look through reference types; they aren't part of the type of an
6901 // expression for the purposes of conversions.
6902 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6903 Ty = RefTy->getPointeeType();
6905 // If we're dealing with an array type, decay to the pointer.
6906 if (Ty->isArrayType())
6907 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6909 // Otherwise, we don't care about qualifiers on the type.
6910 Ty = Ty.getLocalUnqualifiedType();
6912 // Flag if we ever add a non-record type.
6913 const RecordType *TyRec = Ty->getAs<RecordType>();
6914 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6916 // Flag if we encounter an arithmetic type.
6917 HasArithmeticOrEnumeralTypes =
6918 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6920 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6921 PointerTypes.insert(Ty);
6922 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6923 // Insert our type, and its more-qualified variants, into the set
6925 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6927 } else if (Ty->isMemberPointerType()) {
6928 // Member pointers are far easier, since the pointee can't be converted.
6929 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6931 } else if (Ty->isEnumeralType()) {
6932 HasArithmeticOrEnumeralTypes = true;
6933 EnumerationTypes.insert(Ty);
6934 } else if (Ty->isVectorType()) {
6935 // We treat vector types as arithmetic types in many contexts as an
6937 HasArithmeticOrEnumeralTypes = true;
6938 VectorTypes.insert(Ty);
6939 } else if (Ty->isNullPtrType()) {
6940 HasNullPtrType = true;
6941 } else if (AllowUserConversions && TyRec) {
6942 // No conversion functions in incomplete types.
6943 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6946 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6947 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6948 if (isa<UsingShadowDecl>(D))
6949 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6951 // Skip conversion function templates; they don't tell us anything
6952 // about which builtin types we can convert to.
6953 if (isa<FunctionTemplateDecl>(D))
6956 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6957 if (AllowExplicitConversions || !Conv->isExplicit()) {
6958 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6965 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6966 /// the volatile- and non-volatile-qualified assignment operators for the
6967 /// given type to the candidate set.
6968 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6970 ArrayRef<Expr *> Args,
6971 OverloadCandidateSet &CandidateSet) {
6972 QualType ParamTypes[2];
6974 // T& operator=(T&, T)
6975 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6977 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6978 /*IsAssignmentOperator=*/true);
6980 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6981 // volatile T& operator=(volatile T&, T)
6983 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6986 /*IsAssignmentOperator=*/true);
6990 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6991 /// if any, found in visible type conversion functions found in ArgExpr's type.
6992 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6994 const RecordType *TyRec;
6995 if (const MemberPointerType *RHSMPType =
6996 ArgExpr->getType()->getAs<MemberPointerType>())
6997 TyRec = RHSMPType->getClass()->getAs<RecordType>();
6999 TyRec = ArgExpr->getType()->getAs<RecordType>();
7001 // Just to be safe, assume the worst case.
7002 VRQuals.addVolatile();
7003 VRQuals.addRestrict();
7007 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7008 if (!ClassDecl->hasDefinition())
7011 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7012 if (isa<UsingShadowDecl>(D))
7013 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7014 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7015 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7016 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7017 CanTy = ResTypeRef->getPointeeType();
7018 // Need to go down the pointer/mempointer chain and add qualifiers
7022 if (CanTy.isRestrictQualified())
7023 VRQuals.addRestrict();
7024 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7025 CanTy = ResTypePtr->getPointeeType();
7026 else if (const MemberPointerType *ResTypeMPtr =
7027 CanTy->getAs<MemberPointerType>())
7028 CanTy = ResTypeMPtr->getPointeeType();
7031 if (CanTy.isVolatileQualified())
7032 VRQuals.addVolatile();
7033 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7043 /// \brief Helper class to manage the addition of builtin operator overload
7044 /// candidates. It provides shared state and utility methods used throughout
7045 /// the process, as well as a helper method to add each group of builtin
7046 /// operator overloads from the standard to a candidate set.
7047 class BuiltinOperatorOverloadBuilder {
7048 // Common instance state available to all overload candidate addition methods.
7050 ArrayRef<Expr *> Args;
7051 Qualifiers VisibleTypeConversionsQuals;
7052 bool HasArithmeticOrEnumeralCandidateType;
7053 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7054 OverloadCandidateSet &CandidateSet;
7056 // Define some constants used to index and iterate over the arithemetic types
7057 // provided via the getArithmeticType() method below.
7058 // The "promoted arithmetic types" are the arithmetic
7059 // types are that preserved by promotion (C++ [over.built]p2).
7060 static const unsigned FirstIntegralType = 3;
7061 static const unsigned LastIntegralType = 20;
7062 static const unsigned FirstPromotedIntegralType = 3,
7063 LastPromotedIntegralType = 11;
7064 static const unsigned FirstPromotedArithmeticType = 0,
7065 LastPromotedArithmeticType = 11;
7066 static const unsigned NumArithmeticTypes = 20;
7068 /// \brief Get the canonical type for a given arithmetic type index.
7069 CanQualType getArithmeticType(unsigned index) {
7070 assert(index < NumArithmeticTypes);
7071 static CanQualType ASTContext::* const
7072 ArithmeticTypes[NumArithmeticTypes] = {
7073 // Start of promoted types.
7074 &ASTContext::FloatTy,
7075 &ASTContext::DoubleTy,
7076 &ASTContext::LongDoubleTy,
7078 // Start of integral types.
7080 &ASTContext::LongTy,
7081 &ASTContext::LongLongTy,
7082 &ASTContext::Int128Ty,
7083 &ASTContext::UnsignedIntTy,
7084 &ASTContext::UnsignedLongTy,
7085 &ASTContext::UnsignedLongLongTy,
7086 &ASTContext::UnsignedInt128Ty,
7087 // End of promoted types.
7089 &ASTContext::BoolTy,
7090 &ASTContext::CharTy,
7091 &ASTContext::WCharTy,
7092 &ASTContext::Char16Ty,
7093 &ASTContext::Char32Ty,
7094 &ASTContext::SignedCharTy,
7095 &ASTContext::ShortTy,
7096 &ASTContext::UnsignedCharTy,
7097 &ASTContext::UnsignedShortTy,
7098 // End of integral types.
7099 // FIXME: What about complex? What about half?
7101 return S.Context.*ArithmeticTypes[index];
7104 /// \brief Gets the canonical type resulting from the usual arithemetic
7105 /// converions for the given arithmetic types.
7106 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7107 // Accelerator table for performing the usual arithmetic conversions.
7108 // The rules are basically:
7109 // - if either is floating-point, use the wider floating-point
7110 // - if same signedness, use the higher rank
7111 // - if same size, use unsigned of the higher rank
7112 // - use the larger type
7113 // These rules, together with the axiom that higher ranks are
7114 // never smaller, are sufficient to precompute all of these results
7115 // *except* when dealing with signed types of higher rank.
7116 // (we could precompute SLL x UI for all known platforms, but it's
7117 // better not to make any assumptions).
7118 // We assume that int128 has a higher rank than long long on all platforms.
7121 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7123 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7124 [LastPromotedArithmeticType] = {
7125 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7126 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7127 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7128 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7129 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7130 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7131 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7132 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7133 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7134 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7135 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7138 assert(L < LastPromotedArithmeticType);
7139 assert(R < LastPromotedArithmeticType);
7140 int Idx = ConversionsTable[L][R];
7142 // Fast path: the table gives us a concrete answer.
7143 if (Idx != Dep) return getArithmeticType(Idx);
7145 // Slow path: we need to compare widths.
7146 // An invariant is that the signed type has higher rank.
7147 CanQualType LT = getArithmeticType(L),
7148 RT = getArithmeticType(R);
7149 unsigned LW = S.Context.getIntWidth(LT),
7150 RW = S.Context.getIntWidth(RT);
7152 // If they're different widths, use the signed type.
7153 if (LW > RW) return LT;
7154 else if (LW < RW) return RT;
7156 // Otherwise, use the unsigned type of the signed type's rank.
7157 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7158 assert(L == SLL || R == SLL);
7159 return S.Context.UnsignedLongLongTy;
7162 /// \brief Helper method to factor out the common pattern of adding overloads
7163 /// for '++' and '--' builtin operators.
7164 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7167 QualType ParamTypes[2] = {
7168 S.Context.getLValueReferenceType(CandidateTy),
7172 // Non-volatile version.
7173 if (Args.size() == 1)
7174 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7176 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7178 // Use a heuristic to reduce number of builtin candidates in the set:
7179 // add volatile version only if there are conversions to a volatile type.
7182 S.Context.getLValueReferenceType(
7183 S.Context.getVolatileType(CandidateTy));
7184 if (Args.size() == 1)
7185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7187 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7190 // Add restrict version only if there are conversions to a restrict type
7191 // and our candidate type is a non-restrict-qualified pointer.
7192 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7193 !CandidateTy.isRestrictQualified()) {
7195 = S.Context.getLValueReferenceType(
7196 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7197 if (Args.size() == 1)
7198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7200 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7204 = S.Context.getLValueReferenceType(
7205 S.Context.getCVRQualifiedType(CandidateTy,
7206 (Qualifiers::Volatile |
7207 Qualifiers::Restrict)));
7208 if (Args.size() == 1)
7209 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7211 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7218 BuiltinOperatorOverloadBuilder(
7219 Sema &S, ArrayRef<Expr *> Args,
7220 Qualifiers VisibleTypeConversionsQuals,
7221 bool HasArithmeticOrEnumeralCandidateType,
7222 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7223 OverloadCandidateSet &CandidateSet)
7225 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7226 HasArithmeticOrEnumeralCandidateType(
7227 HasArithmeticOrEnumeralCandidateType),
7228 CandidateTypes(CandidateTypes),
7229 CandidateSet(CandidateSet) {
7230 // Validate some of our static helper constants in debug builds.
7231 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7232 "Invalid first promoted integral type");
7233 assert(getArithmeticType(LastPromotedIntegralType - 1)
7234 == S.Context.UnsignedInt128Ty &&
7235 "Invalid last promoted integral type");
7236 assert(getArithmeticType(FirstPromotedArithmeticType)
7237 == S.Context.FloatTy &&
7238 "Invalid first promoted arithmetic type");
7239 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7240 == S.Context.UnsignedInt128Ty &&
7241 "Invalid last promoted arithmetic type");
7244 // C++ [over.built]p3:
7246 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7247 // is either volatile or empty, there exist candidate operator
7248 // functions of the form
7250 // VQ T& operator++(VQ T&);
7251 // T operator++(VQ T&, int);
7253 // C++ [over.built]p4:
7255 // For every pair (T, VQ), where T is an arithmetic type other
7256 // than bool, and VQ is either volatile or empty, there exist
7257 // candidate operator functions of the form
7259 // VQ T& operator--(VQ T&);
7260 // T operator--(VQ T&, int);
7261 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7262 if (!HasArithmeticOrEnumeralCandidateType)
7265 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7266 Arith < NumArithmeticTypes; ++Arith) {
7267 addPlusPlusMinusMinusStyleOverloads(
7268 getArithmeticType(Arith),
7269 VisibleTypeConversionsQuals.hasVolatile(),
7270 VisibleTypeConversionsQuals.hasRestrict());
7274 // C++ [over.built]p5:
7276 // For every pair (T, VQ), where T is a cv-qualified or
7277 // cv-unqualified object type, and VQ is either volatile or
7278 // empty, there exist candidate operator functions of the form
7280 // T*VQ& operator++(T*VQ&);
7281 // T*VQ& operator--(T*VQ&);
7282 // T* operator++(T*VQ&, int);
7283 // T* operator--(T*VQ&, int);
7284 void addPlusPlusMinusMinusPointerOverloads() {
7285 for (BuiltinCandidateTypeSet::iterator
7286 Ptr = CandidateTypes[0].pointer_begin(),
7287 PtrEnd = CandidateTypes[0].pointer_end();
7288 Ptr != PtrEnd; ++Ptr) {
7289 // Skip pointer types that aren't pointers to object types.
7290 if (!(*Ptr)->getPointeeType()->isObjectType())
7293 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7294 (!(*Ptr).isVolatileQualified() &&
7295 VisibleTypeConversionsQuals.hasVolatile()),
7296 (!(*Ptr).isRestrictQualified() &&
7297 VisibleTypeConversionsQuals.hasRestrict()));
7301 // C++ [over.built]p6:
7302 // For every cv-qualified or cv-unqualified object type T, there
7303 // exist candidate operator functions of the form
7305 // T& operator*(T*);
7307 // C++ [over.built]p7:
7308 // For every function type T that does not have cv-qualifiers or a
7309 // ref-qualifier, there exist candidate operator functions of the form
7310 // T& operator*(T*);
7311 void addUnaryStarPointerOverloads() {
7312 for (BuiltinCandidateTypeSet::iterator
7313 Ptr = CandidateTypes[0].pointer_begin(),
7314 PtrEnd = CandidateTypes[0].pointer_end();
7315 Ptr != PtrEnd; ++Ptr) {
7316 QualType ParamTy = *Ptr;
7317 QualType PointeeTy = ParamTy->getPointeeType();
7318 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7321 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7322 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7325 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7326 &ParamTy, Args, CandidateSet);
7330 // C++ [over.built]p9:
7331 // For every promoted arithmetic type T, there exist candidate
7332 // operator functions of the form
7336 void addUnaryPlusOrMinusArithmeticOverloads() {
7337 if (!HasArithmeticOrEnumeralCandidateType)
7340 for (unsigned Arith = FirstPromotedArithmeticType;
7341 Arith < LastPromotedArithmeticType; ++Arith) {
7342 QualType ArithTy = getArithmeticType(Arith);
7343 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7346 // Extension: We also add these operators for vector types.
7347 for (BuiltinCandidateTypeSet::iterator
7348 Vec = CandidateTypes[0].vector_begin(),
7349 VecEnd = CandidateTypes[0].vector_end();
7350 Vec != VecEnd; ++Vec) {
7351 QualType VecTy = *Vec;
7352 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7356 // C++ [over.built]p8:
7357 // For every type T, there exist candidate operator functions of
7360 // T* operator+(T*);
7361 void addUnaryPlusPointerOverloads() {
7362 for (BuiltinCandidateTypeSet::iterator
7363 Ptr = CandidateTypes[0].pointer_begin(),
7364 PtrEnd = CandidateTypes[0].pointer_end();
7365 Ptr != PtrEnd; ++Ptr) {
7366 QualType ParamTy = *Ptr;
7367 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7371 // C++ [over.built]p10:
7372 // For every promoted integral type T, there exist candidate
7373 // operator functions of the form
7376 void addUnaryTildePromotedIntegralOverloads() {
7377 if (!HasArithmeticOrEnumeralCandidateType)
7380 for (unsigned Int = FirstPromotedIntegralType;
7381 Int < LastPromotedIntegralType; ++Int) {
7382 QualType IntTy = getArithmeticType(Int);
7383 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7386 // Extension: We also add this operator for vector types.
7387 for (BuiltinCandidateTypeSet::iterator
7388 Vec = CandidateTypes[0].vector_begin(),
7389 VecEnd = CandidateTypes[0].vector_end();
7390 Vec != VecEnd; ++Vec) {
7391 QualType VecTy = *Vec;
7392 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7396 // C++ [over.match.oper]p16:
7397 // For every pointer to member type T, there exist candidate operator
7398 // functions of the form
7400 // bool operator==(T,T);
7401 // bool operator!=(T,T);
7402 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7403 /// Set of (canonical) types that we've already handled.
7404 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7406 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7407 for (BuiltinCandidateTypeSet::iterator
7408 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7409 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7410 MemPtr != MemPtrEnd;
7412 // Don't add the same builtin candidate twice.
7413 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7416 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7417 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7422 // C++ [over.built]p15:
7424 // For every T, where T is an enumeration type, a pointer type, or
7425 // std::nullptr_t, there exist candidate operator functions of the form
7427 // bool operator<(T, T);
7428 // bool operator>(T, T);
7429 // bool operator<=(T, T);
7430 // bool operator>=(T, T);
7431 // bool operator==(T, T);
7432 // bool operator!=(T, T);
7433 void addRelationalPointerOrEnumeralOverloads() {
7434 // C++ [over.match.oper]p3:
7435 // [...]the built-in candidates include all of the candidate operator
7436 // functions defined in 13.6 that, compared to the given operator, [...]
7437 // do not have the same parameter-type-list as any non-template non-member
7440 // Note that in practice, this only affects enumeration types because there
7441 // aren't any built-in candidates of record type, and a user-defined operator
7442 // must have an operand of record or enumeration type. Also, the only other
7443 // overloaded operator with enumeration arguments, operator=,
7444 // cannot be overloaded for enumeration types, so this is the only place
7445 // where we must suppress candidates like this.
7446 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7447 UserDefinedBinaryOperators;
7449 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7450 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7451 CandidateTypes[ArgIdx].enumeration_end()) {
7452 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7453 CEnd = CandidateSet.end();
7455 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7458 if (C->Function->isFunctionTemplateSpecialization())
7461 QualType FirstParamType =
7462 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7463 QualType SecondParamType =
7464 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7466 // Skip if either parameter isn't of enumeral type.
7467 if (!FirstParamType->isEnumeralType() ||
7468 !SecondParamType->isEnumeralType())
7471 // Add this operator to the set of known user-defined operators.
7472 UserDefinedBinaryOperators.insert(
7473 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7474 S.Context.getCanonicalType(SecondParamType)));
7479 /// Set of (canonical) types that we've already handled.
7480 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7482 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7483 for (BuiltinCandidateTypeSet::iterator
7484 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7485 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7486 Ptr != PtrEnd; ++Ptr) {
7487 // Don't add the same builtin candidate twice.
7488 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7491 QualType ParamTypes[2] = { *Ptr, *Ptr };
7492 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7494 for (BuiltinCandidateTypeSet::iterator
7495 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7496 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7497 Enum != EnumEnd; ++Enum) {
7498 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7500 // Don't add the same builtin candidate twice, or if a user defined
7501 // candidate exists.
7502 if (!AddedTypes.insert(CanonType).second ||
7503 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7507 QualType ParamTypes[2] = { *Enum, *Enum };
7508 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7511 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7512 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7513 if (AddedTypes.insert(NullPtrTy).second &&
7514 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7516 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7517 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7524 // C++ [over.built]p13:
7526 // For every cv-qualified or cv-unqualified object type T
7527 // there exist candidate operator functions of the form
7529 // T* operator+(T*, ptrdiff_t);
7530 // T& operator[](T*, ptrdiff_t); [BELOW]
7531 // T* operator-(T*, ptrdiff_t);
7532 // T* operator+(ptrdiff_t, T*);
7533 // T& operator[](ptrdiff_t, T*); [BELOW]
7535 // C++ [over.built]p14:
7537 // For every T, where T is a pointer to object type, there
7538 // exist candidate operator functions of the form
7540 // ptrdiff_t operator-(T, T);
7541 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7542 /// Set of (canonical) types that we've already handled.
7543 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7545 for (int Arg = 0; Arg < 2; ++Arg) {
7546 QualType AsymetricParamTypes[2] = {
7547 S.Context.getPointerDiffType(),
7548 S.Context.getPointerDiffType(),
7550 for (BuiltinCandidateTypeSet::iterator
7551 Ptr = CandidateTypes[Arg].pointer_begin(),
7552 PtrEnd = CandidateTypes[Arg].pointer_end();
7553 Ptr != PtrEnd; ++Ptr) {
7554 QualType PointeeTy = (*Ptr)->getPointeeType();
7555 if (!PointeeTy->isObjectType())
7558 AsymetricParamTypes[Arg] = *Ptr;
7559 if (Arg == 0 || Op == OO_Plus) {
7560 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7561 // T* operator+(ptrdiff_t, T*);
7562 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7564 if (Op == OO_Minus) {
7565 // ptrdiff_t operator-(T, T);
7566 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7569 QualType ParamTypes[2] = { *Ptr, *Ptr };
7570 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7571 Args, CandidateSet);
7577 // C++ [over.built]p12:
7579 // For every pair of promoted arithmetic types L and R, there
7580 // exist candidate operator functions of the form
7582 // LR operator*(L, R);
7583 // LR operator/(L, R);
7584 // LR operator+(L, R);
7585 // LR operator-(L, R);
7586 // bool operator<(L, R);
7587 // bool operator>(L, R);
7588 // bool operator<=(L, R);
7589 // bool operator>=(L, R);
7590 // bool operator==(L, R);
7591 // bool operator!=(L, R);
7593 // where LR is the result of the usual arithmetic conversions
7594 // between types L and R.
7596 // C++ [over.built]p24:
7598 // For every pair of promoted arithmetic types L and R, there exist
7599 // candidate operator functions of the form
7601 // LR operator?(bool, L, R);
7603 // where LR is the result of the usual arithmetic conversions
7604 // between types L and R.
7605 // Our candidates ignore the first parameter.
7606 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7607 if (!HasArithmeticOrEnumeralCandidateType)
7610 for (unsigned Left = FirstPromotedArithmeticType;
7611 Left < LastPromotedArithmeticType; ++Left) {
7612 for (unsigned Right = FirstPromotedArithmeticType;
7613 Right < LastPromotedArithmeticType; ++Right) {
7614 QualType LandR[2] = { getArithmeticType(Left),
7615 getArithmeticType(Right) };
7617 isComparison ? S.Context.BoolTy
7618 : getUsualArithmeticConversions(Left, Right);
7619 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7623 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7624 // conditional operator for vector types.
7625 for (BuiltinCandidateTypeSet::iterator
7626 Vec1 = CandidateTypes[0].vector_begin(),
7627 Vec1End = CandidateTypes[0].vector_end();
7628 Vec1 != Vec1End; ++Vec1) {
7629 for (BuiltinCandidateTypeSet::iterator
7630 Vec2 = CandidateTypes[1].vector_begin(),
7631 Vec2End = CandidateTypes[1].vector_end();
7632 Vec2 != Vec2End; ++Vec2) {
7633 QualType LandR[2] = { *Vec1, *Vec2 };
7634 QualType Result = S.Context.BoolTy;
7635 if (!isComparison) {
7636 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7642 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7647 // C++ [over.built]p17:
7649 // For every pair of promoted integral types L and R, there
7650 // exist candidate operator functions of the form
7652 // LR operator%(L, R);
7653 // LR operator&(L, R);
7654 // LR operator^(L, R);
7655 // LR operator|(L, R);
7656 // L operator<<(L, R);
7657 // L operator>>(L, R);
7659 // where LR is the result of the usual arithmetic conversions
7660 // between types L and R.
7661 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7662 if (!HasArithmeticOrEnumeralCandidateType)
7665 for (unsigned Left = FirstPromotedIntegralType;
7666 Left < LastPromotedIntegralType; ++Left) {
7667 for (unsigned Right = FirstPromotedIntegralType;
7668 Right < LastPromotedIntegralType; ++Right) {
7669 QualType LandR[2] = { getArithmeticType(Left),
7670 getArithmeticType(Right) };
7671 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7673 : getUsualArithmeticConversions(Left, Right);
7674 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7679 // C++ [over.built]p20:
7681 // For every pair (T, VQ), where T is an enumeration or
7682 // pointer to member type and VQ is either volatile or
7683 // empty, there exist candidate operator functions of the form
7685 // VQ T& operator=(VQ T&, T);
7686 void addAssignmentMemberPointerOrEnumeralOverloads() {
7687 /// Set of (canonical) types that we've already handled.
7688 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7690 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7691 for (BuiltinCandidateTypeSet::iterator
7692 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7693 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7694 Enum != EnumEnd; ++Enum) {
7695 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7698 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7701 for (BuiltinCandidateTypeSet::iterator
7702 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7703 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7704 MemPtr != MemPtrEnd; ++MemPtr) {
7705 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7708 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7713 // C++ [over.built]p19:
7715 // For every pair (T, VQ), where T is any type and VQ is either
7716 // volatile or empty, there exist candidate operator functions
7719 // T*VQ& operator=(T*VQ&, T*);
7721 // C++ [over.built]p21:
7723 // For every pair (T, VQ), where T is a cv-qualified or
7724 // cv-unqualified object type and VQ is either volatile or
7725 // empty, there exist candidate operator functions of the form
7727 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7728 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7729 void addAssignmentPointerOverloads(bool isEqualOp) {
7730 /// Set of (canonical) types that we've already handled.
7731 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7733 for (BuiltinCandidateTypeSet::iterator
7734 Ptr = CandidateTypes[0].pointer_begin(),
7735 PtrEnd = CandidateTypes[0].pointer_end();
7736 Ptr != PtrEnd; ++Ptr) {
7737 // If this is operator=, keep track of the builtin candidates we added.
7739 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7740 else if (!(*Ptr)->getPointeeType()->isObjectType())
7743 // non-volatile version
7744 QualType ParamTypes[2] = {
7745 S.Context.getLValueReferenceType(*Ptr),
7746 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7748 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7749 /*IsAssigmentOperator=*/ isEqualOp);
7751 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7752 VisibleTypeConversionsQuals.hasVolatile();
7756 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7757 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7758 /*IsAssigmentOperator=*/isEqualOp);
7761 if (!(*Ptr).isRestrictQualified() &&
7762 VisibleTypeConversionsQuals.hasRestrict()) {
7765 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7766 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7767 /*IsAssigmentOperator=*/isEqualOp);
7770 // volatile restrict version
7772 = S.Context.getLValueReferenceType(
7773 S.Context.getCVRQualifiedType(*Ptr,
7774 (Qualifiers::Volatile |
7775 Qualifiers::Restrict)));
7776 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7777 /*IsAssigmentOperator=*/isEqualOp);
7783 for (BuiltinCandidateTypeSet::iterator
7784 Ptr = CandidateTypes[1].pointer_begin(),
7785 PtrEnd = CandidateTypes[1].pointer_end();
7786 Ptr != PtrEnd; ++Ptr) {
7787 // Make sure we don't add the same candidate twice.
7788 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7791 QualType ParamTypes[2] = {
7792 S.Context.getLValueReferenceType(*Ptr),
7796 // non-volatile version
7797 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7798 /*IsAssigmentOperator=*/true);
7800 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7801 VisibleTypeConversionsQuals.hasVolatile();
7805 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7806 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7807 /*IsAssigmentOperator=*/true);
7810 if (!(*Ptr).isRestrictQualified() &&
7811 VisibleTypeConversionsQuals.hasRestrict()) {
7814 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7815 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7816 /*IsAssigmentOperator=*/true);
7819 // volatile restrict version
7821 = S.Context.getLValueReferenceType(
7822 S.Context.getCVRQualifiedType(*Ptr,
7823 (Qualifiers::Volatile |
7824 Qualifiers::Restrict)));
7825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7826 /*IsAssigmentOperator=*/true);
7833 // C++ [over.built]p18:
7835 // For every triple (L, VQ, R), where L is an arithmetic type,
7836 // VQ is either volatile or empty, and R is a promoted
7837 // arithmetic type, there exist candidate operator functions of
7840 // VQ L& operator=(VQ L&, R);
7841 // VQ L& operator*=(VQ L&, R);
7842 // VQ L& operator/=(VQ L&, R);
7843 // VQ L& operator+=(VQ L&, R);
7844 // VQ L& operator-=(VQ L&, R);
7845 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7846 if (!HasArithmeticOrEnumeralCandidateType)
7849 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7850 for (unsigned Right = FirstPromotedArithmeticType;
7851 Right < LastPromotedArithmeticType; ++Right) {
7852 QualType ParamTypes[2];
7853 ParamTypes[1] = getArithmeticType(Right);
7855 // Add this built-in operator as a candidate (VQ is empty).
7857 S.Context.getLValueReferenceType(getArithmeticType(Left));
7858 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7859 /*IsAssigmentOperator=*/isEqualOp);
7861 // Add this built-in operator as a candidate (VQ is 'volatile').
7862 if (VisibleTypeConversionsQuals.hasVolatile()) {
7864 S.Context.getVolatileType(getArithmeticType(Left));
7865 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7866 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7867 /*IsAssigmentOperator=*/isEqualOp);
7872 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7873 for (BuiltinCandidateTypeSet::iterator
7874 Vec1 = CandidateTypes[0].vector_begin(),
7875 Vec1End = CandidateTypes[0].vector_end();
7876 Vec1 != Vec1End; ++Vec1) {
7877 for (BuiltinCandidateTypeSet::iterator
7878 Vec2 = CandidateTypes[1].vector_begin(),
7879 Vec2End = CandidateTypes[1].vector_end();
7880 Vec2 != Vec2End; ++Vec2) {
7881 QualType ParamTypes[2];
7882 ParamTypes[1] = *Vec2;
7883 // Add this built-in operator as a candidate (VQ is empty).
7884 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7885 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7886 /*IsAssigmentOperator=*/isEqualOp);
7888 // Add this built-in operator as a candidate (VQ is 'volatile').
7889 if (VisibleTypeConversionsQuals.hasVolatile()) {
7890 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7891 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7893 /*IsAssigmentOperator=*/isEqualOp);
7899 // C++ [over.built]p22:
7901 // For every triple (L, VQ, R), where L is an integral type, VQ
7902 // is either volatile or empty, and R is a promoted integral
7903 // type, there exist candidate operator functions of the form
7905 // VQ L& operator%=(VQ L&, R);
7906 // VQ L& operator<<=(VQ L&, R);
7907 // VQ L& operator>>=(VQ L&, R);
7908 // VQ L& operator&=(VQ L&, R);
7909 // VQ L& operator^=(VQ L&, R);
7910 // VQ L& operator|=(VQ L&, R);
7911 void addAssignmentIntegralOverloads() {
7912 if (!HasArithmeticOrEnumeralCandidateType)
7915 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7916 for (unsigned Right = FirstPromotedIntegralType;
7917 Right < LastPromotedIntegralType; ++Right) {
7918 QualType ParamTypes[2];
7919 ParamTypes[1] = getArithmeticType(Right);
7921 // Add this built-in operator as a candidate (VQ is empty).
7923 S.Context.getLValueReferenceType(getArithmeticType(Left));
7924 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7925 if (VisibleTypeConversionsQuals.hasVolatile()) {
7926 // Add this built-in operator as a candidate (VQ is 'volatile').
7927 ParamTypes[0] = getArithmeticType(Left);
7928 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7929 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7930 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7936 // C++ [over.operator]p23:
7938 // There also exist candidate operator functions of the form
7940 // bool operator!(bool);
7941 // bool operator&&(bool, bool);
7942 // bool operator||(bool, bool);
7943 void addExclaimOverload() {
7944 QualType ParamTy = S.Context.BoolTy;
7945 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7946 /*IsAssignmentOperator=*/false,
7947 /*NumContextualBoolArguments=*/1);
7949 void addAmpAmpOrPipePipeOverload() {
7950 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7951 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7952 /*IsAssignmentOperator=*/false,
7953 /*NumContextualBoolArguments=*/2);
7956 // C++ [over.built]p13:
7958 // For every cv-qualified or cv-unqualified object type T there
7959 // exist candidate operator functions of the form
7961 // T* operator+(T*, ptrdiff_t); [ABOVE]
7962 // T& operator[](T*, ptrdiff_t);
7963 // T* operator-(T*, ptrdiff_t); [ABOVE]
7964 // T* operator+(ptrdiff_t, T*); [ABOVE]
7965 // T& operator[](ptrdiff_t, T*);
7966 void addSubscriptOverloads() {
7967 for (BuiltinCandidateTypeSet::iterator
7968 Ptr = CandidateTypes[0].pointer_begin(),
7969 PtrEnd = CandidateTypes[0].pointer_end();
7970 Ptr != PtrEnd; ++Ptr) {
7971 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7972 QualType PointeeType = (*Ptr)->getPointeeType();
7973 if (!PointeeType->isObjectType())
7976 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7978 // T& operator[](T*, ptrdiff_t)
7979 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7982 for (BuiltinCandidateTypeSet::iterator
7983 Ptr = CandidateTypes[1].pointer_begin(),
7984 PtrEnd = CandidateTypes[1].pointer_end();
7985 Ptr != PtrEnd; ++Ptr) {
7986 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7987 QualType PointeeType = (*Ptr)->getPointeeType();
7988 if (!PointeeType->isObjectType())
7991 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7993 // T& operator[](ptrdiff_t, T*)
7994 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7998 // C++ [over.built]p11:
7999 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8000 // C1 is the same type as C2 or is a derived class of C2, T is an object
8001 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8002 // there exist candidate operator functions of the form
8004 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8006 // where CV12 is the union of CV1 and CV2.
8007 void addArrowStarOverloads() {
8008 for (BuiltinCandidateTypeSet::iterator
8009 Ptr = CandidateTypes[0].pointer_begin(),
8010 PtrEnd = CandidateTypes[0].pointer_end();
8011 Ptr != PtrEnd; ++Ptr) {
8012 QualType C1Ty = (*Ptr);
8014 QualifierCollector Q1;
8015 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8016 if (!isa<RecordType>(C1))
8018 // heuristic to reduce number of builtin candidates in the set.
8019 // Add volatile/restrict version only if there are conversions to a
8020 // volatile/restrict type.
8021 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8023 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8025 for (BuiltinCandidateTypeSet::iterator
8026 MemPtr = CandidateTypes[1].member_pointer_begin(),
8027 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8028 MemPtr != MemPtrEnd; ++MemPtr) {
8029 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8030 QualType C2 = QualType(mptr->getClass(), 0);
8031 C2 = C2.getUnqualifiedType();
8032 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8034 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8036 QualType T = mptr->getPointeeType();
8037 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8038 T.isVolatileQualified())
8040 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8041 T.isRestrictQualified())
8043 T = Q1.apply(S.Context, T);
8044 QualType ResultTy = S.Context.getLValueReferenceType(T);
8045 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8050 // Note that we don't consider the first argument, since it has been
8051 // contextually converted to bool long ago. The candidates below are
8052 // therefore added as binary.
8054 // C++ [over.built]p25:
8055 // For every type T, where T is a pointer, pointer-to-member, or scoped
8056 // enumeration type, there exist candidate operator functions of the form
8058 // T operator?(bool, T, T);
8060 void addConditionalOperatorOverloads() {
8061 /// Set of (canonical) types that we've already handled.
8062 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8064 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8065 for (BuiltinCandidateTypeSet::iterator
8066 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8067 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8068 Ptr != PtrEnd; ++Ptr) {
8069 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8072 QualType ParamTypes[2] = { *Ptr, *Ptr };
8073 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8076 for (BuiltinCandidateTypeSet::iterator
8077 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8078 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8079 MemPtr != MemPtrEnd; ++MemPtr) {
8080 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8083 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8084 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8087 if (S.getLangOpts().CPlusPlus11) {
8088 for (BuiltinCandidateTypeSet::iterator
8089 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8090 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8091 Enum != EnumEnd; ++Enum) {
8092 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8095 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8098 QualType ParamTypes[2] = { *Enum, *Enum };
8099 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8106 } // end anonymous namespace
8108 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8109 /// operator overloads to the candidate set (C++ [over.built]), based
8110 /// on the operator @p Op and the arguments given. For example, if the
8111 /// operator is a binary '+', this routine might add "int
8112 /// operator+(int, int)" to cover integer addition.
8113 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8114 SourceLocation OpLoc,
8115 ArrayRef<Expr *> Args,
8116 OverloadCandidateSet &CandidateSet) {
8117 // Find all of the types that the arguments can convert to, but only
8118 // if the operator we're looking at has built-in operator candidates
8119 // that make use of these types. Also record whether we encounter non-record
8120 // candidate types or either arithmetic or enumeral candidate types.
8121 Qualifiers VisibleTypeConversionsQuals;
8122 VisibleTypeConversionsQuals.addConst();
8123 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8124 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8126 bool HasNonRecordCandidateType = false;
8127 bool HasArithmeticOrEnumeralCandidateType = false;
8128 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8129 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8130 CandidateTypes.emplace_back(*this);
8131 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8134 (Op == OO_Exclaim ||
8137 VisibleTypeConversionsQuals);
8138 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8139 CandidateTypes[ArgIdx].hasNonRecordTypes();
8140 HasArithmeticOrEnumeralCandidateType =
8141 HasArithmeticOrEnumeralCandidateType ||
8142 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8145 // Exit early when no non-record types have been added to the candidate set
8146 // for any of the arguments to the operator.
8148 // We can't exit early for !, ||, or &&, since there we have always have
8149 // 'bool' overloads.
8150 if (!HasNonRecordCandidateType &&
8151 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8154 // Setup an object to manage the common state for building overloads.
8155 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8156 VisibleTypeConversionsQuals,
8157 HasArithmeticOrEnumeralCandidateType,
8158 CandidateTypes, CandidateSet);
8160 // Dispatch over the operation to add in only those overloads which apply.
8163 case NUM_OVERLOADED_OPERATORS:
8164 llvm_unreachable("Expected an overloaded operator");
8169 case OO_Array_Delete:
8172 "Special operators don't use AddBuiltinOperatorCandidates");
8176 // C++ [over.match.oper]p3:
8177 // -- For the operator ',', the unary operator '&', or the
8178 // operator '->', the built-in candidates set is empty.
8181 case OO_Plus: // '+' is either unary or binary
8182 if (Args.size() == 1)
8183 OpBuilder.addUnaryPlusPointerOverloads();
8186 case OO_Minus: // '-' is either unary or binary
8187 if (Args.size() == 1) {
8188 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8190 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8191 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8195 case OO_Star: // '*' is either unary or binary
8196 if (Args.size() == 1)
8197 OpBuilder.addUnaryStarPointerOverloads();
8199 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8203 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8208 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8209 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8213 case OO_ExclaimEqual:
8214 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8220 case OO_GreaterEqual:
8221 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8222 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8229 case OO_GreaterGreater:
8230 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8233 case OO_Amp: // '&' is either unary or binary
8234 if (Args.size() == 1)
8235 // C++ [over.match.oper]p3:
8236 // -- For the operator ',', the unary operator '&', or the
8237 // operator '->', the built-in candidates set is empty.
8240 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8244 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8248 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8253 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8258 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8261 case OO_PercentEqual:
8262 case OO_LessLessEqual:
8263 case OO_GreaterGreaterEqual:
8267 OpBuilder.addAssignmentIntegralOverloads();
8271 OpBuilder.addExclaimOverload();
8276 OpBuilder.addAmpAmpOrPipePipeOverload();
8280 OpBuilder.addSubscriptOverloads();
8284 OpBuilder.addArrowStarOverloads();
8287 case OO_Conditional:
8288 OpBuilder.addConditionalOperatorOverloads();
8289 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8294 /// \brief Add function candidates found via argument-dependent lookup
8295 /// to the set of overloading candidates.
8297 /// This routine performs argument-dependent name lookup based on the
8298 /// given function name (which may also be an operator name) and adds
8299 /// all of the overload candidates found by ADL to the overload
8300 /// candidate set (C++ [basic.lookup.argdep]).
8302 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8304 ArrayRef<Expr *> Args,
8305 TemplateArgumentListInfo *ExplicitTemplateArgs,
8306 OverloadCandidateSet& CandidateSet,
8307 bool PartialOverloading) {
8310 // FIXME: This approach for uniquing ADL results (and removing
8311 // redundant candidates from the set) relies on pointer-equality,
8312 // which means we need to key off the canonical decl. However,
8313 // always going back to the canonical decl might not get us the
8314 // right set of default arguments. What default arguments are
8315 // we supposed to consider on ADL candidates, anyway?
8317 // FIXME: Pass in the explicit template arguments?
8318 ArgumentDependentLookup(Name, Loc, Args, Fns);
8320 // Erase all of the candidates we already knew about.
8321 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8322 CandEnd = CandidateSet.end();
8323 Cand != CandEnd; ++Cand)
8324 if (Cand->Function) {
8325 Fns.erase(Cand->Function);
8326 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8330 // For each of the ADL candidates we found, add it to the overload
8332 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8333 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8334 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8335 if (ExplicitTemplateArgs)
8338 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8339 PartialOverloading);
8341 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8342 FoundDecl, ExplicitTemplateArgs,
8343 Args, CandidateSet, PartialOverloading);
8347 /// isBetterOverloadCandidate - Determines whether the first overload
8348 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8349 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8350 const OverloadCandidate &Cand2,
8352 bool UserDefinedConversion) {
8353 // Define viable functions to be better candidates than non-viable
8356 return Cand1.Viable;
8357 else if (!Cand1.Viable)
8360 // C++ [over.match.best]p1:
8362 // -- if F is a static member function, ICS1(F) is defined such
8363 // that ICS1(F) is neither better nor worse than ICS1(G) for
8364 // any function G, and, symmetrically, ICS1(G) is neither
8365 // better nor worse than ICS1(F).
8366 unsigned StartArg = 0;
8367 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8370 // C++ [over.match.best]p1:
8371 // A viable function F1 is defined to be a better function than another
8372 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8373 // conversion sequence than ICSi(F2), and then...
8374 unsigned NumArgs = Cand1.NumConversions;
8375 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8376 bool HasBetterConversion = false;
8377 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8378 switch (CompareImplicitConversionSequences(S,
8379 Cand1.Conversions[ArgIdx],
8380 Cand2.Conversions[ArgIdx])) {
8381 case ImplicitConversionSequence::Better:
8382 // Cand1 has a better conversion sequence.
8383 HasBetterConversion = true;
8386 case ImplicitConversionSequence::Worse:
8387 // Cand1 can't be better than Cand2.
8390 case ImplicitConversionSequence::Indistinguishable:
8396 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8397 // ICSj(F2), or, if not that,
8398 if (HasBetterConversion)
8401 // -- the context is an initialization by user-defined conversion
8402 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8403 // from the return type of F1 to the destination type (i.e.,
8404 // the type of the entity being initialized) is a better
8405 // conversion sequence than the standard conversion sequence
8406 // from the return type of F2 to the destination type.
8407 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8408 isa<CXXConversionDecl>(Cand1.Function) &&
8409 isa<CXXConversionDecl>(Cand2.Function)) {
8410 // First check whether we prefer one of the conversion functions over the
8411 // other. This only distinguishes the results in non-standard, extension
8412 // cases such as the conversion from a lambda closure type to a function
8413 // pointer or block.
8414 ImplicitConversionSequence::CompareKind Result =
8415 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8416 if (Result == ImplicitConversionSequence::Indistinguishable)
8417 Result = CompareStandardConversionSequences(S,
8418 Cand1.FinalConversion,
8419 Cand2.FinalConversion);
8421 if (Result != ImplicitConversionSequence::Indistinguishable)
8422 return Result == ImplicitConversionSequence::Better;
8424 // FIXME: Compare kind of reference binding if conversion functions
8425 // convert to a reference type used in direct reference binding, per
8426 // C++14 [over.match.best]p1 section 2 bullet 3.
8429 // -- F1 is a non-template function and F2 is a function template
8430 // specialization, or, if not that,
8431 bool Cand1IsSpecialization = Cand1.Function &&
8432 Cand1.Function->getPrimaryTemplate();
8433 bool Cand2IsSpecialization = Cand2.Function &&
8434 Cand2.Function->getPrimaryTemplate();
8435 if (Cand1IsSpecialization != Cand2IsSpecialization)
8436 return Cand2IsSpecialization;
8438 // -- F1 and F2 are function template specializations, and the function
8439 // template for F1 is more specialized than the template for F2
8440 // according to the partial ordering rules described in 14.5.5.2, or,
8442 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8443 if (FunctionTemplateDecl *BetterTemplate
8444 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8445 Cand2.Function->getPrimaryTemplate(),
8447 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8449 Cand1.ExplicitCallArguments,
8450 Cand2.ExplicitCallArguments))
8451 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8454 // Check for enable_if value-based overload resolution.
8455 if (Cand1.Function && Cand2.Function &&
8456 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8457 Cand2.Function->hasAttr<EnableIfAttr>())) {
8458 // FIXME: The next several lines are just
8459 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8460 // instead of reverse order which is how they're stored in the AST.
8462 if (Cand1.Function->hasAttrs()) {
8463 Cand1Attrs = Cand1.Function->getAttrs();
8464 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8467 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8471 if (Cand2.Function->hasAttrs()) {
8472 Cand2Attrs = Cand2.Function->getAttrs();
8473 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8476 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8479 // Candidate 1 is better if it has strictly more attributes and
8480 // the common sequence is identical.
8481 if (Cand1Attrs.size() <= Cand2Attrs.size())
8484 auto Cand1I = Cand1Attrs.begin();
8485 for (auto &Cand2A : Cand2Attrs) {
8486 auto &Cand1A = *Cand1I++;
8487 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8488 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8489 S.getASTContext(), true);
8490 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8491 S.getASTContext(), true);
8492 if (Cand1ID != Cand2ID)
8502 /// \brief Computes the best viable function (C++ 13.3.3)
8503 /// within an overload candidate set.
8505 /// \param Loc The location of the function name (or operator symbol) for
8506 /// which overload resolution occurs.
8508 /// \param Best If overload resolution was successful or found a deleted
8509 /// function, \p Best points to the candidate function found.
8511 /// \returns The result of overload resolution.
8513 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8515 bool UserDefinedConversion) {
8516 // Find the best viable function.
8518 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8520 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8521 UserDefinedConversion))
8525 // If we didn't find any viable functions, abort.
8527 return OR_No_Viable_Function;
8529 // Make sure that this function is better than every other viable
8530 // function. If not, we have an ambiguity.
8531 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8534 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8535 UserDefinedConversion)) {
8537 return OR_Ambiguous;
8541 // Best is the best viable function.
8542 if (Best->Function &&
8543 (Best->Function->isDeleted() ||
8544 S.isFunctionConsideredUnavailable(Best->Function)))
8552 enum OverloadCandidateKind {
8556 oc_function_template,
8558 oc_constructor_template,
8559 oc_implicit_default_constructor,
8560 oc_implicit_copy_constructor,
8561 oc_implicit_move_constructor,
8562 oc_implicit_copy_assignment,
8563 oc_implicit_move_assignment,
8564 oc_implicit_inherited_constructor
8567 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8569 std::string &Description) {
8570 bool isTemplate = false;
8572 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8574 Description = S.getTemplateArgumentBindingsText(
8575 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8578 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8579 if (!Ctor->isImplicit())
8580 return isTemplate ? oc_constructor_template : oc_constructor;
8582 if (Ctor->getInheritedConstructor())
8583 return oc_implicit_inherited_constructor;
8585 if (Ctor->isDefaultConstructor())
8586 return oc_implicit_default_constructor;
8588 if (Ctor->isMoveConstructor())
8589 return oc_implicit_move_constructor;
8591 assert(Ctor->isCopyConstructor() &&
8592 "unexpected sort of implicit constructor");
8593 return oc_implicit_copy_constructor;
8596 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8597 // This actually gets spelled 'candidate function' for now, but
8598 // it doesn't hurt to split it out.
8599 if (!Meth->isImplicit())
8600 return isTemplate ? oc_method_template : oc_method;
8602 if (Meth->isMoveAssignmentOperator())
8603 return oc_implicit_move_assignment;
8605 if (Meth->isCopyAssignmentOperator())
8606 return oc_implicit_copy_assignment;
8608 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8612 return isTemplate ? oc_function_template : oc_function;
8615 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8616 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8619 Ctor = Ctor->getInheritedConstructor();
8622 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8625 } // end anonymous namespace
8627 // Notes the location of an overload candidate.
8628 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8630 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8631 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8632 << (unsigned) K << FnDesc;
8633 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8634 Diag(Fn->getLocation(), PD);
8635 MaybeEmitInheritedConstructorNote(*this, Fn);
8638 // Notes the location of all overload candidates designated through
8640 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8641 assert(OverloadedExpr->getType() == Context.OverloadTy);
8643 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8644 OverloadExpr *OvlExpr = Ovl.Expression;
8646 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8647 IEnd = OvlExpr->decls_end();
8649 if (FunctionTemplateDecl *FunTmpl =
8650 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8651 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8652 } else if (FunctionDecl *Fun
8653 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8654 NoteOverloadCandidate(Fun, DestType);
8659 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
8660 /// "lead" diagnostic; it will be given two arguments, the source and
8661 /// target types of the conversion.
8662 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8664 SourceLocation CaretLoc,
8665 const PartialDiagnostic &PDiag) const {
8666 S.Diag(CaretLoc, PDiag)
8667 << Ambiguous.getFromType() << Ambiguous.getToType();
8668 // FIXME: The note limiting machinery is borrowed from
8669 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8670 // refactoring here.
8671 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8672 unsigned CandsShown = 0;
8673 AmbiguousConversionSequence::const_iterator I, E;
8674 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8675 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8678 S.NoteOverloadCandidate(*I);
8681 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8684 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8686 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8687 assert(Conv.isBad());
8688 assert(Cand->Function && "for now, candidate must be a function");
8689 FunctionDecl *Fn = Cand->Function;
8691 // There's a conversion slot for the object argument if this is a
8692 // non-constructor method. Note that 'I' corresponds the
8693 // conversion-slot index.
8694 bool isObjectArgument = false;
8695 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8697 isObjectArgument = true;
8703 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8705 Expr *FromExpr = Conv.Bad.FromExpr;
8706 QualType FromTy = Conv.Bad.getFromType();
8707 QualType ToTy = Conv.Bad.getToType();
8709 if (FromTy == S.Context.OverloadTy) {
8710 assert(FromExpr && "overload set argument came from implicit argument?");
8711 Expr *E = FromExpr->IgnoreParens();
8712 if (isa<UnaryOperator>(E))
8713 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8714 DeclarationName Name = cast<OverloadExpr>(E)->getName();
8716 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8717 << (unsigned) FnKind << FnDesc
8718 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8719 << ToTy << Name << I+1;
8720 MaybeEmitInheritedConstructorNote(S, Fn);
8724 // Do some hand-waving analysis to see if the non-viability is due
8725 // to a qualifier mismatch.
8726 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8727 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8728 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8729 CToTy = RT->getPointeeType();
8731 // TODO: detect and diagnose the full richness of const mismatches.
8732 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8733 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8734 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8737 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8738 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8739 Qualifiers FromQs = CFromTy.getQualifiers();
8740 Qualifiers ToQs = CToTy.getQualifiers();
8742 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8743 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8744 << (unsigned) FnKind << FnDesc
8745 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8747 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8748 << (unsigned) isObjectArgument << I+1;
8749 MaybeEmitInheritedConstructorNote(S, Fn);
8753 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8755 << (unsigned) FnKind << FnDesc
8756 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8758 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8759 << (unsigned) isObjectArgument << I+1;
8760 MaybeEmitInheritedConstructorNote(S, Fn);
8764 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8765 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8766 << (unsigned) FnKind << FnDesc
8767 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8769 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8770 << (unsigned) isObjectArgument << I+1;
8771 MaybeEmitInheritedConstructorNote(S, Fn);
8775 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8776 assert(CVR && "unexpected qualifiers mismatch");
8778 if (isObjectArgument) {
8779 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8780 << (unsigned) FnKind << FnDesc
8781 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8782 << FromTy << (CVR - 1);
8784 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8785 << (unsigned) FnKind << FnDesc
8786 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8787 << FromTy << (CVR - 1) << I+1;
8789 MaybeEmitInheritedConstructorNote(S, Fn);
8793 // Special diagnostic for failure to convert an initializer list, since
8794 // telling the user that it has type void is not useful.
8795 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8797 << (unsigned) FnKind << FnDesc
8798 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8799 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8800 MaybeEmitInheritedConstructorNote(S, Fn);
8804 // Diagnose references or pointers to incomplete types differently,
8805 // since it's far from impossible that the incompleteness triggered
8807 QualType TempFromTy = FromTy.getNonReferenceType();
8808 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8809 TempFromTy = PTy->getPointeeType();
8810 if (TempFromTy->isIncompleteType()) {
8811 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8812 << (unsigned) FnKind << FnDesc
8813 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8814 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8815 MaybeEmitInheritedConstructorNote(S, Fn);
8819 // Diagnose base -> derived pointer conversions.
8820 unsigned BaseToDerivedConversion = 0;
8821 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8822 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8823 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8824 FromPtrTy->getPointeeType()) &&
8825 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8826 !ToPtrTy->getPointeeType()->isIncompleteType() &&
8827 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8828 FromPtrTy->getPointeeType()))
8829 BaseToDerivedConversion = 1;
8831 } else if (const ObjCObjectPointerType *FromPtrTy
8832 = FromTy->getAs<ObjCObjectPointerType>()) {
8833 if (const ObjCObjectPointerType *ToPtrTy
8834 = ToTy->getAs<ObjCObjectPointerType>())
8835 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8836 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8837 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8838 FromPtrTy->getPointeeType()) &&
8839 FromIface->isSuperClassOf(ToIface))
8840 BaseToDerivedConversion = 2;
8841 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8842 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8843 !FromTy->isIncompleteType() &&
8844 !ToRefTy->getPointeeType()->isIncompleteType() &&
8845 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8846 BaseToDerivedConversion = 3;
8847 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8848 ToTy.getNonReferenceType().getCanonicalType() ==
8849 FromTy.getNonReferenceType().getCanonicalType()) {
8850 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8851 << (unsigned) FnKind << FnDesc
8852 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8853 << (unsigned) isObjectArgument << I + 1;
8854 MaybeEmitInheritedConstructorNote(S, Fn);
8859 if (BaseToDerivedConversion) {
8860 S.Diag(Fn->getLocation(),
8861 diag::note_ovl_candidate_bad_base_to_derived_conv)
8862 << (unsigned) FnKind << FnDesc
8863 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8864 << (BaseToDerivedConversion - 1)
8865 << FromTy << ToTy << I+1;
8866 MaybeEmitInheritedConstructorNote(S, Fn);
8870 if (isa<ObjCObjectPointerType>(CFromTy) &&
8871 isa<PointerType>(CToTy)) {
8872 Qualifiers FromQs = CFromTy.getQualifiers();
8873 Qualifiers ToQs = CToTy.getQualifiers();
8874 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8876 << (unsigned) FnKind << FnDesc
8877 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8878 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8879 MaybeEmitInheritedConstructorNote(S, Fn);
8884 // Emit the generic diagnostic and, optionally, add the hints to it.
8885 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8886 FDiag << (unsigned) FnKind << FnDesc
8887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8888 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8889 << (unsigned) (Cand->Fix.Kind);
8891 // If we can fix the conversion, suggest the FixIts.
8892 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8893 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8895 S.Diag(Fn->getLocation(), FDiag);
8897 MaybeEmitInheritedConstructorNote(S, Fn);
8900 /// Additional arity mismatch diagnosis specific to a function overload
8901 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8902 /// over a candidate in any candidate set.
8903 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8905 FunctionDecl *Fn = Cand->Function;
8906 unsigned MinParams = Fn->getMinRequiredArguments();
8908 // With invalid overloaded operators, it's possible that we think we
8909 // have an arity mismatch when in fact it looks like we have the
8910 // right number of arguments, because only overloaded operators have
8911 // the weird behavior of overloading member and non-member functions.
8912 // Just don't report anything.
8913 if (Fn->isInvalidDecl() &&
8914 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8917 if (NumArgs < MinParams) {
8918 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8919 (Cand->FailureKind == ovl_fail_bad_deduction &&
8920 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8922 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8923 (Cand->FailureKind == ovl_fail_bad_deduction &&
8924 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8930 /// General arity mismatch diagnosis over a candidate in a candidate set.
8931 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8932 assert(isa<FunctionDecl>(D) &&
8933 "The templated declaration should at least be a function"
8934 " when diagnosing bad template argument deduction due to too many"
8935 " or too few arguments");
8937 FunctionDecl *Fn = cast<FunctionDecl>(D);
8939 // TODO: treat calls to a missing default constructor as a special case
8940 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8941 unsigned MinParams = Fn->getMinRequiredArguments();
8943 // at least / at most / exactly
8944 unsigned mode, modeCount;
8945 if (NumFormalArgs < MinParams) {
8946 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8947 FnTy->isTemplateVariadic())
8948 mode = 0; // "at least"
8950 mode = 2; // "exactly"
8951 modeCount = MinParams;
8953 if (MinParams != FnTy->getNumParams())
8954 mode = 1; // "at most"
8956 mode = 2; // "exactly"
8957 modeCount = FnTy->getNumParams();
8960 std::string Description;
8961 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8963 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8964 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8965 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8966 << mode << Fn->getParamDecl(0) << NumFormalArgs;
8968 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8969 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8970 << mode << modeCount << NumFormalArgs;
8971 MaybeEmitInheritedConstructorNote(S, Fn);
8974 /// Arity mismatch diagnosis specific to a function overload candidate.
8975 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8976 unsigned NumFormalArgs) {
8977 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8978 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8981 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8982 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8983 return FD->getDescribedFunctionTemplate();
8984 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8985 return RD->getDescribedClassTemplate();
8987 llvm_unreachable("Unsupported: Getting the described template declaration"
8988 " for bad deduction diagnosis");
8991 /// Diagnose a failed template-argument deduction.
8992 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8993 DeductionFailureInfo &DeductionFailure,
8995 TemplateParameter Param = DeductionFailure.getTemplateParameter();
8997 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8998 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8999 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9000 switch (DeductionFailure.Result) {
9001 case Sema::TDK_Success:
9002 llvm_unreachable("TDK_success while diagnosing bad deduction");
9004 case Sema::TDK_Incomplete: {
9005 assert(ParamD && "no parameter found for incomplete deduction result");
9006 S.Diag(Templated->getLocation(),
9007 diag::note_ovl_candidate_incomplete_deduction)
9008 << ParamD->getDeclName();
9009 MaybeEmitInheritedConstructorNote(S, Templated);
9013 case Sema::TDK_Underqualified: {
9014 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9015 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9017 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9019 // Param will have been canonicalized, but it should just be a
9020 // qualified version of ParamD, so move the qualifiers to that.
9021 QualifierCollector Qs;
9023 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9024 assert(S.Context.hasSameType(Param, NonCanonParam));
9026 // Arg has also been canonicalized, but there's nothing we can do
9027 // about that. It also doesn't matter as much, because it won't
9028 // have any template parameters in it (because deduction isn't
9029 // done on dependent types).
9030 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9032 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9033 << ParamD->getDeclName() << Arg << NonCanonParam;
9034 MaybeEmitInheritedConstructorNote(S, Templated);
9038 case Sema::TDK_Inconsistent: {
9039 assert(ParamD && "no parameter found for inconsistent deduction result");
9041 if (isa<TemplateTypeParmDecl>(ParamD))
9043 else if (isa<NonTypeTemplateParmDecl>(ParamD))
9049 S.Diag(Templated->getLocation(),
9050 diag::note_ovl_candidate_inconsistent_deduction)
9051 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9052 << *DeductionFailure.getSecondArg();
9053 MaybeEmitInheritedConstructorNote(S, Templated);
9057 case Sema::TDK_InvalidExplicitArguments:
9058 assert(ParamD && "no parameter found for invalid explicit arguments");
9059 if (ParamD->getDeclName())
9060 S.Diag(Templated->getLocation(),
9061 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9062 << ParamD->getDeclName();
9065 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9066 index = TTP->getIndex();
9067 else if (NonTypeTemplateParmDecl *NTTP
9068 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9069 index = NTTP->getIndex();
9071 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9072 S.Diag(Templated->getLocation(),
9073 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9076 MaybeEmitInheritedConstructorNote(S, Templated);
9079 case Sema::TDK_TooManyArguments:
9080 case Sema::TDK_TooFewArguments:
9081 DiagnoseArityMismatch(S, Templated, NumArgs);
9084 case Sema::TDK_InstantiationDepth:
9085 S.Diag(Templated->getLocation(),
9086 diag::note_ovl_candidate_instantiation_depth);
9087 MaybeEmitInheritedConstructorNote(S, Templated);
9090 case Sema::TDK_SubstitutionFailure: {
9091 // Format the template argument list into the argument string.
9092 SmallString<128> TemplateArgString;
9093 if (TemplateArgumentList *Args =
9094 DeductionFailure.getTemplateArgumentList()) {
9095 TemplateArgString = " ";
9096 TemplateArgString += S.getTemplateArgumentBindingsText(
9097 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9100 // If this candidate was disabled by enable_if, say so.
9101 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9102 if (PDiag && PDiag->second.getDiagID() ==
9103 diag::err_typename_nested_not_found_enable_if) {
9104 // FIXME: Use the source range of the condition, and the fully-qualified
9105 // name of the enable_if template. These are both present in PDiag.
9106 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9107 << "'enable_if'" << TemplateArgString;
9111 // Format the SFINAE diagnostic into the argument string.
9112 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9113 // formatted message in another diagnostic.
9114 SmallString<128> SFINAEArgString;
9117 SFINAEArgString = ": ";
9118 R = SourceRange(PDiag->first, PDiag->first);
9119 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9122 S.Diag(Templated->getLocation(),
9123 diag::note_ovl_candidate_substitution_failure)
9124 << TemplateArgString << SFINAEArgString << R;
9125 MaybeEmitInheritedConstructorNote(S, Templated);
9129 case Sema::TDK_FailedOverloadResolution: {
9130 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9131 S.Diag(Templated->getLocation(),
9132 diag::note_ovl_candidate_failed_overload_resolution)
9133 << R.Expression->getName();
9137 case Sema::TDK_NonDeducedMismatch: {
9138 // FIXME: Provide a source location to indicate what we couldn't match.
9139 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9140 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9141 if (FirstTA.getKind() == TemplateArgument::Template &&
9142 SecondTA.getKind() == TemplateArgument::Template) {
9143 TemplateName FirstTN = FirstTA.getAsTemplate();
9144 TemplateName SecondTN = SecondTA.getAsTemplate();
9145 if (FirstTN.getKind() == TemplateName::Template &&
9146 SecondTN.getKind() == TemplateName::Template) {
9147 if (FirstTN.getAsTemplateDecl()->getName() ==
9148 SecondTN.getAsTemplateDecl()->getName()) {
9149 // FIXME: This fixes a bad diagnostic where both templates are named
9150 // the same. This particular case is a bit difficult since:
9151 // 1) It is passed as a string to the diagnostic printer.
9152 // 2) The diagnostic printer only attempts to find a better
9153 // name for types, not decls.
9154 // Ideally, this should folded into the diagnostic printer.
9155 S.Diag(Templated->getLocation(),
9156 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9157 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9162 // FIXME: For generic lambda parameters, check if the function is a lambda
9163 // call operator, and if so, emit a prettier and more informative
9164 // diagnostic that mentions 'auto' and lambda in addition to
9165 // (or instead of?) the canonical template type parameters.
9166 S.Diag(Templated->getLocation(),
9167 diag::note_ovl_candidate_non_deduced_mismatch)
9168 << FirstTA << SecondTA;
9171 // TODO: diagnose these individually, then kill off
9172 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9173 case Sema::TDK_MiscellaneousDeductionFailure:
9174 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9175 MaybeEmitInheritedConstructorNote(S, Templated);
9180 /// Diagnose a failed template-argument deduction, for function calls.
9181 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9183 unsigned TDK = Cand->DeductionFailure.Result;
9184 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9185 if (CheckArityMismatch(S, Cand, NumArgs))
9188 DiagnoseBadDeduction(S, Cand->Function, // pattern
9189 Cand->DeductionFailure, NumArgs);
9192 /// CUDA: diagnose an invalid call across targets.
9193 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9194 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9195 FunctionDecl *Callee = Cand->Function;
9197 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9198 CalleeTarget = S.IdentifyCUDATarget(Callee);
9201 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9203 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9204 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9206 // This could be an implicit constructor for which we could not infer the
9207 // target due to a collsion. Diagnose that case.
9208 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9209 if (Meth != nullptr && Meth->isImplicit()) {
9210 CXXRecordDecl *ParentClass = Meth->getParent();
9211 Sema::CXXSpecialMember CSM;
9216 case oc_implicit_default_constructor:
9217 CSM = Sema::CXXDefaultConstructor;
9219 case oc_implicit_copy_constructor:
9220 CSM = Sema::CXXCopyConstructor;
9222 case oc_implicit_move_constructor:
9223 CSM = Sema::CXXMoveConstructor;
9225 case oc_implicit_copy_assignment:
9226 CSM = Sema::CXXCopyAssignment;
9228 case oc_implicit_move_assignment:
9229 CSM = Sema::CXXMoveAssignment;
9233 bool ConstRHS = false;
9234 if (Meth->getNumParams()) {
9235 if (const ReferenceType *RT =
9236 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9237 ConstRHS = RT->getPointeeType().isConstQualified();
9241 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9242 /* ConstRHS */ ConstRHS,
9243 /* Diagnose */ true);
9247 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9248 FunctionDecl *Callee = Cand->Function;
9249 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9251 S.Diag(Callee->getLocation(),
9252 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9253 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9256 /// Generates a 'note' diagnostic for an overload candidate. We've
9257 /// already generated a primary error at the call site.
9259 /// It really does need to be a single diagnostic with its caret
9260 /// pointed at the candidate declaration. Yes, this creates some
9261 /// major challenges of technical writing. Yes, this makes pointing
9262 /// out problems with specific arguments quite awkward. It's still
9263 /// better than generating twenty screens of text for every failed
9266 /// It would be great to be able to express per-candidate problems
9267 /// more richly for those diagnostic clients that cared, but we'd
9268 /// still have to be just as careful with the default diagnostics.
9269 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9271 FunctionDecl *Fn = Cand->Function;
9273 // Note deleted candidates, but only if they're viable.
9274 if (Cand->Viable && (Fn->isDeleted() ||
9275 S.isFunctionConsideredUnavailable(Fn))) {
9277 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9279 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9281 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9282 MaybeEmitInheritedConstructorNote(S, Fn);
9286 // We don't really have anything else to say about viable candidates.
9288 S.NoteOverloadCandidate(Fn);
9292 switch (Cand->FailureKind) {
9293 case ovl_fail_too_many_arguments:
9294 case ovl_fail_too_few_arguments:
9295 return DiagnoseArityMismatch(S, Cand, NumArgs);
9297 case ovl_fail_bad_deduction:
9298 return DiagnoseBadDeduction(S, Cand, NumArgs);
9300 case ovl_fail_illegal_constructor: {
9301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9302 << (Fn->getPrimaryTemplate() ? 1 : 0);
9303 MaybeEmitInheritedConstructorNote(S, Fn);
9307 case ovl_fail_trivial_conversion:
9308 case ovl_fail_bad_final_conversion:
9309 case ovl_fail_final_conversion_not_exact:
9310 return S.NoteOverloadCandidate(Fn);
9312 case ovl_fail_bad_conversion: {
9313 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9314 for (unsigned N = Cand->NumConversions; I != N; ++I)
9315 if (Cand->Conversions[I].isBad())
9316 return DiagnoseBadConversion(S, Cand, I);
9318 // FIXME: this currently happens when we're called from SemaInit
9319 // when user-conversion overload fails. Figure out how to handle
9320 // those conditions and diagnose them well.
9321 return S.NoteOverloadCandidate(Fn);
9324 case ovl_fail_bad_target:
9325 return DiagnoseBadTarget(S, Cand);
9327 case ovl_fail_enable_if:
9328 return DiagnoseFailedEnableIfAttr(S, Cand);
9332 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9333 // Desugar the type of the surrogate down to a function type,
9334 // retaining as many typedefs as possible while still showing
9335 // the function type (and, therefore, its parameter types).
9336 QualType FnType = Cand->Surrogate->getConversionType();
9337 bool isLValueReference = false;
9338 bool isRValueReference = false;
9339 bool isPointer = false;
9340 if (const LValueReferenceType *FnTypeRef =
9341 FnType->getAs<LValueReferenceType>()) {
9342 FnType = FnTypeRef->getPointeeType();
9343 isLValueReference = true;
9344 } else if (const RValueReferenceType *FnTypeRef =
9345 FnType->getAs<RValueReferenceType>()) {
9346 FnType = FnTypeRef->getPointeeType();
9347 isRValueReference = true;
9349 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9350 FnType = FnTypePtr->getPointeeType();
9353 // Desugar down to a function type.
9354 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9355 // Reconstruct the pointer/reference as appropriate.
9356 if (isPointer) FnType = S.Context.getPointerType(FnType);
9357 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9358 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9360 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9362 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9365 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9366 SourceLocation OpLoc,
9367 OverloadCandidate *Cand) {
9368 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9369 std::string TypeStr("operator");
9372 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9373 if (Cand->NumConversions == 1) {
9375 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9378 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9380 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9384 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9385 OverloadCandidate *Cand) {
9386 unsigned NoOperands = Cand->NumConversions;
9387 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9388 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9389 if (ICS.isBad()) break; // all meaningless after first invalid
9390 if (!ICS.isAmbiguous()) continue;
9392 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9393 S.PDiag(diag::note_ambiguous_type_conversion));
9397 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9399 return Cand->Function->getLocation();
9400 if (Cand->IsSurrogate)
9401 return Cand->Surrogate->getLocation();
9402 return SourceLocation();
9405 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9406 switch ((Sema::TemplateDeductionResult)DFI.Result) {
9407 case Sema::TDK_Success:
9408 llvm_unreachable("TDK_success while diagnosing bad deduction");
9410 case Sema::TDK_Invalid:
9411 case Sema::TDK_Incomplete:
9414 case Sema::TDK_Underqualified:
9415 case Sema::TDK_Inconsistent:
9418 case Sema::TDK_SubstitutionFailure:
9419 case Sema::TDK_NonDeducedMismatch:
9420 case Sema::TDK_MiscellaneousDeductionFailure:
9423 case Sema::TDK_InstantiationDepth:
9424 case Sema::TDK_FailedOverloadResolution:
9427 case Sema::TDK_InvalidExplicitArguments:
9430 case Sema::TDK_TooManyArguments:
9431 case Sema::TDK_TooFewArguments:
9434 llvm_unreachable("Unhandled deduction result");
9438 struct CompareOverloadCandidatesForDisplay {
9442 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9443 : S(S), NumArgs(nArgs) {}
9445 bool operator()(const OverloadCandidate *L,
9446 const OverloadCandidate *R) {
9447 // Fast-path this check.
9448 if (L == R) return false;
9450 // Order first by viability.
9452 if (!R->Viable) return true;
9454 // TODO: introduce a tri-valued comparison for overload
9455 // candidates. Would be more worthwhile if we had a sort
9456 // that could exploit it.
9457 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9458 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9459 } else if (R->Viable)
9462 assert(L->Viable == R->Viable);
9464 // Criteria by which we can sort non-viable candidates:
9466 // 1. Arity mismatches come after other candidates.
9467 if (L->FailureKind == ovl_fail_too_many_arguments ||
9468 L->FailureKind == ovl_fail_too_few_arguments) {
9469 if (R->FailureKind == ovl_fail_too_many_arguments ||
9470 R->FailureKind == ovl_fail_too_few_arguments) {
9471 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9472 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9473 if (LDist == RDist) {
9474 if (L->FailureKind == R->FailureKind)
9475 // Sort non-surrogates before surrogates.
9476 return !L->IsSurrogate && R->IsSurrogate;
9477 // Sort candidates requiring fewer parameters than there were
9478 // arguments given after candidates requiring more parameters
9479 // than there were arguments given.
9480 return L->FailureKind == ovl_fail_too_many_arguments;
9482 return LDist < RDist;
9486 if (R->FailureKind == ovl_fail_too_many_arguments ||
9487 R->FailureKind == ovl_fail_too_few_arguments)
9490 // 2. Bad conversions come first and are ordered by the number
9491 // of bad conversions and quality of good conversions.
9492 if (L->FailureKind == ovl_fail_bad_conversion) {
9493 if (R->FailureKind != ovl_fail_bad_conversion)
9496 // The conversion that can be fixed with a smaller number of changes,
9498 unsigned numLFixes = L->Fix.NumConversionsFixed;
9499 unsigned numRFixes = R->Fix.NumConversionsFixed;
9500 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9501 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9502 if (numLFixes != numRFixes) {
9503 return numLFixes < numRFixes;
9506 // If there's any ordering between the defined conversions...
9507 // FIXME: this might not be transitive.
9508 assert(L->NumConversions == R->NumConversions);
9511 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9512 for (unsigned E = L->NumConversions; I != E; ++I) {
9513 switch (CompareImplicitConversionSequences(S,
9515 R->Conversions[I])) {
9516 case ImplicitConversionSequence::Better:
9520 case ImplicitConversionSequence::Worse:
9524 case ImplicitConversionSequence::Indistinguishable:
9528 if (leftBetter > 0) return true;
9529 if (leftBetter < 0) return false;
9531 } else if (R->FailureKind == ovl_fail_bad_conversion)
9534 if (L->FailureKind == ovl_fail_bad_deduction) {
9535 if (R->FailureKind != ovl_fail_bad_deduction)
9538 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9539 return RankDeductionFailure(L->DeductionFailure)
9540 < RankDeductionFailure(R->DeductionFailure);
9541 } else if (R->FailureKind == ovl_fail_bad_deduction)
9547 // Sort everything else by location.
9548 SourceLocation LLoc = GetLocationForCandidate(L);
9549 SourceLocation RLoc = GetLocationForCandidate(R);
9551 // Put candidates without locations (e.g. builtins) at the end.
9552 if (LLoc.isInvalid()) return false;
9553 if (RLoc.isInvalid()) return true;
9555 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9560 /// CompleteNonViableCandidate - Normally, overload resolution only
9561 /// computes up to the first. Produces the FixIt set if possible.
9562 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9563 ArrayRef<Expr *> Args) {
9564 assert(!Cand->Viable);
9566 // Don't do anything on failures other than bad conversion.
9567 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9569 // We only want the FixIts if all the arguments can be corrected.
9570 bool Unfixable = false;
9571 // Use a implicit copy initialization to check conversion fixes.
9572 Cand->Fix.setConversionChecker(TryCopyInitialization);
9574 // Skip forward to the first bad conversion.
9575 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9576 unsigned ConvCount = Cand->NumConversions;
9578 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9580 if (Cand->Conversions[ConvIdx - 1].isBad()) {
9581 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9586 if (ConvIdx == ConvCount)
9589 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9590 "remaining conversion is initialized?");
9592 // FIXME: this should probably be preserved from the overload
9593 // operation somehow.
9594 bool SuppressUserConversions = false;
9596 const FunctionProtoType* Proto;
9597 unsigned ArgIdx = ConvIdx;
9599 if (Cand->IsSurrogate) {
9601 = Cand->Surrogate->getConversionType().getNonReferenceType();
9602 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9603 ConvType = ConvPtrType->getPointeeType();
9604 Proto = ConvType->getAs<FunctionProtoType>();
9606 } else if (Cand->Function) {
9607 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9608 if (isa<CXXMethodDecl>(Cand->Function) &&
9609 !isa<CXXConstructorDecl>(Cand->Function))
9612 // Builtin binary operator with a bad first conversion.
9613 assert(ConvCount <= 3);
9614 for (; ConvIdx != ConvCount; ++ConvIdx)
9615 Cand->Conversions[ConvIdx]
9616 = TryCopyInitialization(S, Args[ConvIdx],
9617 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9618 SuppressUserConversions,
9619 /*InOverloadResolution*/ true,
9620 /*AllowObjCWritebackConversion=*/
9621 S.getLangOpts().ObjCAutoRefCount);
9625 // Fill in the rest of the conversions.
9626 unsigned NumParams = Proto->getNumParams();
9627 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9628 if (ArgIdx < NumParams) {
9629 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9630 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9631 /*InOverloadResolution=*/true,
9632 /*AllowObjCWritebackConversion=*/
9633 S.getLangOpts().ObjCAutoRefCount);
9634 // Store the FixIt in the candidate if it exists.
9635 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9636 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9639 Cand->Conversions[ConvIdx].setEllipsis();
9643 /// PrintOverloadCandidates - When overload resolution fails, prints
9644 /// diagnostic messages containing the candidates in the candidate
9646 void OverloadCandidateSet::NoteCandidates(Sema &S,
9647 OverloadCandidateDisplayKind OCD,
9648 ArrayRef<Expr *> Args,
9650 SourceLocation OpLoc) {
9651 // Sort the candidates by viability and position. Sorting directly would
9652 // be prohibitive, so we make a set of pointers and sort those.
9653 SmallVector<OverloadCandidate*, 32> Cands;
9654 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9655 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9657 Cands.push_back(Cand);
9658 else if (OCD == OCD_AllCandidates) {
9659 CompleteNonViableCandidate(S, Cand, Args);
9660 if (Cand->Function || Cand->IsSurrogate)
9661 Cands.push_back(Cand);
9662 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9663 // want to list every possible builtin candidate.
9667 std::sort(Cands.begin(), Cands.end(),
9668 CompareOverloadCandidatesForDisplay(S, Args.size()));
9670 bool ReportedAmbiguousConversions = false;
9672 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9673 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9674 unsigned CandsShown = 0;
9675 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9676 OverloadCandidate *Cand = *I;
9678 // Set an arbitrary limit on the number of candidate functions we'll spam
9679 // the user with. FIXME: This limit should depend on details of the
9681 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9687 NoteFunctionCandidate(S, Cand, Args.size());
9688 else if (Cand->IsSurrogate)
9689 NoteSurrogateCandidate(S, Cand);
9691 assert(Cand->Viable &&
9692 "Non-viable built-in candidates are not added to Cands.");
9693 // Generally we only see ambiguities including viable builtin
9694 // operators if overload resolution got screwed up by an
9695 // ambiguous user-defined conversion.
9697 // FIXME: It's quite possible for different conversions to see
9698 // different ambiguities, though.
9699 if (!ReportedAmbiguousConversions) {
9700 NoteAmbiguousUserConversions(S, OpLoc, Cand);
9701 ReportedAmbiguousConversions = true;
9704 // If this is a viable builtin, print it.
9705 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9710 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9713 static SourceLocation
9714 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9715 return Cand->Specialization ? Cand->Specialization->getLocation()
9720 struct CompareTemplateSpecCandidatesForDisplay {
9722 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9724 bool operator()(const TemplateSpecCandidate *L,
9725 const TemplateSpecCandidate *R) {
9726 // Fast-path this check.
9730 // Assuming that both candidates are not matches...
9732 // Sort by the ranking of deduction failures.
9733 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9734 return RankDeductionFailure(L->DeductionFailure) <
9735 RankDeductionFailure(R->DeductionFailure);
9737 // Sort everything else by location.
9738 SourceLocation LLoc = GetLocationForCandidate(L);
9739 SourceLocation RLoc = GetLocationForCandidate(R);
9741 // Put candidates without locations (e.g. builtins) at the end.
9742 if (LLoc.isInvalid())
9744 if (RLoc.isInvalid())
9747 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9752 /// Diagnose a template argument deduction failure.
9753 /// We are treating these failures as overload failures due to bad
9755 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9756 DiagnoseBadDeduction(S, Specialization, // pattern
9757 DeductionFailure, /*NumArgs=*/0);
9760 void TemplateSpecCandidateSet::destroyCandidates() {
9761 for (iterator i = begin(), e = end(); i != e; ++i) {
9762 i->DeductionFailure.Destroy();
9766 void TemplateSpecCandidateSet::clear() {
9767 destroyCandidates();
9771 /// NoteCandidates - When no template specialization match is found, prints
9772 /// diagnostic messages containing the non-matching specializations that form
9773 /// the candidate set.
9774 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9775 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9776 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9777 // Sort the candidates by position (assuming no candidate is a match).
9778 // Sorting directly would be prohibitive, so we make a set of pointers
9780 SmallVector<TemplateSpecCandidate *, 32> Cands;
9781 Cands.reserve(size());
9782 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9783 if (Cand->Specialization)
9784 Cands.push_back(Cand);
9785 // Otherwise, this is a non-matching builtin candidate. We do not,
9786 // in general, want to list every possible builtin candidate.
9789 std::sort(Cands.begin(), Cands.end(),
9790 CompareTemplateSpecCandidatesForDisplay(S));
9792 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9793 // for generalization purposes (?).
9794 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9796 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9797 unsigned CandsShown = 0;
9798 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9799 TemplateSpecCandidate *Cand = *I;
9801 // Set an arbitrary limit on the number of candidates we'll spam
9802 // the user with. FIXME: This limit should depend on details of the
9804 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9808 assert(Cand->Specialization &&
9809 "Non-matching built-in candidates are not added to Cands.");
9810 Cand->NoteDeductionFailure(S);
9814 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9817 // [PossiblyAFunctionType] --> [Return]
9818 // NonFunctionType --> NonFunctionType
9820 // R (*)(A) --> R (A)
9821 // R (&)(A) --> R (A)
9822 // R (S::*)(A) --> R (A)
9823 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9824 QualType Ret = PossiblyAFunctionType;
9825 if (const PointerType *ToTypePtr =
9826 PossiblyAFunctionType->getAs<PointerType>())
9827 Ret = ToTypePtr->getPointeeType();
9828 else if (const ReferenceType *ToTypeRef =
9829 PossiblyAFunctionType->getAs<ReferenceType>())
9830 Ret = ToTypeRef->getPointeeType();
9831 else if (const MemberPointerType *MemTypePtr =
9832 PossiblyAFunctionType->getAs<MemberPointerType>())
9833 Ret = MemTypePtr->getPointeeType();
9835 Context.getCanonicalType(Ret).getUnqualifiedType();
9840 // A helper class to help with address of function resolution
9841 // - allows us to avoid passing around all those ugly parameters
9842 class AddressOfFunctionResolver {
9845 const QualType& TargetType;
9846 QualType TargetFunctionType; // Extracted function type from target type
9849 //DeclAccessPair& ResultFunctionAccessPair;
9850 ASTContext& Context;
9852 bool TargetTypeIsNonStaticMemberFunction;
9853 bool FoundNonTemplateFunction;
9854 bool StaticMemberFunctionFromBoundPointer;
9856 OverloadExpr::FindResult OvlExprInfo;
9857 OverloadExpr *OvlExpr;
9858 TemplateArgumentListInfo OvlExplicitTemplateArgs;
9859 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9860 TemplateSpecCandidateSet FailedCandidates;
9863 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9864 const QualType &TargetType, bool Complain)
9865 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9866 Complain(Complain), Context(S.getASTContext()),
9867 TargetTypeIsNonStaticMemberFunction(
9868 !!TargetType->getAs<MemberPointerType>()),
9869 FoundNonTemplateFunction(false),
9870 StaticMemberFunctionFromBoundPointer(false),
9871 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9872 OvlExpr(OvlExprInfo.Expression),
9873 FailedCandidates(OvlExpr->getNameLoc()) {
9874 ExtractUnqualifiedFunctionTypeFromTargetType();
9876 if (TargetFunctionType->isFunctionType()) {
9877 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9878 if (!UME->isImplicitAccess() &&
9879 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9880 StaticMemberFunctionFromBoundPointer = true;
9881 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9883 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9884 OvlExpr, false, &dap)) {
9885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9886 if (!Method->isStatic()) {
9887 // If the target type is a non-function type and the function found
9888 // is a non-static member function, pretend as if that was the
9889 // target, it's the only possible type to end up with.
9890 TargetTypeIsNonStaticMemberFunction = true;
9892 // And skip adding the function if its not in the proper form.
9893 // We'll diagnose this due to an empty set of functions.
9894 if (!OvlExprInfo.HasFormOfMemberPointer)
9898 Matches.push_back(std::make_pair(dap, Fn));
9903 if (OvlExpr->hasExplicitTemplateArgs())
9904 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9906 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9907 // C++ [over.over]p4:
9908 // If more than one function is selected, [...]
9909 if (Matches.size() > 1) {
9910 if (FoundNonTemplateFunction)
9911 EliminateAllTemplateMatches();
9913 EliminateAllExceptMostSpecializedTemplate();
9919 bool isTargetTypeAFunction() const {
9920 return TargetFunctionType->isFunctionType();
9923 // [ToType] [Return]
9925 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9926 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9927 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9928 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9929 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9932 // return true if any matching specializations were found
9933 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9934 const DeclAccessPair& CurAccessFunPair) {
9935 if (CXXMethodDecl *Method
9936 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9937 // Skip non-static function templates when converting to pointer, and
9938 // static when converting to member pointer.
9939 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9942 else if (TargetTypeIsNonStaticMemberFunction)
9945 // C++ [over.over]p2:
9946 // If the name is a function template, template argument deduction is
9947 // done (14.8.2.2), and if the argument deduction succeeds, the
9948 // resulting template argument list is used to generate a single
9949 // function template specialization, which is added to the set of
9950 // overloaded functions considered.
9951 FunctionDecl *Specialization = nullptr;
9952 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9953 if (Sema::TemplateDeductionResult Result
9954 = S.DeduceTemplateArguments(FunctionTemplate,
9955 &OvlExplicitTemplateArgs,
9956 TargetFunctionType, Specialization,
9957 Info, /*InOverloadResolution=*/true)) {
9958 // Make a note of the failed deduction for diagnostics.
9959 FailedCandidates.addCandidate()
9960 .set(FunctionTemplate->getTemplatedDecl(),
9961 MakeDeductionFailureInfo(Context, Result, Info));
9965 // Template argument deduction ensures that we have an exact match or
9966 // compatible pointer-to-function arguments that would be adjusted by ICS.
9967 // This function template specicalization works.
9968 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9969 assert(S.isSameOrCompatibleFunctionType(
9970 Context.getCanonicalType(Specialization->getType()),
9971 Context.getCanonicalType(TargetFunctionType)));
9972 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9976 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9977 const DeclAccessPair& CurAccessFunPair) {
9978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9979 // Skip non-static functions when converting to pointer, and static
9980 // when converting to member pointer.
9981 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9984 else if (TargetTypeIsNonStaticMemberFunction)
9987 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9988 if (S.getLangOpts().CUDA)
9989 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9990 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
9993 // If any candidate has a placeholder return type, trigger its deduction
9995 if (S.getLangOpts().CPlusPlus14 &&
9996 FunDecl->getReturnType()->isUndeducedType() &&
9997 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10001 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10002 FunDecl->getType()) ||
10003 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10005 Matches.push_back(std::make_pair(CurAccessFunPair,
10006 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10007 FoundNonTemplateFunction = true;
10015 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10018 // If the overload expression doesn't have the form of a pointer to
10019 // member, don't try to convert it to a pointer-to-member type.
10020 if (IsInvalidFormOfPointerToMemberFunction())
10023 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10024 E = OvlExpr->decls_end();
10026 // Look through any using declarations to find the underlying function.
10027 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10029 // C++ [over.over]p3:
10030 // Non-member functions and static member functions match
10031 // targets of type "pointer-to-function" or "reference-to-function."
10032 // Nonstatic member functions match targets of
10033 // type "pointer-to-member-function."
10034 // Note that according to DR 247, the containing class does not matter.
10035 if (FunctionTemplateDecl *FunctionTemplate
10036 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10037 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10040 // If we have explicit template arguments supplied, skip non-templates.
10041 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10042 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10045 assert(Ret || Matches.empty());
10049 void EliminateAllExceptMostSpecializedTemplate() {
10050 // [...] and any given function template specialization F1 is
10051 // eliminated if the set contains a second function template
10052 // specialization whose function template is more specialized
10053 // than the function template of F1 according to the partial
10054 // ordering rules of 14.5.5.2.
10056 // The algorithm specified above is quadratic. We instead use a
10057 // two-pass algorithm (similar to the one used to identify the
10058 // best viable function in an overload set) that identifies the
10059 // best function template (if it exists).
10061 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10062 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10063 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10065 // TODO: It looks like FailedCandidates does not serve much purpose
10066 // here, since the no_viable diagnostic has index 0.
10067 UnresolvedSetIterator Result = S.getMostSpecialized(
10068 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10069 SourceExpr->getLocStart(), S.PDiag(),
10070 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10071 .second->getDeclName(),
10072 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10073 Complain, TargetFunctionType);
10075 if (Result != MatchesCopy.end()) {
10076 // Make it the first and only element
10077 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10078 Matches[0].second = cast<FunctionDecl>(*Result);
10083 void EliminateAllTemplateMatches() {
10084 // [...] any function template specializations in the set are
10085 // eliminated if the set also contains a non-template function, [...]
10086 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10087 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10090 Matches[I] = Matches[--N];
10091 Matches.set_size(N);
10097 void ComplainNoMatchesFound() const {
10098 assert(Matches.empty());
10099 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10100 << OvlExpr->getName() << TargetFunctionType
10101 << OvlExpr->getSourceRange();
10102 if (FailedCandidates.empty())
10103 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10105 // We have some deduction failure messages. Use them to diagnose
10106 // the function templates, and diagnose the non-template candidates
10108 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10109 IEnd = OvlExpr->decls_end();
10111 if (FunctionDecl *Fun =
10112 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10113 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10114 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10118 bool IsInvalidFormOfPointerToMemberFunction() const {
10119 return TargetTypeIsNonStaticMemberFunction &&
10120 !OvlExprInfo.HasFormOfMemberPointer;
10123 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10124 // TODO: Should we condition this on whether any functions might
10125 // have matched, or is it more appropriate to do that in callers?
10126 // TODO: a fixit wouldn't hurt.
10127 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10128 << TargetType << OvlExpr->getSourceRange();
10131 bool IsStaticMemberFunctionFromBoundPointer() const {
10132 return StaticMemberFunctionFromBoundPointer;
10135 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10136 S.Diag(OvlExpr->getLocStart(),
10137 diag::err_invalid_form_pointer_member_function)
10138 << OvlExpr->getSourceRange();
10141 void ComplainOfInvalidConversion() const {
10142 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10143 << OvlExpr->getName() << TargetType;
10146 void ComplainMultipleMatchesFound() const {
10147 assert(Matches.size() > 1);
10148 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10149 << OvlExpr->getName()
10150 << OvlExpr->getSourceRange();
10151 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10154 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10156 int getNumMatches() const { return Matches.size(); }
10158 FunctionDecl* getMatchingFunctionDecl() const {
10159 if (Matches.size() != 1) return nullptr;
10160 return Matches[0].second;
10163 const DeclAccessPair* getMatchingFunctionAccessPair() const {
10164 if (Matches.size() != 1) return nullptr;
10165 return &Matches[0].first;
10170 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10171 /// an overloaded function (C++ [over.over]), where @p From is an
10172 /// expression with overloaded function type and @p ToType is the type
10173 /// we're trying to resolve to. For example:
10179 /// int (*pfd)(double) = f; // selects f(double)
10182 /// This routine returns the resulting FunctionDecl if it could be
10183 /// resolved, and NULL otherwise. When @p Complain is true, this
10184 /// routine will emit diagnostics if there is an error.
10186 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10187 QualType TargetType,
10189 DeclAccessPair &FoundResult,
10190 bool *pHadMultipleCandidates) {
10191 assert(AddressOfExpr->getType() == Context.OverloadTy);
10193 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10195 int NumMatches = Resolver.getNumMatches();
10196 FunctionDecl *Fn = nullptr;
10197 if (NumMatches == 0 && Complain) {
10198 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10199 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10201 Resolver.ComplainNoMatchesFound();
10203 else if (NumMatches > 1 && Complain)
10204 Resolver.ComplainMultipleMatchesFound();
10205 else if (NumMatches == 1) {
10206 Fn = Resolver.getMatchingFunctionDecl();
10208 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10210 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10211 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10213 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10217 if (pHadMultipleCandidates)
10218 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10222 /// \brief Given an expression that refers to an overloaded function, try to
10223 /// resolve that overloaded function expression down to a single function.
10225 /// This routine can only resolve template-ids that refer to a single function
10226 /// template, where that template-id refers to a single template whose template
10227 /// arguments are either provided by the template-id or have defaults,
10228 /// as described in C++0x [temp.arg.explicit]p3.
10230 /// If no template-ids are found, no diagnostics are emitted and NULL is
10233 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10235 DeclAccessPair *FoundResult) {
10236 // C++ [over.over]p1:
10237 // [...] [Note: any redundant set of parentheses surrounding the
10238 // overloaded function name is ignored (5.1). ]
10239 // C++ [over.over]p1:
10240 // [...] The overloaded function name can be preceded by the &
10243 // If we didn't actually find any template-ids, we're done.
10244 if (!ovl->hasExplicitTemplateArgs())
10247 TemplateArgumentListInfo ExplicitTemplateArgs;
10248 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10249 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10251 // Look through all of the overloaded functions, searching for one
10252 // whose type matches exactly.
10253 FunctionDecl *Matched = nullptr;
10254 for (UnresolvedSetIterator I = ovl->decls_begin(),
10255 E = ovl->decls_end(); I != E; ++I) {
10256 // C++0x [temp.arg.explicit]p3:
10257 // [...] In contexts where deduction is done and fails, or in contexts
10258 // where deduction is not done, if a template argument list is
10259 // specified and it, along with any default template arguments,
10260 // identifies a single function template specialization, then the
10261 // template-id is an lvalue for the function template specialization.
10262 FunctionTemplateDecl *FunctionTemplate
10263 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10265 // C++ [over.over]p2:
10266 // If the name is a function template, template argument deduction is
10267 // done (14.8.2.2), and if the argument deduction succeeds, the
10268 // resulting template argument list is used to generate a single
10269 // function template specialization, which is added to the set of
10270 // overloaded functions considered.
10271 FunctionDecl *Specialization = nullptr;
10272 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10273 if (TemplateDeductionResult Result
10274 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10275 Specialization, Info,
10276 /*InOverloadResolution=*/true)) {
10277 // Make a note of the failed deduction for diagnostics.
10278 // TODO: Actually use the failed-deduction info?
10279 FailedCandidates.addCandidate()
10280 .set(FunctionTemplate->getTemplatedDecl(),
10281 MakeDeductionFailureInfo(Context, Result, Info));
10285 assert(Specialization && "no specialization and no error?");
10287 // Multiple matches; we can't resolve to a single declaration.
10290 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10292 NoteAllOverloadCandidates(ovl);
10297 Matched = Specialization;
10298 if (FoundResult) *FoundResult = I.getPair();
10301 if (Matched && getLangOpts().CPlusPlus14 &&
10302 Matched->getReturnType()->isUndeducedType() &&
10303 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10312 // Resolve and fix an overloaded expression that can be resolved
10313 // because it identifies a single function template specialization.
10315 // Last three arguments should only be supplied if Complain = true
10317 // Return true if it was logically possible to so resolve the
10318 // expression, regardless of whether or not it succeeded. Always
10319 // returns true if 'complain' is set.
10320 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10321 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10322 bool complain, const SourceRange& OpRangeForComplaining,
10323 QualType DestTypeForComplaining,
10324 unsigned DiagIDForComplaining) {
10325 assert(SrcExpr.get()->getType() == Context.OverloadTy);
10327 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10329 DeclAccessPair found;
10330 ExprResult SingleFunctionExpression;
10331 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10332 ovl.Expression, /*complain*/ false, &found)) {
10333 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10334 SrcExpr = ExprError();
10338 // It is only correct to resolve to an instance method if we're
10339 // resolving a form that's permitted to be a pointer to member.
10340 // Otherwise we'll end up making a bound member expression, which
10341 // is illegal in all the contexts we resolve like this.
10342 if (!ovl.HasFormOfMemberPointer &&
10343 isa<CXXMethodDecl>(fn) &&
10344 cast<CXXMethodDecl>(fn)->isInstance()) {
10345 if (!complain) return false;
10347 Diag(ovl.Expression->getExprLoc(),
10348 diag::err_bound_member_function)
10349 << 0 << ovl.Expression->getSourceRange();
10351 // TODO: I believe we only end up here if there's a mix of
10352 // static and non-static candidates (otherwise the expression
10353 // would have 'bound member' type, not 'overload' type).
10354 // Ideally we would note which candidate was chosen and why
10355 // the static candidates were rejected.
10356 SrcExpr = ExprError();
10360 // Fix the expression to refer to 'fn'.
10361 SingleFunctionExpression =
10362 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10364 // If desired, do function-to-pointer decay.
10365 if (doFunctionPointerConverion) {
10366 SingleFunctionExpression =
10367 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10368 if (SingleFunctionExpression.isInvalid()) {
10369 SrcExpr = ExprError();
10375 if (!SingleFunctionExpression.isUsable()) {
10377 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10378 << ovl.Expression->getName()
10379 << DestTypeForComplaining
10380 << OpRangeForComplaining
10381 << ovl.Expression->getQualifierLoc().getSourceRange();
10382 NoteAllOverloadCandidates(SrcExpr.get());
10384 SrcExpr = ExprError();
10391 SrcExpr = SingleFunctionExpression;
10395 /// \brief Add a single candidate to the overload set.
10396 static void AddOverloadedCallCandidate(Sema &S,
10397 DeclAccessPair FoundDecl,
10398 TemplateArgumentListInfo *ExplicitTemplateArgs,
10399 ArrayRef<Expr *> Args,
10400 OverloadCandidateSet &CandidateSet,
10401 bool PartialOverloading,
10403 NamedDecl *Callee = FoundDecl.getDecl();
10404 if (isa<UsingShadowDecl>(Callee))
10405 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10407 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10408 if (ExplicitTemplateArgs) {
10409 assert(!KnownValid && "Explicit template arguments?");
10412 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10413 /*SuppressUsedConversions=*/false,
10414 PartialOverloading);
10418 if (FunctionTemplateDecl *FuncTemplate
10419 = dyn_cast<FunctionTemplateDecl>(Callee)) {
10420 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10421 ExplicitTemplateArgs, Args, CandidateSet,
10422 /*SuppressUsedConversions=*/false,
10423 PartialOverloading);
10427 assert(!KnownValid && "unhandled case in overloaded call candidate");
10430 /// \brief Add the overload candidates named by callee and/or found by argument
10431 /// dependent lookup to the given overload set.
10432 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10433 ArrayRef<Expr *> Args,
10434 OverloadCandidateSet &CandidateSet,
10435 bool PartialOverloading) {
10438 // Verify that ArgumentDependentLookup is consistent with the rules
10439 // in C++0x [basic.lookup.argdep]p3:
10441 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10442 // and let Y be the lookup set produced by argument dependent
10443 // lookup (defined as follows). If X contains
10445 // -- a declaration of a class member, or
10447 // -- a block-scope function declaration that is not a
10448 // using-declaration, or
10450 // -- a declaration that is neither a function or a function
10453 // then Y is empty.
10455 if (ULE->requiresADL()) {
10456 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10457 E = ULE->decls_end(); I != E; ++I) {
10458 assert(!(*I)->getDeclContext()->isRecord());
10459 assert(isa<UsingShadowDecl>(*I) ||
10460 !(*I)->getDeclContext()->isFunctionOrMethod());
10461 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10466 // It would be nice to avoid this copy.
10467 TemplateArgumentListInfo TABuffer;
10468 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10469 if (ULE->hasExplicitTemplateArgs()) {
10470 ULE->copyTemplateArgumentsInto(TABuffer);
10471 ExplicitTemplateArgs = &TABuffer;
10474 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10475 E = ULE->decls_end(); I != E; ++I)
10476 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10477 CandidateSet, PartialOverloading,
10478 /*KnownValid*/ true);
10480 if (ULE->requiresADL())
10481 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10482 Args, ExplicitTemplateArgs,
10483 CandidateSet, PartialOverloading);
10486 /// Determine whether a declaration with the specified name could be moved into
10487 /// a different namespace.
10488 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10489 switch (Name.getCXXOverloadedOperator()) {
10490 case OO_New: case OO_Array_New:
10491 case OO_Delete: case OO_Array_Delete:
10499 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10500 /// template, where the non-dependent name was declared after the template
10501 /// was defined. This is common in code written for a compilers which do not
10502 /// correctly implement two-stage name lookup.
10504 /// Returns true if a viable candidate was found and a diagnostic was issued.
10506 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10507 const CXXScopeSpec &SS, LookupResult &R,
10508 OverloadCandidateSet::CandidateSetKind CSK,
10509 TemplateArgumentListInfo *ExplicitTemplateArgs,
10510 ArrayRef<Expr *> Args) {
10511 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10514 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10515 if (DC->isTransparentContext())
10518 SemaRef.LookupQualifiedName(R, DC);
10521 R.suppressDiagnostics();
10523 if (isa<CXXRecordDecl>(DC)) {
10524 // Don't diagnose names we find in classes; we get much better
10525 // diagnostics for these from DiagnoseEmptyLookup.
10530 OverloadCandidateSet Candidates(FnLoc, CSK);
10531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10532 AddOverloadedCallCandidate(SemaRef, I.getPair(),
10533 ExplicitTemplateArgs, Args,
10534 Candidates, false, /*KnownValid*/ false);
10536 OverloadCandidateSet::iterator Best;
10537 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10538 // No viable functions. Don't bother the user with notes for functions
10539 // which don't work and shouldn't be found anyway.
10544 // Find the namespaces where ADL would have looked, and suggest
10545 // declaring the function there instead.
10546 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10547 Sema::AssociatedClassSet AssociatedClasses;
10548 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10549 AssociatedNamespaces,
10550 AssociatedClasses);
10551 Sema::AssociatedNamespaceSet SuggestedNamespaces;
10552 if (canBeDeclaredInNamespace(R.getLookupName())) {
10553 DeclContext *Std = SemaRef.getStdNamespace();
10554 for (Sema::AssociatedNamespaceSet::iterator
10555 it = AssociatedNamespaces.begin(),
10556 end = AssociatedNamespaces.end(); it != end; ++it) {
10557 // Never suggest declaring a function within namespace 'std'.
10558 if (Std && Std->Encloses(*it))
10561 // Never suggest declaring a function within a namespace with a
10562 // reserved name, like __gnu_cxx.
10563 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10565 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10568 SuggestedNamespaces.insert(*it);
10572 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10573 << R.getLookupName();
10574 if (SuggestedNamespaces.empty()) {
10575 SemaRef.Diag(Best->Function->getLocation(),
10576 diag::note_not_found_by_two_phase_lookup)
10577 << R.getLookupName() << 0;
10578 } else if (SuggestedNamespaces.size() == 1) {
10579 SemaRef.Diag(Best->Function->getLocation(),
10580 diag::note_not_found_by_two_phase_lookup)
10581 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10583 // FIXME: It would be useful to list the associated namespaces here,
10584 // but the diagnostics infrastructure doesn't provide a way to produce
10585 // a localized representation of a list of items.
10586 SemaRef.Diag(Best->Function->getLocation(),
10587 diag::note_not_found_by_two_phase_lookup)
10588 << R.getLookupName() << 2;
10591 // Try to recover by calling this function.
10601 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10602 /// template, where the non-dependent operator was declared after the template
10605 /// Returns true if a viable candidate was found and a diagnostic was issued.
10607 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10608 SourceLocation OpLoc,
10609 ArrayRef<Expr *> Args) {
10610 DeclarationName OpName =
10611 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10612 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10613 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10614 OverloadCandidateSet::CSK_Operator,
10615 /*ExplicitTemplateArgs=*/nullptr, Args);
10619 class BuildRecoveryCallExprRAII {
10622 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10623 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10624 SemaRef.IsBuildingRecoveryCallExpr = true;
10627 ~BuildRecoveryCallExprRAII() {
10628 SemaRef.IsBuildingRecoveryCallExpr = false;
10634 static std::unique_ptr<CorrectionCandidateCallback>
10635 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10636 bool HasTemplateArgs, bool AllowTypoCorrection) {
10637 if (!AllowTypoCorrection)
10638 return llvm::make_unique<NoTypoCorrectionCCC>();
10639 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10640 HasTemplateArgs, ME);
10643 /// Attempts to recover from a call where no functions were found.
10645 /// Returns true if new candidates were found.
10647 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10648 UnresolvedLookupExpr *ULE,
10649 SourceLocation LParenLoc,
10650 MutableArrayRef<Expr *> Args,
10651 SourceLocation RParenLoc,
10652 bool EmptyLookup, bool AllowTypoCorrection) {
10653 // Do not try to recover if it is already building a recovery call.
10654 // This stops infinite loops for template instantiations like
10656 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10657 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10659 if (SemaRef.IsBuildingRecoveryCallExpr)
10660 return ExprError();
10661 BuildRecoveryCallExprRAII RCE(SemaRef);
10664 SS.Adopt(ULE->getQualifierLoc());
10665 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10667 TemplateArgumentListInfo TABuffer;
10668 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10669 if (ULE->hasExplicitTemplateArgs()) {
10670 ULE->copyTemplateArgumentsInto(TABuffer);
10671 ExplicitTemplateArgs = &TABuffer;
10674 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10675 Sema::LookupOrdinaryName);
10676 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10677 OverloadCandidateSet::CSK_Normal,
10678 ExplicitTemplateArgs, Args) &&
10680 SemaRef.DiagnoseEmptyLookup(
10682 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10683 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10684 ExplicitTemplateArgs, Args)))
10685 return ExprError();
10687 assert(!R.empty() && "lookup results empty despite recovery");
10689 // Build an implicit member call if appropriate. Just drop the
10690 // casts and such from the call, we don't really care.
10691 ExprResult NewFn = ExprError();
10692 if ((*R.begin())->isCXXClassMember())
10693 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10694 R, ExplicitTemplateArgs);
10695 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10696 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10697 ExplicitTemplateArgs);
10699 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10701 if (NewFn.isInvalid())
10702 return ExprError();
10704 // This shouldn't cause an infinite loop because we're giving it
10705 // an expression with viable lookup results, which should never
10707 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10708 MultiExprArg(Args.data(), Args.size()),
10712 /// \brief Constructs and populates an OverloadedCandidateSet from
10713 /// the given function.
10714 /// \returns true when an the ExprResult output parameter has been set.
10715 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10716 UnresolvedLookupExpr *ULE,
10718 SourceLocation RParenLoc,
10719 OverloadCandidateSet *CandidateSet,
10720 ExprResult *Result) {
10722 if (ULE->requiresADL()) {
10723 // To do ADL, we must have found an unqualified name.
10724 assert(!ULE->getQualifier() && "qualified name with ADL");
10726 // We don't perform ADL for implicit declarations of builtins.
10727 // Verify that this was correctly set up.
10729 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10730 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10731 F->getBuiltinID() && F->isImplicit())
10732 llvm_unreachable("performing ADL for builtin");
10734 // We don't perform ADL in C.
10735 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10739 UnbridgedCastsSet UnbridgedCasts;
10740 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10741 *Result = ExprError();
10745 // Add the functions denoted by the callee to the set of candidate
10746 // functions, including those from argument-dependent lookup.
10747 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10749 // If we found nothing, try to recover.
10750 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10751 // out if it fails.
10752 if (CandidateSet->empty()) {
10753 // In Microsoft mode, if we are inside a template class member function then
10754 // create a type dependent CallExpr. The goal is to postpone name lookup
10755 // to instantiation time to be able to search into type dependent base
10757 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10758 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10759 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10760 Context.DependentTy, VK_RValue,
10762 CE->setTypeDependent(true);
10769 UnbridgedCasts.restore();
10773 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10774 /// the completed call expression. If overload resolution fails, emits
10775 /// diagnostics and returns ExprError()
10776 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10777 UnresolvedLookupExpr *ULE,
10778 SourceLocation LParenLoc,
10780 SourceLocation RParenLoc,
10782 OverloadCandidateSet *CandidateSet,
10783 OverloadCandidateSet::iterator *Best,
10784 OverloadingResult OverloadResult,
10785 bool AllowTypoCorrection) {
10786 if (CandidateSet->empty())
10787 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10788 RParenLoc, /*EmptyLookup=*/true,
10789 AllowTypoCorrection);
10791 switch (OverloadResult) {
10793 FunctionDecl *FDecl = (*Best)->Function;
10794 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10795 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10796 return ExprError();
10797 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10798 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10802 case OR_No_Viable_Function: {
10803 // Try to recover by looking for viable functions which the user might
10804 // have meant to call.
10805 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10807 /*EmptyLookup=*/false,
10808 AllowTypoCorrection);
10809 if (!Recovery.isInvalid())
10812 SemaRef.Diag(Fn->getLocStart(),
10813 diag::err_ovl_no_viable_function_in_call)
10814 << ULE->getName() << Fn->getSourceRange();
10815 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10820 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10821 << ULE->getName() << Fn->getSourceRange();
10822 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10826 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10827 << (*Best)->Function->isDeleted()
10829 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10830 << Fn->getSourceRange();
10831 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10833 // We emitted an error for the unvailable/deleted function call but keep
10834 // the call in the AST.
10835 FunctionDecl *FDecl = (*Best)->Function;
10836 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10837 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10842 // Overload resolution failed.
10843 return ExprError();
10846 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10847 /// (which eventually refers to the declaration Func) and the call
10848 /// arguments Args/NumArgs, attempt to resolve the function call down
10849 /// to a specific function. If overload resolution succeeds, returns
10850 /// the call expression produced by overload resolution.
10851 /// Otherwise, emits diagnostics and returns ExprError.
10852 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10853 UnresolvedLookupExpr *ULE,
10854 SourceLocation LParenLoc,
10856 SourceLocation RParenLoc,
10858 bool AllowTypoCorrection) {
10859 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10860 OverloadCandidateSet::CSK_Normal);
10863 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10867 OverloadCandidateSet::iterator Best;
10868 OverloadingResult OverloadResult =
10869 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10871 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10872 RParenLoc, ExecConfig, &CandidateSet,
10873 &Best, OverloadResult,
10874 AllowTypoCorrection);
10877 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10878 return Functions.size() > 1 ||
10879 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10882 /// \brief Create a unary operation that may resolve to an overloaded
10885 /// \param OpLoc The location of the operator itself (e.g., '*').
10887 /// \param OpcIn The UnaryOperator::Opcode that describes this
10890 /// \param Fns The set of non-member functions that will be
10891 /// considered by overload resolution. The caller needs to build this
10892 /// set based on the context using, e.g.,
10893 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10894 /// set should not contain any member functions; those will be added
10895 /// by CreateOverloadedUnaryOp().
10897 /// \param Input The input argument.
10899 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10900 const UnresolvedSetImpl &Fns,
10902 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10904 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10905 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10906 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10907 // TODO: provide better source location info.
10908 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10910 if (checkPlaceholderForOverload(*this, Input))
10911 return ExprError();
10913 Expr *Args[2] = { Input, nullptr };
10914 unsigned NumArgs = 1;
10916 // For post-increment and post-decrement, add the implicit '0' as
10917 // the second argument, so that we know this is a post-increment or
10919 if (Opc == UO_PostInc || Opc == UO_PostDec) {
10920 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10921 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10926 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10928 if (Input->isTypeDependent()) {
10930 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10931 VK_RValue, OK_Ordinary, OpLoc);
10933 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10934 UnresolvedLookupExpr *Fn
10935 = UnresolvedLookupExpr::Create(Context, NamingClass,
10936 NestedNameSpecifierLoc(), OpNameInfo,
10937 /*ADL*/ true, IsOverloaded(Fns),
10938 Fns.begin(), Fns.end());
10939 return new (Context)
10940 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10941 VK_RValue, OpLoc, false);
10944 // Build an empty overload set.
10945 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10947 // Add the candidates from the given function set.
10948 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
10950 // Add operator candidates that are member functions.
10951 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10953 // Add candidates from ADL.
10954 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10955 /*ExplicitTemplateArgs*/nullptr,
10958 // Add builtin operator candidates.
10959 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10961 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10963 // Perform overload resolution.
10964 OverloadCandidateSet::iterator Best;
10965 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10967 // We found a built-in operator or an overloaded operator.
10968 FunctionDecl *FnDecl = Best->Function;
10971 // We matched an overloaded operator. Build a call to that
10974 // Convert the arguments.
10975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10976 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10978 ExprResult InputRes =
10979 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10980 Best->FoundDecl, Method);
10981 if (InputRes.isInvalid())
10982 return ExprError();
10983 Input = InputRes.get();
10985 // Convert the arguments.
10986 ExprResult InputInit
10987 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10989 FnDecl->getParamDecl(0)),
10992 if (InputInit.isInvalid())
10993 return ExprError();
10994 Input = InputInit.get();
10997 // Build the actual expression node.
10998 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10999 HadMultipleCandidates, OpLoc);
11000 if (FnExpr.isInvalid())
11001 return ExprError();
11003 // Determine the result type.
11004 QualType ResultTy = FnDecl->getReturnType();
11005 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11006 ResultTy = ResultTy.getNonLValueExprType(Context);
11009 CallExpr *TheCall =
11010 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11011 ResultTy, VK, OpLoc, false);
11013 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11014 return ExprError();
11016 return MaybeBindToTemporary(TheCall);
11018 // We matched a built-in operator. Convert the arguments, then
11019 // break out so that we will build the appropriate built-in
11021 ExprResult InputRes =
11022 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11023 Best->Conversions[0], AA_Passing);
11024 if (InputRes.isInvalid())
11025 return ExprError();
11026 Input = InputRes.get();
11031 case OR_No_Viable_Function:
11032 // This is an erroneous use of an operator which can be overloaded by
11033 // a non-member function. Check for non-member operators which were
11034 // defined too late to be candidates.
11035 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11036 // FIXME: Recover by calling the found function.
11037 return ExprError();
11039 // No viable function; fall through to handling this as a
11040 // built-in operator, which will produce an error message for us.
11044 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11045 << UnaryOperator::getOpcodeStr(Opc)
11046 << Input->getType()
11047 << Input->getSourceRange();
11048 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11049 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11050 return ExprError();
11053 Diag(OpLoc, diag::err_ovl_deleted_oper)
11054 << Best->Function->isDeleted()
11055 << UnaryOperator::getOpcodeStr(Opc)
11056 << getDeletedOrUnavailableSuffix(Best->Function)
11057 << Input->getSourceRange();
11058 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11059 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11060 return ExprError();
11063 // Either we found no viable overloaded operator or we matched a
11064 // built-in operator. In either case, fall through to trying to
11065 // build a built-in operation.
11066 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11069 /// \brief Create a binary operation that may resolve to an overloaded
11072 /// \param OpLoc The location of the operator itself (e.g., '+').
11074 /// \param OpcIn The BinaryOperator::Opcode that describes this
11077 /// \param Fns The set of non-member functions that will be
11078 /// considered by overload resolution. The caller needs to build this
11079 /// set based on the context using, e.g.,
11080 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11081 /// set should not contain any member functions; those will be added
11082 /// by CreateOverloadedBinOp().
11084 /// \param LHS Left-hand argument.
11085 /// \param RHS Right-hand argument.
11087 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11089 const UnresolvedSetImpl &Fns,
11090 Expr *LHS, Expr *RHS) {
11091 Expr *Args[2] = { LHS, RHS };
11092 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11094 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11095 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11098 // If either side is type-dependent, create an appropriate dependent
11100 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11102 // If there are no functions to store, just build a dependent
11103 // BinaryOperator or CompoundAssignment.
11104 if (Opc <= BO_Assign || Opc > BO_OrAssign)
11105 return new (Context) BinaryOperator(
11106 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11107 OpLoc, FPFeatures.fp_contract);
11109 return new (Context) CompoundAssignOperator(
11110 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11111 Context.DependentTy, Context.DependentTy, OpLoc,
11112 FPFeatures.fp_contract);
11115 // FIXME: save results of ADL from here?
11116 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11117 // TODO: provide better source location info in DNLoc component.
11118 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11119 UnresolvedLookupExpr *Fn
11120 = UnresolvedLookupExpr::Create(Context, NamingClass,
11121 NestedNameSpecifierLoc(), OpNameInfo,
11122 /*ADL*/ true, IsOverloaded(Fns),
11123 Fns.begin(), Fns.end());
11124 return new (Context)
11125 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11126 VK_RValue, OpLoc, FPFeatures.fp_contract);
11129 // Always do placeholder-like conversions on the RHS.
11130 if (checkPlaceholderForOverload(*this, Args[1]))
11131 return ExprError();
11133 // Do placeholder-like conversion on the LHS; note that we should
11134 // not get here with a PseudoObject LHS.
11135 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11136 if (checkPlaceholderForOverload(*this, Args[0]))
11137 return ExprError();
11139 // If this is the assignment operator, we only perform overload resolution
11140 // if the left-hand side is a class or enumeration type. This is actually
11141 // a hack. The standard requires that we do overload resolution between the
11142 // various built-in candidates, but as DR507 points out, this can lead to
11143 // problems. So we do it this way, which pretty much follows what GCC does.
11144 // Note that we go the traditional code path for compound assignment forms.
11145 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11146 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11148 // If this is the .* operator, which is not overloadable, just
11149 // create a built-in binary operator.
11150 if (Opc == BO_PtrMemD)
11151 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11153 // Build an empty overload set.
11154 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11156 // Add the candidates from the given function set.
11157 AddFunctionCandidates(Fns, Args, CandidateSet);
11159 // Add operator candidates that are member functions.
11160 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11162 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11163 // performed for an assignment operator (nor for operator[] nor operator->,
11164 // which don't get here).
11165 if (Opc != BO_Assign)
11166 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11167 /*ExplicitTemplateArgs*/ nullptr,
11170 // Add builtin operator candidates.
11171 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11175 // Perform overload resolution.
11176 OverloadCandidateSet::iterator Best;
11177 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11179 // We found a built-in operator or an overloaded operator.
11180 FunctionDecl *FnDecl = Best->Function;
11183 // We matched an overloaded operator. Build a call to that
11186 // Convert the arguments.
11187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11188 // Best->Access is only meaningful for class members.
11189 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11192 PerformCopyInitialization(
11193 InitializedEntity::InitializeParameter(Context,
11194 FnDecl->getParamDecl(0)),
11195 SourceLocation(), Args[1]);
11196 if (Arg1.isInvalid())
11197 return ExprError();
11200 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11201 Best->FoundDecl, Method);
11202 if (Arg0.isInvalid())
11203 return ExprError();
11204 Args[0] = Arg0.getAs<Expr>();
11205 Args[1] = RHS = Arg1.getAs<Expr>();
11207 // Convert the arguments.
11208 ExprResult Arg0 = PerformCopyInitialization(
11209 InitializedEntity::InitializeParameter(Context,
11210 FnDecl->getParamDecl(0)),
11211 SourceLocation(), Args[0]);
11212 if (Arg0.isInvalid())
11213 return ExprError();
11216 PerformCopyInitialization(
11217 InitializedEntity::InitializeParameter(Context,
11218 FnDecl->getParamDecl(1)),
11219 SourceLocation(), Args[1]);
11220 if (Arg1.isInvalid())
11221 return ExprError();
11222 Args[0] = LHS = Arg0.getAs<Expr>();
11223 Args[1] = RHS = Arg1.getAs<Expr>();
11226 // Build the actual expression node.
11227 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11229 HadMultipleCandidates, OpLoc);
11230 if (FnExpr.isInvalid())
11231 return ExprError();
11233 // Determine the result type.
11234 QualType ResultTy = FnDecl->getReturnType();
11235 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11236 ResultTy = ResultTy.getNonLValueExprType(Context);
11238 CXXOperatorCallExpr *TheCall =
11239 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11240 Args, ResultTy, VK, OpLoc,
11241 FPFeatures.fp_contract);
11243 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11245 return ExprError();
11247 ArrayRef<const Expr *> ArgsArray(Args, 2);
11248 // Cut off the implicit 'this'.
11249 if (isa<CXXMethodDecl>(FnDecl))
11250 ArgsArray = ArgsArray.slice(1);
11252 // Check for a self move.
11253 if (Op == OO_Equal)
11254 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11256 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11257 TheCall->getSourceRange(), VariadicDoesNotApply);
11259 return MaybeBindToTemporary(TheCall);
11261 // We matched a built-in operator. Convert the arguments, then
11262 // break out so that we will build the appropriate built-in
11264 ExprResult ArgsRes0 =
11265 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11266 Best->Conversions[0], AA_Passing);
11267 if (ArgsRes0.isInvalid())
11268 return ExprError();
11269 Args[0] = ArgsRes0.get();
11271 ExprResult ArgsRes1 =
11272 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11273 Best->Conversions[1], AA_Passing);
11274 if (ArgsRes1.isInvalid())
11275 return ExprError();
11276 Args[1] = ArgsRes1.get();
11281 case OR_No_Viable_Function: {
11282 // C++ [over.match.oper]p9:
11283 // If the operator is the operator , [...] and there are no
11284 // viable functions, then the operator is assumed to be the
11285 // built-in operator and interpreted according to clause 5.
11286 if (Opc == BO_Comma)
11289 // For class as left operand for assignment or compound assigment
11290 // operator do not fall through to handling in built-in, but report that
11291 // no overloaded assignment operator found
11292 ExprResult Result = ExprError();
11293 if (Args[0]->getType()->isRecordType() &&
11294 Opc >= BO_Assign && Opc <= BO_OrAssign) {
11295 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11296 << BinaryOperator::getOpcodeStr(Opc)
11297 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11298 if (Args[0]->getType()->isIncompleteType()) {
11299 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11300 << Args[0]->getType()
11301 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11304 // This is an erroneous use of an operator which can be overloaded by
11305 // a non-member function. Check for non-member operators which were
11306 // defined too late to be candidates.
11307 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11308 // FIXME: Recover by calling the found function.
11309 return ExprError();
11311 // No viable function; try to create a built-in operation, which will
11312 // produce an error. Then, show the non-viable candidates.
11313 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11315 assert(Result.isInvalid() &&
11316 "C++ binary operator overloading is missing candidates!");
11317 if (Result.isInvalid())
11318 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11319 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11324 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
11325 << BinaryOperator::getOpcodeStr(Opc)
11326 << Args[0]->getType() << Args[1]->getType()
11327 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11328 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11329 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11330 return ExprError();
11333 if (isImplicitlyDeleted(Best->Function)) {
11334 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11335 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11336 << Context.getRecordType(Method->getParent())
11337 << getSpecialMember(Method);
11339 // The user probably meant to call this special member. Just
11340 // explain why it's deleted.
11341 NoteDeletedFunction(Method);
11342 return ExprError();
11344 Diag(OpLoc, diag::err_ovl_deleted_oper)
11345 << Best->Function->isDeleted()
11346 << BinaryOperator::getOpcodeStr(Opc)
11347 << getDeletedOrUnavailableSuffix(Best->Function)
11348 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11350 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11351 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11352 return ExprError();
11355 // We matched a built-in operator; build it.
11356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11360 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11361 SourceLocation RLoc,
11362 Expr *Base, Expr *Idx) {
11363 Expr *Args[2] = { Base, Idx };
11364 DeclarationName OpName =
11365 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11367 // If either side is type-dependent, create an appropriate dependent
11369 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11371 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11372 // CHECKME: no 'operator' keyword?
11373 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11374 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11375 UnresolvedLookupExpr *Fn
11376 = UnresolvedLookupExpr::Create(Context, NamingClass,
11377 NestedNameSpecifierLoc(), OpNameInfo,
11378 /*ADL*/ true, /*Overloaded*/ false,
11379 UnresolvedSetIterator(),
11380 UnresolvedSetIterator());
11381 // Can't add any actual overloads yet
11383 return new (Context)
11384 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11385 Context.DependentTy, VK_RValue, RLoc, false);
11388 // Handle placeholders on both operands.
11389 if (checkPlaceholderForOverload(*this, Args[0]))
11390 return ExprError();
11391 if (checkPlaceholderForOverload(*this, Args[1]))
11392 return ExprError();
11394 // Build an empty overload set.
11395 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11397 // Subscript can only be overloaded as a member function.
11399 // Add operator candidates that are member functions.
11400 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11402 // Add builtin operator candidates.
11403 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11405 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11407 // Perform overload resolution.
11408 OverloadCandidateSet::iterator Best;
11409 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11411 // We found a built-in operator or an overloaded operator.
11412 FunctionDecl *FnDecl = Best->Function;
11415 // We matched an overloaded operator. Build a call to that
11418 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11420 // Convert the arguments.
11421 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11423 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11424 Best->FoundDecl, Method);
11425 if (Arg0.isInvalid())
11426 return ExprError();
11427 Args[0] = Arg0.get();
11429 // Convert the arguments.
11430 ExprResult InputInit
11431 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11433 FnDecl->getParamDecl(0)),
11436 if (InputInit.isInvalid())
11437 return ExprError();
11439 Args[1] = InputInit.getAs<Expr>();
11441 // Build the actual expression node.
11442 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11443 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11444 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11446 HadMultipleCandidates,
11447 OpLocInfo.getLoc(),
11448 OpLocInfo.getInfo());
11449 if (FnExpr.isInvalid())
11450 return ExprError();
11452 // Determine the result type
11453 QualType ResultTy = FnDecl->getReturnType();
11454 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11455 ResultTy = ResultTy.getNonLValueExprType(Context);
11457 CXXOperatorCallExpr *TheCall =
11458 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11459 FnExpr.get(), Args,
11460 ResultTy, VK, RLoc,
11463 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11464 return ExprError();
11466 return MaybeBindToTemporary(TheCall);
11468 // We matched a built-in operator. Convert the arguments, then
11469 // break out so that we will build the appropriate built-in
11471 ExprResult ArgsRes0 =
11472 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11473 Best->Conversions[0], AA_Passing);
11474 if (ArgsRes0.isInvalid())
11475 return ExprError();
11476 Args[0] = ArgsRes0.get();
11478 ExprResult ArgsRes1 =
11479 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11480 Best->Conversions[1], AA_Passing);
11481 if (ArgsRes1.isInvalid())
11482 return ExprError();
11483 Args[1] = ArgsRes1.get();
11489 case OR_No_Viable_Function: {
11490 if (CandidateSet.empty())
11491 Diag(LLoc, diag::err_ovl_no_oper)
11492 << Args[0]->getType() << /*subscript*/ 0
11493 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11495 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11496 << Args[0]->getType()
11497 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11500 return ExprError();
11504 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
11506 << Args[0]->getType() << Args[1]->getType()
11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11508 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11510 return ExprError();
11513 Diag(LLoc, diag::err_ovl_deleted_oper)
11514 << Best->Function->isDeleted() << "[]"
11515 << getDeletedOrUnavailableSuffix(Best->Function)
11516 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11517 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11519 return ExprError();
11522 // We matched a built-in operator; build it.
11523 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11526 /// BuildCallToMemberFunction - Build a call to a member
11527 /// function. MemExpr is the expression that refers to the member
11528 /// function (and includes the object parameter), Args/NumArgs are the
11529 /// arguments to the function call (not including the object
11530 /// parameter). The caller needs to validate that the member
11531 /// expression refers to a non-static member function or an overloaded
11532 /// member function.
11534 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11535 SourceLocation LParenLoc,
11537 SourceLocation RParenLoc) {
11538 assert(MemExprE->getType() == Context.BoundMemberTy ||
11539 MemExprE->getType() == Context.OverloadTy);
11541 // Dig out the member expression. This holds both the object
11542 // argument and the member function we're referring to.
11543 Expr *NakedMemExpr = MemExprE->IgnoreParens();
11545 // Determine whether this is a call to a pointer-to-member function.
11546 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11547 assert(op->getType() == Context.BoundMemberTy);
11548 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11551 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11553 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11554 QualType resultType = proto->getCallResultType(Context);
11555 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11557 // Check that the object type isn't more qualified than the
11558 // member function we're calling.
11559 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11561 QualType objectType = op->getLHS()->getType();
11562 if (op->getOpcode() == BO_PtrMemI)
11563 objectType = objectType->castAs<PointerType>()->getPointeeType();
11564 Qualifiers objectQuals = objectType.getQualifiers();
11566 Qualifiers difference = objectQuals - funcQuals;
11567 difference.removeObjCGCAttr();
11568 difference.removeAddressSpace();
11570 std::string qualsString = difference.getAsString();
11571 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11572 << fnType.getUnqualifiedType()
11574 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11577 if (resultType->isMemberPointerType())
11578 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11579 RequireCompleteType(LParenLoc, resultType, 0);
11581 CXXMemberCallExpr *call
11582 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11583 resultType, valueKind, RParenLoc);
11585 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11587 return ExprError();
11589 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11590 return ExprError();
11592 if (CheckOtherCall(call, proto))
11593 return ExprError();
11595 return MaybeBindToTemporary(call);
11598 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11599 return new (Context)
11600 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11602 UnbridgedCastsSet UnbridgedCasts;
11603 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11604 return ExprError();
11606 MemberExpr *MemExpr;
11607 CXXMethodDecl *Method = nullptr;
11608 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11609 NestedNameSpecifier *Qualifier = nullptr;
11610 if (isa<MemberExpr>(NakedMemExpr)) {
11611 MemExpr = cast<MemberExpr>(NakedMemExpr);
11612 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11613 FoundDecl = MemExpr->getFoundDecl();
11614 Qualifier = MemExpr->getQualifier();
11615 UnbridgedCasts.restore();
11617 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11618 Qualifier = UnresExpr->getQualifier();
11620 QualType ObjectType = UnresExpr->getBaseType();
11621 Expr::Classification ObjectClassification
11622 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11623 : UnresExpr->getBase()->Classify(Context);
11625 // Add overload candidates
11626 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11627 OverloadCandidateSet::CSK_Normal);
11629 // FIXME: avoid copy.
11630 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11631 if (UnresExpr->hasExplicitTemplateArgs()) {
11632 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11633 TemplateArgs = &TemplateArgsBuffer;
11636 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11637 E = UnresExpr->decls_end(); I != E; ++I) {
11639 NamedDecl *Func = *I;
11640 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11641 if (isa<UsingShadowDecl>(Func))
11642 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11645 // Microsoft supports direct constructor calls.
11646 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11647 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11648 Args, CandidateSet);
11649 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11650 // If explicit template arguments were provided, we can't call a
11651 // non-template member function.
11655 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11656 ObjectClassification, Args, CandidateSet,
11657 /*SuppressUserConversions=*/false);
11659 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11660 I.getPair(), ActingDC, TemplateArgs,
11661 ObjectType, ObjectClassification,
11662 Args, CandidateSet,
11663 /*SuppressUsedConversions=*/false);
11667 DeclarationName DeclName = UnresExpr->getMemberName();
11669 UnbridgedCasts.restore();
11671 OverloadCandidateSet::iterator Best;
11672 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11675 Method = cast<CXXMethodDecl>(Best->Function);
11676 FoundDecl = Best->FoundDecl;
11677 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11678 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11679 return ExprError();
11680 // If FoundDecl is different from Method (such as if one is a template
11681 // and the other a specialization), make sure DiagnoseUseOfDecl is
11683 // FIXME: This would be more comprehensively addressed by modifying
11684 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11686 if (Method != FoundDecl.getDecl() &&
11687 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11688 return ExprError();
11691 case OR_No_Viable_Function:
11692 Diag(UnresExpr->getMemberLoc(),
11693 diag::err_ovl_no_viable_member_function_in_call)
11694 << DeclName << MemExprE->getSourceRange();
11695 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11696 // FIXME: Leaking incoming expressions!
11697 return ExprError();
11700 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11701 << DeclName << MemExprE->getSourceRange();
11702 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11703 // FIXME: Leaking incoming expressions!
11704 return ExprError();
11707 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11708 << Best->Function->isDeleted()
11710 << getDeletedOrUnavailableSuffix(Best->Function)
11711 << MemExprE->getSourceRange();
11712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11713 // FIXME: Leaking incoming expressions!
11714 return ExprError();
11717 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11719 // If overload resolution picked a static member, build a
11720 // non-member call based on that function.
11721 if (Method->isStatic()) {
11722 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11726 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11729 QualType ResultType = Method->getReturnType();
11730 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11731 ResultType = ResultType.getNonLValueExprType(Context);
11733 assert(Method && "Member call to something that isn't a method?");
11734 CXXMemberCallExpr *TheCall =
11735 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11736 ResultType, VK, RParenLoc);
11738 // (CUDA B.1): Check for invalid calls between targets.
11739 if (getLangOpts().CUDA) {
11740 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11741 if (CheckCUDATarget(Caller, Method)) {
11742 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11743 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11744 << IdentifyCUDATarget(Caller);
11745 return ExprError();
11750 // Check for a valid return type.
11751 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11753 return ExprError();
11755 // Convert the object argument (for a non-static member function call).
11756 // We only need to do this if there was actually an overload; otherwise
11757 // it was done at lookup.
11758 if (!Method->isStatic()) {
11759 ExprResult ObjectArg =
11760 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11761 FoundDecl, Method);
11762 if (ObjectArg.isInvalid())
11763 return ExprError();
11764 MemExpr->setBase(ObjectArg.get());
11767 // Convert the rest of the arguments
11768 const FunctionProtoType *Proto =
11769 Method->getType()->getAs<FunctionProtoType>();
11770 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11772 return ExprError();
11774 DiagnoseSentinelCalls(Method, LParenLoc, Args);
11776 if (CheckFunctionCall(Method, TheCall, Proto))
11777 return ExprError();
11779 if ((isa<CXXConstructorDecl>(CurContext) ||
11780 isa<CXXDestructorDecl>(CurContext)) &&
11781 TheCall->getMethodDecl()->isPure()) {
11782 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11784 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11785 Diag(MemExpr->getLocStart(),
11786 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11787 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11788 << MD->getParent()->getDeclName();
11790 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11793 return MaybeBindToTemporary(TheCall);
11796 /// BuildCallToObjectOfClassType - Build a call to an object of class
11797 /// type (C++ [over.call.object]), which can end up invoking an
11798 /// overloaded function call operator (@c operator()) or performing a
11799 /// user-defined conversion on the object argument.
11801 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11802 SourceLocation LParenLoc,
11804 SourceLocation RParenLoc) {
11805 if (checkPlaceholderForOverload(*this, Obj))
11806 return ExprError();
11807 ExprResult Object = Obj;
11809 UnbridgedCastsSet UnbridgedCasts;
11810 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11811 return ExprError();
11813 assert(Object.get()->getType()->isRecordType() &&
11814 "Requires object type argument");
11815 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11817 // C++ [over.call.object]p1:
11818 // If the primary-expression E in the function call syntax
11819 // evaluates to a class object of type "cv T", then the set of
11820 // candidate functions includes at least the function call
11821 // operators of T. The function call operators of T are obtained by
11822 // ordinary lookup of the name operator() in the context of
11824 OverloadCandidateSet CandidateSet(LParenLoc,
11825 OverloadCandidateSet::CSK_Operator);
11826 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11828 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11829 diag::err_incomplete_object_call, Object.get()))
11832 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11833 LookupQualifiedName(R, Record->getDecl());
11834 R.suppressDiagnostics();
11836 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11837 Oper != OperEnd; ++Oper) {
11838 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11839 Object.get()->Classify(Context),
11840 Args, CandidateSet,
11841 /*SuppressUserConversions=*/ false);
11844 // C++ [over.call.object]p2:
11845 // In addition, for each (non-explicit in C++0x) conversion function
11846 // declared in T of the form
11848 // operator conversion-type-id () cv-qualifier;
11850 // where cv-qualifier is the same cv-qualification as, or a
11851 // greater cv-qualification than, cv, and where conversion-type-id
11852 // denotes the type "pointer to function of (P1,...,Pn) returning
11853 // R", or the type "reference to pointer to function of
11854 // (P1,...,Pn) returning R", or the type "reference to function
11855 // of (P1,...,Pn) returning R", a surrogate call function [...]
11856 // is also considered as a candidate function. Similarly,
11857 // surrogate call functions are added to the set of candidate
11858 // functions for each conversion function declared in an
11859 // accessible base class provided the function is not hidden
11860 // within T by another intervening declaration.
11861 const auto &Conversions =
11862 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11863 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11866 if (isa<UsingShadowDecl>(D))
11867 D = cast<UsingShadowDecl>(D)->getTargetDecl();
11869 // Skip over templated conversion functions; they aren't
11871 if (isa<FunctionTemplateDecl>(D))
11874 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11875 if (!Conv->isExplicit()) {
11876 // Strip the reference type (if any) and then the pointer type (if
11877 // any) to get down to what might be a function type.
11878 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11879 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11880 ConvType = ConvPtrType->getPointeeType();
11882 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11884 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11885 Object.get(), Args, CandidateSet);
11890 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11892 // Perform overload resolution.
11893 OverloadCandidateSet::iterator Best;
11894 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11897 // Overload resolution succeeded; we'll build the appropriate call
11901 case OR_No_Viable_Function:
11902 if (CandidateSet.empty())
11903 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11904 << Object.get()->getType() << /*call*/ 1
11905 << Object.get()->getSourceRange();
11907 Diag(Object.get()->getLocStart(),
11908 diag::err_ovl_no_viable_object_call)
11909 << Object.get()->getType() << Object.get()->getSourceRange();
11910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11914 Diag(Object.get()->getLocStart(),
11915 diag::err_ovl_ambiguous_object_call)
11916 << Object.get()->getType() << Object.get()->getSourceRange();
11917 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11921 Diag(Object.get()->getLocStart(),
11922 diag::err_ovl_deleted_object_call)
11923 << Best->Function->isDeleted()
11924 << Object.get()->getType()
11925 << getDeletedOrUnavailableSuffix(Best->Function)
11926 << Object.get()->getSourceRange();
11927 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11931 if (Best == CandidateSet.end())
11934 UnbridgedCasts.restore();
11936 if (Best->Function == nullptr) {
11937 // Since there is no function declaration, this is one of the
11938 // surrogate candidates. Dig out the conversion function.
11939 CXXConversionDecl *Conv
11940 = cast<CXXConversionDecl>(
11941 Best->Conversions[0].UserDefined.ConversionFunction);
11943 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11945 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11946 return ExprError();
11947 assert(Conv == Best->FoundDecl.getDecl() &&
11948 "Found Decl & conversion-to-functionptr should be same, right?!");
11949 // We selected one of the surrogate functions that converts the
11950 // object parameter to a function pointer. Perform the conversion
11951 // on the object argument, then let ActOnCallExpr finish the job.
11953 // Create an implicit member expr to refer to the conversion operator.
11954 // and then call it.
11955 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11956 Conv, HadMultipleCandidates);
11957 if (Call.isInvalid())
11958 return ExprError();
11959 // Record usage of conversion in an implicit cast.
11960 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11961 CK_UserDefinedConversion, Call.get(),
11962 nullptr, VK_RValue);
11964 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11967 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11969 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11970 // that calls this method, using Object for the implicit object
11971 // parameter and passing along the remaining arguments.
11972 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11974 // An error diagnostic has already been printed when parsing the declaration.
11975 if (Method->isInvalidDecl())
11976 return ExprError();
11978 const FunctionProtoType *Proto =
11979 Method->getType()->getAs<FunctionProtoType>();
11981 unsigned NumParams = Proto->getNumParams();
11983 DeclarationNameInfo OpLocInfo(
11984 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11985 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11986 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11987 HadMultipleCandidates,
11988 OpLocInfo.getLoc(),
11989 OpLocInfo.getInfo());
11990 if (NewFn.isInvalid())
11993 // Build the full argument list for the method call (the implicit object
11994 // parameter is placed at the beginning of the list).
11995 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11996 MethodArgs[0] = Object.get();
11997 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11999 // Once we've built TheCall, all of the expressions are properly
12001 QualType ResultTy = Method->getReturnType();
12002 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12003 ResultTy = ResultTy.getNonLValueExprType(Context);
12005 CXXOperatorCallExpr *TheCall = new (Context)
12006 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12007 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12008 ResultTy, VK, RParenLoc, false);
12009 MethodArgs.reset();
12011 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12014 // We may have default arguments. If so, we need to allocate more
12015 // slots in the call for them.
12016 if (Args.size() < NumParams)
12017 TheCall->setNumArgs(Context, NumParams + 1);
12019 bool IsError = false;
12021 // Initialize the implicit object parameter.
12022 ExprResult ObjRes =
12023 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12024 Best->FoundDecl, Method);
12025 if (ObjRes.isInvalid())
12029 TheCall->setArg(0, Object.get());
12031 // Check the argument types.
12032 for (unsigned i = 0; i != NumParams; i++) {
12034 if (i < Args.size()) {
12037 // Pass the argument.
12039 ExprResult InputInit
12040 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12042 Method->getParamDecl(i)),
12043 SourceLocation(), Arg);
12045 IsError |= InputInit.isInvalid();
12046 Arg = InputInit.getAs<Expr>();
12049 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12050 if (DefArg.isInvalid()) {
12055 Arg = DefArg.getAs<Expr>();
12058 TheCall->setArg(i + 1, Arg);
12061 // If this is a variadic call, handle args passed through "...".
12062 if (Proto->isVariadic()) {
12063 // Promote the arguments (C99 6.5.2.2p7).
12064 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12065 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12067 IsError |= Arg.isInvalid();
12068 TheCall->setArg(i + 1, Arg.get());
12072 if (IsError) return true;
12074 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12076 if (CheckFunctionCall(Method, TheCall, Proto))
12079 return MaybeBindToTemporary(TheCall);
12082 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12083 /// (if one exists), where @c Base is an expression of class type and
12084 /// @c Member is the name of the member we're trying to find.
12086 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12087 bool *NoArrowOperatorFound) {
12088 assert(Base->getType()->isRecordType() &&
12089 "left-hand side must have class type");
12091 if (checkPlaceholderForOverload(*this, Base))
12092 return ExprError();
12094 SourceLocation Loc = Base->getExprLoc();
12096 // C++ [over.ref]p1:
12098 // [...] An expression x->m is interpreted as (x.operator->())->m
12099 // for a class object x of type T if T::operator->() exists and if
12100 // the operator is selected as the best match function by the
12101 // overload resolution mechanism (13.3).
12102 DeclarationName OpName =
12103 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12104 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12105 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12107 if (RequireCompleteType(Loc, Base->getType(),
12108 diag::err_typecheck_incomplete_tag, Base))
12109 return ExprError();
12111 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12112 LookupQualifiedName(R, BaseRecord->getDecl());
12113 R.suppressDiagnostics();
12115 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12116 Oper != OperEnd; ++Oper) {
12117 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12118 None, CandidateSet, /*SuppressUserConversions=*/false);
12121 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12123 // Perform overload resolution.
12124 OverloadCandidateSet::iterator Best;
12125 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12127 // Overload resolution succeeded; we'll build the call below.
12130 case OR_No_Viable_Function:
12131 if (CandidateSet.empty()) {
12132 QualType BaseType = Base->getType();
12133 if (NoArrowOperatorFound) {
12134 // Report this specific error to the caller instead of emitting a
12135 // diagnostic, as requested.
12136 *NoArrowOperatorFound = true;
12137 return ExprError();
12139 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12140 << BaseType << Base->getSourceRange();
12141 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12142 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12143 << FixItHint::CreateReplacement(OpLoc, ".");
12146 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12147 << "operator->" << Base->getSourceRange();
12148 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12149 return ExprError();
12152 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12153 << "->" << Base->getType() << Base->getSourceRange();
12154 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12155 return ExprError();
12158 Diag(OpLoc, diag::err_ovl_deleted_oper)
12159 << Best->Function->isDeleted()
12161 << getDeletedOrUnavailableSuffix(Best->Function)
12162 << Base->getSourceRange();
12163 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12164 return ExprError();
12167 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12169 // Convert the object parameter.
12170 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12171 ExprResult BaseResult =
12172 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12173 Best->FoundDecl, Method);
12174 if (BaseResult.isInvalid())
12175 return ExprError();
12176 Base = BaseResult.get();
12178 // Build the operator call.
12179 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12180 HadMultipleCandidates, OpLoc);
12181 if (FnExpr.isInvalid())
12182 return ExprError();
12184 QualType ResultTy = Method->getReturnType();
12185 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12186 ResultTy = ResultTy.getNonLValueExprType(Context);
12187 CXXOperatorCallExpr *TheCall =
12188 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12189 Base, ResultTy, VK, OpLoc, false);
12191 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12192 return ExprError();
12194 return MaybeBindToTemporary(TheCall);
12197 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12198 /// a literal operator described by the provided lookup results.
12199 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12200 DeclarationNameInfo &SuffixInfo,
12201 ArrayRef<Expr*> Args,
12202 SourceLocation LitEndLoc,
12203 TemplateArgumentListInfo *TemplateArgs) {
12204 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12206 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12207 OverloadCandidateSet::CSK_Normal);
12208 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12209 /*SuppressUserConversions=*/true);
12211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12213 // Perform overload resolution. This will usually be trivial, but might need
12214 // to perform substitutions for a literal operator template.
12215 OverloadCandidateSet::iterator Best;
12216 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12221 case OR_No_Viable_Function:
12222 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12223 << R.getLookupName();
12224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12225 return ExprError();
12228 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12229 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12230 return ExprError();
12233 FunctionDecl *FD = Best->Function;
12234 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12235 HadMultipleCandidates,
12236 SuffixInfo.getLoc(),
12237 SuffixInfo.getInfo());
12238 if (Fn.isInvalid())
12241 // Check the argument types. This should almost always be a no-op, except
12242 // that array-to-pointer decay is applied to string literals.
12244 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12245 ExprResult InputInit = PerformCopyInitialization(
12246 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12247 SourceLocation(), Args[ArgIdx]);
12248 if (InputInit.isInvalid())
12250 ConvArgs[ArgIdx] = InputInit.get();
12253 QualType ResultTy = FD->getReturnType();
12254 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12255 ResultTy = ResultTy.getNonLValueExprType(Context);
12257 UserDefinedLiteral *UDL =
12258 new (Context) UserDefinedLiteral(Context, Fn.get(),
12259 llvm::makeArrayRef(ConvArgs, Args.size()),
12260 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12262 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12263 return ExprError();
12265 if (CheckFunctionCall(FD, UDL, nullptr))
12266 return ExprError();
12268 return MaybeBindToTemporary(UDL);
12271 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12272 /// given LookupResult is non-empty, it is assumed to describe a member which
12273 /// will be invoked. Otherwise, the function will be found via argument
12274 /// dependent lookup.
12275 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12276 /// otherwise CallExpr is set to ExprError() and some non-success value
12278 Sema::ForRangeStatus
12279 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12280 SourceLocation RangeLoc, VarDecl *Decl,
12281 BeginEndFunction BEF,
12282 const DeclarationNameInfo &NameInfo,
12283 LookupResult &MemberLookup,
12284 OverloadCandidateSet *CandidateSet,
12285 Expr *Range, ExprResult *CallExpr) {
12286 CandidateSet->clear();
12287 if (!MemberLookup.empty()) {
12288 ExprResult MemberRef =
12289 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12290 /*IsPtr=*/false, CXXScopeSpec(),
12291 /*TemplateKWLoc=*/SourceLocation(),
12292 /*FirstQualifierInScope=*/nullptr,
12294 /*TemplateArgs=*/nullptr);
12295 if (MemberRef.isInvalid()) {
12296 *CallExpr = ExprError();
12297 Diag(Range->getLocStart(), diag::note_in_for_range)
12298 << RangeLoc << BEF << Range->getType();
12299 return FRS_DiagnosticIssued;
12301 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12302 if (CallExpr->isInvalid()) {
12303 *CallExpr = ExprError();
12304 Diag(Range->getLocStart(), diag::note_in_for_range)
12305 << RangeLoc << BEF << Range->getType();
12306 return FRS_DiagnosticIssued;
12309 UnresolvedSet<0> FoundNames;
12310 UnresolvedLookupExpr *Fn =
12311 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12312 NestedNameSpecifierLoc(), NameInfo,
12313 /*NeedsADL=*/true, /*Overloaded=*/false,
12314 FoundNames.begin(), FoundNames.end());
12316 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12317 CandidateSet, CallExpr);
12318 if (CandidateSet->empty() || CandidateSetError) {
12319 *CallExpr = ExprError();
12320 return FRS_NoViableFunction;
12322 OverloadCandidateSet::iterator Best;
12323 OverloadingResult OverloadResult =
12324 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12326 if (OverloadResult == OR_No_Viable_Function) {
12327 *CallExpr = ExprError();
12328 return FRS_NoViableFunction;
12330 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12331 Loc, nullptr, CandidateSet, &Best,
12333 /*AllowTypoCorrection=*/false);
12334 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12335 *CallExpr = ExprError();
12336 Diag(Range->getLocStart(), diag::note_in_for_range)
12337 << RangeLoc << BEF << Range->getType();
12338 return FRS_DiagnosticIssued;
12341 return FRS_Success;
12345 /// FixOverloadedFunctionReference - E is an expression that refers to
12346 /// a C++ overloaded function (possibly with some parentheses and
12347 /// perhaps a '&' around it). We have resolved the overloaded function
12348 /// to the function declaration Fn, so patch up the expression E to
12349 /// refer (possibly indirectly) to Fn. Returns the new expr.
12350 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12351 FunctionDecl *Fn) {
12352 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12353 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12355 if (SubExpr == PE->getSubExpr())
12358 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12361 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12362 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12364 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12365 SubExpr->getType()) &&
12366 "Implicit cast type cannot be determined from overload");
12367 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12368 if (SubExpr == ICE->getSubExpr())
12371 return ImplicitCastExpr::Create(Context, ICE->getType(),
12372 ICE->getCastKind(),
12374 ICE->getValueKind());
12377 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12378 assert(UnOp->getOpcode() == UO_AddrOf &&
12379 "Can only take the address of an overloaded function");
12380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12381 if (Method->isStatic()) {
12382 // Do nothing: static member functions aren't any different
12383 // from non-member functions.
12385 // Fix the subexpression, which really has to be an
12386 // UnresolvedLookupExpr holding an overloaded member function
12388 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12390 if (SubExpr == UnOp->getSubExpr())
12393 assert(isa<DeclRefExpr>(SubExpr)
12394 && "fixed to something other than a decl ref");
12395 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12396 && "fixed to a member ref with no nested name qualifier");
12398 // We have taken the address of a pointer to member
12399 // function. Perform the computation here so that we get the
12400 // appropriate pointer to member type.
12402 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12403 QualType MemPtrType
12404 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12406 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12407 VK_RValue, OK_Ordinary,
12408 UnOp->getOperatorLoc());
12411 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12413 if (SubExpr == UnOp->getSubExpr())
12416 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12417 Context.getPointerType(SubExpr->getType()),
12418 VK_RValue, OK_Ordinary,
12419 UnOp->getOperatorLoc());
12422 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12423 // FIXME: avoid copy.
12424 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12425 if (ULE->hasExplicitTemplateArgs()) {
12426 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12427 TemplateArgs = &TemplateArgsBuffer;
12430 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12431 ULE->getQualifierLoc(),
12432 ULE->getTemplateKeywordLoc(),
12434 /*enclosing*/ false, // FIXME?
12440 MarkDeclRefReferenced(DRE);
12441 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12445 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12446 // FIXME: avoid copy.
12447 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12448 if (MemExpr->hasExplicitTemplateArgs()) {
12449 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12450 TemplateArgs = &TemplateArgsBuffer;
12455 // If we're filling in a static method where we used to have an
12456 // implicit member access, rewrite to a simple decl ref.
12457 if (MemExpr->isImplicitAccess()) {
12458 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12459 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12460 MemExpr->getQualifierLoc(),
12461 MemExpr->getTemplateKeywordLoc(),
12463 /*enclosing*/ false,
12464 MemExpr->getMemberLoc(),
12469 MarkDeclRefReferenced(DRE);
12470 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12473 SourceLocation Loc = MemExpr->getMemberLoc();
12474 if (MemExpr->getQualifier())
12475 Loc = MemExpr->getQualifierLoc().getBeginLoc();
12476 CheckCXXThisCapture(Loc);
12477 Base = new (Context) CXXThisExpr(Loc,
12478 MemExpr->getBaseType(),
12479 /*isImplicit=*/true);
12482 Base = MemExpr->getBase();
12484 ExprValueKind valueKind;
12486 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12487 valueKind = VK_LValue;
12488 type = Fn->getType();
12490 valueKind = VK_RValue;
12491 type = Context.BoundMemberTy;
12494 MemberExpr *ME = MemberExpr::Create(
12495 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12496 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12497 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12499 ME->setHadMultipleCandidates(true);
12500 MarkMemberReferenced(ME);
12504 llvm_unreachable("Invalid reference to overloaded function");
12507 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12508 DeclAccessPair Found,
12509 FunctionDecl *Fn) {
12510 return FixOverloadedFunctionReference(E.get(), Found, Fn);