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 "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
29 class CXXConstructorDecl;
30 class CXXConversionDecl;
34 /// OverloadingResult - Capture the result of performing overload
36 enum OverloadingResult {
37 OR_Success, ///< Overload resolution succeeded.
38 OR_No_Viable_Function, ///< No viable function found.
39 OR_Ambiguous, ///< Ambiguous candidates found.
40 OR_Deleted ///< Succeeded, but refers to a deleted function.
43 enum OverloadCandidateDisplayKind {
44 /// Requests that all candidates be shown. Viable candidates will
48 /// Requests that only viable candidates be shown.
52 /// ImplicitConversionKind - The kind of implicit conversion used to
53 /// convert an argument to a parameter's type. The enumerator values
54 /// match with Table 9 of (C++ 13.3.3.1.1) and are listed such that
55 /// better conversion kinds have smaller values.
56 enum ImplicitConversionKind {
57 ICK_Identity = 0, ///< Identity conversion (no conversion)
58 ICK_Lvalue_To_Rvalue, ///< Lvalue-to-rvalue conversion (C++ 4.1)
59 ICK_Array_To_Pointer, ///< Array-to-pointer conversion (C++ 4.2)
60 ICK_Function_To_Pointer, ///< Function-to-pointer (C++ 4.3)
61 ICK_NoReturn_Adjustment, ///< Removal of noreturn from a type (Clang)
62 ICK_Qualification, ///< Qualification conversions (C++ 4.4)
63 ICK_Integral_Promotion, ///< Integral promotions (C++ 4.5)
64 ICK_Floating_Promotion, ///< Floating point promotions (C++ 4.6)
65 ICK_Complex_Promotion, ///< Complex promotions (Clang extension)
66 ICK_Integral_Conversion, ///< Integral conversions (C++ 4.7)
67 ICK_Floating_Conversion, ///< Floating point conversions (C++ 4.8)
68 ICK_Complex_Conversion, ///< Complex conversions (C99 6.3.1.6)
69 ICK_Floating_Integral, ///< Floating-integral conversions (C++ 4.9)
70 ICK_Pointer_Conversion, ///< Pointer conversions (C++ 4.10)
71 ICK_Pointer_Member, ///< Pointer-to-member conversions (C++ 4.11)
72 ICK_Boolean_Conversion, ///< Boolean conversions (C++ 4.12)
73 ICK_Compatible_Conversion, ///< Conversions between compatible types in C99
74 ICK_Derived_To_Base, ///< Derived-to-base (C++ [over.best.ics])
75 ICK_Vector_Conversion, ///< Vector conversions
76 ICK_Vector_Splat, ///< A vector splat from an arithmetic type
77 ICK_Complex_Real, ///< Complex-real conversions (C99 6.3.1.7)
78 ICK_Block_Pointer_Conversion, ///< Block Pointer conversions
79 ICK_TransparentUnionConversion, /// Transparent Union Conversions
80 ICK_Writeback_Conversion, ///< Objective-C ARC writeback conversion
81 ICK_Num_Conversion_Kinds ///< The number of conversion kinds
84 /// ImplicitConversionCategory - The category of an implicit
85 /// conversion kind. The enumerator values match with Table 9 of
86 /// (C++ 13.3.3.1.1) and are listed such that better conversion
87 /// categories have smaller values.
88 enum ImplicitConversionCategory {
89 ICC_Identity = 0, ///< Identity
90 ICC_Lvalue_Transformation, ///< Lvalue transformation
91 ICC_Qualification_Adjustment, ///< Qualification adjustment
92 ICC_Promotion, ///< Promotion
93 ICC_Conversion ///< Conversion
96 ImplicitConversionCategory
97 GetConversionCategory(ImplicitConversionKind Kind);
99 /// ImplicitConversionRank - The rank of an implicit conversion
100 /// kind. The enumerator values match with Table 9 of (C++
101 /// 13.3.3.1.1) and are listed such that better conversion ranks
102 /// have smaller values.
103 enum ImplicitConversionRank {
104 ICR_Exact_Match = 0, ///< Exact Match
105 ICR_Promotion, ///< Promotion
106 ICR_Conversion, ///< Conversion
107 ICR_Complex_Real_Conversion, ///< Complex <-> Real conversion
108 ICR_Writeback_Conversion ///< ObjC ARC writeback conversion
111 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
113 /// StandardConversionSequence - represents a standard conversion
114 /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
115 /// contains between zero and three conversions. If a particular
116 /// conversion is not needed, it will be set to the identity conversion
117 /// (ICK_Identity). Note that the three conversions are
118 /// specified as separate members (rather than in an array) so that
119 /// we can keep the size of a standard conversion sequence to a
121 class StandardConversionSequence {
123 /// First -- The first conversion can be an lvalue-to-rvalue
124 /// conversion, array-to-pointer conversion, or
125 /// function-to-pointer conversion.
126 ImplicitConversionKind First : 8;
128 /// Second - The second conversion can be an integral promotion,
129 /// floating point promotion, integral conversion, floating point
130 /// conversion, floating-integral conversion, pointer conversion,
131 /// pointer-to-member conversion, or boolean conversion.
132 ImplicitConversionKind Second : 8;
134 /// Third - The third conversion can be a qualification conversion.
135 ImplicitConversionKind Third : 8;
137 /// \brief Whether this is the deprecated conversion of a
138 /// string literal to a pointer to non-const character data
140 unsigned DeprecatedStringLiteralToCharPtr : 1;
142 /// \brief Whether the qualification conversion involves a change in the
143 /// Objective-C lifetime (for automatic reference counting).
144 unsigned QualificationIncludesObjCLifetime : 1;
146 /// IncompatibleObjC - Whether this is an Objective-C conversion
147 /// that we should warn about (if we actually use it).
148 unsigned IncompatibleObjC : 1;
150 /// ReferenceBinding - True when this is a reference binding
151 /// (C++ [over.ics.ref]).
152 unsigned ReferenceBinding : 1;
154 /// DirectBinding - True when this is a reference binding that is a
155 /// direct binding (C++ [dcl.init.ref]).
156 unsigned DirectBinding : 1;
158 /// \brief Whether this is an lvalue reference binding (otherwise, it's
159 /// an rvalue reference binding).
160 unsigned IsLvalueReference : 1;
162 /// \brief Whether we're binding to a function lvalue.
163 unsigned BindsToFunctionLvalue : 1;
165 /// \brief Whether we're binding to an rvalue.
166 unsigned BindsToRvalue : 1;
168 /// \brief Whether this binds an implicit object argument to a
169 /// non-static member function without a ref-qualifier.
170 unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
172 /// \brief Whether this binds a reference to an object with a different
173 /// Objective-C lifetime qualifier.
174 unsigned ObjCLifetimeConversionBinding : 1;
176 /// FromType - The type that this conversion is converting
177 /// from. This is an opaque pointer that can be translated into a
181 /// ToType - The types that this conversion is converting to in
182 /// each step. This is an opaque pointer that can be translated
186 /// CopyConstructor - The copy constructor that is used to perform
187 /// this conversion, when the conversion is actually just the
188 /// initialization of an object via copy constructor. Such
189 /// conversions are either identity conversions or derived-to-base
191 CXXConstructorDecl *CopyConstructor;
193 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
194 void setToType(unsigned Idx, QualType T) {
195 assert(Idx < 3 && "To type index is out of range");
196 ToTypePtrs[Idx] = T.getAsOpaquePtr();
198 void setAllToTypes(QualType T) {
199 ToTypePtrs[0] = T.getAsOpaquePtr();
200 ToTypePtrs[1] = ToTypePtrs[0];
201 ToTypePtrs[2] = ToTypePtrs[0];
204 QualType getFromType() const {
205 return QualType::getFromOpaquePtr(FromTypePtr);
207 QualType getToType(unsigned Idx) const {
208 assert(Idx < 3 && "To type index is out of range");
209 return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
212 void setAsIdentityConversion();
214 bool isIdentityConversion() const {
215 return Second == ICK_Identity && Third == ICK_Identity;
218 ImplicitConversionRank getRank() const;
219 bool isPointerConversionToBool() const;
220 bool isPointerConversionToVoidPointer(ASTContext& Context) const;
221 void DebugPrint() const;
224 /// UserDefinedConversionSequence - Represents a user-defined
225 /// conversion sequence (C++ 13.3.3.1.2).
226 struct UserDefinedConversionSequence {
227 /// Before - Represents the standard conversion that occurs before
228 /// the actual user-defined conversion. (C++ 13.3.3.1.2p1):
230 /// If the user-defined conversion is specified by a constructor
231 /// (12.3.1), the initial standard conversion sequence converts
232 /// the source type to the type required by the argument of the
233 /// constructor. If the user-defined conversion is specified by
234 /// a conversion function (12.3.2), the initial standard
235 /// conversion sequence converts the source type to the implicit
236 /// object parameter of the conversion function.
237 StandardConversionSequence Before;
239 /// EllipsisConversion - When this is true, it means user-defined
240 /// conversion sequence starts with a ... (elipsis) conversion, instead of
241 /// a standard conversion. In this case, 'Before' field must be ignored.
242 // FIXME. I much rather put this as the first field. But there seems to be
243 // a gcc code gen. bug which causes a crash in a test. Putting it here seems
244 // to work around the crash.
245 bool EllipsisConversion : 1;
247 /// After - Represents the standard conversion that occurs after
248 /// the actual user-defined conversion.
249 StandardConversionSequence After;
251 /// ConversionFunction - The function that will perform the
252 /// user-defined conversion.
253 FunctionDecl* ConversionFunction;
255 /// \brief The declaration that we found via name lookup, which might be
256 /// the same as \c ConversionFunction or it might be a using declaration
257 /// that refers to \c ConversionFunction.
258 NamedDecl *FoundConversionFunction;
260 void DebugPrint() const;
263 /// Represents an ambiguous user-defined conversion sequence.
264 struct AmbiguousConversionSequence {
265 typedef llvm::SmallVector<FunctionDecl*, 4> ConversionSet;
269 char Buffer[sizeof(ConversionSet)];
271 QualType getFromType() const {
272 return QualType::getFromOpaquePtr(FromTypePtr);
274 QualType getToType() const {
275 return QualType::getFromOpaquePtr(ToTypePtr);
277 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
278 void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
280 ConversionSet &conversions() {
281 return *reinterpret_cast<ConversionSet*>(Buffer);
284 const ConversionSet &conversions() const {
285 return *reinterpret_cast<const ConversionSet*>(Buffer);
288 void addConversion(FunctionDecl *D) {
289 conversions().push_back(D);
292 typedef ConversionSet::iterator iterator;
293 iterator begin() { return conversions().begin(); }
294 iterator end() { return conversions().end(); }
296 typedef ConversionSet::const_iterator const_iterator;
297 const_iterator begin() const { return conversions().begin(); }
298 const_iterator end() const { return conversions().end(); }
302 void copyFrom(const AmbiguousConversionSequence &);
305 /// BadConversionSequence - Records information about an invalid
306 /// conversion sequence.
307 struct BadConversionSequence {
313 lvalue_ref_to_rvalue,
317 // This can be null, e.g. for implicit object arguments.
323 // The type we're converting from (an opaque QualType).
326 // The type we're converting to (an opaque QualType).
330 void init(FailureKind K, Expr *From, QualType To) {
331 init(K, From->getType(), To);
334 void init(FailureKind K, QualType From, QualType To) {
341 QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
342 QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
344 void setFromExpr(Expr *E) {
346 setFromType(E->getType());
348 void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
349 void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
352 /// ImplicitConversionSequence - Represents an implicit conversion
353 /// sequence, which may be a standard conversion sequence
354 /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
355 /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
356 class ImplicitConversionSequence {
358 /// Kind - The kind of implicit conversion sequence. BadConversion
359 /// specifies that there is no conversion from the source type to
360 /// the target type. AmbiguousConversion represents the unique
361 /// ambiguous conversion (C++0x [over.best.ics]p10).
363 StandardConversion = 0,
364 UserDefinedConversion,
372 Uninitialized = BadConversion + 1
375 /// ConversionKind - The kind of implicit conversion sequence.
376 unsigned ConversionKind;
378 void setKind(Kind K) {
384 if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
389 /// When ConversionKind == StandardConversion, provides the
390 /// details of the standard conversion sequence.
391 StandardConversionSequence Standard;
393 /// When ConversionKind == UserDefinedConversion, provides the
394 /// details of the user-defined conversion sequence.
395 UserDefinedConversionSequence UserDefined;
397 /// When ConversionKind == AmbiguousConversion, provides the
398 /// details of the ambiguous conversion.
399 AmbiguousConversionSequence Ambiguous;
401 /// When ConversionKind == BadConversion, provides the details
402 /// of the bad conversion.
403 BadConversionSequence Bad;
406 ImplicitConversionSequence() : ConversionKind(Uninitialized) {}
407 ~ImplicitConversionSequence() {
410 ImplicitConversionSequence(const ImplicitConversionSequence &Other)
411 : ConversionKind(Other.ConversionKind)
413 switch (ConversionKind) {
414 case Uninitialized: break;
415 case StandardConversion: Standard = Other.Standard; break;
416 case UserDefinedConversion: UserDefined = Other.UserDefined; break;
417 case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
418 case EllipsisConversion: break;
419 case BadConversion: Bad = Other.Bad; break;
423 ImplicitConversionSequence &
424 operator=(const ImplicitConversionSequence &Other) {
426 new (this) ImplicitConversionSequence(Other);
430 Kind getKind() const {
431 assert(isInitialized() && "querying uninitialized conversion");
432 return Kind(ConversionKind);
435 /// \brief Return a ranking of the implicit conversion sequence
436 /// kind, where smaller ranks represent better conversion
439 /// In particular, this routine gives user-defined conversion
440 /// sequences and ambiguous conversion sequences the same rank,
441 /// per C++ [over.best.ics]p10.
442 unsigned getKindRank() const {
444 case StandardConversion:
447 case UserDefinedConversion:
448 case AmbiguousConversion:
451 case EllipsisConversion:
461 bool isBad() const { return getKind() == BadConversion; }
462 bool isStandard() const { return getKind() == StandardConversion; }
463 bool isEllipsis() const { return getKind() == EllipsisConversion; }
464 bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
465 bool isUserDefined() const { return getKind() == UserDefinedConversion; }
467 /// Determines whether this conversion sequence has been
468 /// initialized. Most operations should never need to query
469 /// uninitialized conversions and should assert as above.
470 bool isInitialized() const { return ConversionKind != Uninitialized; }
472 /// Sets this sequence as a bad conversion for an explicit argument.
473 void setBad(BadConversionSequence::FailureKind Failure,
474 Expr *FromExpr, QualType ToType) {
475 setKind(BadConversion);
476 Bad.init(Failure, FromExpr, ToType);
479 /// Sets this sequence as a bad conversion for an implicit argument.
480 void setBad(BadConversionSequence::FailureKind Failure,
481 QualType FromType, QualType ToType) {
482 setKind(BadConversion);
483 Bad.init(Failure, FromType, ToType);
486 void setStandard() { setKind(StandardConversion); }
487 void setEllipsis() { setKind(EllipsisConversion); }
488 void setUserDefined() { setKind(UserDefinedConversion); }
489 void setAmbiguous() {
490 if (ConversionKind == AmbiguousConversion) return;
491 ConversionKind = AmbiguousConversion;
492 Ambiguous.construct();
495 // The result of a comparison between implicit conversion
496 // sequences. Use Sema::CompareImplicitConversionSequences to
497 // actually perform the comparison.
500 Indistinguishable = 0,
504 void DiagnoseAmbiguousConversion(Sema &S,
505 SourceLocation CaretLoc,
506 const PartialDiagnostic &PDiag) const;
508 void DebugPrint() const;
511 enum OverloadFailureKind {
512 ovl_fail_too_many_arguments,
513 ovl_fail_too_few_arguments,
514 ovl_fail_bad_conversion,
515 ovl_fail_bad_deduction,
517 /// This conversion candidate was not considered because it
518 /// duplicates the work of a trivial or derived-to-base
520 ovl_fail_trivial_conversion,
522 /// This conversion candidate is not viable because its result
523 /// type is not implicitly convertible to the desired type.
524 ovl_fail_bad_final_conversion,
526 /// This conversion function template specialization candidate is not
527 /// viable because the final conversion was not an exact match.
528 ovl_fail_final_conversion_not_exact
531 /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
532 struct OverloadCandidate {
533 /// Function - The actual function that this candidate
534 /// represents. When NULL, this is a built-in candidate
535 /// (C++ [over.oper]) or a surrogate for a conversion to a
536 /// function pointer or reference (C++ [over.call.object]).
537 FunctionDecl *Function;
539 /// FoundDecl - The original declaration that was looked up /
540 /// invented / otherwise found, together with its access.
541 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
542 DeclAccessPair FoundDecl;
544 // BuiltinTypes - Provides the return and parameter types of a
545 // built-in overload candidate. Only valid when Function is NULL.
548 QualType ParamTypes[3];
551 /// Surrogate - The conversion function for which this candidate
552 /// is a surrogate, but only if IsSurrogate is true.
553 CXXConversionDecl *Surrogate;
555 /// Conversions - The conversion sequences used to convert the
556 /// function arguments to the function parameters.
557 llvm::SmallVector<ImplicitConversionSequence, 4> Conversions;
559 /// Viable - True to indicate that this overload candidate is viable.
562 /// IsSurrogate - True to indicate that this candidate is a
563 /// surrogate for a conversion to a function pointer or reference
564 /// (C++ [over.call.object]).
567 /// IgnoreObjectArgument - True to indicate that the first
568 /// argument's conversion, which for this function represents the
569 /// implicit object argument, should be ignored. This will be true
570 /// when the candidate is a static member function (where the
571 /// implicit object argument is just a placeholder) or a
572 /// non-static member function when the call doesn't have an
574 bool IgnoreObjectArgument;
576 /// FailureKind - The reason why this candidate is not viable.
577 /// Actually an OverloadFailureKind.
578 unsigned char FailureKind;
580 /// \brief The number of call arguments that were explicitly provided,
581 /// to be used while performing partial ordering of function templates.
582 unsigned ExplicitCallArguments;
584 /// A structure used to record information about a failed
585 /// template argument deduction.
586 struct DeductionFailureInfo {
587 // A Sema::TemplateDeductionResult.
590 /// \brief Opaque pointer containing additional data about
591 /// this deduction failure.
594 /// \brief Retrieve the template parameter this deduction failure
595 /// refers to, if any.
596 TemplateParameter getTemplateParameter();
598 /// \brief Retrieve the template argument list associated with this
599 /// deduction failure, if any.
600 TemplateArgumentList *getTemplateArgumentList();
602 /// \brief Return the first template argument this deduction failure
603 /// refers to, if any.
604 const TemplateArgument *getFirstArg();
606 /// \brief Return the second template argument this deduction failure
607 /// refers to, if any.
608 const TemplateArgument *getSecondArg();
610 /// \brief Free any memory associated with this deduction failure.
615 DeductionFailureInfo DeductionFailure;
617 /// FinalConversion - For a conversion function (where Function is
618 /// a CXXConversionDecl), the standard conversion that occurs
619 /// after the call to the overload candidate to convert the result
620 /// of calling the conversion function to the required type.
621 StandardConversionSequence FinalConversion;
624 /// hasAmbiguousConversion - Returns whether this overload
625 /// candidate requires an ambiguous conversion or not.
626 bool hasAmbiguousConversion() const {
627 for (llvm::SmallVectorImpl<ImplicitConversionSequence>::const_iterator
628 I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
629 if (!I->isInitialized()) return false;
630 if (I->isAmbiguous()) return true;
636 /// OverloadCandidateSet - A set of overload candidates, used in C++
637 /// overload resolution (C++ 13.3).
638 class OverloadCandidateSet : public llvm::SmallVector<OverloadCandidate, 16> {
639 typedef llvm::SmallVector<OverloadCandidate, 16> inherited;
640 llvm::SmallPtrSet<Decl *, 16> Functions;
644 OverloadCandidateSet(const OverloadCandidateSet &);
645 OverloadCandidateSet &operator=(const OverloadCandidateSet &);
648 OverloadCandidateSet(SourceLocation Loc) : Loc(Loc) {}
650 SourceLocation getLocation() const { return Loc; }
652 /// \brief Determine when this overload candidate will be new to the
654 bool isNewCandidate(Decl *F) {
655 return Functions.insert(F->getCanonicalDecl());
658 /// \brief Clear out all of the candidates.
661 /// Find the best viable function on this overload set, if it exists.
662 OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
663 OverloadCandidateSet::iterator& Best,
664 bool UserDefinedConversion = false);
666 void NoteCandidates(Sema &S,
667 OverloadCandidateDisplayKind OCD,
668 Expr **Args, unsigned NumArgs,
670 SourceLocation Loc = SourceLocation());
673 bool isBetterOverloadCandidate(Sema &S,
674 const OverloadCandidate& Cand1,
675 const OverloadCandidate& Cand2,
677 bool UserDefinedConversion = false);
678 } // end namespace clang
680 #endif // LLVM_CLANG_SEMA_OVERLOAD_H