Initialization.h revision 263508
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 name of the variable being captured by an EK_LambdaCapture.
120    IdentifierInfo *VarID;
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 accommodate 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(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
187    : Kind(EK_LambdaCapture), Parent(0), Type(FieldType)
188  {
189    Capture.VarID = VarID;
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(IdentifierInfo *VarID,
313                                                   QualType FieldType,
314                                                   SourceLocation Loc) {
315    return InitializedEntity(VarID, FieldType, 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  /// \brief For a lambda capture, return the capture's name.
406  StringRef getCapturedVarName() const {
407    assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
408    return Capture.VarID->getName();
409  }
410  /// \brief Determine the location of the capture when initializing
411  /// field from a captured variable in a lambda.
412  SourceLocation getCaptureLoc() const {
413    assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
414    return SourceLocation::getFromRawEncoding(Capture.Location);
415  }
416
417  void setParameterCFAudited() {
418    Kind = EK_Parameter_CF_Audited;
419  }
420
421  /// Dump a representation of the initialized entity to standard error,
422  /// for debugging purposes.
423  void dump() const;
424
425private:
426  unsigned dumpImpl(raw_ostream &OS) const;
427};
428
429/// \brief Describes the kind of initialization being performed, along with
430/// location information for tokens related to the initialization (equal sign,
431/// parentheses).
432class InitializationKind {
433public:
434  /// \brief The kind of initialization being performed.
435  enum InitKind {
436    IK_Direct,       ///< Direct initialization
437    IK_DirectList,   ///< Direct list-initialization
438    IK_Copy,         ///< Copy initialization
439    IK_Default,      ///< Default initialization
440    IK_Value         ///< Value initialization
441  };
442
443private:
444  /// \brief The context of the initialization.
445  enum InitContext {
446    IC_Normal,         ///< Normal context
447    IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion funcs
448    IC_Implicit,       ///< Implicit context (value initialization)
449    IC_StaticCast,     ///< Static cast context
450    IC_CStyleCast,     ///< C-style cast context
451    IC_FunctionalCast  ///< Functional cast context
452  };
453
454  /// \brief The kind of initialization being performed.
455  InitKind Kind : 8;
456
457  /// \brief The context of the initialization.
458  InitContext Context : 8;
459
460  /// \brief The source locations involved in the initialization.
461  SourceLocation Locations[3];
462
463  InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
464                     SourceLocation Loc2, SourceLocation Loc3)
465    : Kind(Kind), Context(Context)
466  {
467    Locations[0] = Loc1;
468    Locations[1] = Loc2;
469    Locations[2] = Loc3;
470  }
471
472public:
473  /// \brief Create a direct initialization.
474  static InitializationKind CreateDirect(SourceLocation InitLoc,
475                                         SourceLocation LParenLoc,
476                                         SourceLocation RParenLoc) {
477    return InitializationKind(IK_Direct, IC_Normal,
478                              InitLoc, LParenLoc, RParenLoc);
479  }
480
481  static InitializationKind CreateDirectList(SourceLocation InitLoc) {
482    return InitializationKind(IK_DirectList, IC_Normal,
483                              InitLoc, InitLoc, InitLoc);
484  }
485
486  /// \brief Create a direct initialization due to a cast that isn't a C-style
487  /// or functional cast.
488  static InitializationKind CreateCast(SourceRange TypeRange) {
489    return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
490                              TypeRange.getBegin(), TypeRange.getEnd());
491  }
492
493  /// \brief Create a direct initialization for a C-style cast.
494  static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
495                                             SourceRange TypeRange,
496                                             bool InitList) {
497    // C++ cast syntax doesn't permit init lists, but C compound literals are
498    // exactly that.
499    return InitializationKind(InitList ? IK_DirectList : IK_Direct,
500                              IC_CStyleCast, StartLoc, TypeRange.getBegin(),
501                              TypeRange.getEnd());
502  }
503
504  /// \brief Create a direct initialization for a functional cast.
505  static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
506                                                 bool InitList) {
507    return InitializationKind(InitList ? IK_DirectList : IK_Direct,
508                              IC_FunctionalCast, TypeRange.getBegin(),
509                              TypeRange.getBegin(), TypeRange.getEnd());
510  }
511
512  /// \brief Create a copy initialization.
513  static InitializationKind CreateCopy(SourceLocation InitLoc,
514                                       SourceLocation EqualLoc,
515                                       bool AllowExplicitConvs = false) {
516    return InitializationKind(IK_Copy,
517                              AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
518                              InitLoc, EqualLoc, EqualLoc);
519  }
520
521  /// \brief Create a default initialization.
522  static InitializationKind CreateDefault(SourceLocation InitLoc) {
523    return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
524  }
525
526  /// \brief Create a value initialization.
527  static InitializationKind CreateValue(SourceLocation InitLoc,
528                                        SourceLocation LParenLoc,
529                                        SourceLocation RParenLoc,
530                                        bool isImplicit = false) {
531    return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
532                              InitLoc, LParenLoc, RParenLoc);
533  }
534
535  /// \brief Determine the initialization kind.
536  InitKind getKind() const {
537    return Kind;
538  }
539
540  /// \brief Determine whether this initialization is an explicit cast.
541  bool isExplicitCast() const {
542    return Context >= IC_StaticCast;
543  }
544
545  /// \brief Determine whether this initialization is a C-style cast.
546  bool isCStyleOrFunctionalCast() const {
547    return Context >= IC_CStyleCast;
548  }
549
550  /// \brief Determine whether this is a C-style cast.
551  bool isCStyleCast() const {
552    return Context == IC_CStyleCast;
553  }
554
555  /// \brief Determine whether this is a functional-style cast.
556  bool isFunctionalCast() const {
557    return Context == IC_FunctionalCast;
558  }
559
560  /// \brief Determine whether this initialization is an implicit
561  /// value-initialization, e.g., as occurs during aggregate
562  /// initialization.
563  bool isImplicitValueInit() const { return Context == IC_Implicit; }
564
565  /// \brief Retrieve the location at which initialization is occurring.
566  SourceLocation getLocation() const { return Locations[0]; }
567
568  /// \brief Retrieve the source range that covers the initialization.
569  SourceRange getRange() const {
570    return SourceRange(Locations[0], Locations[2]);
571  }
572
573  /// \brief Retrieve the location of the equal sign for copy initialization
574  /// (if present).
575  SourceLocation getEqualLoc() const {
576    assert(Kind == IK_Copy && "Only copy initialization has an '='");
577    return Locations[1];
578  }
579
580  bool isCopyInit() const { return Kind == IK_Copy; }
581
582  /// \brief Retrieve whether this initialization allows the use of explicit
583  ///        constructors.
584  bool AllowExplicit() const { return !isCopyInit(); }
585
586  /// \brief Retrieve whether this initialization allows the use of explicit
587  /// conversion functions when binding a reference. If the reference is the
588  /// first parameter in a copy or move constructor, such conversions are
589  /// permitted even though we are performing copy-initialization.
590  bool allowExplicitConversionFunctionsInRefBinding() 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 an implicit conversion sequence without narrowing.
656    SK_ConversionSequenceNoNarrowing,
657    /// \brief Perform list-initialization without a constructor
658    SK_ListInitialization,
659    /// \brief Perform list-initialization with a constructor.
660    SK_ListConstructorCall,
661    /// \brief Unwrap the single-element initializer list for a reference.
662    SK_UnwrapInitList,
663    /// \brief Rewrap the single-element initializer list for a reference.
664    SK_RewrapInitList,
665    /// \brief Perform initialization via a constructor.
666    SK_ConstructorInitialization,
667    /// \brief Zero-initialize the object
668    SK_ZeroInitialization,
669    /// \brief C assignment
670    SK_CAssignment,
671    /// \brief Initialization by string
672    SK_StringInit,
673    /// \brief An initialization that "converts" an Objective-C object
674    /// (not a point to an object) to another Objective-C object type.
675    SK_ObjCObjectConversion,
676    /// \brief Array initialization (from an array rvalue).
677    /// This is a GNU C extension.
678    SK_ArrayInit,
679    /// \brief Array initialization from a parenthesized initializer list.
680    /// This is a GNU C++ extension.
681    SK_ParenthesizedArrayInit,
682    /// \brief Pass an object by indirect copy-and-restore.
683    SK_PassByIndirectCopyRestore,
684    /// \brief Pass an object by indirect restore.
685    SK_PassByIndirectRestore,
686    /// \brief Produce an Objective-C object pointer.
687    SK_ProduceObjCObject,
688    /// \brief Construct a std::initializer_list from an initializer list.
689    SK_StdInitializerList,
690    /// \brief Initialize an OpenCL sampler from an integer.
691    SK_OCLSamplerInit,
692    /// \brief Passing zero to a function where OpenCL event_t is expected.
693    SK_OCLZeroEvent
694  };
695
696  /// \brief A single step in the initialization sequence.
697  class Step {
698  public:
699    /// \brief The kind of conversion or initialization step we are taking.
700    StepKind Kind;
701
702    // \brief The type that results from this initialization.
703    QualType Type;
704
705    struct F {
706      bool HadMultipleCandidates;
707      FunctionDecl *Function;
708      DeclAccessPair FoundDecl;
709    };
710
711    union {
712      /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
713      /// SK_UserConversion, the function that the expression should be
714      /// resolved to or the conversion function to call, respectively.
715      /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
716      /// the constructor to be called.
717      ///
718      /// Always a FunctionDecl, plus a Boolean flag telling if it was
719      /// selected from an overloaded set having size greater than 1.
720      /// For conversion decls, the naming class is the source type.
721      /// For construct decls, the naming class is the target type.
722      struct F Function;
723
724      /// \brief When Kind = SK_ConversionSequence, the implicit conversion
725      /// sequence.
726      ImplicitConversionSequence *ICS;
727
728      /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
729      /// wrapping list.
730      InitListExpr *WrappingSyntacticList;
731    };
732
733    void Destroy();
734  };
735
736private:
737  /// \brief The kind of initialization sequence computed.
738  enum SequenceKind SequenceKind;
739
740  /// \brief Steps taken by this initialization.
741  SmallVector<Step, 4> Steps;
742
743public:
744  /// \brief Describes why initialization failed.
745  enum FailureKind {
746    /// \brief Too many initializers provided for a reference.
747    FK_TooManyInitsForReference,
748    /// \brief Array must be initialized with an initializer list.
749    FK_ArrayNeedsInitList,
750    /// \brief Array must be initialized with an initializer list or a
751    /// string literal.
752    FK_ArrayNeedsInitListOrStringLiteral,
753    /// \brief Array must be initialized with an initializer list or a
754    /// wide string literal.
755    FK_ArrayNeedsInitListOrWideStringLiteral,
756    /// \brief Initializing a wide char array with narrow string literal.
757    FK_NarrowStringIntoWideCharArray,
758    /// \brief Initializing char array with wide string literal.
759    FK_WideStringIntoCharArray,
760    /// \brief Initializing wide char array with incompatible wide string
761    /// literal.
762    FK_IncompatWideStringIntoWideChar,
763    /// \brief Array type mismatch.
764    FK_ArrayTypeMismatch,
765    /// \brief Non-constant array initializer
766    FK_NonConstantArrayInit,
767    /// \brief Cannot resolve the address of an overloaded function.
768    FK_AddressOfOverloadFailed,
769    /// \brief Overloading due to reference initialization failed.
770    FK_ReferenceInitOverloadFailed,
771    /// \brief Non-const lvalue reference binding to a temporary.
772    FK_NonConstLValueReferenceBindingToTemporary,
773    /// \brief Non-const lvalue reference binding to an lvalue of unrelated
774    /// type.
775    FK_NonConstLValueReferenceBindingToUnrelated,
776    /// \brief Rvalue reference binding to an lvalue.
777    FK_RValueReferenceBindingToLValue,
778    /// \brief Reference binding drops qualifiers.
779    FK_ReferenceInitDropsQualifiers,
780    /// \brief Reference binding failed.
781    FK_ReferenceInitFailed,
782    /// \brief Implicit conversion failed.
783    FK_ConversionFailed,
784    /// \brief Implicit conversion failed.
785    FK_ConversionFromPropertyFailed,
786    /// \brief Too many initializers for scalar
787    FK_TooManyInitsForScalar,
788    /// \brief Reference initialization from an initializer list
789    FK_ReferenceBindingToInitList,
790    /// \brief Initialization of some unused destination type with an
791    /// initializer list.
792    FK_InitListBadDestinationType,
793    /// \brief Overloading for a user-defined conversion failed.
794    FK_UserConversionOverloadFailed,
795    /// \brief Overloading for initialization by constructor failed.
796    FK_ConstructorOverloadFailed,
797    /// \brief Overloading for list-initialization by constructor failed.
798    FK_ListConstructorOverloadFailed,
799    /// \brief Default-initialization of a 'const' object.
800    FK_DefaultInitOfConst,
801    /// \brief Initialization of an incomplete type.
802    FK_Incomplete,
803    /// \brief Variable-length array must not have an initializer.
804    FK_VariableLengthArrayHasInitializer,
805    /// \brief List initialization failed at some point.
806    FK_ListInitializationFailed,
807    /// \brief Initializer has a placeholder type which cannot be
808    /// resolved by initialization.
809    FK_PlaceholderType,
810    /// \brief List-copy-initialization chose an explicit constructor.
811    FK_ExplicitConstructor
812  };
813
814private:
815  /// \brief The reason why initialization failed.
816  FailureKind Failure;
817
818  /// \brief The failed result of overload resolution.
819  OverloadingResult FailedOverloadResult;
820
821  /// \brief The candidate set created when initialization failed.
822  OverloadCandidateSet FailedCandidateSet;
823
824  /// \brief The incomplete type that caused a failure.
825  QualType FailedIncompleteType;
826
827  /// \brief Prints a follow-up note that highlights the location of
828  /// the initialized entity, if it's remote.
829  void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
830
831public:
832  /// \brief Try to perform initialization of the given entity, creating a
833  /// record of the steps required to perform the initialization.
834  ///
835  /// The generated initialization sequence will either contain enough
836  /// information to diagnose
837  ///
838  /// \param S the semantic analysis object.
839  ///
840  /// \param Entity the entity being initialized.
841  ///
842  /// \param Kind the kind of initialization being performed.
843  ///
844  /// \param Args the argument(s) provided for initialization.
845  ///
846  /// \param InInitList true if we are initializing from an expression within
847  ///        an initializer list. This disallows narrowing conversions in C++11
848  ///        onwards.
849  InitializationSequence(Sema &S,
850                         const InitializedEntity &Entity,
851                         const InitializationKind &Kind,
852                         MultiExprArg Args,
853                         bool InInitList = false);
854  void InitializeFrom(Sema &S, const InitializedEntity &Entity,
855                      const InitializationKind &Kind, MultiExprArg Args,
856                      bool InInitList);
857
858  ~InitializationSequence();
859
860  /// \brief Perform the actual initialization of the given entity based on
861  /// the computed initialization sequence.
862  ///
863  /// \param S the semantic analysis object.
864  ///
865  /// \param Entity the entity being initialized.
866  ///
867  /// \param Kind the kind of initialization being performed.
868  ///
869  /// \param Args the argument(s) provided for initialization, ownership of
870  /// which is transferred into the routine.
871  ///
872  /// \param ResultType if non-NULL, will be set to the type of the
873  /// initialized object, which is the type of the declaration in most
874  /// cases. However, when the initialized object is a variable of
875  /// incomplete array type and the initializer is an initializer
876  /// list, this type will be set to the completed array type.
877  ///
878  /// \returns an expression that performs the actual object initialization, if
879  /// the initialization is well-formed. Otherwise, emits diagnostics
880  /// and returns an invalid expression.
881  ExprResult Perform(Sema &S,
882                     const InitializedEntity &Entity,
883                     const InitializationKind &Kind,
884                     MultiExprArg Args,
885                     QualType *ResultType = 0);
886
887  /// \brief Diagnose an potentially-invalid initialization sequence.
888  ///
889  /// \returns true if the initialization sequence was ill-formed,
890  /// false otherwise.
891  bool Diagnose(Sema &S,
892                const InitializedEntity &Entity,
893                const InitializationKind &Kind,
894                ArrayRef<Expr *> Args);
895
896  /// \brief Determine the kind of initialization sequence computed.
897  enum SequenceKind getKind() const { return SequenceKind; }
898
899  /// \brief Set the kind of sequence computed.
900  void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
901
902  /// \brief Determine whether the initialization sequence is valid.
903  LLVM_EXPLICIT operator bool() const { return !Failed(); }
904
905  /// \brief Determine whether the initialization sequence is invalid.
906  bool Failed() const { return SequenceKind == FailedSequence; }
907
908  typedef SmallVectorImpl<Step>::const_iterator step_iterator;
909  step_iterator step_begin() const { return Steps.begin(); }
910  step_iterator step_end()   const { return Steps.end(); }
911
912  /// \brief Determine whether this initialization is a direct reference
913  /// binding (C++ [dcl.init.ref]).
914  bool isDirectReferenceBinding() const;
915
916  /// \brief Determine whether this initialization failed due to an ambiguity.
917  bool isAmbiguous() const;
918
919  /// \brief Determine whether this initialization is direct call to a
920  /// constructor.
921  bool isConstructorInitialization() const;
922
923  /// \brief Returns whether the last step in this initialization sequence is a
924  /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
925  ///
926  /// If this function returns true, *isInitializerConstant will be set to
927  /// describe whether *Initializer was a constant expression.  If
928  /// *isInitializerConstant is set to true, *ConstantValue will be set to the
929  /// evaluated value of *Initializer.
930  bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
931                         bool *isInitializerConstant,
932                         APValue *ConstantValue) const;
933
934  /// \brief Add a new step in the initialization that resolves the address
935  /// of an overloaded function to a specific function declaration.
936  ///
937  /// \param Function the function to which the overloaded function reference
938  /// resolves.
939  void AddAddressOverloadResolutionStep(FunctionDecl *Function,
940                                        DeclAccessPair Found,
941                                        bool HadMultipleCandidates);
942
943  /// \brief Add a new step in the initialization that performs a derived-to-
944  /// base cast.
945  ///
946  /// \param BaseType the base type to which we will be casting.
947  ///
948  /// \param Category Indicates whether the result will be treated as an
949  /// rvalue, an xvalue, or an lvalue.
950  void AddDerivedToBaseCastStep(QualType BaseType,
951                                ExprValueKind Category);
952
953  /// \brief Add a new step binding a reference to an object.
954  ///
955  /// \param BindingTemporary True if we are binding a reference to a temporary
956  /// object (thereby extending its lifetime); false if we are binding to an
957  /// lvalue or an lvalue treated as an rvalue.
958  void AddReferenceBindingStep(QualType T, bool BindingTemporary);
959
960  /// \brief Add a new step that makes an extraneous copy of the input
961  /// to a temporary of the same class type.
962  ///
963  /// This extraneous copy only occurs during reference binding in
964  /// C++98/03, where we are permitted (but not required) to introduce
965  /// an extra copy. At a bare minimum, we must check that we could
966  /// call the copy constructor, and produce a diagnostic if the copy
967  /// constructor is inaccessible or no copy constructor matches.
968  //
969  /// \param T The type of the temporary being created.
970  void AddExtraneousCopyToTemporary(QualType T);
971
972  /// \brief Add a new step invoking a conversion function, which is either
973  /// a constructor or a conversion function.
974  void AddUserConversionStep(FunctionDecl *Function,
975                             DeclAccessPair FoundDecl,
976                             QualType T,
977                             bool HadMultipleCandidates);
978
979  /// \brief Add a new step that performs a qualification conversion to the
980  /// given type.
981  void AddQualificationConversionStep(QualType Ty,
982                                     ExprValueKind Category);
983
984  /// \brief Add a new step that performs a load of the given type.
985  ///
986  /// Although the term "LValueToRValue" is conventional, this applies to both
987  /// lvalues and xvalues.
988  void AddLValueToRValueStep(QualType Ty);
989
990  /// \brief Add a new step that applies an implicit conversion sequence.
991  void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
992                                 QualType T, bool TopLevelOfInitList = false);
993
994  /// \brief Add a list-initialization step.
995  void AddListInitializationStep(QualType T);
996
997  /// \brief Add a constructor-initialization step.
998  ///
999  /// \param FromInitList The constructor call is syntactically an initializer
1000  /// list.
1001  /// \param AsInitList The constructor is called as an init list constructor.
1002  void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
1003                                        AccessSpecifier Access,
1004                                        QualType T,
1005                                        bool HadMultipleCandidates,
1006                                        bool FromInitList, bool AsInitList);
1007
1008  /// \brief Add a zero-initialization step.
1009  void AddZeroInitializationStep(QualType T);
1010
1011  /// \brief Add a C assignment step.
1012  //
1013  // FIXME: It isn't clear whether this should ever be needed;
1014  // ideally, we would handle everything needed in C in the common
1015  // path. However, that isn't the case yet.
1016  void AddCAssignmentStep(QualType T);
1017
1018  /// \brief Add a string init step.
1019  void AddStringInitStep(QualType T);
1020
1021  /// \brief Add an Objective-C object conversion step, which is
1022  /// always a no-op.
1023  void AddObjCObjectConversionStep(QualType T);
1024
1025  /// \brief Add an array initialization step.
1026  void AddArrayInitStep(QualType T);
1027
1028  /// \brief Add a parenthesized array initialization step.
1029  void AddParenthesizedArrayInitStep(QualType T);
1030
1031  /// \brief Add a step to pass an object by indirect copy-restore.
1032  void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1033
1034  /// \brief Add a step to "produce" an Objective-C object (by
1035  /// retaining it).
1036  void AddProduceObjCObjectStep(QualType T);
1037
1038  /// \brief Add a step to construct a std::initializer_list object from an
1039  /// initializer list.
1040  void AddStdInitializerListConstructionStep(QualType T);
1041
1042  /// \brief Add a step to initialize an OpenCL sampler from an integer
1043  /// constant.
1044  void AddOCLSamplerInitStep(QualType T);
1045
1046  /// \brief Add a step to initialize an OpenCL event_t from a NULL
1047  /// constant.
1048  void AddOCLZeroEventStep(QualType T);
1049
1050  /// \brief Add steps to unwrap a initializer list for a reference around a
1051  /// single element and rewrap it at the end.
1052  void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1053
1054  /// \brief Note that this initialization sequence failed.
1055  void SetFailed(FailureKind Failure) {
1056    SequenceKind = FailedSequence;
1057    this->Failure = Failure;
1058    assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1059           "Incomplete type failure requires a type!");
1060  }
1061
1062  /// \brief Note that this initialization sequence failed due to failed
1063  /// overload resolution.
1064  void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1065
1066  /// \brief Retrieve a reference to the candidate set when overload
1067  /// resolution fails.
1068  OverloadCandidateSet &getFailedCandidateSet() {
1069    return FailedCandidateSet;
1070  }
1071
1072  /// \brief Get the overloading result, for when the initialization
1073  /// sequence failed due to a bad overload.
1074  OverloadingResult getFailedOverloadResult() const {
1075    return FailedOverloadResult;
1076  }
1077
1078  /// \brief Note that this initialization sequence failed due to an
1079  /// incomplete type.
1080  void setIncompleteTypeFailure(QualType IncompleteType) {
1081    FailedIncompleteType = IncompleteType;
1082    SetFailed(FK_Incomplete);
1083  }
1084
1085  /// \brief Determine why initialization failed.
1086  FailureKind getFailureKind() const {
1087    assert(Failed() && "Not an initialization failure!");
1088    return Failure;
1089  }
1090
1091  /// \brief Dump a representation of this initialization sequence to
1092  /// the given stream, for debugging purposes.
1093  void dump(raw_ostream &OS) const;
1094
1095  /// \brief Dump a representation of this initialization sequence to
1096  /// standard error, for debugging purposes.
1097  void dump() const;
1098};
1099
1100} // end namespace clang
1101
1102#endif // LLVM_CLANG_SEMA_INITIALIZATION_H
1103