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