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