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