]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Sema/Overload.h
Merge clang trunk r321017 to contrib/llvm/tools/clang.
[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_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.
108   };
109
110   ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
111
112   /// NarrowingKind - The kind of narrowing conversion being performed by a
113   /// standard conversion sequence according to C++11 [dcl.init.list]p7.
114   enum NarrowingKind {
115     /// Not a narrowing conversion.
116     NK_Not_Narrowing,
117
118     /// A narrowing conversion by virtue of the source and destination types.
119     NK_Type_Narrowing,
120
121     /// A narrowing conversion, because a constant expression got narrowed.
122     NK_Constant_Narrowing,
123
124     /// A narrowing conversion, because a non-constant-expression variable might
125     /// have got narrowed.
126     NK_Variable_Narrowing,
127
128     /// Cannot tell whether this is a narrowing conversion because the
129     /// expression is value-dependent.
130     NK_Dependent_Narrowing,
131   };
132
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
140   /// single word.
141   class StandardConversionSequence {
142   public:
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;
147
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;
153
154     /// Third - The third conversion can be a qualification conversion
155     /// or a function conversion.
156     ImplicitConversionKind Third : 8;
157
158     /// \brief Whether this is the deprecated conversion of a
159     /// string literal to a pointer to non-const character data
160     /// (C++ 4.2p2).
161     unsigned DeprecatedStringLiteralToCharPtr : 1;
162
163     /// \brief Whether the qualification conversion involves a change in the
164     /// Objective-C lifetime (for automatic reference counting).
165     unsigned QualificationIncludesObjCLifetime : 1;
166     
167     /// IncompatibleObjC - Whether this is an Objective-C conversion
168     /// that we should warn about (if we actually use it).
169     unsigned IncompatibleObjC : 1;
170
171     /// ReferenceBinding - True when this is a reference binding
172     /// (C++ [over.ics.ref]).
173     unsigned ReferenceBinding : 1;
174
175     /// DirectBinding - True when this is a reference binding that is a
176     /// direct binding (C++ [dcl.init.ref]).
177     unsigned DirectBinding : 1;
178
179     /// \brief Whether this is an lvalue reference binding (otherwise, it's
180     /// an rvalue reference binding).
181     unsigned IsLvalueReference : 1;
182     
183     /// \brief Whether we're binding to a function lvalue.
184     unsigned BindsToFunctionLvalue : 1;
185     
186     /// \brief Whether we're binding to an rvalue.
187     unsigned BindsToRvalue : 1;
188     
189     /// \brief Whether this binds an implicit object argument to a 
190     /// non-static member function without a ref-qualifier.
191     unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
192     
193     /// \brief Whether this binds a reference to an object with a different
194     /// Objective-C lifetime qualifier.
195     unsigned ObjCLifetimeConversionBinding : 1;
196     
197     /// FromType - The type that this conversion is converting
198     /// from. This is an opaque pointer that can be translated into a
199     /// QualType.
200     void *FromTypePtr;
201
202     /// ToType - The types that this conversion is converting to in
203     /// each step. This is an opaque pointer that can be translated
204     /// into a QualType.
205     void *ToTypePtrs[3];
206
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
211     /// conversions.
212     CXXConstructorDecl *CopyConstructor;
213     DeclAccessPair FoundCopyConstructor;
214
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(); 
219     }
220     void setAllToTypes(QualType T) {
221       ToTypePtrs[0] = T.getAsOpaquePtr(); 
222       ToTypePtrs[1] = ToTypePtrs[0];
223       ToTypePtrs[2] = ToTypePtrs[0];
224     }
225
226     QualType getFromType() const {
227       return QualType::getFromOpaquePtr(FromTypePtr);
228     }
229     QualType getToType(unsigned Idx) const {
230       assert(Idx < 3 && "To type index is out of range");
231       return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
232     }
233
234     void setAsIdentityConversion();
235     
236     bool isIdentityConversion() const {
237       return Second == ICK_Identity && Third == ICK_Identity;
238     }
239     
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;
246     void dump() const;
247   };
248
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.
254     ///
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;
264
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;
272
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;
277
278     /// After - Represents the standard conversion that occurs after
279     /// the actual user-defined conversion.
280     StandardConversionSequence After;
281
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;
286
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;
291
292     void dump() const;
293   };
294
295   /// Represents an ambiguous user-defined conversion sequence.
296   struct AmbiguousConversionSequence {
297     typedef SmallVector<std::pair<NamedDecl*, FunctionDecl*>, 4> ConversionSet;
298
299     void *FromTypePtr;
300     void *ToTypePtr;
301     char Buffer[sizeof(ConversionSet)];
302
303     QualType getFromType() const {
304       return QualType::getFromOpaquePtr(FromTypePtr);
305     }
306     QualType getToType() const {
307       return QualType::getFromOpaquePtr(ToTypePtr);
308     }
309     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
310     void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
311
312     ConversionSet &conversions() {
313       return *reinterpret_cast<ConversionSet*>(Buffer);
314     }
315
316     const ConversionSet &conversions() const {
317       return *reinterpret_cast<const ConversionSet*>(Buffer);
318     }
319
320     void addConversion(NamedDecl *Found, FunctionDecl *D) {
321       conversions().push_back(std::make_pair(Found, D));
322     }
323
324     typedef ConversionSet::iterator iterator;
325     iterator begin() { return conversions().begin(); }
326     iterator end() { return conversions().end(); }
327
328     typedef ConversionSet::const_iterator const_iterator;
329     const_iterator begin() const { return conversions().begin(); }
330     const_iterator end() const { return conversions().end(); }
331
332     void construct();
333     void destruct();
334     void copyFrom(const AmbiguousConversionSequence &);
335   };
336
337   /// BadConversionSequence - Records information about an invalid
338   /// conversion sequence.
339   struct BadConversionSequence {
340     enum FailureKind {
341       no_conversion,
342       unrelated_class,
343       bad_qualifiers,
344       lvalue_ref_to_rvalue,
345       rvalue_ref_to_lvalue
346     };
347
348     // This can be null, e.g. for implicit object arguments.
349     Expr *FromExpr;
350
351     FailureKind Kind;
352
353   private:
354     // The type we're converting from (an opaque QualType).
355     void *FromTy;
356
357     // The type we're converting to (an opaque QualType).
358     void *ToTy;
359
360   public:
361     void init(FailureKind K, Expr *From, QualType To) {
362       init(K, From->getType(), To);
363       FromExpr = From;
364     }
365     void init(FailureKind K, QualType From, QualType To) {
366       Kind = K;
367       FromExpr = nullptr;
368       setFromType(From);
369       setToType(To);
370     }
371
372     QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
373     QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
374
375     void setFromExpr(Expr *E) {
376       FromExpr = E;
377       setFromType(E->getType());
378     }
379     void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
380     void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
381   };
382
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 {
388   public:
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).
393     enum Kind {
394       StandardConversion = 0,
395       UserDefinedConversion,
396       AmbiguousConversion,
397       EllipsisConversion,
398       BadConversion
399     };
400
401   private:
402     enum {
403       Uninitialized = BadConversion + 1
404     };
405
406     /// ConversionKind - The kind of implicit conversion sequence.
407     unsigned ConversionKind : 30;
408
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;
412
413     void setKind(Kind K) {
414       destruct();
415       ConversionKind = K;
416     }
417
418     void destruct() {
419       if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
420     }
421
422   public:
423     union {
424       /// When ConversionKind == StandardConversion, provides the
425       /// details of the standard conversion sequence.
426       StandardConversionSequence Standard;
427
428       /// When ConversionKind == UserDefinedConversion, provides the
429       /// details of the user-defined conversion sequence.
430       UserDefinedConversionSequence UserDefined;
431
432       /// When ConversionKind == AmbiguousConversion, provides the
433       /// details of the ambiguous conversion.
434       AmbiguousConversionSequence Ambiguous;
435
436       /// When ConversionKind == BadConversion, provides the details
437       /// of the bad conversion.
438       BadConversionSequence Bad;
439     };
440
441     ImplicitConversionSequence()
442         : ConversionKind(Uninitialized), StdInitializerListElement(false) {
443       Standard.setAsIdentityConversion();
444     }
445     ~ImplicitConversionSequence() {
446       destruct();
447     }
448     ImplicitConversionSequence(const ImplicitConversionSequence &Other)
449       : ConversionKind(Other.ConversionKind),
450         StdInitializerListElement(Other.StdInitializerListElement)
451     {
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;
459       }
460     }
461
462     ImplicitConversionSequence &
463         operator=(const ImplicitConversionSequence &Other) {
464       destruct();
465       new (this) ImplicitConversionSequence(Other);
466       return *this;
467     }
468     
469     Kind getKind() const {
470       assert(isInitialized() && "querying uninitialized conversion");
471       return Kind(ConversionKind);
472     }
473     
474     /// \brief Return a ranking of the implicit conversion sequence
475     /// kind, where smaller ranks represent better conversion
476     /// sequences.
477     ///
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 {
482       switch (getKind()) {
483       case StandardConversion: 
484         return 0;
485
486       case UserDefinedConversion:
487       case AmbiguousConversion: 
488         return 1;
489
490       case EllipsisConversion:
491         return 2;
492
493       case BadConversion:
494         return 3;
495       }
496
497       llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
498     }
499
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(); }
506
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; }
511
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);
517     }
518
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);
524     }
525
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();
533     }
534
535     void setAsIdentityConversion(QualType T) {
536       setStandard();
537       Standard.setAsIdentityConversion();
538       Standard.setFromType(T);
539       Standard.setAllToTypes(T);
540     }
541
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;
546     }
547
548     void setStdInitializerListElement(bool V = true) {
549       StdInitializerListElement = V;
550     }
551
552     // The result of a comparison between implicit conversion
553     // sequences. Use Sema::CompareImplicitConversionSequences to
554     // actually perform the comparison.
555     enum CompareKind {
556       Better = -1,
557       Indistinguishable = 0,
558       Worse = 1
559     };
560
561     void DiagnoseAmbiguousConversion(Sema &S,
562                                      SourceLocation CaretLoc,
563                                      const PartialDiagnostic &PDiag) const;
564
565     void dump() const;
566   };
567
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,
573
574     /// This conversion candidate was not considered because it
575     /// duplicates the work of a trivial or derived-to-base
576     /// conversion.
577     ovl_fail_trivial_conversion,
578
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.
583     ///
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,
589
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,
593
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,
597
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).
601     ovl_fail_bad_target,
602
603     /// This candidate function was not viable because an enable_if
604     /// attribute disabled it.
605     ovl_fail_enable_if,
606
607     /// This candidate was not viable because its address could not be taken.
608     ovl_fail_addr_not_available,
609
610     /// This candidate was not viable because its OpenCL extension is disabled.
611     ovl_fail_ext_disabled,
612
613     /// This inherited constructor is not viable because it would slice the
614     /// argument.
615     ovl_fail_inhctor_slice,
616   };
617
618   /// A list of implicit conversion sequences for the arguments of an
619   /// OverloadCandidate.
620   typedef llvm::MutableArrayRef<ImplicitConversionSequence>
621       ConversionSequenceList;
622
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;
630
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;
635
636     /// BuiltinParamTypes - Provides the parameter types of a built-in overload
637     /// candidate. Only valid when Function is NULL.
638     QualType BuiltinParamTypes[3];
639
640     /// Surrogate - The conversion function for which this candidate
641     /// is a surrogate, but only if IsSurrogate is true.
642     CXXConversionDecl *Surrogate;
643
644     /// The conversion sequences used to convert the function arguments
645     /// to the function parameters.
646     ConversionSequenceList Conversions;
647
648     /// The FixIt hints which can be used to fix the Bad candidate.
649     ConversionFixItGenerator Fix;
650
651     /// Viable - True to indicate that this overload candidate is viable.
652     bool Viable;
653
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]).
657     bool IsSurrogate;
658
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
665     /// object argument.
666     bool IgnoreObjectArgument;
667
668     /// FailureKind - The reason why this candidate is not viable.
669     /// Actually an OverloadFailureKind.
670     unsigned char FailureKind;
671
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;
675
676     union {
677       DeductionFailureInfo DeductionFailure;
678       
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;
684     };
685
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;
692       }
693       return false;
694     }
695
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);
701
702       // If at least one conversion fails, the candidate cannot be fixed.
703       if (!CanFix)
704         Fix.clear();
705
706       return CanFix;
707     }
708
709     unsigned getNumParams() const {
710       if (IsSurrogate) {
711         auto STy = Surrogate->getConversionType();
712         while (STy->isPointerType() || STy->isReferenceType())
713           STy = STy->getPointeeType();
714         return STy->getAs<FunctionProtoType>()->getNumParams();
715       }
716       if (Function)
717         return Function->getNumParams();
718       return ExplicitCallArguments;
719     }
720   };
721
722   /// OverloadCandidateSet - A set of overload candidates, used in C++
723   /// overload resolution (C++ 13.3).
724   class OverloadCandidateSet {
725   public:
726     enum CandidateSetKind {
727       /// Normal lookup.
728       CSK_Normal,
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.
734       CSK_Operator,
735       /// C++ [over.match.copy]:
736       /// Copy-initialization of an object of class type by user-defined
737       /// conversion.
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,
743     };
744
745   private:
746     SmallVector<OverloadCandidate, 16> Candidates;
747     llvm::SmallPtrSet<Decl *, 16> Functions;
748
749     // Allocator for ConversionSequenceLists. We store the first few of these
750     // inline to avoid allocation for small sets.
751     llvm::BumpPtrAllocator SlabAllocator;
752
753     SourceLocation Loc;
754     CandidateSetKind Kind;
755
756     constexpr static unsigned NumInlineBytes =
757         24 * sizeof(ImplicitConversionSequence);
758     unsigned NumInlineBytesUsed;
759     llvm::AlignedCharArray<alignof(void *), NumInlineBytes> InlineSpace;
760
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
764     /// instead.
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().");
775
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!");
782
783       NumInlineBytesUsed += NBytes;
784       return reinterpret_cast<T *>(FreeSpaceStart);
785     }
786
787     OverloadCandidateSet(const OverloadCandidateSet &) = delete;
788     void operator=(const OverloadCandidateSet &) = delete;
789
790     void destroyCandidates();
791
792   public:
793     OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK)
794         : Loc(Loc), Kind(CSK), NumInlineBytesUsed(0) {}
795     ~OverloadCandidateSet() { destroyCandidates(); }
796
797     SourceLocation getLocation() const { return Loc; }
798     CandidateSetKind getKind() const { return Kind; }
799
800     /// \brief Determine when this overload candidate will be new to the
801     /// overload set.
802     bool isNewCandidate(Decl *F) {
803       return Functions.insert(F->getCanonicalDecl()).second;
804     }
805
806     /// \brief Clear out all of the candidates.
807     void clear(CandidateSetKind CSK);
808
809     typedef SmallVectorImpl<OverloadCandidate>::iterator iterator;
810     iterator begin() { return Candidates.begin(); }
811     iterator end() { return Candidates.end(); }
812
813     size_t size() const { return Candidates.size(); }
814     bool empty() const { return Candidates.empty(); }
815
816     /// \brief Allocate storage for conversion sequences for NumConversions
817     /// conversions.
818     ConversionSequenceList
819     allocateConversionSequences(unsigned NumConversions) {
820       ImplicitConversionSequence *Conversions =
821           slabAllocate<ImplicitConversionSequence>(NumConversions);
822
823       // Construct the new objects.
824       for (unsigned I = 0; I != NumConversions; ++I)
825         new (&Conversions[I]) ImplicitConversionSequence();
826
827       return ConversionSequenceList(Conversions, NumConversions);
828     }
829
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");
836
837       Candidates.push_back(OverloadCandidate());
838       OverloadCandidate &C = Candidates.back();
839       C.Conversions = Conversions.empty()
840                           ? allocateConversionSequences(NumConversions)
841                           : Conversions;
842       return C;
843     }
844
845     /// Find the best viable function on this overload set, if it exists.
846     OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
847                                          OverloadCandidateSet::iterator& Best);
848
849     void NoteCandidates(Sema &S,
850                         OverloadCandidateDisplayKind OCD,
851                         ArrayRef<Expr *> Args,
852                         StringRef Opc = "",
853                         SourceLocation Loc = SourceLocation(),
854                         llvm::function_ref<bool(OverloadCandidate&)> Filter =
855                           [](OverloadCandidate&) { return true; });
856   };
857
858   bool isBetterOverloadCandidate(Sema &S,
859                                  const OverloadCandidate &Cand1,
860                                  const OverloadCandidate &Cand2,
861                                  SourceLocation Loc,
862                                  OverloadCandidateSet::CandidateSetKind Kind);
863
864   struct ConstructorInfo {
865     DeclAccessPair FoundDecl;
866     CXXConstructorDecl *Constructor;
867     FunctionTemplateDecl *ConstructorTmpl;
868     explicit operator bool() const { return Constructor; }
869   };
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{};
875
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,
880                             nullptr};
881     Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
882     if (Info.ConstructorTmpl)
883       D = Info.ConstructorTmpl->getTemplatedDecl();
884     Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
885     return Info;
886   }
887 } // end namespace clang
888
889 #endif // LLVM_CLANG_SEMA_OVERLOAD_H