Initialization.h revision 70e24fccc8ef4aa8be03a778e9655bfcfa79dd14
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
25namespace clang {
26
27class CXXBaseSpecifier;
28class DeclaratorDecl;
29class DeclaratorInfo;
30class FieldDecl;
31class FunctionDecl;
32class ParmVarDecl;
33class Sema;
34class TypeLoc;
35class VarDecl;
36
37/// \brief Describes an entity that is being initialized.
38class InitializedEntity {
39public:
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
79private:
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
169public:
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           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).
364class InitializationKind {
365public:
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
375private:
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
404public:
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.
535class InitializationSequence {
536public:
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
656private:
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
663public:
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
727private:
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 Prints a follow-up note that highlights the location of
738  /// the initialized entity, if it's remote.
739  void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
740
741public:
742  /// \brief Try to perform initialization of the given entity, creating a
743  /// record of the steps required to perform the initialization.
744  ///
745  /// The generated initialization sequence will either contain enough
746  /// information to diagnose
747  ///
748  /// \param S the semantic analysis object.
749  ///
750  /// \param Entity the entity being initialized.
751  ///
752  /// \param Kind the kind of initialization being performed.
753  ///
754  /// \param Args the argument(s) provided for initialization.
755  ///
756  /// \param NumArgs the number of arguments provided for initialization.
757  InitializationSequence(Sema &S,
758                         const InitializedEntity &Entity,
759                         const InitializationKind &Kind,
760                         Expr **Args,
761                         unsigned NumArgs);
762
763  ~InitializationSequence();
764
765  /// \brief Perform the actual initialization of the given entity based on
766  /// the computed initialization sequence.
767  ///
768  /// \param S the semantic analysis object.
769  ///
770  /// \param Entity the entity being initialized.
771  ///
772  /// \param Kind the kind of initialization being performed.
773  ///
774  /// \param Args the argument(s) provided for initialization, ownership of
775  /// which is transferred into the routine.
776  ///
777  /// \param ResultType if non-NULL, will be set to the type of the
778  /// initialized object, which is the type of the declaration in most
779  /// cases. However, when the initialized object is a variable of
780  /// incomplete array type and the initializer is an initializer
781  /// list, this type will be set to the completed array type.
782  ///
783  /// \returns an expression that performs the actual object initialization, if
784  /// the initialization is well-formed. Otherwise, emits diagnostics
785  /// and returns an invalid expression.
786  ExprResult Perform(Sema &S,
787                     const InitializedEntity &Entity,
788                     const InitializationKind &Kind,
789                     MultiExprArg Args,
790                     QualType *ResultType = 0);
791
792  /// \brief Diagnose an potentially-invalid initialization sequence.
793  ///
794  /// \returns true if the initialization sequence was ill-formed,
795  /// false otherwise.
796  bool Diagnose(Sema &S,
797                const InitializedEntity &Entity,
798                const InitializationKind &Kind,
799                Expr **Args, unsigned NumArgs);
800
801  /// \brief Determine the kind of initialization sequence computed.
802  enum SequenceKind getKind() const { return SequenceKind; }
803
804  /// \brief Set the kind of sequence computed.
805  void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
806
807  /// \brief Determine whether the initialization sequence is valid.
808  operator bool() const { return !Failed(); }
809
810  /// \brief Determine whether the initialization sequence is invalid.
811  bool Failed() const { return SequenceKind == FailedSequence; }
812
813  typedef SmallVector<Step, 4>::const_iterator step_iterator;
814  step_iterator step_begin() const { return Steps.begin(); }
815  step_iterator step_end()   const { return Steps.end(); }
816
817  /// \brief Determine whether this initialization is a direct reference
818  /// binding (C++ [dcl.init.ref]).
819  bool isDirectReferenceBinding() const;
820
821  /// \brief Determine whether this initialization failed due to an ambiguity.
822  bool isAmbiguous() const;
823
824  /// \brief Determine whether this initialization is direct call to a
825  /// constructor.
826  bool isConstructorInitialization() const;
827
828  /// \brief Returns whether the last step in this initialization sequence is a
829  /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
830  ///
831  /// If this function returns true, *isInitializerConstant will be set to
832  /// describe whether *Initializer was a constant expression.  If
833  /// *isInitializerConstant is set to true, *ConstantValue will be set to the
834  /// evaluated value of *Initializer.
835  bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
836                         bool *isInitializerConstant,
837                         APValue *ConstantValue) const;
838
839  /// \brief Add a new step in the initialization that resolves the address
840  /// of an overloaded function to a specific function declaration.
841  ///
842  /// \param Function the function to which the overloaded function reference
843  /// resolves.
844  void AddAddressOverloadResolutionStep(FunctionDecl *Function,
845                                        DeclAccessPair Found,
846                                        bool HadMultipleCandidates);
847
848  /// \brief Add a new step in the initialization that performs a derived-to-
849  /// base cast.
850  ///
851  /// \param BaseType the base type to which we will be casting.
852  ///
853  /// \param IsLValue true if the result of this cast will be treated as
854  /// an lvalue.
855  void AddDerivedToBaseCastStep(QualType BaseType,
856                                ExprValueKind Category);
857
858  /// \brief Add a new step binding a reference to an object.
859  ///
860  /// \param BindingTemporary True if we are binding a reference to a temporary
861  /// object (thereby extending its lifetime); false if we are binding to an
862  /// lvalue or an lvalue treated as an rvalue.
863  ///
864  /// \param UnnecessaryCopy True if we should check for a copy
865  /// constructor for a completely unnecessary but
866  void AddReferenceBindingStep(QualType T, bool BindingTemporary);
867
868  /// \brief Add a new step that makes an extraneous copy of the input
869  /// to a temporary of the same class type.
870  ///
871  /// This extraneous copy only occurs during reference binding in
872  /// C++98/03, where we are permitted (but not required) to introduce
873  /// an extra copy. At a bare minimum, we must check that we could
874  /// call the copy constructor, and produce a diagnostic if the copy
875  /// constructor is inaccessible or no copy constructor matches.
876  //
877  /// \param T The type of the temporary being created.
878  void AddExtraneousCopyToTemporary(QualType T);
879
880  /// \brief Add a new step invoking a conversion function, which is either
881  /// a constructor or a conversion function.
882  void AddUserConversionStep(FunctionDecl *Function,
883                             DeclAccessPair FoundDecl,
884                             QualType T,
885                             bool HadMultipleCandidates);
886
887  /// \brief Add a new step that performs a qualification conversion to the
888  /// given type.
889  void AddQualificationConversionStep(QualType Ty,
890                                     ExprValueKind Category);
891
892  /// \brief Add a new step that applies an implicit conversion sequence.
893  void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
894                                 QualType T);
895
896  /// \brief Add a list-initialization step.
897  void AddListInitializationStep(QualType T);
898
899  /// \brief Add a constructor-initialization step.
900  ///
901  /// \arg FromInitList The constructor call is syntactically an initializer
902  /// list.
903  /// \arg AsInitList The constructor is called as an init list constructor.
904  void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
905                                        AccessSpecifier Access,
906                                        QualType T,
907                                        bool HadMultipleCandidates,
908                                        bool FromInitList, bool AsInitList);
909
910  /// \brief Add a zero-initialization step.
911  void AddZeroInitializationStep(QualType T);
912
913  /// \brief Add a C assignment step.
914  //
915  // FIXME: It isn't clear whether this should ever be needed;
916  // ideally, we would handle everything needed in C in the common
917  // path. However, that isn't the case yet.
918  void AddCAssignmentStep(QualType T);
919
920  /// \brief Add a string init step.
921  void AddStringInitStep(QualType T);
922
923  /// \brief Add an Objective-C object conversion step, which is
924  /// always a no-op.
925  void AddObjCObjectConversionStep(QualType T);
926
927  /// \brief Add an array initialization step.
928  void AddArrayInitStep(QualType T);
929
930  /// \brief Add a parenthesized array initialization step.
931  void AddParenthesizedArrayInitStep(QualType T);
932
933  /// \brief Add a step to pass an object by indirect copy-restore.
934  void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
935
936  /// \brief Add a step to "produce" an Objective-C object (by
937  /// retaining it).
938  void AddProduceObjCObjectStep(QualType T);
939
940  /// \brief Add a step to construct a std::initializer_list object from an
941  /// initializer list.
942  void AddStdInitializerListConstructionStep(QualType T);
943
944  /// \brief Add steps to unwrap a initializer list for a reference around a
945  /// single element and rewrap it at the end.
946  void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
947
948  /// \brief Note that this initialization sequence failed.
949  void SetFailed(FailureKind Failure) {
950    SequenceKind = FailedSequence;
951    this->Failure = Failure;
952  }
953
954  /// \brief Note that this initialization sequence failed due to failed
955  /// overload resolution.
956  void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
957
958  /// \brief Retrieve a reference to the candidate set when overload
959  /// resolution fails.
960  OverloadCandidateSet &getFailedCandidateSet() {
961    return FailedCandidateSet;
962  }
963
964  /// \brief Get the overloading result, for when the initialization
965  /// sequence failed due to a bad overload.
966  OverloadingResult getFailedOverloadResult() const {
967    return FailedOverloadResult;
968  }
969
970  /// \brief Determine why initialization failed.
971  FailureKind getFailureKind() const {
972    assert(Failed() && "Not an initialization failure!");
973    return Failure;
974  }
975
976  /// \brief Dump a representation of this initialization sequence to
977  /// the given stream, for debugging purposes.
978  void dump(raw_ostream &OS) const;
979
980  /// \brief Dump a representation of this initialization sequence to
981  /// standard error, for debugging purposes.
982  void dump() const;
983};
984
985} // end namespace clang
986
987#endif // LLVM_CLANG_SEMA_INITIALIZATION_H
988