]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/include/clang/Sema/Initialization.h
MFC r234353:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / include / clang / Sema / Initialization.h
1 //===--- Initialization.h - Semantic Analysis for Initializers --*- 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 provides supporting data types for initialization of objects.
11 //
12 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
14 #define LLVM_CLANG_SEMA_INITIALIZATION_H
15
16 #include "clang/Sema/Ownership.h"
17 #include "clang/Sema/Overload.h"
18 #include "clang/AST/Type.h"
19 #include "clang/AST/UnresolvedSet.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include <cassert>
24
25 namespace clang {
26   
27 class CXXBaseSpecifier;
28 class DeclaratorDecl;
29 class DeclaratorInfo;
30 class FieldDecl;
31 class FunctionDecl;
32 class ParmVarDecl;
33 class Sema;
34 class TypeLoc;
35 class VarDecl;
36   
37 /// \brief Describes an entity that is being initialized.
38 class InitializedEntity {
39 public:
40   /// \brief Specifies the kind of entity being initialized.
41   enum EntityKind {
42     /// \brief The entity being initialized is a variable.
43     EK_Variable,
44     /// \brief The entity being initialized is a function parameter.
45     EK_Parameter,
46     /// \brief The entity being initialized is the result of a function call.
47     EK_Result,
48     /// \brief The entity being initialized is an exception object that
49     /// is being thrown.
50     EK_Exception,
51     /// \brief The entity being initialized is a non-static data member 
52     /// subobject.
53     EK_Member,
54     /// \brief The entity being initialized is an element of an array.
55     EK_ArrayElement,
56     /// \brief The entity being initialized is an object (or array of
57     /// objects) allocated via new.
58     EK_New,
59     /// \brief The entity being initialized is a temporary object.
60     EK_Temporary,
61     /// \brief The entity being initialized is a base member subobject.
62     EK_Base,
63     /// \brief The initialization is being done by a delegating constructor.
64     EK_Delegating,
65     /// \brief The entity being initialized is an element of a vector.
66     /// or vector.
67     EK_VectorElement,
68     /// \brief The entity being initialized is a field of block descriptor for
69     /// the copied-in c++ object.
70     EK_BlockElement,
71     /// \brief The entity being initialized is the real or imaginary part of a
72     /// complex number.
73     EK_ComplexElement,
74     /// \brief The entity being initialized is the field that captures a 
75     /// variable in a lambda.
76     EK_LambdaCapture
77   };
78   
79 private:
80   /// \brief The kind of entity being initialized.
81   EntityKind Kind;
82
83   /// \brief If non-NULL, the parent entity in which this
84   /// initialization occurs.
85   const InitializedEntity *Parent;
86
87   /// \brief The type of the object or reference being initialized.
88   QualType Type;
89   
90   union {
91     /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
92     /// FieldDecl, respectively.
93     DeclaratorDecl *VariableOrMember;
94
95     /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
96     /// low bit indicating whether the parameter is "consumed".
97     uintptr_t Parameter;
98     
99     /// \brief When Kind == EK_Temporary, the type source information for
100     /// the temporary.
101     TypeSourceInfo *TypeInfo;
102     
103     struct {
104       /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
105       /// location of the 'return', 'throw', or 'new' keyword,
106       /// respectively. When Kind == EK_Temporary, the location where
107       /// the temporary is being created.
108       unsigned Location;
109       
110       /// \brief Whether the entity being initialized may end up using the
111       /// named return value optimization (NRVO).
112       bool NRVO;
113     } LocAndNRVO;
114     
115     /// \brief When Kind == EK_Base, the base specifier that provides the 
116     /// base class. The lower bit specifies whether the base is an inherited
117     /// virtual base.
118     uintptr_t Base;
119
120     /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
121     /// EK_ComplexElement, the index of the array or vector element being
122     /// initialized. 
123     unsigned Index;
124     
125     struct {
126       /// \brief The variable being captured by an EK_LambdaCapture.
127       VarDecl *Var;
128       
129       /// \brief The source location at which the capture occurs.
130       unsigned Location;
131     } Capture;
132   };
133
134   InitializedEntity() { }
135
136   /// \brief Create the initialization entity for a variable.
137   InitializedEntity(VarDecl *Var)
138     : Kind(EK_Variable), Parent(0), Type(Var->getType()),
139       VariableOrMember(Var) { }
140   
141   /// \brief Create the initialization entity for the result of a
142   /// function, throwing an object, performing an explicit cast, or
143   /// initializing a parameter for which there is no declaration.
144   InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
145                     bool NRVO = false)
146     : Kind(Kind), Parent(0), Type(Type)
147   {
148     LocAndNRVO.Location = Loc.getRawEncoding();
149     LocAndNRVO.NRVO = NRVO;
150   }
151   
152   /// \brief Create the initialization entity for a member subobject.
153   InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent) 
154     : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
155       VariableOrMember(Member) { }
156   
157   /// \brief Create the initialization entity for an array element.
158   InitializedEntity(ASTContext &Context, unsigned Index, 
159                     const InitializedEntity &Parent);
160
161   /// \brief Create the initialization entity for a lambda capture.
162   InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
163     : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType()) 
164   {
165     Capture.Var = Var;
166     Capture.Location = Loc.getRawEncoding();
167   }
168   
169 public:
170   /// \brief Create the initialization entity for a variable.
171   static InitializedEntity InitializeVariable(VarDecl *Var) {
172     return InitializedEntity(Var);
173   }
174   
175   /// \brief Create the initialization entity for a parameter.
176   static InitializedEntity InitializeParameter(ASTContext &Context,
177                                                ParmVarDecl *Parm) {
178     bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
179                      Parm->hasAttr<NSConsumedAttr>());
180
181     InitializedEntity Entity;
182     Entity.Kind = EK_Parameter;
183     Entity.Type = Context.getVariableArrayDecayedType(
184                                        Parm->getType().getUnqualifiedType());
185     Entity.Parent = 0;
186     Entity.Parameter
187       = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
188     return Entity;
189   }
190
191   /// \brief Create the initialization entity for a parameter that is
192   /// only known by its type.
193   static InitializedEntity InitializeParameter(ASTContext &Context,
194                                                QualType Type,
195                                                bool Consumed) {
196     InitializedEntity Entity;
197     Entity.Kind = EK_Parameter;
198     Entity.Type = Context.getVariableArrayDecayedType(Type);
199     Entity.Parent = 0;
200     Entity.Parameter = (Consumed);
201     return Entity;
202   }
203
204   /// \brief Create the initialization entity for the result of a function.
205   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
206                                             QualType Type, bool NRVO) {
207     return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
208   }
209
210   static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
211                                            QualType Type, bool NRVO) {
212     return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
213   }
214   
215   /// \brief Create the initialization entity for an exception object.
216   static InitializedEntity InitializeException(SourceLocation ThrowLoc,
217                                                QualType Type, bool NRVO) {
218     return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
219   }
220
221   /// \brief Create the initialization entity for an object allocated via new.
222   static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
223     return InitializedEntity(EK_New, NewLoc, Type);
224   }
225   
226   /// \brief Create the initialization entity for a temporary.
227   static InitializedEntity InitializeTemporary(QualType Type) {
228     return InitializedEntity(EK_Temporary, SourceLocation(), Type);
229   }
230
231   /// \brief Create the initialization entity for a temporary.
232   static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
233     InitializedEntity Result(EK_Temporary, SourceLocation(), 
234                              TypeInfo->getType());
235     Result.TypeInfo = TypeInfo;
236     return Result;
237   }
238
239   /// \brief Create the initialization entity for a base class subobject.
240   static InitializedEntity InitializeBase(ASTContext &Context,
241                                           CXXBaseSpecifier *Base,
242                                           bool IsInheritedVirtualBase);
243
244   /// \brief Create the initialization entity for a delegated constructor.
245   static InitializedEntity InitializeDelegation(QualType Type) {
246     return InitializedEntity(EK_Delegating, SourceLocation(), Type);
247   }
248   
249   /// \brief Create the initialization entity for a member subobject.
250   static InitializedEntity InitializeMember(FieldDecl *Member,
251                                           const InitializedEntity *Parent = 0) {
252     return InitializedEntity(Member, Parent);
253   }
254   
255   /// \brief Create the initialization entity for a member subobject.
256   static InitializedEntity InitializeMember(IndirectFieldDecl *Member,
257                                       const InitializedEntity *Parent = 0) {
258     return InitializedEntity(Member->getAnonField(), Parent);
259   }
260
261   /// \brief Create the initialization entity for an array element.
262   static InitializedEntity InitializeElement(ASTContext &Context, 
263                                              unsigned Index, 
264                                              const InitializedEntity &Parent) {
265     return InitializedEntity(Context, Index, Parent);
266   }
267
268   /// \brief Create the initialization entity for a lambda capture.
269   static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
270                                                    FieldDecl *Field,
271                                                    SourceLocation Loc) {
272     return InitializedEntity(Var, Field, Loc);
273   }
274                                                    
275   /// \brief Determine the kind of initialization.
276   EntityKind getKind() const { return Kind; }
277   
278   /// \brief Retrieve the parent of the entity being initialized, when
279   /// the initialization itself is occurring within the context of a
280   /// larger initialization.
281   const InitializedEntity *getParent() const { return Parent; }
282
283   /// \brief Retrieve type being initialized.
284   QualType getType() const { return Type; }
285   
286   /// \brief Retrieve complete type-source information for the object being 
287   /// constructed, if known.
288   TypeSourceInfo *getTypeSourceInfo() const {
289     if (Kind == EK_Temporary)
290       return TypeInfo;
291     
292     return 0;
293   }
294   
295   /// \brief Retrieve the name of the entity being initialized.
296   DeclarationName getName() const;
297
298   /// \brief Retrieve the variable, parameter, or field being
299   /// initialized.
300   DeclaratorDecl *getDecl() const;
301
302   /// \brief Determine whether this initialization allows the named return 
303   /// value optimization, which also applies to thrown objects.
304   bool allowsNRVO() const;
305
306   /// \brief Determine whether this initialization consumes the
307   /// parameter.
308   bool isParameterConsumed() const {
309     assert(getKind() == EK_Parameter && "Not a parameter");
310     return (Parameter & 1);
311   }
312                                   
313   /// \brief Retrieve the base specifier.
314   CXXBaseSpecifier *getBaseSpecifier() const {
315     assert(getKind() == EK_Base && "Not a base specifier");
316     return reinterpret_cast<CXXBaseSpecifier *>(Base & ~0x1);
317   }
318
319   /// \brief Return whether the base is an inherited virtual base.
320   bool isInheritedVirtualBase() const {
321     assert(getKind() == EK_Base && "Not a base specifier");
322     return Base & 0x1;
323   }
324
325   /// \brief Determine the location of the 'return' keyword when initializing
326   /// the result of a function call.
327   SourceLocation getReturnLoc() const {
328     assert(getKind() == EK_Result && "No 'return' location!");
329     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
330   }
331
332   /// \brief Determine the location of the 'throw' keyword when initializing
333   /// an exception object.
334   SourceLocation getThrowLoc() const {
335     assert(getKind() == EK_Exception && "No 'throw' location!");
336     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
337   }
338
339   /// \brief If this is already the initializer for an array or vector
340   /// element, sets the element index.
341   void setElementIndex(unsigned Index) {
342     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
343            getKind() == EK_ComplexElement);
344     this->Index = Index;
345   }
346
347   /// \brief Retrieve the variable for a captured variable in a lambda.
348   VarDecl *getCapturedVar() const {
349     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
350     return Capture.Var;
351   }
352   
353   /// \brief Determine the location of the capture when initializing
354   /// field from a captured variable in a lambda.
355   SourceLocation getCaptureLoc() const {
356     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
357     return SourceLocation::getFromRawEncoding(Capture.Location);
358   }
359 };
360   
361 /// \brief Describes the kind of initialization being performed, along with 
362 /// location information for tokens related to the initialization (equal sign,
363 /// parentheses).
364 class InitializationKind {
365 public:
366   /// \brief The kind of initialization being performed.
367   enum InitKind {
368     IK_Direct,       ///< Direct initialization
369     IK_DirectList,   ///< Direct list-initialization
370     IK_Copy,         ///< Copy initialization
371     IK_Default,      ///< Default initialization
372     IK_Value         ///< Value initialization
373   };
374   
375 private:
376   /// \brief The context of the initialization.
377   enum InitContext {
378     IC_Normal,         ///< Normal context
379     IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion funcs
380     IC_Implicit,       ///< Implicit context (value initialization)
381     IC_StaticCast,     ///< Static cast context
382     IC_CStyleCast,     ///< C-style cast context
383     IC_FunctionalCast  ///< Functional cast context
384   };
385   
386   /// \brief The kind of initialization being performed.
387   InitKind Kind : 8;
388
389   /// \brief The context of the initialization.
390   InitContext Context : 8;
391   
392   /// \brief The source locations involved in the initialization.
393   SourceLocation Locations[3];
394   
395   InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, 
396                      SourceLocation Loc2, SourceLocation Loc3)
397     : Kind(Kind), Context(Context)
398   {
399     Locations[0] = Loc1;
400     Locations[1] = Loc2;
401     Locations[2] = Loc3;
402   }
403   
404 public:
405   /// \brief Create a direct initialization.
406   static InitializationKind CreateDirect(SourceLocation InitLoc,
407                                          SourceLocation LParenLoc,
408                                          SourceLocation RParenLoc) {
409     return InitializationKind(IK_Direct, IC_Normal,
410                               InitLoc, LParenLoc, RParenLoc);
411   }
412
413   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
414     return InitializationKind(IK_DirectList, IC_Normal,
415                               InitLoc, InitLoc, InitLoc);
416   }
417
418   /// \brief Create a direct initialization due to a cast that isn't a C-style 
419   /// or functional cast.
420   static InitializationKind CreateCast(SourceRange TypeRange) {
421     return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
422                               TypeRange.getBegin(), TypeRange.getEnd());
423   }
424   
425   /// \brief Create a direct initialization for a C-style cast.
426   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
427                                              SourceRange TypeRange,
428                                              bool InitList) {
429     // C++ cast syntax doesn't permit init lists, but C compound literals are
430     // exactly that.
431     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
432                               IC_CStyleCast, StartLoc, TypeRange.getBegin(),
433                               TypeRange.getEnd());
434   }
435
436   /// \brief Create a direct initialization for a functional cast.
437   static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
438                                                  bool InitList) {
439     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
440                               IC_FunctionalCast, TypeRange.getBegin(),
441                               TypeRange.getBegin(), TypeRange.getEnd());
442   }
443
444   /// \brief Create a copy initialization.
445   static InitializationKind CreateCopy(SourceLocation InitLoc,
446                                        SourceLocation EqualLoc,
447                                        bool AllowExplicitConvs = false) {
448     return InitializationKind(IK_Copy, 
449                               AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
450                               InitLoc, EqualLoc, EqualLoc);
451   }
452   
453   /// \brief Create a default initialization.
454   static InitializationKind CreateDefault(SourceLocation InitLoc) {
455     return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
456   }
457   
458   /// \brief Create a value initialization.
459   static InitializationKind CreateValue(SourceLocation InitLoc,
460                                         SourceLocation LParenLoc,
461                                         SourceLocation RParenLoc,
462                                         bool isImplicit = false) {
463     return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
464                               InitLoc, LParenLoc, RParenLoc);
465   }
466   
467   /// \brief Determine the initialization kind.
468   InitKind getKind() const {
469     return Kind;
470   }
471   
472   /// \brief Determine whether this initialization is an explicit cast.
473   bool isExplicitCast() const {
474     return Context >= IC_StaticCast;
475   }
476   
477   /// \brief Determine whether this initialization is a C-style cast.
478   bool isCStyleOrFunctionalCast() const { 
479     return Context >= IC_CStyleCast; 
480   }
481
482   /// \brief Determine whether this is a C-style cast.
483   bool isCStyleCast() const {
484     return Context == IC_CStyleCast;
485   }
486
487   /// \brief Determine whether this is a functional-style cast.
488   bool isFunctionalCast() const {
489     return Context == IC_FunctionalCast;
490   }
491
492   /// \brief Determine whether this initialization is an implicit
493   /// value-initialization, e.g., as occurs during aggregate
494   /// initialization.
495   bool isImplicitValueInit() const { return Context == IC_Implicit; }
496
497   /// \brief Retrieve the location at which initialization is occurring.
498   SourceLocation getLocation() const { return Locations[0]; }
499   
500   /// \brief Retrieve the source range that covers the initialization.
501   SourceRange getRange() const { 
502     return SourceRange(Locations[0], Locations[2]);
503   }
504   
505   /// \brief Retrieve the location of the equal sign for copy initialization
506   /// (if present).
507   SourceLocation getEqualLoc() const {
508     assert(Kind == IK_Copy && "Only copy initialization has an '='");
509     return Locations[1];
510   }
511
512   bool isCopyInit() const { return Kind == IK_Copy; }
513
514   /// \brief Retrieve whether this initialization allows the use of explicit
515   ///        constructors.
516   bool AllowExplicit() const { return !isCopyInit(); }
517
518   /// \brief Retrieve whether this initialization allows the use of explicit
519   /// conversion functions.
520   bool allowExplicitConversionFunctions() const {
521     return !isCopyInit() || Context == IC_ExplicitConvs;
522   }
523   
524   /// \brief Retrieve the source range containing the locations of the open
525   /// and closing parentheses for value and direct initializations.
526   SourceRange getParenRange() const {
527     assert((Kind == IK_Direct || Kind == IK_Value) &&
528            "Only direct- and value-initialization have parentheses");
529     return SourceRange(Locations[1], Locations[2]);
530   }
531 };
532
533 /// \brief Describes the sequence of initializations required to initialize
534 /// a given object or reference with a set of arguments.
535 class InitializationSequence {
536 public:
537   /// \brief Describes the kind of initialization sequence computed.
538   enum SequenceKind {
539     /// \brief A failed initialization sequence. The failure kind tells what
540     /// happened.
541     FailedSequence = 0,
542
543     /// \brief A dependent initialization, which could not be
544     /// type-checked due to the presence of dependent types or
545     /// dependently-typed expressions.
546     DependentSequence,
547
548     /// \brief A normal sequence.
549     NormalSequence
550   };
551   
552   /// \brief Describes the kind of a particular step in an initialization
553   /// sequence.
554   enum StepKind {
555     /// \brief Resolve the address of an overloaded function to a specific
556     /// function declaration.
557     SK_ResolveAddressOfOverloadedFunction,
558     /// \brief Perform a derived-to-base cast, producing an rvalue.
559     SK_CastDerivedToBaseRValue,
560     /// \brief Perform a derived-to-base cast, producing an xvalue.
561     SK_CastDerivedToBaseXValue,
562     /// \brief Perform a derived-to-base cast, producing an lvalue.
563     SK_CastDerivedToBaseLValue,
564     /// \brief Reference binding to an lvalue.
565     SK_BindReference,
566     /// \brief Reference binding to a temporary.
567     SK_BindReferenceToTemporary,
568     /// \brief An optional copy of a temporary object to another
569     /// temporary object, which is permitted (but not required) by
570     /// C++98/03 but not C++0x.
571     SK_ExtraneousCopyToTemporary,
572     /// \brief Perform a user-defined conversion, either via a conversion
573     /// function or via a constructor.
574     SK_UserConversion,
575     /// \brief Perform a qualification conversion, producing an rvalue.
576     SK_QualificationConversionRValue,
577     /// \brief Perform a qualification conversion, producing an xvalue.
578     SK_QualificationConversionXValue,
579     /// \brief Perform a qualification conversion, producing an lvalue.
580     SK_QualificationConversionLValue,
581     /// \brief Perform an implicit conversion sequence.
582     SK_ConversionSequence,
583     /// \brief Perform list-initialization without a constructor
584     SK_ListInitialization,
585     /// \brief Perform list-initialization with a constructor.
586     SK_ListConstructorCall,
587     /// \brief Unwrap the single-element initializer list for a reference.
588     SK_UnwrapInitList,
589     /// \brief Rewrap the single-element initializer list for a reference.
590     SK_RewrapInitList,
591     /// \brief Perform initialization via a constructor.
592     SK_ConstructorInitialization,
593     /// \brief Zero-initialize the object
594     SK_ZeroInitialization,
595     /// \brief C assignment
596     SK_CAssignment,
597     /// \brief Initialization by string
598     SK_StringInit,
599     /// \brief An initialization that "converts" an Objective-C object
600     /// (not a point to an object) to another Objective-C object type.
601     SK_ObjCObjectConversion,
602     /// \brief Array initialization (from an array rvalue).
603     /// This is a GNU C extension.
604     SK_ArrayInit,
605     /// \brief Array initialization from a parenthesized initializer list.
606     /// This is a GNU C++ extension.
607     SK_ParenthesizedArrayInit,
608     /// \brief Pass an object by indirect copy-and-restore.
609     SK_PassByIndirectCopyRestore,
610     /// \brief Pass an object by indirect restore.
611     SK_PassByIndirectRestore,
612     /// \brief Produce an Objective-C object pointer.
613     SK_ProduceObjCObject,
614     /// \brief Construct a std::initializer_list from an initializer list.
615     SK_StdInitializerList
616   };
617   
618   /// \brief A single step in the initialization sequence.
619   class Step {
620   public:
621     /// \brief The kind of conversion or initialization step we are taking.
622     StepKind Kind;
623     
624     // \brief The type that results from this initialization.
625     QualType Type;
626     
627     union {
628       /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
629       /// SK_UserConversion, the function that the expression should be 
630       /// resolved to or the conversion function to call, respectively.
631       /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
632       /// the constructor to be called.
633       ///
634       /// Always a FunctionDecl, plus a Boolean flag telling if it was
635       /// selected from an overloaded set having size greater than 1.
636       /// For conversion decls, the naming class is the source type.
637       /// For construct decls, the naming class is the target type.
638       struct {
639         bool HadMultipleCandidates;
640         FunctionDecl *Function;
641         DeclAccessPair FoundDecl;
642       } Function;
643
644       /// \brief When Kind = SK_ConversionSequence, the implicit conversion
645       /// sequence.
646       ImplicitConversionSequence *ICS;
647
648       /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
649       /// wrapping list.
650       InitListExpr *WrappingSyntacticList;
651     };
652
653     void Destroy();
654   };
655   
656 private:
657   /// \brief The kind of initialization sequence computed.
658   enum SequenceKind SequenceKind;
659   
660   /// \brief Steps taken by this initialization.
661   SmallVector<Step, 4> Steps;
662   
663 public:
664   /// \brief Describes why initialization failed.
665   enum FailureKind {
666     /// \brief Too many initializers provided for a reference.
667     FK_TooManyInitsForReference,
668     /// \brief Array must be initialized with an initializer list.
669     FK_ArrayNeedsInitList,
670     /// \brief Array must be initialized with an initializer list or a 
671     /// string literal.
672     FK_ArrayNeedsInitListOrStringLiteral,
673     /// \brief Array type mismatch.
674     FK_ArrayTypeMismatch,
675     /// \brief Non-constant array initializer
676     FK_NonConstantArrayInit,
677     /// \brief Cannot resolve the address of an overloaded function.
678     FK_AddressOfOverloadFailed,
679     /// \brief Overloading due to reference initialization failed.
680     FK_ReferenceInitOverloadFailed,
681     /// \brief Non-const lvalue reference binding to a temporary.
682     FK_NonConstLValueReferenceBindingToTemporary,
683     /// \brief Non-const lvalue reference binding to an lvalue of unrelated
684     /// type.
685     FK_NonConstLValueReferenceBindingToUnrelated,
686     /// \brief Rvalue reference binding to an lvalue.
687     FK_RValueReferenceBindingToLValue,
688     /// \brief Reference binding drops qualifiers.
689     FK_ReferenceInitDropsQualifiers,
690     /// \brief Reference binding failed.
691     FK_ReferenceInitFailed,
692     /// \brief Implicit conversion failed.
693     FK_ConversionFailed,
694     /// \brief Implicit conversion failed.
695     FK_ConversionFromPropertyFailed,
696     /// \brief Too many initializers for scalar
697     FK_TooManyInitsForScalar,
698     /// \brief Reference initialization from an initializer list
699     FK_ReferenceBindingToInitList,
700     /// \brief Initialization of some unused destination type with an
701     /// initializer list.
702     FK_InitListBadDestinationType,
703     /// \brief Overloading for a user-defined conversion failed.
704     FK_UserConversionOverloadFailed,
705     /// \brief Overloading for initialization by constructor failed.
706     FK_ConstructorOverloadFailed,
707     /// \brief Overloading for list-initialization by constructor failed.
708     FK_ListConstructorOverloadFailed,
709     /// \brief Default-initialization of a 'const' object.
710     FK_DefaultInitOfConst,
711     /// \brief Initialization of an incomplete type.
712     FK_Incomplete,
713     /// \brief Variable-length array must not have an initializer.
714     FK_VariableLengthArrayHasInitializer,
715     /// \brief List initialization failed at some point.
716     FK_ListInitializationFailed,
717     /// \brief Initializer has a placeholder type which cannot be
718     /// resolved by initialization.
719     FK_PlaceholderType,
720     /// \brief Failed to initialize a std::initializer_list because copy
721     /// construction of some element failed.
722     FK_InitListElementCopyFailure,
723     /// \brief List-copy-initialization chose an explicit constructor.
724     FK_ExplicitConstructor
725   };
726   
727 private:
728   /// \brief The reason why initialization failed.
729   FailureKind Failure;
730
731   /// \brief The failed result of overload resolution.
732   OverloadingResult FailedOverloadResult;
733   
734   /// \brief The candidate set created when initialization failed.
735   OverloadCandidateSet FailedCandidateSet;
736
737   /// \brief The incomplete type that caused a failure.
738   QualType FailedIncompleteType;
739   
740   /// \brief Prints a follow-up note that highlights the location of
741   /// the initialized entity, if it's remote.
742   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
743
744 public:
745   /// \brief Try to perform initialization of the given entity, creating a 
746   /// record of the steps required to perform the initialization.
747   ///
748   /// The generated initialization sequence will either contain enough
749   /// information to diagnose 
750   ///
751   /// \param S the semantic analysis object.
752   ///
753   /// \param Entity the entity being initialized.
754   ///
755   /// \param Kind the kind of initialization being performed.
756   ///
757   /// \param Args the argument(s) provided for initialization.
758   ///
759   /// \param NumArgs the number of arguments provided for initialization.
760   InitializationSequence(Sema &S, 
761                          const InitializedEntity &Entity,
762                          const InitializationKind &Kind,
763                          Expr **Args,
764                          unsigned NumArgs);
765   
766   ~InitializationSequence();
767   
768   /// \brief Perform the actual initialization of the given entity based on
769   /// the computed initialization sequence.
770   ///
771   /// \param S the semantic analysis object.
772   ///
773   /// \param Entity the entity being initialized.
774   ///
775   /// \param Kind the kind of initialization being performed.
776   ///
777   /// \param Args the argument(s) provided for initialization, ownership of
778   /// which is transferred into the routine.
779   ///
780   /// \param ResultType if non-NULL, will be set to the type of the
781   /// initialized object, which is the type of the declaration in most
782   /// cases. However, when the initialized object is a variable of
783   /// incomplete array type and the initializer is an initializer
784   /// list, this type will be set to the completed array type.
785   ///
786   /// \returns an expression that performs the actual object initialization, if
787   /// the initialization is well-formed. Otherwise, emits diagnostics
788   /// and returns an invalid expression.
789   ExprResult Perform(Sema &S,
790                      const InitializedEntity &Entity,
791                      const InitializationKind &Kind,
792                      MultiExprArg Args,
793                      QualType *ResultType = 0);
794   
795   /// \brief Diagnose an potentially-invalid initialization sequence.
796   ///
797   /// \returns true if the initialization sequence was ill-formed, 
798   /// false otherwise.
799   bool Diagnose(Sema &S, 
800                 const InitializedEntity &Entity,
801                 const InitializationKind &Kind,
802                 Expr **Args, unsigned NumArgs);
803   
804   /// \brief Determine the kind of initialization sequence computed.
805   enum SequenceKind getKind() const { return SequenceKind; }
806   
807   /// \brief Set the kind of sequence computed.
808   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
809   
810   /// \brief Determine whether the initialization sequence is valid.
811   operator bool() const { return !Failed(); }
812
813   /// \brief Determine whether the initialization sequence is invalid.
814   bool Failed() const { return SequenceKind == FailedSequence; }
815   
816   typedef SmallVector<Step, 4>::const_iterator step_iterator;
817   step_iterator step_begin() const { return Steps.begin(); }
818   step_iterator step_end()   const { return Steps.end(); }
819
820   /// \brief Determine whether this initialization is a direct reference 
821   /// binding (C++ [dcl.init.ref]).
822   bool isDirectReferenceBinding() const;
823   
824   /// \brief Determine whether this initialization failed due to an ambiguity.
825   bool isAmbiguous() const;
826   
827   /// \brief Determine whether this initialization is direct call to a 
828   /// constructor.
829   bool isConstructorInitialization() const;
830
831   /// \brief Returns whether the last step in this initialization sequence is a
832   /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
833   ///
834   /// If this function returns true, *isInitializerConstant will be set to
835   /// describe whether *Initializer was a constant expression.  If
836   /// *isInitializerConstant is set to true, *ConstantValue will be set to the
837   /// evaluated value of *Initializer.
838   bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
839                          bool *isInitializerConstant,
840                          APValue *ConstantValue) const;
841
842   /// \brief Add a new step in the initialization that resolves the address
843   /// of an overloaded function to a specific function declaration.
844   ///
845   /// \param Function the function to which the overloaded function reference
846   /// resolves.
847   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
848                                         DeclAccessPair Found,
849                                         bool HadMultipleCandidates);
850
851   /// \brief Add a new step in the initialization that performs a derived-to-
852   /// base cast.
853   ///
854   /// \param BaseType the base type to which we will be casting.
855   ///
856   /// \param IsLValue true if the result of this cast will be treated as 
857   /// an lvalue.
858   void AddDerivedToBaseCastStep(QualType BaseType,
859                                 ExprValueKind Category);
860      
861   /// \brief Add a new step binding a reference to an object.
862   ///
863   /// \param BindingTemporary True if we are binding a reference to a temporary
864   /// object (thereby extending its lifetime); false if we are binding to an
865   /// lvalue or an lvalue treated as an rvalue.
866   ///
867   /// \param UnnecessaryCopy True if we should check for a copy
868   /// constructor for a completely unnecessary but
869   void AddReferenceBindingStep(QualType T, bool BindingTemporary);
870
871   /// \brief Add a new step that makes an extraneous copy of the input
872   /// to a temporary of the same class type.
873   ///
874   /// This extraneous copy only occurs during reference binding in
875   /// C++98/03, where we are permitted (but not required) to introduce
876   /// an extra copy. At a bare minimum, we must check that we could
877   /// call the copy constructor, and produce a diagnostic if the copy
878   /// constructor is inaccessible or no copy constructor matches.
879   //
880   /// \param T The type of the temporary being created.
881   void AddExtraneousCopyToTemporary(QualType T);
882
883   /// \brief Add a new step invoking a conversion function, which is either
884   /// a constructor or a conversion function.
885   void AddUserConversionStep(FunctionDecl *Function,
886                              DeclAccessPair FoundDecl,
887                              QualType T,
888                              bool HadMultipleCandidates);
889
890   /// \brief Add a new step that performs a qualification conversion to the
891   /// given type.
892   void AddQualificationConversionStep(QualType Ty,
893                                      ExprValueKind Category);
894   
895   /// \brief Add a new step that applies an implicit conversion sequence.
896   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
897                                  QualType T);
898
899   /// \brief Add a list-initialization step.
900   void AddListInitializationStep(QualType T);
901
902   /// \brief Add a constructor-initialization step.
903   ///
904   /// \arg FromInitList The constructor call is syntactically an initializer
905   /// list.
906   /// \arg AsInitList The constructor is called as an init list constructor.
907   void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
908                                         AccessSpecifier Access,
909                                         QualType T,
910                                         bool HadMultipleCandidates,
911                                         bool FromInitList, bool AsInitList);
912
913   /// \brief Add a zero-initialization step.
914   void AddZeroInitializationStep(QualType T);
915
916   /// \brief Add a C assignment step.
917   //
918   // FIXME: It isn't clear whether this should ever be needed;
919   // ideally, we would handle everything needed in C in the common
920   // path. However, that isn't the case yet.
921   void AddCAssignmentStep(QualType T);
922
923   /// \brief Add a string init step.
924   void AddStringInitStep(QualType T);
925
926   /// \brief Add an Objective-C object conversion step, which is
927   /// always a no-op.
928   void AddObjCObjectConversionStep(QualType T);
929
930   /// \brief Add an array initialization step.
931   void AddArrayInitStep(QualType T);
932
933   /// \brief Add a parenthesized array initialization step.
934   void AddParenthesizedArrayInitStep(QualType T);
935
936   /// \brief Add a step to pass an object by indirect copy-restore.
937   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
938
939   /// \brief Add a step to "produce" an Objective-C object (by
940   /// retaining it).
941   void AddProduceObjCObjectStep(QualType T);
942
943   /// \brief Add a step to construct a std::initializer_list object from an
944   /// initializer list.
945   void AddStdInitializerListConstructionStep(QualType T);
946
947   /// \brief Add steps to unwrap a initializer list for a reference around a
948   /// single element and rewrap it at the end.
949   void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
950
951   /// \brief Note that this initialization sequence failed.
952   void SetFailed(FailureKind Failure) {
953     SequenceKind = FailedSequence;
954     this->Failure = Failure;
955     assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
956            "Incomplete type failure requires a type!");
957   }
958   
959   /// \brief Note that this initialization sequence failed due to failed
960   /// overload resolution.
961   void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
962   
963   /// \brief Retrieve a reference to the candidate set when overload
964   /// resolution fails.
965   OverloadCandidateSet &getFailedCandidateSet() {
966     return FailedCandidateSet;
967   }
968
969   /// \brief Get the overloading result, for when the initialization
970   /// sequence failed due to a bad overload.
971   OverloadingResult getFailedOverloadResult() const {
972     return FailedOverloadResult;
973   }
974
975   /// \brief Note that this initialization sequence failed due to an
976   /// incomplete type.
977   void setIncompleteTypeFailure(QualType IncompleteType) {
978     FailedIncompleteType = IncompleteType;
979     SetFailed(FK_Incomplete);
980   }
981
982   /// \brief Determine why initialization failed.
983   FailureKind getFailureKind() const {
984     assert(Failed() && "Not an initialization failure!");
985     return Failure;
986   }
987
988   /// \brief Dump a representation of this initialization sequence to 
989   /// the given stream, for debugging purposes.
990   void dump(raw_ostream &OS) const;
991   
992   /// \brief Dump a representation of this initialization sequence to 
993   /// standard error, for debugging purposes.
994   void dump() const;
995 };
996   
997 } // end namespace clang
998
999 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H