clang API Documentation

Initialization.h
Go to the documentation of this file.
00001 //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file provides supporting data types for initialization of objects.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
00014 #define LLVM_CLANG_SEMA_INITIALIZATION_H
00015 
00016 #include "clang/Sema/Ownership.h"
00017 #include "clang/Sema/Overload.h"
00018 #include "clang/AST/Type.h"
00019 #include "clang/AST/UnresolvedSet.h"
00020 #include "clang/Basic/SourceLocation.h"
00021 #include "llvm/ADT/PointerIntPair.h"
00022 #include "llvm/ADT/SmallVector.h"
00023 #include <cassert>
00024 
00025 namespace clang {
00026   
00027 class CXXBaseSpecifier;
00028 class DeclaratorDecl;
00029 class DeclaratorInfo;
00030 class FieldDecl;
00031 class FunctionDecl;
00032 class ParmVarDecl;
00033 class Sema;
00034 class TypeLoc;
00035 class VarDecl;
00036   
00037 /// \brief Describes an entity that is being initialized.
00038 class InitializedEntity {
00039 public:
00040   /// \brief Specifies the kind of entity being initialized.
00041   enum EntityKind {
00042     /// \brief The entity being initialized is a variable.
00043     EK_Variable,
00044     /// \brief The entity being initialized is a function parameter.
00045     EK_Parameter,
00046     /// \brief The entity being initialized is the result of a function call.
00047     EK_Result,
00048     /// \brief The entity being initialized is an exception object that
00049     /// is being thrown.
00050     EK_Exception,
00051     /// \brief The entity being initialized is a non-static data member 
00052     /// subobject.
00053     EK_Member,
00054     /// \brief The entity being initialized is an element of an array.
00055     EK_ArrayElement,
00056     /// \brief The entity being initialized is an object (or array of
00057     /// objects) allocated via new.
00058     EK_New,
00059     /// \brief The entity being initialized is a temporary object.
00060     EK_Temporary,
00061     /// \brief The entity being initialized is a base member subobject.
00062     EK_Base,
00063     /// \brief The initialization is being done by a delegating constructor.
00064     EK_Delegating,
00065     /// \brief The entity being initialized is an element of a vector.
00066     /// or vector.
00067     EK_VectorElement,
00068     /// \brief The entity being initialized is a field of block descriptor for
00069     /// the copied-in c++ object.
00070     EK_BlockElement,
00071     /// \brief The entity being initialized is the real or imaginary part of a
00072     /// complex number.
00073     EK_ComplexElement,
00074     /// \brief The entity being initialized is the field that captures a 
00075     /// variable in a lambda.
00076     EK_LambdaCapture
00077   };
00078   
00079 private:
00080   /// \brief The kind of entity being initialized.
00081   EntityKind Kind;
00082 
00083   /// \brief If non-NULL, the parent entity in which this
00084   /// initialization occurs.
00085   const InitializedEntity *Parent;
00086 
00087   /// \brief The type of the object or reference being initialized.
00088   QualType Type;
00089   
00090   union {
00091     /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
00092     /// FieldDecl, respectively.
00093     DeclaratorDecl *VariableOrMember;
00094 
00095     /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
00096     /// low bit indicating whether the parameter is "consumed".
00097     uintptr_t Parameter;
00098     
00099     /// \brief When Kind == EK_Temporary, the type source information for
00100     /// the temporary.
00101     TypeSourceInfo *TypeInfo;
00102     
00103     struct {
00104       /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
00105       /// location of the 'return', 'throw', or 'new' keyword,
00106       /// respectively. When Kind == EK_Temporary, the location where
00107       /// the temporary is being created.
00108       unsigned Location;
00109       
00110       /// \brief Whether the entity being initialized may end up using the
00111       /// named return value optimization (NRVO).
00112       bool NRVO;
00113     } LocAndNRVO;
00114     
00115     /// \brief When Kind == EK_Base, the base specifier that provides the 
00116     /// base class. The lower bit specifies whether the base is an inherited
00117     /// virtual base.
00118     uintptr_t Base;
00119 
00120     /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
00121     /// EK_ComplexElement, the index of the array or vector element being
00122     /// initialized. 
00123     unsigned Index;
00124     
00125     struct {
00126       /// \brief The variable being captured by an EK_LambdaCapture.
00127       VarDecl *Var;
00128       
00129       /// \brief The source location at which the capture occurs.
00130       unsigned Location;
00131     } Capture;
00132   };
00133 
00134   InitializedEntity() { }
00135 
00136   /// \brief Create the initialization entity for a variable.
00137   InitializedEntity(VarDecl *Var)
00138     : Kind(EK_Variable), Parent(0), Type(Var->getType()),
00139       VariableOrMember(Var) { }
00140   
00141   /// \brief Create the initialization entity for the result of a
00142   /// function, throwing an object, performing an explicit cast, or
00143   /// initializing a parameter for which there is no declaration.
00144   InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
00145                     bool NRVO = false)
00146     : Kind(Kind), Parent(0), Type(Type)
00147   {
00148     LocAndNRVO.Location = Loc.getRawEncoding();
00149     LocAndNRVO.NRVO = NRVO;
00150   }
00151   
00152   /// \brief Create the initialization entity for a member subobject.
00153   InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent) 
00154     : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
00155       VariableOrMember(Member) { }
00156   
00157   /// \brief Create the initialization entity for an array element.
00158   InitializedEntity(ASTContext &Context, unsigned Index, 
00159                     const InitializedEntity &Parent);
00160 
00161   /// \brief Create the initialization entity for a lambda capture.
00162   InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
00163     : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType()) 
00164   {
00165     Capture.Var = Var;
00166     Capture.Location = Loc.getRawEncoding();
00167   }
00168   
00169 public:
00170   /// \brief Create the initialization entity for a variable.
00171   static InitializedEntity InitializeVariable(VarDecl *Var) {
00172     return InitializedEntity(Var);
00173   }
00174   
00175   /// \brief Create the initialization entity for a parameter.
00176   static InitializedEntity InitializeParameter(ASTContext &Context,
00177                                                ParmVarDecl *Parm) {
00178     bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
00179                      Parm->hasAttr<NSConsumedAttr>());
00180 
00181     InitializedEntity Entity;
00182     Entity.Kind = EK_Parameter;
00183     Entity.Type = Context.getVariableArrayDecayedType(
00184                                        Parm->getType().getUnqualifiedType());
00185     Entity.Parent = 0;
00186     Entity.Parameter
00187       = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
00188     return Entity;
00189   }
00190 
00191   /// \brief Create the initialization entity for a parameter that is
00192   /// only known by its type.
00193   static InitializedEntity InitializeParameter(ASTContext &Context,
00194                                                QualType Type,
00195                                                bool Consumed) {
00196     InitializedEntity Entity;
00197     Entity.Kind = EK_Parameter;
00198     Entity.Type = Context.getVariableArrayDecayedType(Type);
00199     Entity.Parent = 0;
00200     Entity.Parameter = (Consumed);
00201     return Entity;
00202   }
00203 
00204   /// \brief Create the initialization entity for the result of a function.
00205   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
00206                                             QualType Type, bool NRVO) {
00207     return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
00208   }
00209 
00210   static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
00211                                            QualType Type, bool NRVO) {
00212     return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
00213   }
00214   
00215   /// \brief Create the initialization entity for an exception object.
00216   static InitializedEntity InitializeException(SourceLocation ThrowLoc,
00217                                                QualType Type, bool NRVO) {
00218     return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
00219   }
00220 
00221   /// \brief Create the initialization entity for an object allocated via new.
00222   static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
00223     return InitializedEntity(EK_New, NewLoc, Type);
00224   }
00225   
00226   /// \brief Create the initialization entity for a temporary.
00227   static InitializedEntity InitializeTemporary(QualType Type) {
00228     InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
00229     Result.TypeInfo = 0;
00230     return Result;
00231   }
00232 
00233   /// \brief Create the initialization entity for a temporary.
00234   static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
00235     InitializedEntity Result(EK_Temporary, SourceLocation(), 
00236                              TypeInfo->getType());
00237     Result.TypeInfo = TypeInfo;
00238     return Result;
00239   }
00240 
00241   /// \brief Create the initialization entity for a base class subobject.
00242   static InitializedEntity InitializeBase(ASTContext &Context,
00243                                           CXXBaseSpecifier *Base,
00244                                           bool IsInheritedVirtualBase);
00245 
00246   /// \brief Create the initialization entity for a delegated constructor.
00247   static InitializedEntity InitializeDelegation(QualType Type) {
00248     return InitializedEntity(EK_Delegating, SourceLocation(), Type);
00249   }
00250   
00251   /// \brief Create the initialization entity for a member subobject.
00252   static InitializedEntity InitializeMember(FieldDecl *Member,
00253                                           const InitializedEntity *Parent = 0) {
00254     return InitializedEntity(Member, Parent);
00255   }
00256   
00257   /// \brief Create the initialization entity for a member subobject.
00258   static InitializedEntity InitializeMember(IndirectFieldDecl *Member,
00259                                       const InitializedEntity *Parent = 0) {
00260     return InitializedEntity(Member->getAnonField(), Parent);
00261   }
00262 
00263   /// \brief Create the initialization entity for an array element.
00264   static InitializedEntity InitializeElement(ASTContext &Context, 
00265                                              unsigned Index, 
00266                                              const InitializedEntity &Parent) {
00267     return InitializedEntity(Context, Index, Parent);
00268   }
00269 
00270   /// \brief Create the initialization entity for a lambda capture.
00271   static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
00272                                                    FieldDecl *Field,
00273                                                    SourceLocation Loc) {
00274     return InitializedEntity(Var, Field, Loc);
00275   }
00276                                                    
00277   /// \brief Determine the kind of initialization.
00278   EntityKind getKind() const { return Kind; }
00279   
00280   /// \brief Retrieve the parent of the entity being initialized, when
00281   /// the initialization itself is occurring within the context of a
00282   /// larger initialization.
00283   const InitializedEntity *getParent() const { return Parent; }
00284 
00285   /// \brief Retrieve type being initialized.
00286   QualType getType() const { return Type; }
00287   
00288   /// \brief Retrieve complete type-source information for the object being 
00289   /// constructed, if known.
00290   TypeSourceInfo *getTypeSourceInfo() const {
00291     if (Kind == EK_Temporary)
00292       return TypeInfo;
00293     
00294     return 0;
00295   }
00296   
00297   /// \brief Retrieve the name of the entity being initialized.
00298   DeclarationName getName() const;
00299 
00300   /// \brief Retrieve the variable, parameter, or field being
00301   /// initialized.
00302   DeclaratorDecl *getDecl() const;
00303 
00304   /// \brief Determine whether this initialization allows the named return 
00305   /// value optimization, which also applies to thrown objects.
00306   bool allowsNRVO() const;
00307 
00308   /// \brief Determine whether this initialization consumes the
00309   /// parameter.
00310   bool isParameterConsumed() const {
00311     assert(getKind() == EK_Parameter && "Not a parameter");
00312     return (Parameter & 1);
00313   }
00314                                   
00315   /// \brief Retrieve the base specifier.
00316   CXXBaseSpecifier *getBaseSpecifier() const {
00317     assert(getKind() == EK_Base && "Not a base specifier");
00318     return reinterpret_cast<CXXBaseSpecifier *>(Base & ~0x1);
00319   }
00320 
00321   /// \brief Return whether the base is an inherited virtual base.
00322   bool isInheritedVirtualBase() const {
00323     assert(getKind() == EK_Base && "Not a base specifier");
00324     return Base & 0x1;
00325   }
00326 
00327   /// \brief Determine the location of the 'return' keyword when initializing
00328   /// the result of a function call.
00329   SourceLocation getReturnLoc() const {
00330     assert(getKind() == EK_Result && "No 'return' location!");
00331     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
00332   }
00333 
00334   /// \brief Determine the location of the 'throw' keyword when initializing
00335   /// an exception object.
00336   SourceLocation getThrowLoc() const {
00337     assert(getKind() == EK_Exception && "No 'throw' location!");
00338     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
00339   }
00340 
00341   /// \brief If this is already the initializer for an array or vector
00342   /// element, sets the element index.
00343   void setElementIndex(unsigned Index) {
00344     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
00345            getKind() == EK_ComplexElement);
00346     this->Index = Index;
00347   }
00348 
00349   /// \brief Retrieve the variable for a captured variable in a lambda.
00350   VarDecl *getCapturedVar() const {
00351     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
00352     return Capture.Var;
00353   }
00354   
00355   /// \brief Determine the location of the capture when initializing
00356   /// field from a captured variable in a lambda.
00357   SourceLocation getCaptureLoc() const {
00358     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
00359     return SourceLocation::getFromRawEncoding(Capture.Location);
00360   }
00361 };
00362   
00363 /// \brief Describes the kind of initialization being performed, along with 
00364 /// location information for tokens related to the initialization (equal sign,
00365 /// parentheses).
00366 class InitializationKind {
00367 public:
00368   /// \brief The kind of initialization being performed.
00369   enum InitKind {
00370     IK_Direct,       ///< Direct initialization
00371     IK_DirectList,   ///< Direct list-initialization
00372     IK_Copy,         ///< Copy initialization
00373     IK_Default,      ///< Default initialization
00374     IK_Value         ///< Value initialization
00375   };
00376   
00377 private:
00378   /// \brief The context of the initialization.
00379   enum InitContext {
00380     IC_Normal,         ///< Normal context
00381     IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion funcs
00382     IC_Implicit,       ///< Implicit context (value initialization)
00383     IC_StaticCast,     ///< Static cast context
00384     IC_CStyleCast,     ///< C-style cast context
00385     IC_FunctionalCast  ///< Functional cast context
00386   };
00387   
00388   /// \brief The kind of initialization being performed.
00389   InitKind Kind : 8;
00390 
00391   /// \brief The context of the initialization.
00392   InitContext Context : 8;
00393   
00394   /// \brief The source locations involved in the initialization.
00395   SourceLocation Locations[3];
00396   
00397   InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, 
00398                      SourceLocation Loc2, SourceLocation Loc3)
00399     : Kind(Kind), Context(Context)
00400   {
00401     Locations[0] = Loc1;
00402     Locations[1] = Loc2;
00403     Locations[2] = Loc3;
00404   }
00405   
00406 public:
00407   /// \brief Create a direct initialization.
00408   static InitializationKind CreateDirect(SourceLocation InitLoc,
00409                                          SourceLocation LParenLoc,
00410                                          SourceLocation RParenLoc) {
00411     return InitializationKind(IK_Direct, IC_Normal,
00412                               InitLoc, LParenLoc, RParenLoc);
00413   }
00414 
00415   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
00416     return InitializationKind(IK_DirectList, IC_Normal,
00417                               InitLoc, InitLoc, InitLoc);
00418   }
00419 
00420   /// \brief Create a direct initialization due to a cast that isn't a C-style 
00421   /// or functional cast.
00422   static InitializationKind CreateCast(SourceRange TypeRange) {
00423     return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
00424                               TypeRange.getBegin(), TypeRange.getEnd());
00425   }
00426   
00427   /// \brief Create a direct initialization for a C-style cast.
00428   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
00429                                              SourceRange TypeRange,
00430                                              bool InitList) {
00431     // C++ cast syntax doesn't permit init lists, but C compound literals are
00432     // exactly that.
00433     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
00434                               IC_CStyleCast, StartLoc, TypeRange.getBegin(),
00435                               TypeRange.getEnd());
00436   }
00437 
00438   /// \brief Create a direct initialization for a functional cast.
00439   static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
00440                                                  bool InitList) {
00441     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
00442                               IC_FunctionalCast, TypeRange.getBegin(),
00443                               TypeRange.getBegin(), TypeRange.getEnd());
00444   }
00445 
00446   /// \brief Create a copy initialization.
00447   static InitializationKind CreateCopy(SourceLocation InitLoc,
00448                                        SourceLocation EqualLoc,
00449                                        bool AllowExplicitConvs = false) {
00450     return InitializationKind(IK_Copy, 
00451                               AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
00452                               InitLoc, EqualLoc, EqualLoc);
00453   }
00454   
00455   /// \brief Create a default initialization.
00456   static InitializationKind CreateDefault(SourceLocation InitLoc) {
00457     return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
00458   }
00459   
00460   /// \brief Create a value initialization.
00461   static InitializationKind CreateValue(SourceLocation InitLoc,
00462                                         SourceLocation LParenLoc,
00463                                         SourceLocation RParenLoc,
00464                                         bool isImplicit = false) {
00465     return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
00466                               InitLoc, LParenLoc, RParenLoc);
00467   }
00468   
00469   /// \brief Determine the initialization kind.
00470   InitKind getKind() const {
00471     return Kind;
00472   }
00473   
00474   /// \brief Determine whether this initialization is an explicit cast.
00475   bool isExplicitCast() const {
00476     return Context >= IC_StaticCast;
00477   }
00478   
00479   /// \brief Determine whether this initialization is a C-style cast.
00480   bool isCStyleOrFunctionalCast() const { 
00481     return Context >= IC_CStyleCast; 
00482   }
00483 
00484   /// \brief Determine whether this is a C-style cast.
00485   bool isCStyleCast() const {
00486     return Context == IC_CStyleCast;
00487   }
00488 
00489   /// \brief Determine whether this is a functional-style cast.
00490   bool isFunctionalCast() const {
00491     return Context == IC_FunctionalCast;
00492   }
00493 
00494   /// \brief Determine whether this initialization is an implicit
00495   /// value-initialization, e.g., as occurs during aggregate
00496   /// initialization.
00497   bool isImplicitValueInit() const { return Context == IC_Implicit; }
00498 
00499   /// \brief Retrieve the location at which initialization is occurring.
00500   SourceLocation getLocation() const { return Locations[0]; }
00501   
00502   /// \brief Retrieve the source range that covers the initialization.
00503   SourceRange getRange() const { 
00504     return SourceRange(Locations[0], Locations[2]);
00505   }
00506   
00507   /// \brief Retrieve the location of the equal sign for copy initialization
00508   /// (if present).
00509   SourceLocation getEqualLoc() const {
00510     assert(Kind == IK_Copy && "Only copy initialization has an '='");
00511     return Locations[1];
00512   }
00513 
00514   bool isCopyInit() const { return Kind == IK_Copy; }
00515 
00516   /// \brief Retrieve whether this initialization allows the use of explicit
00517   ///        constructors.
00518   bool AllowExplicit() const { return !isCopyInit(); }
00519 
00520   /// \brief Retrieve whether this initialization allows the use of explicit
00521   /// conversion functions.
00522   bool allowExplicitConversionFunctions() const {
00523     return !isCopyInit() || Context == IC_ExplicitConvs;
00524   }
00525   
00526   /// \brief Retrieve the source range containing the locations of the open
00527   /// and closing parentheses for value and direct initializations.
00528   SourceRange getParenRange() const {
00529     assert((Kind == IK_Direct || Kind == IK_Value) &&
00530            "Only direct- and value-initialization have parentheses");
00531     return SourceRange(Locations[1], Locations[2]);
00532   }
00533 };
00534 
00535 /// \brief Describes the sequence of initializations required to initialize
00536 /// a given object or reference with a set of arguments.
00537 class InitializationSequence {
00538 public:
00539   /// \brief Describes the kind of initialization sequence computed.
00540   enum SequenceKind {
00541     /// \brief A failed initialization sequence. The failure kind tells what
00542     /// happened.
00543     FailedSequence = 0,
00544 
00545     /// \brief A dependent initialization, which could not be
00546     /// type-checked due to the presence of dependent types or
00547     /// dependently-typed expressions.
00548     DependentSequence,
00549 
00550     /// \brief A normal sequence.
00551     NormalSequence
00552   };
00553   
00554   /// \brief Describes the kind of a particular step in an initialization
00555   /// sequence.
00556   enum StepKind {
00557     /// \brief Resolve the address of an overloaded function to a specific
00558     /// function declaration.
00559     SK_ResolveAddressOfOverloadedFunction,
00560     /// \brief Perform a derived-to-base cast, producing an rvalue.
00561     SK_CastDerivedToBaseRValue,
00562     /// \brief Perform a derived-to-base cast, producing an xvalue.
00563     SK_CastDerivedToBaseXValue,
00564     /// \brief Perform a derived-to-base cast, producing an lvalue.
00565     SK_CastDerivedToBaseLValue,
00566     /// \brief Reference binding to an lvalue.
00567     SK_BindReference,
00568     /// \brief Reference binding to a temporary.
00569     SK_BindReferenceToTemporary,
00570     /// \brief An optional copy of a temporary object to another
00571     /// temporary object, which is permitted (but not required) by
00572     /// C++98/03 but not C++0x.
00573     SK_ExtraneousCopyToTemporary,
00574     /// \brief Perform a user-defined conversion, either via a conversion
00575     /// function or via a constructor.
00576     SK_UserConversion,
00577     /// \brief Perform a qualification conversion, producing an rvalue.
00578     SK_QualificationConversionRValue,
00579     /// \brief Perform a qualification conversion, producing an xvalue.
00580     SK_QualificationConversionXValue,
00581     /// \brief Perform a qualification conversion, producing an lvalue.
00582     SK_QualificationConversionLValue,
00583     /// \brief Perform an implicit conversion sequence.
00584     SK_ConversionSequence,
00585     /// \brief Perform list-initialization without a constructor
00586     SK_ListInitialization,
00587     /// \brief Perform list-initialization with a constructor.
00588     SK_ListConstructorCall,
00589     /// \brief Unwrap the single-element initializer list for a reference.
00590     SK_UnwrapInitList,
00591     /// \brief Rewrap the single-element initializer list for a reference.
00592     SK_RewrapInitList,
00593     /// \brief Perform initialization via a constructor.
00594     SK_ConstructorInitialization,
00595     /// \brief Zero-initialize the object
00596     SK_ZeroInitialization,
00597     /// \brief C assignment
00598     SK_CAssignment,
00599     /// \brief Initialization by string
00600     SK_StringInit,
00601     /// \brief An initialization that "converts" an Objective-C object
00602     /// (not a point to an object) to another Objective-C object type.
00603     SK_ObjCObjectConversion,
00604     /// \brief Array initialization (from an array rvalue).
00605     /// This is a GNU C extension.
00606     SK_ArrayInit,
00607     /// \brief Array initialization from a parenthesized initializer list.
00608     /// This is a GNU C++ extension.
00609     SK_ParenthesizedArrayInit,
00610     /// \brief Pass an object by indirect copy-and-restore.
00611     SK_PassByIndirectCopyRestore,
00612     /// \brief Pass an object by indirect restore.
00613     SK_PassByIndirectRestore,
00614     /// \brief Produce an Objective-C object pointer.
00615     SK_ProduceObjCObject,
00616     /// \brief Construct a std::initializer_list from an initializer list.
00617     SK_StdInitializerList
00618   };
00619   
00620   /// \brief A single step in the initialization sequence.
00621   class Step {
00622   public:
00623     /// \brief The kind of conversion or initialization step we are taking.
00624     StepKind Kind;
00625     
00626     // \brief The type that results from this initialization.
00627     QualType Type;
00628     
00629     union {
00630       /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
00631       /// SK_UserConversion, the function that the expression should be 
00632       /// resolved to or the conversion function to call, respectively.
00633       /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
00634       /// the constructor to be called.
00635       ///
00636       /// Always a FunctionDecl, plus a Boolean flag telling if it was
00637       /// selected from an overloaded set having size greater than 1.
00638       /// For conversion decls, the naming class is the source type.
00639       /// For construct decls, the naming class is the target type.
00640       struct {
00641         bool HadMultipleCandidates;
00642         FunctionDecl *Function;
00643         DeclAccessPair FoundDecl;
00644       } Function;
00645 
00646       /// \brief When Kind = SK_ConversionSequence, the implicit conversion
00647       /// sequence.
00648       ImplicitConversionSequence *ICS;
00649 
00650       /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
00651       /// wrapping list.
00652       InitListExpr *WrappingSyntacticList;
00653     };
00654 
00655     void Destroy();
00656   };
00657   
00658 private:
00659   /// \brief The kind of initialization sequence computed.
00660   enum SequenceKind SequenceKind;
00661   
00662   /// \brief Steps taken by this initialization.
00663   SmallVector<Step, 4> Steps;
00664   
00665 public:
00666   /// \brief Describes why initialization failed.
00667   enum FailureKind {
00668     /// \brief Too many initializers provided for a reference.
00669     FK_TooManyInitsForReference,
00670     /// \brief Array must be initialized with an initializer list.
00671     FK_ArrayNeedsInitList,
00672     /// \brief Array must be initialized with an initializer list or a 
00673     /// string literal.
00674     FK_ArrayNeedsInitListOrStringLiteral,
00675     /// \brief Array type mismatch.
00676     FK_ArrayTypeMismatch,
00677     /// \brief Non-constant array initializer
00678     FK_NonConstantArrayInit,
00679     /// \brief Cannot resolve the address of an overloaded function.
00680     FK_AddressOfOverloadFailed,
00681     /// \brief Overloading due to reference initialization failed.
00682     FK_ReferenceInitOverloadFailed,
00683     /// \brief Non-const lvalue reference binding to a temporary.
00684     FK_NonConstLValueReferenceBindingToTemporary,
00685     /// \brief Non-const lvalue reference binding to an lvalue of unrelated
00686     /// type.
00687     FK_NonConstLValueReferenceBindingToUnrelated,
00688     /// \brief Rvalue reference binding to an lvalue.
00689     FK_RValueReferenceBindingToLValue,
00690     /// \brief Reference binding drops qualifiers.
00691     FK_ReferenceInitDropsQualifiers,
00692     /// \brief Reference binding failed.
00693     FK_ReferenceInitFailed,
00694     /// \brief Implicit conversion failed.
00695     FK_ConversionFailed,
00696     /// \brief Implicit conversion failed.
00697     FK_ConversionFromPropertyFailed,
00698     /// \brief Too many initializers for scalar
00699     FK_TooManyInitsForScalar,
00700     /// \brief Reference initialization from an initializer list
00701     FK_ReferenceBindingToInitList,
00702     /// \brief Initialization of some unused destination type with an
00703     /// initializer list.
00704     FK_InitListBadDestinationType,
00705     /// \brief Overloading for a user-defined conversion failed.
00706     FK_UserConversionOverloadFailed,
00707     /// \brief Overloading for initialization by constructor failed.
00708     FK_ConstructorOverloadFailed,
00709     /// \brief Overloading for list-initialization by constructor failed.
00710     FK_ListConstructorOverloadFailed,
00711     /// \brief Default-initialization of a 'const' object.
00712     FK_DefaultInitOfConst,
00713     /// \brief Initialization of an incomplete type.
00714     FK_Incomplete,
00715     /// \brief Variable-length array must not have an initializer.
00716     FK_VariableLengthArrayHasInitializer,
00717     /// \brief List initialization failed at some point.
00718     FK_ListInitializationFailed,
00719     /// \brief Initializer has a placeholder type which cannot be
00720     /// resolved by initialization.
00721     FK_PlaceholderType,
00722     /// \brief Failed to initialize a std::initializer_list because copy
00723     /// construction of some element failed.
00724     FK_InitListElementCopyFailure,
00725     /// \brief List-copy-initialization chose an explicit constructor.
00726     FK_ExplicitConstructor
00727   };
00728   
00729 private:
00730   /// \brief The reason why initialization failed.
00731   FailureKind Failure;
00732 
00733   /// \brief The failed result of overload resolution.
00734   OverloadingResult FailedOverloadResult;
00735   
00736   /// \brief The candidate set created when initialization failed.
00737   OverloadCandidateSet FailedCandidateSet;
00738 
00739   /// \brief The incomplete type that caused a failure.
00740   QualType FailedIncompleteType;
00741   
00742   /// \brief Prints a follow-up note that highlights the location of
00743   /// the initialized entity, if it's remote.
00744   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
00745 
00746 public:
00747   /// \brief Try to perform initialization of the given entity, creating a 
00748   /// record of the steps required to perform the initialization.
00749   ///
00750   /// The generated initialization sequence will either contain enough
00751   /// information to diagnose 
00752   ///
00753   /// \param S the semantic analysis object.
00754   ///
00755   /// \param Entity the entity being initialized.
00756   ///
00757   /// \param Kind the kind of initialization being performed.
00758   ///
00759   /// \param Args the argument(s) provided for initialization.
00760   ///
00761   /// \param NumArgs the number of arguments provided for initialization.
00762   InitializationSequence(Sema &S, 
00763                          const InitializedEntity &Entity,
00764                          const InitializationKind &Kind,
00765                          Expr **Args,
00766                          unsigned NumArgs);
00767   
00768   ~InitializationSequence();
00769   
00770   /// \brief Perform the actual initialization of the given entity based on
00771   /// the computed initialization sequence.
00772   ///
00773   /// \param S the semantic analysis object.
00774   ///
00775   /// \param Entity the entity being initialized.
00776   ///
00777   /// \param Kind the kind of initialization being performed.
00778   ///
00779   /// \param Args the argument(s) provided for initialization, ownership of
00780   /// which is transferred into the routine.
00781   ///
00782   /// \param ResultType if non-NULL, will be set to the type of the
00783   /// initialized object, which is the type of the declaration in most
00784   /// cases. However, when the initialized object is a variable of
00785   /// incomplete array type and the initializer is an initializer
00786   /// list, this type will be set to the completed array type.
00787   ///
00788   /// \returns an expression that performs the actual object initialization, if
00789   /// the initialization is well-formed. Otherwise, emits diagnostics
00790   /// and returns an invalid expression.
00791   ExprResult Perform(Sema &S,
00792                      const InitializedEntity &Entity,
00793                      const InitializationKind &Kind,
00794                      MultiExprArg Args,
00795                      QualType *ResultType = 0);
00796   
00797   /// \brief Diagnose an potentially-invalid initialization sequence.
00798   ///
00799   /// \returns true if the initialization sequence was ill-formed, 
00800   /// false otherwise.
00801   bool Diagnose(Sema &S, 
00802                 const InitializedEntity &Entity,
00803                 const InitializationKind &Kind,
00804                 Expr **Args, unsigned NumArgs);
00805   
00806   /// \brief Determine the kind of initialization sequence computed.
00807   enum SequenceKind getKind() const { return SequenceKind; }
00808   
00809   /// \brief Set the kind of sequence computed.
00810   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
00811   
00812   /// \brief Determine whether the initialization sequence is valid.
00813   operator bool() const { return !Failed(); }
00814 
00815   /// \brief Determine whether the initialization sequence is invalid.
00816   bool Failed() const { return SequenceKind == FailedSequence; }
00817   
00818   typedef SmallVector<Step, 4>::const_iterator step_iterator;
00819   step_iterator step_begin() const { return Steps.begin(); }
00820   step_iterator step_end()   const { return Steps.end(); }
00821 
00822   /// \brief Determine whether this initialization is a direct reference 
00823   /// binding (C++ [dcl.init.ref]).
00824   bool isDirectReferenceBinding() const;
00825   
00826   /// \brief Determine whether this initialization failed due to an ambiguity.
00827   bool isAmbiguous() const;
00828   
00829   /// \brief Determine whether this initialization is direct call to a 
00830   /// constructor.
00831   bool isConstructorInitialization() const;
00832 
00833   /// \brief Returns whether the last step in this initialization sequence is a
00834   /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
00835   ///
00836   /// If this function returns true, *isInitializerConstant will be set to
00837   /// describe whether *Initializer was a constant expression.  If
00838   /// *isInitializerConstant is set to true, *ConstantValue will be set to the
00839   /// evaluated value of *Initializer.
00840   bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
00841                          bool *isInitializerConstant,
00842                          APValue *ConstantValue) const;
00843 
00844   /// \brief Add a new step in the initialization that resolves the address
00845   /// of an overloaded function to a specific function declaration.
00846   ///
00847   /// \param Function the function to which the overloaded function reference
00848   /// resolves.
00849   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
00850                                         DeclAccessPair Found,
00851                                         bool HadMultipleCandidates);
00852 
00853   /// \brief Add a new step in the initialization that performs a derived-to-
00854   /// base cast.
00855   ///
00856   /// \param BaseType the base type to which we will be casting.
00857   ///
00858   /// \param IsLValue true if the result of this cast will be treated as 
00859   /// an lvalue.
00860   void AddDerivedToBaseCastStep(QualType BaseType,
00861                                 ExprValueKind Category);
00862      
00863   /// \brief Add a new step binding a reference to an object.
00864   ///
00865   /// \param BindingTemporary True if we are binding a reference to a temporary
00866   /// object (thereby extending its lifetime); false if we are binding to an
00867   /// lvalue or an lvalue treated as an rvalue.
00868   ///
00869   /// \param UnnecessaryCopy True if we should check for a copy
00870   /// constructor for a completely unnecessary but
00871   void AddReferenceBindingStep(QualType T, bool BindingTemporary);
00872 
00873   /// \brief Add a new step that makes an extraneous copy of the input
00874   /// to a temporary of the same class type.
00875   ///
00876   /// This extraneous copy only occurs during reference binding in
00877   /// C++98/03, where we are permitted (but not required) to introduce
00878   /// an extra copy. At a bare minimum, we must check that we could
00879   /// call the copy constructor, and produce a diagnostic if the copy
00880   /// constructor is inaccessible or no copy constructor matches.
00881   //
00882   /// \param T The type of the temporary being created.
00883   void AddExtraneousCopyToTemporary(QualType T);
00884 
00885   /// \brief Add a new step invoking a conversion function, which is either
00886   /// a constructor or a conversion function.
00887   void AddUserConversionStep(FunctionDecl *Function,
00888                              DeclAccessPair FoundDecl,
00889                              QualType T,
00890                              bool HadMultipleCandidates);
00891 
00892   /// \brief Add a new step that performs a qualification conversion to the
00893   /// given type.
00894   void AddQualificationConversionStep(QualType Ty,
00895                                      ExprValueKind Category);
00896   
00897   /// \brief Add a new step that applies an implicit conversion sequence.
00898   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
00899                                  QualType T);
00900 
00901   /// \brief Add a list-initialization step.
00902   void AddListInitializationStep(QualType T);
00903 
00904   /// \brief Add a constructor-initialization step.
00905   ///
00906   /// \arg FromInitList The constructor call is syntactically an initializer
00907   /// list.
00908   /// \arg AsInitList The constructor is called as an init list constructor.
00909   void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
00910                                         AccessSpecifier Access,
00911                                         QualType T,
00912                                         bool HadMultipleCandidates,
00913                                         bool FromInitList, bool AsInitList);
00914 
00915   /// \brief Add a zero-initialization step.
00916   void AddZeroInitializationStep(QualType T);
00917 
00918   /// \brief Add a C assignment step.
00919   //
00920   // FIXME: It isn't clear whether this should ever be needed;
00921   // ideally, we would handle everything needed in C in the common
00922   // path. However, that isn't the case yet.
00923   void AddCAssignmentStep(QualType T);
00924 
00925   /// \brief Add a string init step.
00926   void AddStringInitStep(QualType T);
00927 
00928   /// \brief Add an Objective-C object conversion step, which is
00929   /// always a no-op.
00930   void AddObjCObjectConversionStep(QualType T);
00931 
00932   /// \brief Add an array initialization step.
00933   void AddArrayInitStep(QualType T);
00934 
00935   /// \brief Add a parenthesized array initialization step.
00936   void AddParenthesizedArrayInitStep(QualType T);
00937 
00938   /// \brief Add a step to pass an object by indirect copy-restore.
00939   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
00940 
00941   /// \brief Add a step to "produce" an Objective-C object (by
00942   /// retaining it).
00943   void AddProduceObjCObjectStep(QualType T);
00944 
00945   /// \brief Add a step to construct a std::initializer_list object from an
00946   /// initializer list.
00947   void AddStdInitializerListConstructionStep(QualType T);
00948 
00949   /// \brief Add steps to unwrap a initializer list for a reference around a
00950   /// single element and rewrap it at the end.
00951   void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
00952 
00953   /// \brief Note that this initialization sequence failed.
00954   void SetFailed(FailureKind Failure) {
00955     SequenceKind = FailedSequence;
00956     this->Failure = Failure;
00957     assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
00958            "Incomplete type failure requires a type!");
00959   }
00960   
00961   /// \brief Note that this initialization sequence failed due to failed
00962   /// overload resolution.
00963   void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
00964   
00965   /// \brief Retrieve a reference to the candidate set when overload
00966   /// resolution fails.
00967   OverloadCandidateSet &getFailedCandidateSet() {
00968     return FailedCandidateSet;
00969   }
00970 
00971   /// \brief Get the overloading result, for when the initialization
00972   /// sequence failed due to a bad overload.
00973   OverloadingResult getFailedOverloadResult() const {
00974     return FailedOverloadResult;
00975   }
00976 
00977   /// \brief Note that this initialization sequence failed due to an
00978   /// incomplete type.
00979   void setIncompleteTypeFailure(QualType IncompleteType) {
00980     FailedIncompleteType = IncompleteType;
00981     SetFailed(FK_Incomplete);
00982   }
00983 
00984   /// \brief Determine why initialization failed.
00985   FailureKind getFailureKind() const {
00986     assert(Failed() && "Not an initialization failure!");
00987     return Failure;
00988   }
00989 
00990   /// \brief Dump a representation of this initialization sequence to 
00991   /// the given stream, for debugging purposes.
00992   void dump(raw_ostream &OS) const;
00993   
00994   /// \brief Dump a representation of this initialization sequence to 
00995   /// standard error, for debugging purposes.
00996   void dump() const;
00997 };
00998   
00999 } // end namespace clang
01000 
01001 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H