Initialization.h revision 4773654f2700d6fbb20612fbb6763b35860fa74d
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.getLangOptions().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_Implicit,       ///< Implicit context (value initialization)
380    IC_StaticCast,     ///< Static cast context
381    IC_CStyleCast,     ///< C-style cast context
382    IC_FunctionalCast  ///< Functional cast context
383  };
384
385  /// \brief The kind of initialization being performed.
386  InitKind Kind : 8;
387
388  /// \brief The context of the initialization.
389  InitContext Context : 8;
390
391  /// \brief The source locations involved in the initialization.
392  SourceLocation Locations[3];
393
394  InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
395                     SourceLocation Loc2, SourceLocation Loc3)
396    : Kind(Kind), Context(Context)
397  {
398    Locations[0] = Loc1;
399    Locations[1] = Loc2;
400    Locations[2] = Loc3;
401  }
402
403public:
404  /// \brief Create a direct initialization.
405  static InitializationKind CreateDirect(SourceLocation InitLoc,
406                                         SourceLocation LParenLoc,
407                                         SourceLocation RParenLoc) {
408    return InitializationKind(IK_Direct, IC_Normal,
409                              InitLoc, LParenLoc, RParenLoc);
410  }
411
412  static InitializationKind CreateDirectList(SourceLocation InitLoc) {
413    return InitializationKind(IK_DirectList, IC_Normal,
414                              InitLoc, InitLoc, InitLoc);
415  }
416
417  /// \brief Create a direct initialization due to a cast that isn't a C-style
418  /// or functional cast.
419  static InitializationKind CreateCast(SourceRange TypeRange) {
420    return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
421                              TypeRange.getBegin(), TypeRange.getEnd());
422  }
423
424  /// \brief Create a direct initialization for a C-style cast.
425  static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
426                                             SourceRange TypeRange,
427                                             bool InitList) {
428    // C++ cast syntax doesn't permit init lists, but C compound literals are
429    // exactly that.
430    return InitializationKind(InitList ? IK_DirectList : IK_Direct,
431                              IC_CStyleCast, StartLoc, TypeRange.getBegin(),
432                              TypeRange.getEnd());
433  }
434
435  /// \brief Create a direct initialization for a functional cast.
436  static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
437                                                 bool InitList) {
438    return InitializationKind(InitList ? IK_DirectList : IK_Direct,
439                              IC_FunctionalCast, TypeRange.getBegin(),
440                              TypeRange.getBegin(), TypeRange.getEnd());
441  }
442
443  /// \brief Create a copy initialization.
444  static InitializationKind CreateCopy(SourceLocation InitLoc,
445                                       SourceLocation EqualLoc) {
446    return InitializationKind(IK_Copy, IC_Normal, InitLoc, EqualLoc, EqualLoc);
447  }
448
449  /// \brief Create a default initialization.
450  static InitializationKind CreateDefault(SourceLocation InitLoc) {
451    return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
452  }
453
454  /// \brief Create a value initialization.
455  static InitializationKind CreateValue(SourceLocation InitLoc,
456                                        SourceLocation LParenLoc,
457                                        SourceLocation RParenLoc,
458                                        bool isImplicit = false) {
459    return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
460                              InitLoc, LParenLoc, RParenLoc);
461  }
462
463  /// \brief Determine the initialization kind.
464  InitKind getKind() const {
465    return Kind;
466  }
467
468  /// \brief Determine whether this initialization is an explicit cast.
469  bool isExplicitCast() const {
470    return Context >= IC_StaticCast;
471  }
472
473  /// \brief Determine whether this initialization is a C-style cast.
474  bool isCStyleOrFunctionalCast() const {
475    return Context >= IC_CStyleCast;
476  }
477
478  /// \brief Determine whether this is a C-style cast.
479  bool isCStyleCast() const {
480    return Context == IC_CStyleCast;
481  }
482
483  /// \brief Determine whether this is a functional-style cast.
484  bool isFunctionalCast() const {
485    return Context == IC_FunctionalCast;
486  }
487
488  /// \brief Determine whether this initialization is an implicit
489  /// value-initialization, e.g., as occurs during aggregate
490  /// initialization.
491  bool isImplicitValueInit() const { return Context == IC_Implicit; }
492
493  /// \brief Retrieve the location at which initialization is occurring.
494  SourceLocation getLocation() const { return Locations[0]; }
495
496  /// \brief Retrieve the source range that covers the initialization.
497  SourceRange getRange() const {
498    return SourceRange(Locations[0], Locations[2]);
499  }
500
501  /// \brief Retrieve the location of the equal sign for copy initialization
502  /// (if present).
503  SourceLocation getEqualLoc() const {
504    assert(Kind == IK_Copy && "Only copy initialization has an '='");
505    return Locations[1];
506  }
507
508  bool isCopyInit() const { return Kind == IK_Copy; }
509
510  /// \brief Retrieve whether this initialization allows the use of explicit
511  ///        constructors.
512  bool AllowExplicit() const { return !isCopyInit(); }
513
514  /// \brief Retrieve the source range containing the locations of the open
515  /// and closing parentheses for value and direct initializations.
516  SourceRange getParenRange() const {
517    assert((Kind == IK_Direct || Kind == IK_Value) &&
518           "Only direct- and value-initialization have parentheses");
519    return SourceRange(Locations[1], Locations[2]);
520  }
521};
522
523/// \brief Describes the sequence of initializations required to initialize
524/// a given object or reference with a set of arguments.
525class InitializationSequence {
526public:
527  /// \brief Describes the kind of initialization sequence computed.
528  enum SequenceKind {
529    /// \brief A failed initialization sequence. The failure kind tells what
530    /// happened.
531    FailedSequence = 0,
532
533    /// \brief A dependent initialization, which could not be
534    /// type-checked due to the presence of dependent types or
535    /// dependently-typed expressions.
536    DependentSequence,
537
538    /// \brief A normal sequence.
539    NormalSequence
540  };
541
542  /// \brief Describes the kind of a particular step in an initialization
543  /// sequence.
544  enum StepKind {
545    /// \brief Resolve the address of an overloaded function to a specific
546    /// function declaration.
547    SK_ResolveAddressOfOverloadedFunction,
548    /// \brief Perform a derived-to-base cast, producing an rvalue.
549    SK_CastDerivedToBaseRValue,
550    /// \brief Perform a derived-to-base cast, producing an xvalue.
551    SK_CastDerivedToBaseXValue,
552    /// \brief Perform a derived-to-base cast, producing an lvalue.
553    SK_CastDerivedToBaseLValue,
554    /// \brief Reference binding to an lvalue.
555    SK_BindReference,
556    /// \brief Reference binding to a temporary.
557    SK_BindReferenceToTemporary,
558    /// \brief An optional copy of a temporary object to another
559    /// temporary object, which is permitted (but not required) by
560    /// C++98/03 but not C++0x.
561    SK_ExtraneousCopyToTemporary,
562    /// \brief Perform a user-defined conversion, either via a conversion
563    /// function or via a constructor.
564    SK_UserConversion,
565    /// \brief Perform a qualification conversion, producing an rvalue.
566    SK_QualificationConversionRValue,
567    /// \brief Perform a qualification conversion, producing an xvalue.
568    SK_QualificationConversionXValue,
569    /// \brief Perform a qualification conversion, producing an lvalue.
570    SK_QualificationConversionLValue,
571    /// \brief Perform an implicit conversion sequence.
572    SK_ConversionSequence,
573    /// \brief Perform list-initialization without a constructor
574    SK_ListInitialization,
575    /// \brief Perform list-initialization with a constructor.
576    SK_ListConstructorCall,
577    /// \brief Unwrap the single-element initializer list for a reference.
578    SK_UnwrapInitList,
579    /// \brief Rewrap the single-element initializer list for a reference.
580    SK_RewrapInitList,
581    /// \brief Perform initialization via a constructor.
582    SK_ConstructorInitialization,
583    /// \brief Zero-initialize the object
584    SK_ZeroInitialization,
585    /// \brief C assignment
586    SK_CAssignment,
587    /// \brief Initialization by string
588    SK_StringInit,
589    /// \brief An initialization that "converts" an Objective-C object
590    /// (not a point to an object) to another Objective-C object type.
591    SK_ObjCObjectConversion,
592    /// \brief Array initialization (from an array rvalue).
593    /// This is a GNU C extension.
594    SK_ArrayInit,
595    /// \brief Pass an object by indirect copy-and-restore.
596    SK_PassByIndirectCopyRestore,
597    /// \brief Pass an object by indirect restore.
598    SK_PassByIndirectRestore,
599    /// \brief Produce an Objective-C object pointer.
600    SK_ProduceObjCObject,
601    /// \brief Construct a std::initializer_list from an initializer list.
602    SK_StdInitializerList
603  };
604
605  /// \brief A single step in the initialization sequence.
606  class Step {
607  public:
608    /// \brief The kind of conversion or initialization step we are taking.
609    StepKind Kind;
610
611    // \brief The type that results from this initialization.
612    QualType Type;
613
614    union {
615      /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
616      /// SK_UserConversion, the function that the expression should be
617      /// resolved to or the conversion function to call, respectively.
618      /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
619      /// the constructor to be called.
620      ///
621      /// Always a FunctionDecl, plus a Boolean flag telling if it was
622      /// selected from an overloaded set having size greater than 1.
623      /// For conversion decls, the naming class is the source type.
624      /// For construct decls, the naming class is the target type.
625      struct {
626        bool HadMultipleCandidates;
627        FunctionDecl *Function;
628        DeclAccessPair FoundDecl;
629      } Function;
630
631      /// \brief When Kind = SK_ConversionSequence, the implicit conversion
632      /// sequence.
633      ImplicitConversionSequence *ICS;
634
635      /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
636      /// wrapping list.
637      InitListExpr *WrappingSyntacticList;
638    };
639
640    void Destroy();
641  };
642
643private:
644  /// \brief The kind of initialization sequence computed.
645  enum SequenceKind SequenceKind;
646
647  /// \brief Steps taken by this initialization.
648  SmallVector<Step, 4> Steps;
649
650public:
651  /// \brief Describes why initialization failed.
652  enum FailureKind {
653    /// \brief Too many initializers provided for a reference.
654    FK_TooManyInitsForReference,
655    /// \brief Array must be initialized with an initializer list.
656    FK_ArrayNeedsInitList,
657    /// \brief Array must be initialized with an initializer list or a
658    /// string literal.
659    FK_ArrayNeedsInitListOrStringLiteral,
660    /// \brief Array type mismatch.
661    FK_ArrayTypeMismatch,
662    /// \brief Non-constant array initializer
663    FK_NonConstantArrayInit,
664    /// \brief Cannot resolve the address of an overloaded function.
665    FK_AddressOfOverloadFailed,
666    /// \brief Overloading due to reference initialization failed.
667    FK_ReferenceInitOverloadFailed,
668    /// \brief Non-const lvalue reference binding to a temporary.
669    FK_NonConstLValueReferenceBindingToTemporary,
670    /// \brief Non-const lvalue reference binding to an lvalue of unrelated
671    /// type.
672    FK_NonConstLValueReferenceBindingToUnrelated,
673    /// \brief Rvalue reference binding to an lvalue.
674    FK_RValueReferenceBindingToLValue,
675    /// \brief Reference binding drops qualifiers.
676    FK_ReferenceInitDropsQualifiers,
677    /// \brief Reference binding failed.
678    FK_ReferenceInitFailed,
679    /// \brief Implicit conversion failed.
680    FK_ConversionFailed,
681    /// \brief Implicit conversion failed.
682    FK_ConversionFromPropertyFailed,
683    /// \brief Too many initializers for scalar
684    FK_TooManyInitsForScalar,
685    /// \brief Reference initialization from an initializer list
686    FK_ReferenceBindingToInitList,
687    /// \brief Initialization of some unused destination type with an
688    /// initializer list.
689    FK_InitListBadDestinationType,
690    /// \brief Overloading for a user-defined conversion failed.
691    FK_UserConversionOverloadFailed,
692    /// \brief Overloading for initialization by constructor failed.
693    FK_ConstructorOverloadFailed,
694    /// \brief Overloading for list-initialization by constructor failed.
695    FK_ListConstructorOverloadFailed,
696    /// \brief Default-initialization of a 'const' object.
697    FK_DefaultInitOfConst,
698    /// \brief Initialization of an incomplete type.
699    FK_Incomplete,
700    /// \brief Variable-length array must not have an initializer.
701    FK_VariableLengthArrayHasInitializer,
702    /// \brief List initialization failed at some point.
703    FK_ListInitializationFailed,
704    /// \brief Initializer has a placeholder type which cannot be
705    /// resolved by initialization.
706    FK_PlaceholderType,
707    /// \brief Failed to initialize a std::initializer_list because copy
708    /// construction of some element failed.
709    FK_InitListElementCopyFailure
710  };
711
712private:
713  /// \brief The reason why initialization failed.
714  FailureKind Failure;
715
716  /// \brief The failed result of overload resolution.
717  OverloadingResult FailedOverloadResult;
718
719  /// \brief The candidate set created when initialization failed.
720  OverloadCandidateSet FailedCandidateSet;
721
722  /// \brief Prints a follow-up note that highlights the location of
723  /// the initialized entity, if it's remote.
724  void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
725
726public:
727  /// \brief Try to perform initialization of the given entity, creating a
728  /// record of the steps required to perform the initialization.
729  ///
730  /// The generated initialization sequence will either contain enough
731  /// information to diagnose
732  ///
733  /// \param S the semantic analysis object.
734  ///
735  /// \param Entity the entity being initialized.
736  ///
737  /// \param Kind the kind of initialization being performed.
738  ///
739  /// \param Args the argument(s) provided for initialization.
740  ///
741  /// \param NumArgs the number of arguments provided for initialization.
742  InitializationSequence(Sema &S,
743                         const InitializedEntity &Entity,
744                         const InitializationKind &Kind,
745                         Expr **Args,
746                         unsigned NumArgs);
747
748  ~InitializationSequence();
749
750  /// \brief Perform the actual initialization of the given entity based on
751  /// the computed initialization sequence.
752  ///
753  /// \param S the semantic analysis object.
754  ///
755  /// \param Entity the entity being initialized.
756  ///
757  /// \param Kind the kind of initialization being performed.
758  ///
759  /// \param Args the argument(s) provided for initialization, ownership of
760  /// which is transferred into the routine.
761  ///
762  /// \param ResultType if non-NULL, will be set to the type of the
763  /// initialized object, which is the type of the declaration in most
764  /// cases. However, when the initialized object is a variable of
765  /// incomplete array type and the initializer is an initializer
766  /// list, this type will be set to the completed array type.
767  ///
768  /// \returns an expression that performs the actual object initialization, if
769  /// the initialization is well-formed. Otherwise, emits diagnostics
770  /// and returns an invalid expression.
771  ExprResult Perform(Sema &S,
772                     const InitializedEntity &Entity,
773                     const InitializationKind &Kind,
774                     MultiExprArg Args,
775                     QualType *ResultType = 0);
776
777  /// \brief Diagnose an potentially-invalid initialization sequence.
778  ///
779  /// \returns true if the initialization sequence was ill-formed,
780  /// false otherwise.
781  bool Diagnose(Sema &S,
782                const InitializedEntity &Entity,
783                const InitializationKind &Kind,
784                Expr **Args, unsigned NumArgs);
785
786  /// \brief Determine the kind of initialization sequence computed.
787  enum SequenceKind getKind() const { return SequenceKind; }
788
789  /// \brief Set the kind of sequence computed.
790  void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
791
792  /// \brief Determine whether the initialization sequence is valid.
793  operator bool() const { return !Failed(); }
794
795  /// \brief Determine whether the initialization sequence is invalid.
796  bool Failed() const { return SequenceKind == FailedSequence; }
797
798  typedef SmallVector<Step, 4>::const_iterator step_iterator;
799  step_iterator step_begin() const { return Steps.begin(); }
800  step_iterator step_end()   const { return Steps.end(); }
801
802  /// \brief Determine whether this initialization is a direct reference
803  /// binding (C++ [dcl.init.ref]).
804  bool isDirectReferenceBinding() const;
805
806  /// \brief Determine whether this initialization failed due to an ambiguity.
807  bool isAmbiguous() const;
808
809  /// \brief Determine whether this initialization is direct call to a
810  /// constructor.
811  bool isConstructorInitialization() const;
812
813  /// \brief Returns whether the last step in this initialization sequence is a
814  /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
815  ///
816  /// If this function returns true, *isInitializerConstant will be set to
817  /// describe whether *Initializer was a constant expression.  If
818  /// *isInitializerConstant is set to true, *ConstantValue will be set to the
819  /// evaluated value of *Initializer.
820  bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
821                         bool *isInitializerConstant,
822                         APValue *ConstantValue) const;
823
824  /// \brief Add a new step in the initialization that resolves the address
825  /// of an overloaded function to a specific function declaration.
826  ///
827  /// \param Function the function to which the overloaded function reference
828  /// resolves.
829  void AddAddressOverloadResolutionStep(FunctionDecl *Function,
830                                        DeclAccessPair Found,
831                                        bool HadMultipleCandidates);
832
833  /// \brief Add a new step in the initialization that performs a derived-to-
834  /// base cast.
835  ///
836  /// \param BaseType the base type to which we will be casting.
837  ///
838  /// \param IsLValue true if the result of this cast will be treated as
839  /// an lvalue.
840  void AddDerivedToBaseCastStep(QualType BaseType,
841                                ExprValueKind Category);
842
843  /// \brief Add a new step binding a reference to an object.
844  ///
845  /// \param BindingTemporary True if we are binding a reference to a temporary
846  /// object (thereby extending its lifetime); false if we are binding to an
847  /// lvalue or an lvalue treated as an rvalue.
848  ///
849  /// \param UnnecessaryCopy True if we should check for a copy
850  /// constructor for a completely unnecessary but
851  void AddReferenceBindingStep(QualType T, bool BindingTemporary);
852
853  /// \brief Add a new step that makes an extraneous copy of the input
854  /// to a temporary of the same class type.
855  ///
856  /// This extraneous copy only occurs during reference binding in
857  /// C++98/03, where we are permitted (but not required) to introduce
858  /// an extra copy. At a bare minimum, we must check that we could
859  /// call the copy constructor, and produce a diagnostic if the copy
860  /// constructor is inaccessible or no copy constructor matches.
861  //
862  /// \param T The type of the temporary being created.
863  void AddExtraneousCopyToTemporary(QualType T);
864
865  /// \brief Add a new step invoking a conversion function, which is either
866  /// a constructor or a conversion function.
867  void AddUserConversionStep(FunctionDecl *Function,
868                             DeclAccessPair FoundDecl,
869                             QualType T,
870                             bool HadMultipleCandidates);
871
872  /// \brief Add a new step that performs a qualification conversion to the
873  /// given type.
874  void AddQualificationConversionStep(QualType Ty,
875                                     ExprValueKind Category);
876
877  /// \brief Add a new step that applies an implicit conversion sequence.
878  void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
879                                 QualType T);
880
881  /// \brief Add a list-initialization step.
882  void AddListInitializationStep(QualType T);
883
884  /// \brief Add a constructor-initialization step.
885  ///
886  /// \arg FromInitList The constructor call is syntactically an initializer
887  /// list.
888  /// \arg AsInitList The constructor is called as an init list constructor.
889  void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
890                                        AccessSpecifier Access,
891                                        QualType T,
892                                        bool HadMultipleCandidates,
893                                        bool FromInitList, bool AsInitList);
894
895  /// \brief Add a zero-initialization step.
896  void AddZeroInitializationStep(QualType T);
897
898  /// \brief Add a C assignment step.
899  //
900  // FIXME: It isn't clear whether this should ever be needed;
901  // ideally, we would handle everything needed in C in the common
902  // path. However, that isn't the case yet.
903  void AddCAssignmentStep(QualType T);
904
905  /// \brief Add a string init step.
906  void AddStringInitStep(QualType T);
907
908  /// \brief Add an Objective-C object conversion step, which is
909  /// always a no-op.
910  void AddObjCObjectConversionStep(QualType T);
911
912  /// \brief Add an array initialization step.
913  void AddArrayInitStep(QualType T);
914
915  /// \brief Add a step to pass an object by indirect copy-restore.
916  void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
917
918  /// \brief Add a step to "produce" an Objective-C object (by
919  /// retaining it).
920  void AddProduceObjCObjectStep(QualType T);
921
922  /// \brief Add a step to construct a std::initializer_list object from an
923  /// initializer list.
924  void AddStdInitializerListConstructionStep(QualType T);
925
926  /// \brief Add steps to unwrap a initializer list for a reference around a
927  /// single element and rewrap it at the end.
928  void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
929
930  /// \brief Note that this initialization sequence failed.
931  void SetFailed(FailureKind Failure) {
932    SequenceKind = FailedSequence;
933    this->Failure = Failure;
934  }
935
936  /// \brief Note that this initialization sequence failed due to failed
937  /// overload resolution.
938  void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
939
940  /// \brief Retrieve a reference to the candidate set when overload
941  /// resolution fails.
942  OverloadCandidateSet &getFailedCandidateSet() {
943    return FailedCandidateSet;
944  }
945
946  /// \brief Get the overloading result, for when the initialization
947  /// sequence failed due to a bad overload.
948  OverloadingResult getFailedOverloadResult() const {
949    return FailedOverloadResult;
950  }
951
952  /// \brief Determine why initialization failed.
953  FailureKind getFailureKind() const {
954    assert(Failed() && "Not an initialization failure!");
955    return Failure;
956  }
957
958  /// \brief Dump a representation of this initialization sequence to
959  /// the given stream, for debugging purposes.
960  void dump(raw_ostream &OS) const;
961
962  /// \brief Dump a representation of this initialization sequence to
963  /// standard error, for debugging purposes.
964  void dump() const;
965};
966
967} // end namespace clang
968
969#endif // LLVM_CLANG_SEMA_INITIALIZATION_H
970