]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Sema/Overload.h
Merge llvm, clang, lld and lldb trunk r291476.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Sema / Overload.h
1 //===--- Overload.h - C++ Overloading ---------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the data structures and types used in C++
11 // overload resolution.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_SEMA_OVERLOAD_H
16 #define LLVM_CLANG_SEMA_OVERLOAD_H
17
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"
30
31 namespace clang {
32   class ASTContext;
33   class CXXConstructorDecl;
34   class CXXConversionDecl;
35   class FunctionDecl;
36   class Sema;
37
38   /// OverloadingResult - Capture the result of performing overload
39   /// resolution.
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.
45   };
46   
47   enum OverloadCandidateDisplayKind {
48     /// Requests that all candidates be shown.  Viable candidates will
49     /// be printed first.
50     OCD_AllCandidates,
51
52     /// Requests that only viable candidates be shown.
53     OCD_ViableCandidates
54   };
55
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
91   };
92
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_Complex_Real_Conversion, ///< Complex <-> Real conversion
102     ICR_Writeback_Conversion,    ///< ObjC ARC writeback conversion
103     ICR_C_Conversion,            ///< Conversion only allowed in the C standard.
104                                  ///  (e.g. void* to char*)
105     ICR_C_Conversion_Extension   ///< Conversion not allowed by the C standard,
106                                  ///  but that we accept as an extension anyway.
107   };
108
109   ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
110
111   /// NarrowingKind - The kind of narrowing conversion being performed by a
112   /// standard conversion sequence according to C++11 [dcl.init.list]p7.
113   enum NarrowingKind {
114     /// Not a narrowing conversion.
115     NK_Not_Narrowing,
116
117     /// A narrowing conversion by virtue of the source and destination types.
118     NK_Type_Narrowing,
119
120     /// A narrowing conversion, because a constant expression got narrowed.
121     NK_Constant_Narrowing,
122
123     /// A narrowing conversion, because a non-constant-expression variable might
124     /// have got narrowed.
125     NK_Variable_Narrowing,
126
127     /// Cannot tell whether this is a narrowing conversion because the
128     /// expression is value-dependent.
129     NK_Dependent_Narrowing,
130   };
131
132   /// StandardConversionSequence - represents a standard conversion
133   /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
134   /// contains between zero and three conversions. If a particular
135   /// conversion is not needed, it will be set to the identity conversion
136   /// (ICK_Identity). Note that the three conversions are
137   /// specified as separate members (rather than in an array) so that
138   /// we can keep the size of a standard conversion sequence to a
139   /// single word.
140   class StandardConversionSequence {
141   public:
142     /// First -- The first conversion can be an lvalue-to-rvalue
143     /// conversion, array-to-pointer conversion, or
144     /// function-to-pointer conversion.
145     ImplicitConversionKind First : 8;
146
147     /// Second - The second conversion can be an integral promotion,
148     /// floating point promotion, integral conversion, floating point
149     /// conversion, floating-integral conversion, pointer conversion,
150     /// pointer-to-member conversion, or boolean conversion.
151     ImplicitConversionKind Second : 8;
152
153     /// Third - The third conversion can be a qualification conversion
154     /// or a function conversion.
155     ImplicitConversionKind Third : 8;
156
157     /// \brief Whether this is the deprecated conversion of a
158     /// string literal to a pointer to non-const character data
159     /// (C++ 4.2p2).
160     unsigned DeprecatedStringLiteralToCharPtr : 1;
161
162     /// \brief Whether the qualification conversion involves a change in the
163     /// Objective-C lifetime (for automatic reference counting).
164     unsigned QualificationIncludesObjCLifetime : 1;
165     
166     /// IncompatibleObjC - Whether this is an Objective-C conversion
167     /// that we should warn about (if we actually use it).
168     unsigned IncompatibleObjC : 1;
169
170     /// ReferenceBinding - True when this is a reference binding
171     /// (C++ [over.ics.ref]).
172     unsigned ReferenceBinding : 1;
173
174     /// DirectBinding - True when this is a reference binding that is a
175     /// direct binding (C++ [dcl.init.ref]).
176     unsigned DirectBinding : 1;
177
178     /// \brief Whether this is an lvalue reference binding (otherwise, it's
179     /// an rvalue reference binding).
180     unsigned IsLvalueReference : 1;
181     
182     /// \brief Whether we're binding to a function lvalue.
183     unsigned BindsToFunctionLvalue : 1;
184     
185     /// \brief Whether we're binding to an rvalue.
186     unsigned BindsToRvalue : 1;
187     
188     /// \brief Whether this binds an implicit object argument to a 
189     /// non-static member function without a ref-qualifier.
190     unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
191     
192     /// \brief Whether this binds a reference to an object with a different
193     /// Objective-C lifetime qualifier.
194     unsigned ObjCLifetimeConversionBinding : 1;
195     
196     /// FromType - The type that this conversion is converting
197     /// from. This is an opaque pointer that can be translated into a
198     /// QualType.
199     void *FromTypePtr;
200
201     /// ToType - The types that this conversion is converting to in
202     /// each step. This is an opaque pointer that can be translated
203     /// into a QualType.
204     void *ToTypePtrs[3];
205
206     /// CopyConstructor - The copy constructor that is used to perform
207     /// this conversion, when the conversion is actually just the
208     /// initialization of an object via copy constructor. Such
209     /// conversions are either identity conversions or derived-to-base
210     /// conversions.
211     CXXConstructorDecl *CopyConstructor;
212     DeclAccessPair FoundCopyConstructor;
213
214     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
215     void setToType(unsigned Idx, QualType T) { 
216       assert(Idx < 3 && "To type index is out of range");
217       ToTypePtrs[Idx] = T.getAsOpaquePtr(); 
218     }
219     void setAllToTypes(QualType T) {
220       ToTypePtrs[0] = T.getAsOpaquePtr(); 
221       ToTypePtrs[1] = ToTypePtrs[0];
222       ToTypePtrs[2] = ToTypePtrs[0];
223     }
224
225     QualType getFromType() const {
226       return QualType::getFromOpaquePtr(FromTypePtr);
227     }
228     QualType getToType(unsigned Idx) const {
229       assert(Idx < 3 && "To type index is out of range");
230       return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
231     }
232
233     void setAsIdentityConversion();
234     
235     bool isIdentityConversion() const {
236       return Second == ICK_Identity && Third == ICK_Identity;
237     }
238     
239     ImplicitConversionRank getRank() const;
240     NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted,
241                                    APValue &ConstantValue,
242                                    QualType &ConstantType) const;
243     bool isPointerConversionToBool() const;
244     bool isPointerConversionToVoidPointer(ASTContext& Context) const;
245     void dump() const;
246   };
247
248   /// UserDefinedConversionSequence - Represents a user-defined
249   /// conversion sequence (C++ 13.3.3.1.2).
250   struct UserDefinedConversionSequence {
251     /// \brief Represents the standard conversion that occurs before
252     /// the actual user-defined conversion.
253     ///
254     /// C++11 13.3.3.1.2p1:
255     ///   If the user-defined conversion is specified by a constructor
256     ///   (12.3.1), the initial standard conversion sequence converts
257     ///   the source type to the type required by the argument of the
258     ///   constructor. If the user-defined conversion is specified by
259     ///   a conversion function (12.3.2), the initial standard
260     ///   conversion sequence converts the source type to the implicit
261     ///   object parameter of the conversion function.
262     StandardConversionSequence Before;
263
264     /// EllipsisConversion - When this is true, it means user-defined
265     /// conversion sequence starts with a ... (ellipsis) conversion, instead of
266     /// a standard conversion. In this case, 'Before' field must be ignored.
267     // FIXME. I much rather put this as the first field. But there seems to be
268     // a gcc code gen. bug which causes a crash in a test. Putting it here seems
269     // to work around the crash.
270     bool EllipsisConversion : 1;
271
272     /// HadMultipleCandidates - When this is true, it means that the
273     /// conversion function was resolved from an overloaded set having
274     /// size greater than 1.
275     bool HadMultipleCandidates : 1;
276
277     /// After - Represents the standard conversion that occurs after
278     /// the actual user-defined conversion.
279     StandardConversionSequence After;
280
281     /// ConversionFunction - The function that will perform the
282     /// user-defined conversion. Null if the conversion is an
283     /// aggregate initialization from an initializer list.
284     FunctionDecl* ConversionFunction;
285
286     /// \brief The declaration that we found via name lookup, which might be
287     /// the same as \c ConversionFunction or it might be a using declaration
288     /// that refers to \c ConversionFunction.
289     DeclAccessPair FoundConversionFunction;
290
291     void dump() const;
292   };
293
294   /// Represents an ambiguous user-defined conversion sequence.
295   struct AmbiguousConversionSequence {
296     typedef SmallVector<std::pair<NamedDecl*, FunctionDecl*>, 4> ConversionSet;
297
298     void *FromTypePtr;
299     void *ToTypePtr;
300     char Buffer[sizeof(ConversionSet)];
301
302     QualType getFromType() const {
303       return QualType::getFromOpaquePtr(FromTypePtr);
304     }
305     QualType getToType() const {
306       return QualType::getFromOpaquePtr(ToTypePtr);
307     }
308     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
309     void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
310
311     ConversionSet &conversions() {
312       return *reinterpret_cast<ConversionSet*>(Buffer);
313     }
314
315     const ConversionSet &conversions() const {
316       return *reinterpret_cast<const ConversionSet*>(Buffer);
317     }
318
319     void addConversion(NamedDecl *Found, FunctionDecl *D) {
320       conversions().push_back(std::make_pair(Found, D));
321     }
322
323     typedef ConversionSet::iterator iterator;
324     iterator begin() { return conversions().begin(); }
325     iterator end() { return conversions().end(); }
326
327     typedef ConversionSet::const_iterator const_iterator;
328     const_iterator begin() const { return conversions().begin(); }
329     const_iterator end() const { return conversions().end(); }
330
331     void construct();
332     void destruct();
333     void copyFrom(const AmbiguousConversionSequence &);
334   };
335
336   /// BadConversionSequence - Records information about an invalid
337   /// conversion sequence.
338   struct BadConversionSequence {
339     enum FailureKind {
340       no_conversion,
341       unrelated_class,
342       bad_qualifiers,
343       lvalue_ref_to_rvalue,
344       rvalue_ref_to_lvalue
345     };
346
347     // This can be null, e.g. for implicit object arguments.
348     Expr *FromExpr;
349
350     FailureKind Kind;
351
352   private:
353     // The type we're converting from (an opaque QualType).
354     void *FromTy;
355
356     // The type we're converting to (an opaque QualType).
357     void *ToTy;
358
359   public:
360     void init(FailureKind K, Expr *From, QualType To) {
361       init(K, From->getType(), To);
362       FromExpr = From;
363     }
364     void init(FailureKind K, QualType From, QualType To) {
365       Kind = K;
366       FromExpr = nullptr;
367       setFromType(From);
368       setToType(To);
369     }
370
371     QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
372     QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
373
374     void setFromExpr(Expr *E) {
375       FromExpr = E;
376       setFromType(E->getType());
377     }
378     void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
379     void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
380   };
381
382   /// ImplicitConversionSequence - Represents an implicit conversion
383   /// sequence, which may be a standard conversion sequence
384   /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
385   /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
386   class ImplicitConversionSequence {
387   public:
388     /// Kind - The kind of implicit conversion sequence. BadConversion
389     /// specifies that there is no conversion from the source type to
390     /// the target type.  AmbiguousConversion represents the unique
391     /// ambiguous conversion (C++0x [over.best.ics]p10).
392     enum Kind {
393       StandardConversion = 0,
394       UserDefinedConversion,
395       AmbiguousConversion,
396       EllipsisConversion,
397       BadConversion
398     };
399
400   private:
401     enum {
402       Uninitialized = BadConversion + 1
403     };
404
405     /// ConversionKind - The kind of implicit conversion sequence.
406     unsigned ConversionKind : 30;
407
408     /// \brief Whether the target is really a std::initializer_list, and the
409     /// sequence only represents the worst element conversion.
410     unsigned StdInitializerListElement : 1;
411
412     void setKind(Kind K) {
413       destruct();
414       ConversionKind = K;
415     }
416
417     void destruct() {
418       if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
419     }
420
421   public:
422     union {
423       /// When ConversionKind == StandardConversion, provides the
424       /// details of the standard conversion sequence.
425       StandardConversionSequence Standard;
426
427       /// When ConversionKind == UserDefinedConversion, provides the
428       /// details of the user-defined conversion sequence.
429       UserDefinedConversionSequence UserDefined;
430
431       /// When ConversionKind == AmbiguousConversion, provides the
432       /// details of the ambiguous conversion.
433       AmbiguousConversionSequence Ambiguous;
434
435       /// When ConversionKind == BadConversion, provides the details
436       /// of the bad conversion.
437       BadConversionSequence Bad;
438     };
439
440     ImplicitConversionSequence()
441         : ConversionKind(Uninitialized), StdInitializerListElement(false) {
442       Standard.setAsIdentityConversion();
443     }
444     ~ImplicitConversionSequence() {
445       destruct();
446     }
447     ImplicitConversionSequence(const ImplicitConversionSequence &Other)
448       : ConversionKind(Other.ConversionKind),
449         StdInitializerListElement(Other.StdInitializerListElement)
450     {
451       switch (ConversionKind) {
452       case Uninitialized: break;
453       case StandardConversion: Standard = Other.Standard; break;
454       case UserDefinedConversion: UserDefined = Other.UserDefined; break;
455       case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
456       case EllipsisConversion: break;
457       case BadConversion: Bad = Other.Bad; break;
458       }
459     }
460
461     ImplicitConversionSequence &
462         operator=(const ImplicitConversionSequence &Other) {
463       destruct();
464       new (this) ImplicitConversionSequence(Other);
465       return *this;
466     }
467     
468     Kind getKind() const {
469       assert(isInitialized() && "querying uninitialized conversion");
470       return Kind(ConversionKind);
471     }
472     
473     /// \brief Return a ranking of the implicit conversion sequence
474     /// kind, where smaller ranks represent better conversion
475     /// sequences.
476     ///
477     /// In particular, this routine gives user-defined conversion
478     /// sequences and ambiguous conversion sequences the same rank,
479     /// per C++ [over.best.ics]p10.
480     unsigned getKindRank() const {
481       switch (getKind()) {
482       case StandardConversion: 
483         return 0;
484
485       case UserDefinedConversion:
486       case AmbiguousConversion: 
487         return 1;
488
489       case EllipsisConversion:
490         return 2;
491
492       case BadConversion:
493         return 3;
494       }
495
496       llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
497     }
498
499     bool isBad() const { return getKind() == BadConversion; }
500     bool isStandard() const { return getKind() == StandardConversion; }
501     bool isEllipsis() const { return getKind() == EllipsisConversion; }
502     bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
503     bool isUserDefined() const { return getKind() == UserDefinedConversion; }
504     bool isFailure() const { return isBad() || isAmbiguous(); }
505
506     /// Determines whether this conversion sequence has been
507     /// initialized.  Most operations should never need to query
508     /// uninitialized conversions and should assert as above.
509     bool isInitialized() const { return ConversionKind != Uninitialized; }
510
511     /// Sets this sequence as a bad conversion for an explicit argument.
512     void setBad(BadConversionSequence::FailureKind Failure,
513                 Expr *FromExpr, QualType ToType) {
514       setKind(BadConversion);
515       Bad.init(Failure, FromExpr, ToType);
516     }
517
518     /// Sets this sequence as a bad conversion for an implicit argument.
519     void setBad(BadConversionSequence::FailureKind Failure,
520                 QualType FromType, QualType ToType) {
521       setKind(BadConversion);
522       Bad.init(Failure, FromType, ToType);
523     }
524
525     void setStandard() { setKind(StandardConversion); }
526     void setEllipsis() { setKind(EllipsisConversion); }
527     void setUserDefined() { setKind(UserDefinedConversion); }
528     void setAmbiguous() {
529       if (ConversionKind == AmbiguousConversion) return;
530       ConversionKind = AmbiguousConversion;
531       Ambiguous.construct();
532     }
533
534     void setAsIdentityConversion(QualType T) {
535       setStandard();
536       Standard.setAsIdentityConversion();
537       Standard.setFromType(T);
538       Standard.setAllToTypes(T);
539     }
540
541     /// \brief Whether the target is really a std::initializer_list, and the
542     /// sequence only represents the worst element conversion.
543     bool isStdInitializerListElement() const {
544       return StdInitializerListElement;
545     }
546
547     void setStdInitializerListElement(bool V = true) {
548       StdInitializerListElement = V;
549     }
550
551     // The result of a comparison between implicit conversion
552     // sequences. Use Sema::CompareImplicitConversionSequences to
553     // actually perform the comparison.
554     enum CompareKind {
555       Better = -1,
556       Indistinguishable = 0,
557       Worse = 1
558     };
559
560     void DiagnoseAmbiguousConversion(Sema &S,
561                                      SourceLocation CaretLoc,
562                                      const PartialDiagnostic &PDiag) const;
563
564     void dump() const;
565   };
566
567   enum OverloadFailureKind {
568     ovl_fail_too_many_arguments,
569     ovl_fail_too_few_arguments,
570     ovl_fail_bad_conversion,
571     ovl_fail_bad_deduction,
572
573     /// This conversion candidate was not considered because it
574     /// duplicates the work of a trivial or derived-to-base
575     /// conversion.
576     ovl_fail_trivial_conversion,
577
578     /// This conversion candidate was not considered because it is
579     /// an illegal instantiation of a constructor temploid: it is
580     /// callable with one argument, we only have one argument, and
581     /// its first parameter type is exactly the type of the class.
582     ///
583     /// Defining such a constructor directly is illegal, and
584     /// template-argument deduction is supposed to ignore such
585     /// instantiations, but we can still get one with the right
586     /// kind of implicit instantiation.
587     ovl_fail_illegal_constructor,
588
589     /// This conversion candidate is not viable because its result
590     /// type is not implicitly convertible to the desired type.
591     ovl_fail_bad_final_conversion,
592
593     /// This conversion function template specialization candidate is not
594     /// viable because the final conversion was not an exact match.
595     ovl_fail_final_conversion_not_exact,
596
597     /// (CUDA) This candidate was not viable because the callee
598     /// was not accessible from the caller's target (i.e. host->device,
599     /// global->host, device->host).
600     ovl_fail_bad_target,
601
602     /// This candidate function was not viable because an enable_if
603     /// attribute disabled it.
604     ovl_fail_enable_if,
605
606     /// This candidate was not viable because its address could not be taken.
607     ovl_fail_addr_not_available,
608
609     /// This candidate was not viable because its OpenCL extension is disabled.
610     ovl_fail_ext_disabled,
611
612     /// This inherited constructor is not viable because it would slice the
613     /// argument.
614     ovl_fail_inhctor_slice,
615   };
616
617   /// A list of implicit conversion sequences for the arguments of an
618   /// OverloadCandidate.
619   typedef llvm::MutableArrayRef<ImplicitConversionSequence>
620       ConversionSequenceList;
621
622   /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
623   struct OverloadCandidate {
624     /// Function - The actual function that this candidate
625     /// represents. When NULL, this is a built-in candidate
626     /// (C++ [over.oper]) or a surrogate for a conversion to a
627     /// function pointer or reference (C++ [over.call.object]).
628     FunctionDecl *Function;
629
630     /// FoundDecl - The original declaration that was looked up /
631     /// invented / otherwise found, together with its access.
632     /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
633     DeclAccessPair FoundDecl;
634
635     // BuiltinTypes - Provides the return and parameter types of a
636     // built-in overload candidate. Only valid when Function is NULL.
637     struct {
638       QualType ResultTy;
639       QualType ParamTypes[3];
640     } BuiltinTypes;
641
642     /// Surrogate - The conversion function for which this candidate
643     /// is a surrogate, but only if IsSurrogate is true.
644     CXXConversionDecl *Surrogate;
645
646     /// The conversion sequences used to convert the function arguments
647     /// to the function parameters.
648     ConversionSequenceList Conversions;
649
650     /// The FixIt hints which can be used to fix the Bad candidate.
651     ConversionFixItGenerator Fix;
652
653     /// Viable - True to indicate that this overload candidate is viable.
654     bool Viable;
655
656     /// IsSurrogate - True to indicate that this candidate is a
657     /// surrogate for a conversion to a function pointer or reference
658     /// (C++ [over.call.object]).
659     bool IsSurrogate;
660
661     /// IgnoreObjectArgument - True to indicate that the first
662     /// argument's conversion, which for this function represents the
663     /// implicit object argument, should be ignored. This will be true
664     /// when the candidate is a static member function (where the
665     /// implicit object argument is just a placeholder) or a
666     /// non-static member function when the call doesn't have an
667     /// object argument.
668     bool IgnoreObjectArgument;
669
670     /// FailureKind - The reason why this candidate is not viable.
671     /// Actually an OverloadFailureKind.
672     unsigned char FailureKind;
673
674     /// \brief The number of call arguments that were explicitly provided,
675     /// to be used while performing partial ordering of function templates.
676     unsigned ExplicitCallArguments;
677
678     /// The number of diagnose_if attributes that this overload triggered.
679     /// If any of the triggered attributes are errors, this won't count
680     /// diagnose_if warnings.
681     unsigned NumTriggeredDiagnoseIfs = 0;
682
683     /// Basically a TinyPtrVector<DiagnoseIfAttr *> that doesn't own the vector:
684     /// If NumTriggeredDiagnoseIfs is 0 or 1, this is a DiagnoseIfAttr *,
685     /// otherwise it's a pointer to an array of `NumTriggeredDiagnoseIfs`
686     /// DiagnoseIfAttr *s.
687     llvm::PointerUnion<DiagnoseIfAttr *, DiagnoseIfAttr **> DiagnoseIfInfo;
688
689     /// Gets an ArrayRef for the data at DiagnoseIfInfo. Note that this may give
690     /// you a pointer into DiagnoseIfInfo.
691     ArrayRef<DiagnoseIfAttr *> getDiagnoseIfInfo() const {
692       auto *Ptr = NumTriggeredDiagnoseIfs <= 1
693                       ? DiagnoseIfInfo.getAddrOfPtr1()
694                       : DiagnoseIfInfo.get<DiagnoseIfAttr **>();
695       return {Ptr, NumTriggeredDiagnoseIfs};
696     }
697
698     union {
699       DeductionFailureInfo DeductionFailure;
700       
701       /// FinalConversion - For a conversion function (where Function is
702       /// a CXXConversionDecl), the standard conversion that occurs
703       /// after the call to the overload candidate to convert the result
704       /// of calling the conversion function to the required type.
705       StandardConversionSequence FinalConversion;
706     };
707
708     /// hasAmbiguousConversion - Returns whether this overload
709     /// candidate requires an ambiguous conversion or not.
710     bool hasAmbiguousConversion() const {
711       for (auto &C : Conversions) {
712         if (!C.isInitialized()) return false;
713         if (C.isAmbiguous()) return true;
714       }
715       return false;
716     }
717
718     bool TryToFixBadConversion(unsigned Idx, Sema &S) {
719       bool CanFix = Fix.tryToFixConversion(
720                       Conversions[Idx].Bad.FromExpr,
721                       Conversions[Idx].Bad.getFromType(),
722                       Conversions[Idx].Bad.getToType(), S);
723
724       // If at least one conversion fails, the candidate cannot be fixed.
725       if (!CanFix)
726         Fix.clear();
727
728       return CanFix;
729     }
730
731     unsigned getNumParams() const {
732       if (IsSurrogate) {
733         auto STy = Surrogate->getConversionType();
734         while (STy->isPointerType() || STy->isReferenceType())
735           STy = STy->getPointeeType();
736         return STy->getAs<FunctionProtoType>()->getNumParams();
737       }
738       if (Function)
739         return Function->getNumParams();
740       return ExplicitCallArguments;
741     }
742   };
743
744   /// OverloadCandidateSet - A set of overload candidates, used in C++
745   /// overload resolution (C++ 13.3).
746   class OverloadCandidateSet {
747   public:
748     enum CandidateSetKind {
749       /// Normal lookup.
750       CSK_Normal,
751       /// Lookup for candidates for a call using operator syntax. Candidates
752       /// that have no parameters of class type will be skipped unless there
753       /// is a parameter of (reference to) enum type and the corresponding
754       /// argument is of the same enum type.
755       CSK_Operator
756     };
757
758   private:
759     SmallVector<OverloadCandidate, 16> Candidates;
760     llvm::SmallPtrSet<Decl *, 16> Functions;
761
762     // Allocator for ConversionSequenceLists and DiagnoseIfAttr* arrays.
763     // We store the first few of each of these inline to avoid allocation for
764     // small sets.
765     llvm::BumpPtrAllocator SlabAllocator;
766
767     SourceLocation Loc;
768     CandidateSetKind Kind;
769
770     constexpr static unsigned NumInlineBytes =
771         24 * sizeof(ImplicitConversionSequence);
772     unsigned NumInlineBytesUsed;
773     llvm::AlignedCharArray<alignof(void *), NumInlineBytes> InlineSpace;
774
775     /// If we have space, allocates from inline storage. Otherwise, allocates
776     /// from the slab allocator.
777     /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
778     /// instead.
779     template <typename T>
780     T *slabAllocate(unsigned N) {
781       // It's simpler if this doesn't need to consider alignment.
782       static_assert(alignof(T) == alignof(void *),
783                     "Only works for pointer-aligned types.");
784       static_assert(std::is_trivial<T>::value ||
785                         std::is_same<ImplicitConversionSequence, T>::value,
786                     "Add destruction logic to OverloadCandidateSet::clear().");
787
788       unsigned NBytes = sizeof(T) * N;
789       if (NBytes > NumInlineBytes - NumInlineBytesUsed)
790         return SlabAllocator.Allocate<T>(N);
791       char *FreeSpaceStart = InlineSpace.buffer + NumInlineBytesUsed;
792       assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
793              "Misaligned storage!");
794
795       NumInlineBytesUsed += NBytes;
796       return reinterpret_cast<T *>(FreeSpaceStart);
797     }
798
799     OverloadCandidateSet(const OverloadCandidateSet &) = delete;
800     void operator=(const OverloadCandidateSet &) = delete;
801
802     void destroyCandidates();
803
804   public:
805     OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK)
806         : Loc(Loc), Kind(CSK), NumInlineBytesUsed(0) {}
807     ~OverloadCandidateSet() { destroyCandidates(); }
808
809     SourceLocation getLocation() const { return Loc; }
810     CandidateSetKind getKind() const { return Kind; }
811
812     /// Make a DiagnoseIfAttr* array in a block of memory that will live for
813     /// as long as this OverloadCandidateSet. Returns a pointer to the start
814     /// of that array.
815     DiagnoseIfAttr **addDiagnoseIfComplaints(ArrayRef<DiagnoseIfAttr *> CA);
816
817     /// \brief Determine when this overload candidate will be new to the
818     /// overload set.
819     bool isNewCandidate(Decl *F) {
820       return Functions.insert(F->getCanonicalDecl()).second;
821     }
822
823     /// \brief Clear out all of the candidates.
824     void clear();
825
826     typedef SmallVectorImpl<OverloadCandidate>::iterator iterator;
827     iterator begin() { return Candidates.begin(); }
828     iterator end() { return Candidates.end(); }
829
830     size_t size() const { return Candidates.size(); }
831     bool empty() const { return Candidates.empty(); }
832
833     /// \brief Allocate storage for conversion sequences for NumConversions
834     /// conversions.
835     ConversionSequenceList
836     allocateConversionSequences(unsigned NumConversions) {
837       ImplicitConversionSequence *Conversions =
838           slabAllocate<ImplicitConversionSequence>(NumConversions);
839
840       // Construct the new objects.
841       for (unsigned I = 0; I != NumConversions; ++I)
842         new (&Conversions[I]) ImplicitConversionSequence();
843
844       return ConversionSequenceList(Conversions, NumConversions);
845     }
846
847     /// \brief Add a new candidate with NumConversions conversion sequence slots
848     /// to the overload set.
849     OverloadCandidate &addCandidate(unsigned NumConversions = 0,
850                                     ConversionSequenceList Conversions = None) {
851       assert((Conversions.empty() || Conversions.size() == NumConversions) &&
852              "preallocated conversion sequence has wrong length");
853
854       Candidates.push_back(OverloadCandidate());
855       OverloadCandidate &C = Candidates.back();
856       C.Conversions = Conversions.empty()
857                           ? allocateConversionSequences(NumConversions)
858                           : Conversions;
859       return C;
860     }
861
862     /// Find the best viable function on this overload set, if it exists.
863     OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
864                                          OverloadCandidateSet::iterator& Best,
865                                          bool UserDefinedConversion = false);
866
867     void NoteCandidates(Sema &S,
868                         OverloadCandidateDisplayKind OCD,
869                         ArrayRef<Expr *> Args,
870                         StringRef Opc = "",
871                         SourceLocation Loc = SourceLocation(),
872                         llvm::function_ref<bool(OverloadCandidate&)> Filter =
873                           [](OverloadCandidate&) { return true; });
874   };
875
876   bool isBetterOverloadCandidate(Sema &S,
877                                  const OverloadCandidate& Cand1,
878                                  const OverloadCandidate& Cand2,
879                                  SourceLocation Loc,
880                                  bool UserDefinedConversion = false);
881
882   struct ConstructorInfo {
883     DeclAccessPair FoundDecl;
884     CXXConstructorDecl *Constructor;
885     FunctionTemplateDecl *ConstructorTmpl;
886     explicit operator bool() const { return Constructor; }
887   };
888   // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
889   // that takes one of these.
890   inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
891     if (isa<UsingDecl>(ND))
892       return ConstructorInfo{};
893
894     // For constructors, the access check is performed against the underlying
895     // declaration, not the found declaration.
896     auto *D = ND->getUnderlyingDecl();
897     ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr,
898                             nullptr};
899     Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
900     if (Info.ConstructorTmpl)
901       D = Info.ConstructorTmpl->getTemplatedDecl();
902     Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
903     return Info;
904   }
905 } // end namespace clang
906
907 #endif // LLVM_CLANG_SEMA_OVERLOAD_H