1 //===--- Overload.h - C++ Overloading ---------------------------*- C++ -*-===//
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 defines the data structures and types used in C++
11 // overload resolution.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_OVERLOAD_H
16 #define LLVM_CLANG_SEMA_OVERLOAD_H
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/TemplateBase.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/UnresolvedSet.h"
24 #include "clang/Sema/SemaFixItUtils.h"
25 #include "clang/Sema/TemplateDeduction.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/AlignOf.h"
29 #include "llvm/Support/Allocator.h"
33 class CXXConstructorDecl;
34 class CXXConversionDecl;
38 /// OverloadingResult - Capture the result of performing overload
40 enum OverloadingResult {
41 OR_Success, ///< Overload resolution succeeded.
42 OR_No_Viable_Function, ///< No viable function found.
43 OR_Ambiguous, ///< Ambiguous candidates found.
44 OR_Deleted ///< Succeeded, but refers to a deleted function.
47 enum OverloadCandidateDisplayKind {
48 /// Requests that all candidates be shown. Viable candidates will
52 /// Requests that only viable candidates be shown.
56 /// ImplicitConversionKind - The kind of implicit conversion used to
57 /// convert an argument to a parameter's type. The enumerator values
58 /// match with Table 9 of (C++ 13.3.3.1.1) and are listed such that
59 /// better conversion kinds have smaller values.
60 enum ImplicitConversionKind {
61 ICK_Identity = 0, ///< Identity conversion (no conversion)
62 ICK_Lvalue_To_Rvalue, ///< Lvalue-to-rvalue conversion (C++ 4.1)
63 ICK_Array_To_Pointer, ///< Array-to-pointer conversion (C++ 4.2)
64 ICK_Function_To_Pointer, ///< Function-to-pointer (C++ 4.3)
65 ICK_Function_Conversion, ///< Function pointer conversion (C++17 4.13)
66 ICK_Qualification, ///< Qualification conversions (C++ 4.4)
67 ICK_Integral_Promotion, ///< Integral promotions (C++ 4.5)
68 ICK_Floating_Promotion, ///< Floating point promotions (C++ 4.6)
69 ICK_Complex_Promotion, ///< Complex promotions (Clang extension)
70 ICK_Integral_Conversion, ///< Integral conversions (C++ 4.7)
71 ICK_Floating_Conversion, ///< Floating point conversions (C++ 4.8)
72 ICK_Complex_Conversion, ///< Complex conversions (C99 6.3.1.6)
73 ICK_Floating_Integral, ///< Floating-integral conversions (C++ 4.9)
74 ICK_Pointer_Conversion, ///< Pointer conversions (C++ 4.10)
75 ICK_Pointer_Member, ///< Pointer-to-member conversions (C++ 4.11)
76 ICK_Boolean_Conversion, ///< Boolean conversions (C++ 4.12)
77 ICK_Compatible_Conversion, ///< Conversions between compatible types in C99
78 ICK_Derived_To_Base, ///< Derived-to-base (C++ [over.best.ics])
79 ICK_Vector_Conversion, ///< Vector conversions
80 ICK_Vector_Splat, ///< A vector splat from an arithmetic type
81 ICK_Complex_Real, ///< Complex-real conversions (C99 6.3.1.7)
82 ICK_Block_Pointer_Conversion, ///< Block Pointer conversions
83 ICK_TransparentUnionConversion, ///< Transparent Union Conversions
84 ICK_Writeback_Conversion, ///< Objective-C ARC writeback conversion
85 ICK_Zero_Event_Conversion, ///< Zero constant to event (OpenCL1.2 6.12.10)
86 ICK_Zero_Queue_Conversion, ///< Zero constant to queue
87 ICK_C_Only_Conversion, ///< Conversions allowed in C, but not C++
88 ICK_Incompatible_Pointer_Conversion, ///< C-only conversion between pointers
89 /// with incompatible types
90 ICK_Num_Conversion_Kinds, ///< The number of conversion kinds
93 /// ImplicitConversionRank - The rank of an implicit conversion
94 /// kind. The enumerator values match with Table 9 of (C++
95 /// 13.3.3.1.1) and are listed such that better conversion ranks
96 /// have smaller values.
97 enum ImplicitConversionRank {
98 ICR_Exact_Match = 0, ///< Exact Match
99 ICR_Promotion, ///< Promotion
100 ICR_Conversion, ///< Conversion
101 ICR_OCL_Scalar_Widening, ///< OpenCL Scalar Widening
102 ICR_Complex_Real_Conversion, ///< Complex <-> Real conversion
103 ICR_Writeback_Conversion, ///< ObjC ARC writeback conversion
104 ICR_C_Conversion, ///< Conversion only allowed in the C standard.
105 /// (e.g. void* to char*)
106 ICR_C_Conversion_Extension ///< Conversion not allowed by the C standard,
107 /// but that we accept as an extension anyway.
110 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
112 /// NarrowingKind - The kind of narrowing conversion being performed by a
113 /// standard conversion sequence according to C++11 [dcl.init.list]p7.
115 /// Not a narrowing conversion.
118 /// A narrowing conversion by virtue of the source and destination types.
121 /// A narrowing conversion, because a constant expression got narrowed.
122 NK_Constant_Narrowing,
124 /// A narrowing conversion, because a non-constant-expression variable might
125 /// have got narrowed.
126 NK_Variable_Narrowing,
128 /// Cannot tell whether this is a narrowing conversion because the
129 /// expression is value-dependent.
130 NK_Dependent_Narrowing,
133 /// StandardConversionSequence - represents a standard conversion
134 /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
135 /// contains between zero and three conversions. If a particular
136 /// conversion is not needed, it will be set to the identity conversion
137 /// (ICK_Identity). Note that the three conversions are
138 /// specified as separate members (rather than in an array) so that
139 /// we can keep the size of a standard conversion sequence to a
141 class StandardConversionSequence {
143 /// First -- The first conversion can be an lvalue-to-rvalue
144 /// conversion, array-to-pointer conversion, or
145 /// function-to-pointer conversion.
146 ImplicitConversionKind First : 8;
148 /// Second - The second conversion can be an integral promotion,
149 /// floating point promotion, integral conversion, floating point
150 /// conversion, floating-integral conversion, pointer conversion,
151 /// pointer-to-member conversion, or boolean conversion.
152 ImplicitConversionKind Second : 8;
154 /// Third - The third conversion can be a qualification conversion
155 /// or a function conversion.
156 ImplicitConversionKind Third : 8;
158 /// \brief Whether this is the deprecated conversion of a
159 /// string literal to a pointer to non-const character data
161 unsigned DeprecatedStringLiteralToCharPtr : 1;
163 /// \brief Whether the qualification conversion involves a change in the
164 /// Objective-C lifetime (for automatic reference counting).
165 unsigned QualificationIncludesObjCLifetime : 1;
167 /// IncompatibleObjC - Whether this is an Objective-C conversion
168 /// that we should warn about (if we actually use it).
169 unsigned IncompatibleObjC : 1;
171 /// ReferenceBinding - True when this is a reference binding
172 /// (C++ [over.ics.ref]).
173 unsigned ReferenceBinding : 1;
175 /// DirectBinding - True when this is a reference binding that is a
176 /// direct binding (C++ [dcl.init.ref]).
177 unsigned DirectBinding : 1;
179 /// \brief Whether this is an lvalue reference binding (otherwise, it's
180 /// an rvalue reference binding).
181 unsigned IsLvalueReference : 1;
183 /// \brief Whether we're binding to a function lvalue.
184 unsigned BindsToFunctionLvalue : 1;
186 /// \brief Whether we're binding to an rvalue.
187 unsigned BindsToRvalue : 1;
189 /// \brief Whether this binds an implicit object argument to a
190 /// non-static member function without a ref-qualifier.
191 unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
193 /// \brief Whether this binds a reference to an object with a different
194 /// Objective-C lifetime qualifier.
195 unsigned ObjCLifetimeConversionBinding : 1;
197 /// FromType - The type that this conversion is converting
198 /// from. This is an opaque pointer that can be translated into a
202 /// ToType - The types that this conversion is converting to in
203 /// each step. This is an opaque pointer that can be translated
207 /// CopyConstructor - The copy constructor that is used to perform
208 /// this conversion, when the conversion is actually just the
209 /// initialization of an object via copy constructor. Such
210 /// conversions are either identity conversions or derived-to-base
212 CXXConstructorDecl *CopyConstructor;
213 DeclAccessPair FoundCopyConstructor;
215 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
216 void setToType(unsigned Idx, QualType T) {
217 assert(Idx < 3 && "To type index is out of range");
218 ToTypePtrs[Idx] = T.getAsOpaquePtr();
220 void setAllToTypes(QualType T) {
221 ToTypePtrs[0] = T.getAsOpaquePtr();
222 ToTypePtrs[1] = ToTypePtrs[0];
223 ToTypePtrs[2] = ToTypePtrs[0];
226 QualType getFromType() const {
227 return QualType::getFromOpaquePtr(FromTypePtr);
229 QualType getToType(unsigned Idx) const {
230 assert(Idx < 3 && "To type index is out of range");
231 return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
234 void setAsIdentityConversion();
236 bool isIdentityConversion() const {
237 return Second == ICK_Identity && Third == ICK_Identity;
240 ImplicitConversionRank getRank() const;
241 NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted,
242 APValue &ConstantValue,
243 QualType &ConstantType) const;
244 bool isPointerConversionToBool() const;
245 bool isPointerConversionToVoidPointer(ASTContext& Context) const;
249 /// UserDefinedConversionSequence - Represents a user-defined
250 /// conversion sequence (C++ 13.3.3.1.2).
251 struct UserDefinedConversionSequence {
252 /// \brief Represents the standard conversion that occurs before
253 /// the actual user-defined conversion.
255 /// C++11 13.3.3.1.2p1:
256 /// If the user-defined conversion is specified by a constructor
257 /// (12.3.1), the initial standard conversion sequence converts
258 /// the source type to the type required by the argument of the
259 /// constructor. If the user-defined conversion is specified by
260 /// a conversion function (12.3.2), the initial standard
261 /// conversion sequence converts the source type to the implicit
262 /// object parameter of the conversion function.
263 StandardConversionSequence Before;
265 /// EllipsisConversion - When this is true, it means user-defined
266 /// conversion sequence starts with a ... (ellipsis) conversion, instead of
267 /// a standard conversion. In this case, 'Before' field must be ignored.
268 // FIXME. I much rather put this as the first field. But there seems to be
269 // a gcc code gen. bug which causes a crash in a test. Putting it here seems
270 // to work around the crash.
271 bool EllipsisConversion : 1;
273 /// HadMultipleCandidates - When this is true, it means that the
274 /// conversion function was resolved from an overloaded set having
275 /// size greater than 1.
276 bool HadMultipleCandidates : 1;
278 /// After - Represents the standard conversion that occurs after
279 /// the actual user-defined conversion.
280 StandardConversionSequence After;
282 /// ConversionFunction - The function that will perform the
283 /// user-defined conversion. Null if the conversion is an
284 /// aggregate initialization from an initializer list.
285 FunctionDecl* ConversionFunction;
287 /// \brief The declaration that we found via name lookup, which might be
288 /// the same as \c ConversionFunction or it might be a using declaration
289 /// that refers to \c ConversionFunction.
290 DeclAccessPair FoundConversionFunction;
295 /// Represents an ambiguous user-defined conversion sequence.
296 struct AmbiguousConversionSequence {
297 typedef SmallVector<std::pair<NamedDecl*, FunctionDecl*>, 4> ConversionSet;
301 char Buffer[sizeof(ConversionSet)];
303 QualType getFromType() const {
304 return QualType::getFromOpaquePtr(FromTypePtr);
306 QualType getToType() const {
307 return QualType::getFromOpaquePtr(ToTypePtr);
309 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
310 void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
312 ConversionSet &conversions() {
313 return *reinterpret_cast<ConversionSet*>(Buffer);
316 const ConversionSet &conversions() const {
317 return *reinterpret_cast<const ConversionSet*>(Buffer);
320 void addConversion(NamedDecl *Found, FunctionDecl *D) {
321 conversions().push_back(std::make_pair(Found, D));
324 typedef ConversionSet::iterator iterator;
325 iterator begin() { return conversions().begin(); }
326 iterator end() { return conversions().end(); }
328 typedef ConversionSet::const_iterator const_iterator;
329 const_iterator begin() const { return conversions().begin(); }
330 const_iterator end() const { return conversions().end(); }
334 void copyFrom(const AmbiguousConversionSequence &);
337 /// BadConversionSequence - Records information about an invalid
338 /// conversion sequence.
339 struct BadConversionSequence {
344 lvalue_ref_to_rvalue,
348 // This can be null, e.g. for implicit object arguments.
354 // The type we're converting from (an opaque QualType).
357 // The type we're converting to (an opaque QualType).
361 void init(FailureKind K, Expr *From, QualType To) {
362 init(K, From->getType(), To);
365 void init(FailureKind K, QualType From, QualType To) {
372 QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
373 QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
375 void setFromExpr(Expr *E) {
377 setFromType(E->getType());
379 void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
380 void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
383 /// ImplicitConversionSequence - Represents an implicit conversion
384 /// sequence, which may be a standard conversion sequence
385 /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
386 /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
387 class ImplicitConversionSequence {
389 /// Kind - The kind of implicit conversion sequence. BadConversion
390 /// specifies that there is no conversion from the source type to
391 /// the target type. AmbiguousConversion represents the unique
392 /// ambiguous conversion (C++0x [over.best.ics]p10).
394 StandardConversion = 0,
395 UserDefinedConversion,
403 Uninitialized = BadConversion + 1
406 /// ConversionKind - The kind of implicit conversion sequence.
407 unsigned ConversionKind : 30;
409 /// \brief Whether the target is really a std::initializer_list, and the
410 /// sequence only represents the worst element conversion.
411 unsigned StdInitializerListElement : 1;
413 void setKind(Kind K) {
419 if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
424 /// When ConversionKind == StandardConversion, provides the
425 /// details of the standard conversion sequence.
426 StandardConversionSequence Standard;
428 /// When ConversionKind == UserDefinedConversion, provides the
429 /// details of the user-defined conversion sequence.
430 UserDefinedConversionSequence UserDefined;
432 /// When ConversionKind == AmbiguousConversion, provides the
433 /// details of the ambiguous conversion.
434 AmbiguousConversionSequence Ambiguous;
436 /// When ConversionKind == BadConversion, provides the details
437 /// of the bad conversion.
438 BadConversionSequence Bad;
441 ImplicitConversionSequence()
442 : ConversionKind(Uninitialized), StdInitializerListElement(false) {
443 Standard.setAsIdentityConversion();
445 ~ImplicitConversionSequence() {
448 ImplicitConversionSequence(const ImplicitConversionSequence &Other)
449 : ConversionKind(Other.ConversionKind),
450 StdInitializerListElement(Other.StdInitializerListElement)
452 switch (ConversionKind) {
453 case Uninitialized: break;
454 case StandardConversion: Standard = Other.Standard; break;
455 case UserDefinedConversion: UserDefined = Other.UserDefined; break;
456 case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
457 case EllipsisConversion: break;
458 case BadConversion: Bad = Other.Bad; break;
462 ImplicitConversionSequence &
463 operator=(const ImplicitConversionSequence &Other) {
465 new (this) ImplicitConversionSequence(Other);
469 Kind getKind() const {
470 assert(isInitialized() && "querying uninitialized conversion");
471 return Kind(ConversionKind);
474 /// \brief Return a ranking of the implicit conversion sequence
475 /// kind, where smaller ranks represent better conversion
478 /// In particular, this routine gives user-defined conversion
479 /// sequences and ambiguous conversion sequences the same rank,
480 /// per C++ [over.best.ics]p10.
481 unsigned getKindRank() const {
483 case StandardConversion:
486 case UserDefinedConversion:
487 case AmbiguousConversion:
490 case EllipsisConversion:
497 llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
500 bool isBad() const { return getKind() == BadConversion; }
501 bool isStandard() const { return getKind() == StandardConversion; }
502 bool isEllipsis() const { return getKind() == EllipsisConversion; }
503 bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
504 bool isUserDefined() const { return getKind() == UserDefinedConversion; }
505 bool isFailure() const { return isBad() || isAmbiguous(); }
507 /// Determines whether this conversion sequence has been
508 /// initialized. Most operations should never need to query
509 /// uninitialized conversions and should assert as above.
510 bool isInitialized() const { return ConversionKind != Uninitialized; }
512 /// Sets this sequence as a bad conversion for an explicit argument.
513 void setBad(BadConversionSequence::FailureKind Failure,
514 Expr *FromExpr, QualType ToType) {
515 setKind(BadConversion);
516 Bad.init(Failure, FromExpr, ToType);
519 /// Sets this sequence as a bad conversion for an implicit argument.
520 void setBad(BadConversionSequence::FailureKind Failure,
521 QualType FromType, QualType ToType) {
522 setKind(BadConversion);
523 Bad.init(Failure, FromType, ToType);
526 void setStandard() { setKind(StandardConversion); }
527 void setEllipsis() { setKind(EllipsisConversion); }
528 void setUserDefined() { setKind(UserDefinedConversion); }
529 void setAmbiguous() {
530 if (ConversionKind == AmbiguousConversion) return;
531 ConversionKind = AmbiguousConversion;
532 Ambiguous.construct();
535 void setAsIdentityConversion(QualType T) {
537 Standard.setAsIdentityConversion();
538 Standard.setFromType(T);
539 Standard.setAllToTypes(T);
542 /// \brief Whether the target is really a std::initializer_list, and the
543 /// sequence only represents the worst element conversion.
544 bool isStdInitializerListElement() const {
545 return StdInitializerListElement;
548 void setStdInitializerListElement(bool V = true) {
549 StdInitializerListElement = V;
552 // The result of a comparison between implicit conversion
553 // sequences. Use Sema::CompareImplicitConversionSequences to
554 // actually perform the comparison.
557 Indistinguishable = 0,
561 void DiagnoseAmbiguousConversion(Sema &S,
562 SourceLocation CaretLoc,
563 const PartialDiagnostic &PDiag) const;
568 enum OverloadFailureKind {
569 ovl_fail_too_many_arguments,
570 ovl_fail_too_few_arguments,
571 ovl_fail_bad_conversion,
572 ovl_fail_bad_deduction,
574 /// This conversion candidate was not considered because it
575 /// duplicates the work of a trivial or derived-to-base
577 ovl_fail_trivial_conversion,
579 /// This conversion candidate was not considered because it is
580 /// an illegal instantiation of a constructor temploid: it is
581 /// callable with one argument, we only have one argument, and
582 /// its first parameter type is exactly the type of the class.
584 /// Defining such a constructor directly is illegal, and
585 /// template-argument deduction is supposed to ignore such
586 /// instantiations, but we can still get one with the right
587 /// kind of implicit instantiation.
588 ovl_fail_illegal_constructor,
590 /// This conversion candidate is not viable because its result
591 /// type is not implicitly convertible to the desired type.
592 ovl_fail_bad_final_conversion,
594 /// This conversion function template specialization candidate is not
595 /// viable because the final conversion was not an exact match.
596 ovl_fail_final_conversion_not_exact,
598 /// (CUDA) This candidate was not viable because the callee
599 /// was not accessible from the caller's target (i.e. host->device,
600 /// global->host, device->host).
603 /// This candidate function was not viable because an enable_if
604 /// attribute disabled it.
607 /// This candidate was not viable because its address could not be taken.
608 ovl_fail_addr_not_available,
610 /// This candidate was not viable because its OpenCL extension is disabled.
611 ovl_fail_ext_disabled,
613 /// This inherited constructor is not viable because it would slice the
615 ovl_fail_inhctor_slice,
618 /// A list of implicit conversion sequences for the arguments of an
619 /// OverloadCandidate.
620 typedef llvm::MutableArrayRef<ImplicitConversionSequence>
621 ConversionSequenceList;
623 /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
624 struct OverloadCandidate {
625 /// Function - The actual function that this candidate
626 /// represents. When NULL, this is a built-in candidate
627 /// (C++ [over.oper]) or a surrogate for a conversion to a
628 /// function pointer or reference (C++ [over.call.object]).
629 FunctionDecl *Function;
631 /// FoundDecl - The original declaration that was looked up /
632 /// invented / otherwise found, together with its access.
633 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
634 DeclAccessPair FoundDecl;
636 /// BuiltinParamTypes - Provides the parameter types of a built-in overload
637 /// candidate. Only valid when Function is NULL.
638 QualType BuiltinParamTypes[3];
640 /// Surrogate - The conversion function for which this candidate
641 /// is a surrogate, but only if IsSurrogate is true.
642 CXXConversionDecl *Surrogate;
644 /// The conversion sequences used to convert the function arguments
645 /// to the function parameters.
646 ConversionSequenceList Conversions;
648 /// The FixIt hints which can be used to fix the Bad candidate.
649 ConversionFixItGenerator Fix;
651 /// Viable - True to indicate that this overload candidate is viable.
654 /// IsSurrogate - True to indicate that this candidate is a
655 /// surrogate for a conversion to a function pointer or reference
656 /// (C++ [over.call.object]).
659 /// IgnoreObjectArgument - True to indicate that the first
660 /// argument's conversion, which for this function represents the
661 /// implicit object argument, should be ignored. This will be true
662 /// when the candidate is a static member function (where the
663 /// implicit object argument is just a placeholder) or a
664 /// non-static member function when the call doesn't have an
666 bool IgnoreObjectArgument;
668 /// FailureKind - The reason why this candidate is not viable.
669 /// Actually an OverloadFailureKind.
670 unsigned char FailureKind;
672 /// \brief The number of call arguments that were explicitly provided,
673 /// to be used while performing partial ordering of function templates.
674 unsigned ExplicitCallArguments;
677 DeductionFailureInfo DeductionFailure;
679 /// FinalConversion - For a conversion function (where Function is
680 /// a CXXConversionDecl), the standard conversion that occurs
681 /// after the call to the overload candidate to convert the result
682 /// of calling the conversion function to the required type.
683 StandardConversionSequence FinalConversion;
686 /// hasAmbiguousConversion - Returns whether this overload
687 /// candidate requires an ambiguous conversion or not.
688 bool hasAmbiguousConversion() const {
689 for (auto &C : Conversions) {
690 if (!C.isInitialized()) return false;
691 if (C.isAmbiguous()) return true;
696 bool TryToFixBadConversion(unsigned Idx, Sema &S) {
697 bool CanFix = Fix.tryToFixConversion(
698 Conversions[Idx].Bad.FromExpr,
699 Conversions[Idx].Bad.getFromType(),
700 Conversions[Idx].Bad.getToType(), S);
702 // If at least one conversion fails, the candidate cannot be fixed.
709 unsigned getNumParams() const {
711 auto STy = Surrogate->getConversionType();
712 while (STy->isPointerType() || STy->isReferenceType())
713 STy = STy->getPointeeType();
714 return STy->getAs<FunctionProtoType>()->getNumParams();
717 return Function->getNumParams();
718 return ExplicitCallArguments;
722 /// OverloadCandidateSet - A set of overload candidates, used in C++
723 /// overload resolution (C++ 13.3).
724 class OverloadCandidateSet {
726 enum CandidateSetKind {
729 /// C++ [over.match.oper]:
730 /// Lookup of operator function candidates in a call using operator
731 /// syntax. Candidates that have no parameters of class type will be
732 /// skipped unless there is a parameter of (reference to) enum type and
733 /// the corresponding argument is of the same enum type.
735 /// C++ [over.match.copy]:
736 /// Copy-initialization of an object of class type by user-defined
738 CSK_InitByUserDefinedConversion,
739 /// C++ [over.match.ctor], [over.match.list]
740 /// Initialization of an object of class type by constructor,
741 /// using either a parenthesized or braced list of arguments.
742 CSK_InitByConstructor,
746 SmallVector<OverloadCandidate, 16> Candidates;
747 llvm::SmallPtrSet<Decl *, 16> Functions;
749 // Allocator for ConversionSequenceLists. We store the first few of these
750 // inline to avoid allocation for small sets.
751 llvm::BumpPtrAllocator SlabAllocator;
754 CandidateSetKind Kind;
756 constexpr static unsigned NumInlineBytes =
757 24 * sizeof(ImplicitConversionSequence);
758 unsigned NumInlineBytesUsed;
759 llvm::AlignedCharArray<alignof(void *), NumInlineBytes> InlineSpace;
761 /// If we have space, allocates from inline storage. Otherwise, allocates
762 /// from the slab allocator.
763 /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
765 /// FIXME: Now that this only allocates ImplicitConversionSequences, do we
766 /// want to un-generalize this?
767 template <typename T>
768 T *slabAllocate(unsigned N) {
769 // It's simpler if this doesn't need to consider alignment.
770 static_assert(alignof(T) == alignof(void *),
771 "Only works for pointer-aligned types.");
772 static_assert(std::is_trivial<T>::value ||
773 std::is_same<ImplicitConversionSequence, T>::value,
774 "Add destruction logic to OverloadCandidateSet::clear().");
776 unsigned NBytes = sizeof(T) * N;
777 if (NBytes > NumInlineBytes - NumInlineBytesUsed)
778 return SlabAllocator.Allocate<T>(N);
779 char *FreeSpaceStart = InlineSpace.buffer + NumInlineBytesUsed;
780 assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
781 "Misaligned storage!");
783 NumInlineBytesUsed += NBytes;
784 return reinterpret_cast<T *>(FreeSpaceStart);
787 OverloadCandidateSet(const OverloadCandidateSet &) = delete;
788 void operator=(const OverloadCandidateSet &) = delete;
790 void destroyCandidates();
793 OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK)
794 : Loc(Loc), Kind(CSK), NumInlineBytesUsed(0) {}
795 ~OverloadCandidateSet() { destroyCandidates(); }
797 SourceLocation getLocation() const { return Loc; }
798 CandidateSetKind getKind() const { return Kind; }
800 /// \brief Determine when this overload candidate will be new to the
802 bool isNewCandidate(Decl *F) {
803 return Functions.insert(F->getCanonicalDecl()).second;
806 /// \brief Clear out all of the candidates.
807 void clear(CandidateSetKind CSK);
809 typedef SmallVectorImpl<OverloadCandidate>::iterator iterator;
810 iterator begin() { return Candidates.begin(); }
811 iterator end() { return Candidates.end(); }
813 size_t size() const { return Candidates.size(); }
814 bool empty() const { return Candidates.empty(); }
816 /// \brief Allocate storage for conversion sequences for NumConversions
818 ConversionSequenceList
819 allocateConversionSequences(unsigned NumConversions) {
820 ImplicitConversionSequence *Conversions =
821 slabAllocate<ImplicitConversionSequence>(NumConversions);
823 // Construct the new objects.
824 for (unsigned I = 0; I != NumConversions; ++I)
825 new (&Conversions[I]) ImplicitConversionSequence();
827 return ConversionSequenceList(Conversions, NumConversions);
830 /// \brief Add a new candidate with NumConversions conversion sequence slots
831 /// to the overload set.
832 OverloadCandidate &addCandidate(unsigned NumConversions = 0,
833 ConversionSequenceList Conversions = None) {
834 assert((Conversions.empty() || Conversions.size() == NumConversions) &&
835 "preallocated conversion sequence has wrong length");
837 Candidates.push_back(OverloadCandidate());
838 OverloadCandidate &C = Candidates.back();
839 C.Conversions = Conversions.empty()
840 ? allocateConversionSequences(NumConversions)
845 /// Find the best viable function on this overload set, if it exists.
846 OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
847 OverloadCandidateSet::iterator& Best);
849 void NoteCandidates(Sema &S,
850 OverloadCandidateDisplayKind OCD,
851 ArrayRef<Expr *> Args,
853 SourceLocation Loc = SourceLocation(),
854 llvm::function_ref<bool(OverloadCandidate&)> Filter =
855 [](OverloadCandidate&) { return true; });
858 bool isBetterOverloadCandidate(Sema &S,
859 const OverloadCandidate &Cand1,
860 const OverloadCandidate &Cand2,
862 OverloadCandidateSet::CandidateSetKind Kind);
864 struct ConstructorInfo {
865 DeclAccessPair FoundDecl;
866 CXXConstructorDecl *Constructor;
867 FunctionTemplateDecl *ConstructorTmpl;
868 explicit operator bool() const { return Constructor; }
870 // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
871 // that takes one of these.
872 inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
873 if (isa<UsingDecl>(ND))
874 return ConstructorInfo{};
876 // For constructors, the access check is performed against the underlying
877 // declaration, not the found declaration.
878 auto *D = ND->getUnderlyingDecl();
879 ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr,
881 Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
882 if (Info.ConstructorTmpl)
883 D = Info.ConstructorTmpl->getTemplatedDecl();
884 Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
887 } // end namespace clang
889 #endif // LLVM_CLANG_SEMA_OVERLOAD_H