Home | History | Annotate | Download | only in AST
      1 //===--- Decl.h - Classes for representing declarations ---------*- 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 defines the Decl subclasses.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_AST_DECL_H
     15 #define LLVM_CLANG_AST_DECL_H
     16 
     17 #include "clang/AST/APValue.h"
     18 #include "clang/AST/DeclBase.h"
     19 #include "clang/AST/Redeclarable.h"
     20 #include "clang/AST/DeclarationName.h"
     21 #include "clang/AST/ExternalASTSource.h"
     22 #include "clang/Basic/Linkage.h"
     23 #include "llvm/ADT/ArrayRef.h"
     24 #include "llvm/ADT/Optional.h"
     25 
     26 namespace clang {
     27 class CXXTemporary;
     28 class Expr;
     29 class FunctionTemplateDecl;
     30 class Stmt;
     31 class CompoundStmt;
     32 class StringLiteral;
     33 class NestedNameSpecifier;
     34 class TemplateParameterList;
     35 class TemplateArgumentList;
     36 struct ASTTemplateArgumentListInfo;
     37 class MemberSpecializationInfo;
     38 class FunctionTemplateSpecializationInfo;
     39 class DependentFunctionTemplateSpecializationInfo;
     40 class TypeLoc;
     41 class UnresolvedSetImpl;
     42 class LabelStmt;
     43 
     44 /// \brief A container of type source information.
     45 ///
     46 /// A client can read the relevant info using TypeLoc wrappers, e.g:
     47 /// @code
     48 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
     49 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
     50 ///   PL->getStarLoc().print(OS, SrcMgr);
     51 /// @endcode
     52 ///
     53 class TypeSourceInfo {
     54   QualType Ty;
     55   // Contains a memory block after the class, used for type source information,
     56   // allocated by ASTContext.
     57   friend class ASTContext;
     58   TypeSourceInfo(QualType ty) : Ty(ty) { }
     59 public:
     60   /// \brief Return the type wrapped by this type source info.
     61   QualType getType() const { return Ty; }
     62 
     63   /// \brief Return the TypeLoc wrapper for the type source info.
     64   TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
     65 };
     66 
     67 /// TranslationUnitDecl - The top declaration context.
     68 class TranslationUnitDecl : public Decl, public DeclContext {
     69   ASTContext &Ctx;
     70 
     71   /// The (most recently entered) anonymous namespace for this
     72   /// translation unit, if one has been created.
     73   NamespaceDecl *AnonymousNamespace;
     74 
     75   explicit TranslationUnitDecl(ASTContext &ctx)
     76     : Decl(TranslationUnit, 0, SourceLocation()),
     77       DeclContext(TranslationUnit),
     78       Ctx(ctx), AnonymousNamespace(0) {}
     79 public:
     80   ASTContext &getASTContext() const { return Ctx; }
     81 
     82   NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
     83   void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
     84 
     85   static TranslationUnitDecl *Create(ASTContext &C);
     86   // Implement isa/cast/dyncast/etc.
     87   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
     88   static bool classof(const TranslationUnitDecl *D) { return true; }
     89   static bool classofKind(Kind K) { return K == TranslationUnit; }
     90   static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
     91     return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
     92   }
     93   static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
     94     return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
     95   }
     96 };
     97 
     98 /// NamedDecl - This represents a decl with a name.  Many decls have names such
     99 /// as ObjCMethodDecl, but not @class, etc.
    100 class NamedDecl : public Decl {
    101   /// Name - The name of this declaration, which is typically a normal
    102   /// identifier but may also be a special kind of name (C++
    103   /// constructor, Objective-C selector, etc.)
    104   DeclarationName Name;
    105 
    106 protected:
    107   NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
    108     : Decl(DK, DC, L), Name(N) { }
    109 
    110 public:
    111   /// getIdentifier - Get the identifier that names this declaration,
    112   /// if there is one. This will return NULL if this declaration has
    113   /// no name (e.g., for an unnamed class) or if the name is a special
    114   /// name (C++ constructor, Objective-C selector, etc.).
    115   IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
    116 
    117   /// getName - Get the name of identifier for this declaration as a StringRef.
    118   /// This requires that the declaration have a name and that it be a simple
    119   /// identifier.
    120   StringRef getName() const {
    121     assert(Name.isIdentifier() && "Name is not a simple identifier");
    122     return getIdentifier() ? getIdentifier()->getName() : "";
    123   }
    124 
    125   /// getNameAsString - Get a human-readable name for the declaration, even if
    126   /// it is one of the special kinds of names (C++ constructor, Objective-C
    127   /// selector, etc).  Creating this name requires expensive string
    128   /// manipulation, so it should be called only when performance doesn't matter.
    129   /// For simple declarations, getNameAsCString() should suffice.
    130   //
    131   // FIXME: This function should be renamed to indicate that it is not just an
    132   // alternate form of getName(), and clients should move as appropriate.
    133   //
    134   // FIXME: Deprecated, move clients to getName().
    135   std::string getNameAsString() const { return Name.getAsString(); }
    136 
    137   void printName(raw_ostream &os) const { return Name.printName(os); }
    138 
    139   /// getDeclName - Get the actual, stored name of the declaration,
    140   /// which may be a special name.
    141   DeclarationName getDeclName() const { return Name; }
    142 
    143   /// \brief Set the name of this declaration.
    144   void setDeclName(DeclarationName N) { Name = N; }
    145 
    146   /// getQualifiedNameAsString - Returns human-readable qualified name for
    147   /// declaration, like A::B::i, for i being member of namespace A::B.
    148   /// If declaration is not member of context which can be named (record,
    149   /// namespace), it will return same result as getNameAsString().
    150   /// Creating this name is expensive, so it should be called only when
    151   /// performance doesn't matter.
    152   std::string getQualifiedNameAsString() const;
    153   std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
    154 
    155   /// getNameForDiagnostic - Appends a human-readable name for this
    156   /// declaration into the given string.
    157   ///
    158   /// This is the method invoked by Sema when displaying a NamedDecl
    159   /// in a diagnostic.  It does not necessarily produce the same
    160   /// result as getNameAsString(); for example, class template
    161   /// specializations are printed with their template arguments.
    162   ///
    163   /// TODO: use an API that doesn't require so many temporary strings
    164   virtual void getNameForDiagnostic(std::string &S,
    165                                     const PrintingPolicy &Policy,
    166                                     bool Qualified) const {
    167     if (Qualified)
    168       S += getQualifiedNameAsString(Policy);
    169     else
    170       S += getNameAsString();
    171   }
    172 
    173   /// declarationReplaces - Determine whether this declaration, if
    174   /// known to be well-formed within its context, will replace the
    175   /// declaration OldD if introduced into scope. A declaration will
    176   /// replace another declaration if, for example, it is a
    177   /// redeclaration of the same variable or function, but not if it is
    178   /// a declaration of a different kind (function vs. class) or an
    179   /// overloaded function.
    180   bool declarationReplaces(NamedDecl *OldD) const;
    181 
    182   /// \brief Determine whether this declaration has linkage.
    183   bool hasLinkage() const;
    184 
    185   /// \brief Whether this declaration was marked as being private to the
    186   /// module in which it was defined.
    187   bool isModulePrivate() const { return ModulePrivate; }
    188 
    189   /// \brief Specify whether this declaration was marked as being private
    190   /// to the module in which it was defined.
    191   void setModulePrivate(bool MP = true) {
    192     ModulePrivate = MP;
    193   }
    194 
    195   /// \brief Determine whether this declaration is a C++ class member.
    196   bool isCXXClassMember() const {
    197     const DeclContext *DC = getDeclContext();
    198 
    199     // C++0x [class.mem]p1:
    200     //   The enumerators of an unscoped enumeration defined in
    201     //   the class are members of the class.
    202     // FIXME: support C++0x scoped enumerations.
    203     if (isa<EnumDecl>(DC))
    204       DC = DC->getParent();
    205 
    206     return DC->isRecord();
    207   }
    208 
    209   /// \brief Given that this declaration is a C++ class member,
    210   /// determine whether it's an instance member of its class.
    211   bool isCXXInstanceMember() const;
    212 
    213   class LinkageInfo {
    214     Linkage linkage_;
    215     Visibility visibility_;
    216     bool explicit_;
    217 
    218   public:
    219     LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
    220                     explicit_(false) {}
    221     LinkageInfo(Linkage L, Visibility V, bool E)
    222       : linkage_(L), visibility_(V), explicit_(E) {}
    223 
    224     static LinkageInfo external() {
    225       return LinkageInfo();
    226     }
    227     static LinkageInfo internal() {
    228       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
    229     }
    230     static LinkageInfo uniqueExternal() {
    231       return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
    232     }
    233     static LinkageInfo none() {
    234       return LinkageInfo(NoLinkage, DefaultVisibility, false);
    235     }
    236 
    237     Linkage linkage() const { return linkage_; }
    238     Visibility visibility() const { return visibility_; }
    239     bool visibilityExplicit() const { return explicit_; }
    240 
    241     void setLinkage(Linkage L) { linkage_ = L; }
    242     void setVisibility(Visibility V) { visibility_ = V; }
    243     void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
    244     void setVisibility(LinkageInfo Other) {
    245       setVisibility(Other.visibility(), Other.visibilityExplicit());
    246     }
    247 
    248     void mergeLinkage(Linkage L) {
    249       setLinkage(minLinkage(linkage(), L));
    250     }
    251     void mergeLinkage(LinkageInfo Other) {
    252       setLinkage(minLinkage(linkage(), Other.linkage()));
    253     }
    254 
    255     void mergeVisibility(Visibility V) {
    256       setVisibility(minVisibility(visibility(), V));
    257     }
    258     void mergeVisibility(Visibility V, bool E) {
    259       setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
    260     }
    261     void mergeVisibility(LinkageInfo Other) {
    262       mergeVisibility(Other.visibility(), Other.visibilityExplicit());
    263     }
    264 
    265     void merge(LinkageInfo Other) {
    266       mergeLinkage(Other);
    267       mergeVisibility(Other);
    268     }
    269     void merge(std::pair<Linkage,Visibility> LV) {
    270       mergeLinkage(LV.first);
    271       mergeVisibility(LV.second);
    272     }
    273 
    274     friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
    275       L.merge(R);
    276       return L;
    277     }
    278   };
    279 
    280   /// \brief Determine what kind of linkage this entity has.
    281   Linkage getLinkage() const;
    282 
    283   /// \brief Determines the visibility of this entity.
    284   Visibility getVisibility() const { return getLinkageAndVisibility().visibility(); }
    285 
    286   /// \brief Determines the linkage and visibility of this entity.
    287   LinkageInfo getLinkageAndVisibility() const;
    288 
    289   /// \brief If visibility was explicitly specified for this
    290   /// declaration, return that visibility.
    291   llvm::Optional<Visibility> getExplicitVisibility() const;
    292 
    293   /// \brief Clear the linkage cache in response to a change
    294   /// to the declaration.
    295   void ClearLinkageCache();
    296 
    297   /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
    298   /// the underlying named decl.
    299   NamedDecl *getUnderlyingDecl();
    300   const NamedDecl *getUnderlyingDecl() const {
    301     return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
    302   }
    303 
    304   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    305   static bool classof(const NamedDecl *D) { return true; }
    306   static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
    307 };
    308 
    309 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
    310   ND.printName(OS);
    311   return OS;
    312 }
    313 
    314 /// LabelDecl - Represents the declaration of a label.  Labels also have a
    315 /// corresponding LabelStmt, which indicates the position that the label was
    316 /// defined at.  For normal labels, the location of the decl is the same as the
    317 /// location of the statement.  For GNU local labels (__label__), the decl
    318 /// location is where the __label__ is.
    319 class LabelDecl : public NamedDecl {
    320   LabelStmt *TheStmt;
    321   /// LocStart - For normal labels, this is the same as the main declaration
    322   /// label, i.e., the location of the identifier; for GNU local labels,
    323   /// this is the location of the __label__ keyword.
    324   SourceLocation LocStart;
    325 
    326   LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
    327             LabelStmt *S, SourceLocation StartL)
    328     : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
    329 
    330 public:
    331   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
    332                            SourceLocation IdentL, IdentifierInfo *II);
    333   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
    334                            SourceLocation IdentL, IdentifierInfo *II,
    335                            SourceLocation GnuLabelL);
    336 
    337   LabelStmt *getStmt() const { return TheStmt; }
    338   void setStmt(LabelStmt *T) { TheStmt = T; }
    339 
    340   bool isGnuLocal() const { return LocStart != getLocation(); }
    341   void setLocStart(SourceLocation L) { LocStart = L; }
    342 
    343   SourceRange getSourceRange() const {
    344     return SourceRange(LocStart, getLocation());
    345   }
    346 
    347   // Implement isa/cast/dyncast/etc.
    348   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    349   static bool classof(const LabelDecl *D) { return true; }
    350   static bool classofKind(Kind K) { return K == Label; }
    351 };
    352 
    353 /// NamespaceDecl - Represent a C++ namespace.
    354 class NamespaceDecl : public NamedDecl, public DeclContext {
    355   bool IsInline : 1;
    356 
    357   /// LocStart - The starting location of the source range, pointing
    358   /// to either the namespace or the inline keyword.
    359   SourceLocation LocStart;
    360   /// RBraceLoc - The ending location of the source range.
    361   SourceLocation RBraceLoc;
    362 
    363   // For extended namespace definitions:
    364   //
    365   // namespace A { int x; }
    366   // namespace A { int y; }
    367   //
    368   // there will be one NamespaceDecl for each declaration.
    369   // NextNamespace points to the next extended declaration.
    370   // OrigNamespace points to the original namespace declaration.
    371   // OrigNamespace of the first namespace decl points to its anonymous namespace
    372   LazyDeclPtr NextNamespace;
    373 
    374   /// \brief A pointer to either the original namespace definition for
    375   /// this namespace (if the boolean value is false) or the anonymous
    376   /// namespace that lives just inside this namespace (if the boolean
    377   /// value is true).
    378   ///
    379   /// We can combine these two notions because the anonymous namespace
    380   /// must only be stored in one of the namespace declarations (so all
    381   /// of the namespace declarations can find it). We therefore choose
    382   /// the original namespace declaration, since all of the namespace
    383   /// declarations have a link directly to it; the original namespace
    384   /// declaration itself only needs to know that it is the original
    385   /// namespace declaration (which the boolean indicates).
    386   llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace;
    387 
    388   NamespaceDecl(DeclContext *DC, SourceLocation StartLoc,
    389                 SourceLocation IdLoc, IdentifierInfo *Id)
    390     : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
    391       IsInline(false), LocStart(StartLoc), RBraceLoc(),
    392       NextNamespace(), OrigOrAnonNamespace(0, true) { }
    393 
    394 public:
    395   static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
    396                                SourceLocation StartLoc,
    397                                SourceLocation IdLoc, IdentifierInfo *Id);
    398 
    399   /// \brief Returns true if this is an anonymous namespace declaration.
    400   ///
    401   /// For example:
    402   /// \code
    403   ///   namespace {
    404   ///     ...
    405   ///   };
    406   /// \endcode
    407   /// q.v. C++ [namespace.unnamed]
    408   bool isAnonymousNamespace() const {
    409     return !getIdentifier();
    410   }
    411 
    412   /// \brief Returns true if this is an inline namespace declaration.
    413   bool isInline() const {
    414     return IsInline;
    415   }
    416 
    417   /// \brief Set whether this is an inline namespace declaration.
    418   void setInline(bool Inline) {
    419     IsInline = Inline;
    420   }
    421 
    422   /// \brief Return the next extended namespace declaration or null if there
    423   /// is none.
    424   NamespaceDecl *getNextNamespace();
    425   const NamespaceDecl *getNextNamespace() const {
    426     return const_cast<NamespaceDecl *>(this)->getNextNamespace();
    427   }
    428 
    429   /// \brief Set the next extended namespace declaration.
    430   void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
    431 
    432   /// \brief Get the original (first) namespace declaration.
    433   NamespaceDecl *getOriginalNamespace() const {
    434     if (OrigOrAnonNamespace.getInt())
    435       return const_cast<NamespaceDecl *>(this);
    436 
    437     return OrigOrAnonNamespace.getPointer();
    438   }
    439 
    440   /// \brief Return true if this declaration is an original (first) declaration
    441   /// of the namespace. This is false for non-original (subsequent) namespace
    442   /// declarations and anonymous namespaces.
    443   bool isOriginalNamespace() const {
    444     return getOriginalNamespace() == this;
    445   }
    446 
    447   /// \brief Set the original (first) namespace declaration.
    448   void setOriginalNamespace(NamespaceDecl *ND) {
    449     if (ND != this) {
    450       OrigOrAnonNamespace.setPointer(ND);
    451       OrigOrAnonNamespace.setInt(false);
    452     }
    453   }
    454 
    455   NamespaceDecl *getAnonymousNamespace() const {
    456     return getOriginalNamespace()->OrigOrAnonNamespace.getPointer();
    457   }
    458 
    459   void setAnonymousNamespace(NamespaceDecl *D) {
    460     assert(!D || D->isAnonymousNamespace());
    461     assert(!D || D->getParent()->getRedeclContext() == this);
    462     getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D);
    463   }
    464 
    465   virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(); }
    466   const NamespaceDecl *getCanonicalDecl() const {
    467     return getOriginalNamespace();
    468   }
    469 
    470   virtual SourceRange getSourceRange() const {
    471     return SourceRange(LocStart, RBraceLoc);
    472   }
    473 
    474   SourceLocation getLocStart() const { return LocStart; }
    475   SourceLocation getRBraceLoc() const { return RBraceLoc; }
    476   void setLocStart(SourceLocation L) { LocStart = L; }
    477   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
    478 
    479   // Implement isa/cast/dyncast/etc.
    480   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    481   static bool classof(const NamespaceDecl *D) { return true; }
    482   static bool classofKind(Kind K) { return K == Namespace; }
    483   static DeclContext *castToDeclContext(const NamespaceDecl *D) {
    484     return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
    485   }
    486   static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
    487     return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
    488   }
    489 
    490   friend class ASTDeclReader;
    491   friend class ASTDeclWriter;
    492 };
    493 
    494 /// ValueDecl - Represent the declaration of a variable (in which case it is
    495 /// an lvalue) a function (in which case it is a function designator) or
    496 /// an enum constant.
    497 class ValueDecl : public NamedDecl {
    498   QualType DeclType;
    499 
    500 protected:
    501   ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
    502             DeclarationName N, QualType T)
    503     : NamedDecl(DK, DC, L, N), DeclType(T) {}
    504 public:
    505   QualType getType() const { return DeclType; }
    506   void setType(QualType newType) { DeclType = newType; }
    507 
    508   // Implement isa/cast/dyncast/etc.
    509   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    510   static bool classof(const ValueDecl *D) { return true; }
    511   static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
    512 };
    513 
    514 /// QualifierInfo - A struct with extended info about a syntactic
    515 /// name qualifier, to be used for the case of out-of-line declarations.
    516 struct QualifierInfo {
    517   NestedNameSpecifierLoc QualifierLoc;
    518 
    519   /// NumTemplParamLists - The number of "outer" template parameter lists.
    520   /// The count includes all of the template parameter lists that were matched
    521   /// against the template-ids occurring into the NNS and possibly (in the
    522   /// case of an explicit specialization) a final "template <>".
    523   unsigned NumTemplParamLists;
    524 
    525   /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
    526   /// containing pointers to the "outer" template parameter lists.
    527   /// It includes all of the template parameter lists that were matched
    528   /// against the template-ids occurring into the NNS and possibly (in the
    529   /// case of an explicit specialization) a final "template <>".
    530   TemplateParameterList** TemplParamLists;
    531 
    532   /// Default constructor.
    533   QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
    534 
    535   /// setTemplateParameterListsInfo - Sets info about "outer" template
    536   /// parameter lists.
    537   void setTemplateParameterListsInfo(ASTContext &Context,
    538                                      unsigned NumTPLists,
    539                                      TemplateParameterList **TPLists);
    540 
    541 private:
    542   // Copy constructor and copy assignment are disabled.
    543   QualifierInfo(const QualifierInfo&);
    544   QualifierInfo& operator=(const QualifierInfo&);
    545 };
    546 
    547 /// \brief Represents a ValueDecl that came out of a declarator.
    548 /// Contains type source information through TypeSourceInfo.
    549 class DeclaratorDecl : public ValueDecl {
    550   // A struct representing both a TInfo and a syntactic qualifier,
    551   // to be used for the (uncommon) case of out-of-line declarations.
    552   struct ExtInfo : public QualifierInfo {
    553     TypeSourceInfo *TInfo;
    554   };
    555 
    556   llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
    557 
    558   /// InnerLocStart - The start of the source range for this declaration,
    559   /// ignoring outer template declarations.
    560   SourceLocation InnerLocStart;
    561 
    562   bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
    563   ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
    564   const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
    565 
    566 protected:
    567   DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
    568                  DeclarationName N, QualType T, TypeSourceInfo *TInfo,
    569                  SourceLocation StartL)
    570     : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
    571   }
    572 
    573 public:
    574   TypeSourceInfo *getTypeSourceInfo() const {
    575     return hasExtInfo()
    576       ? getExtInfo()->TInfo
    577       : DeclInfo.get<TypeSourceInfo*>();
    578   }
    579   void setTypeSourceInfo(TypeSourceInfo *TI) {
    580     if (hasExtInfo())
    581       getExtInfo()->TInfo = TI;
    582     else
    583       DeclInfo = TI;
    584   }
    585 
    586   /// getInnerLocStart - Return SourceLocation representing start of source
    587   /// range ignoring outer template declarations.
    588   SourceLocation getInnerLocStart() const { return InnerLocStart; }
    589   void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
    590 
    591   /// getOuterLocStart - Return SourceLocation representing start of source
    592   /// range taking into account any outer template declarations.
    593   SourceLocation getOuterLocStart() const;
    594 
    595   virtual SourceRange getSourceRange() const;
    596 
    597   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
    598   /// declaration, if it was present in the source.
    599   NestedNameSpecifier *getQualifier() const {
    600     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
    601                         : 0;
    602   }
    603 
    604   /// \brief Retrieve the nested-name-specifier (with source-location
    605   /// information) that qualifies the name of this declaration, if it was
    606   /// present in the source.
    607   NestedNameSpecifierLoc getQualifierLoc() const {
    608     return hasExtInfo() ? getExtInfo()->QualifierLoc
    609                         : NestedNameSpecifierLoc();
    610   }
    611 
    612   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
    613 
    614   unsigned getNumTemplateParameterLists() const {
    615     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
    616   }
    617   TemplateParameterList *getTemplateParameterList(unsigned index) const {
    618     assert(index < getNumTemplateParameterLists());
    619     return getExtInfo()->TemplParamLists[index];
    620   }
    621   void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
    622                                      TemplateParameterList **TPLists);
    623 
    624   SourceLocation getTypeSpecStartLoc() const;
    625 
    626   // Implement isa/cast/dyncast/etc.
    627   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    628   static bool classof(const DeclaratorDecl *D) { return true; }
    629   static bool classofKind(Kind K) {
    630     return K >= firstDeclarator && K <= lastDeclarator;
    631   }
    632 
    633   friend class ASTDeclReader;
    634   friend class ASTDeclWriter;
    635 };
    636 
    637 /// \brief Structure used to store a statement, the constant value to
    638 /// which it was evaluated (if any), and whether or not the statement
    639 /// is an integral constant expression (if known).
    640 struct EvaluatedStmt {
    641   EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
    642                     CheckingICE(false), IsICE(false) { }
    643 
    644   /// \brief Whether this statement was already evaluated.
    645   bool WasEvaluated : 1;
    646 
    647   /// \brief Whether this statement is being evaluated.
    648   bool IsEvaluating : 1;
    649 
    650   /// \brief Whether we already checked whether this statement was an
    651   /// integral constant expression.
    652   bool CheckedICE : 1;
    653 
    654   /// \brief Whether we are checking whether this statement is an
    655   /// integral constant expression.
    656   bool CheckingICE : 1;
    657 
    658   /// \brief Whether this statement is an integral constant
    659   /// expression. Only valid if CheckedICE is true.
    660   bool IsICE : 1;
    661 
    662   Stmt *Value;
    663   APValue Evaluated;
    664 };
    665 
    666 /// VarDecl - An instance of this class is created to represent a variable
    667 /// declaration or definition.
    668 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
    669 public:
    670   typedef clang::StorageClass StorageClass;
    671 
    672   /// getStorageClassSpecifierString - Return the string used to
    673   /// specify the storage class \arg SC.
    674   ///
    675   /// It is illegal to call this function with SC == None.
    676   static const char *getStorageClassSpecifierString(StorageClass SC);
    677 
    678 protected:
    679   /// \brief Placeholder type used in Init to denote an unparsed C++ default
    680   /// argument.
    681   struct UnparsedDefaultArgument;
    682 
    683   /// \brief Placeholder type used in Init to denote an uninstantiated C++
    684   /// default argument.
    685   struct UninstantiatedDefaultArgument;
    686 
    687   typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
    688                               UnparsedDefaultArgument *,
    689                               UninstantiatedDefaultArgument *> InitType;
    690 
    691   /// \brief The initializer for this variable or, for a ParmVarDecl, the
    692   /// C++ default argument.
    693   mutable InitType Init;
    694 
    695 private:
    696   class VarDeclBitfields {
    697     friend class VarDecl;
    698     friend class ASTDeclReader;
    699 
    700     unsigned SClass : 3;
    701     unsigned SClassAsWritten : 3;
    702     unsigned ThreadSpecified : 1;
    703     unsigned HasCXXDirectInit : 1;
    704 
    705     /// \brief Whether this variable is the exception variable in a C++ catch
    706     /// or an Objective-C @catch statement.
    707     unsigned ExceptionVar : 1;
    708 
    709     /// \brief Whether this local variable could be allocated in the return
    710     /// slot of its function, enabling the named return value optimization (NRVO).
    711     unsigned NRVOVariable : 1;
    712 
    713     /// \brief Whether this variable is the for-range-declaration in a C++0x
    714     /// for-range statement.
    715     unsigned CXXForRangeDecl : 1;
    716 
    717     /// \brief Whether this variable is an ARC pseudo-__strong
    718     /// variable;  see isARCPseudoStrong() for details.
    719     unsigned ARCPseudoStrong : 1;
    720 
    721     /// \brief Whether this variable is (C++0x) constexpr.
    722     unsigned IsConstexpr : 1;
    723   };
    724   enum { NumVarDeclBits = 13 };
    725 
    726   friend class ASTDeclReader;
    727   friend class StmtIteratorBase;
    728 
    729 protected:
    730   enum { NumParameterIndexBits = 8 };
    731 
    732   class ParmVarDeclBitfields {
    733     friend class ParmVarDecl;
    734     friend class ASTDeclReader;
    735 
    736     unsigned : NumVarDeclBits;
    737 
    738     /// Whether this parameter inherits a default argument from a
    739     /// prior declaration.
    740     unsigned HasInheritedDefaultArg : 1;
    741 
    742     /// Whether this parameter undergoes K&R argument promotion.
    743     unsigned IsKNRPromoted : 1;
    744 
    745     /// Whether this parameter is an ObjC method parameter or not.
    746     unsigned IsObjCMethodParam : 1;
    747 
    748     /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
    749     /// Otherwise, the number of function parameter scopes enclosing
    750     /// the function parameter scope in which this parameter was
    751     /// declared.
    752     unsigned ScopeDepthOrObjCQuals : 8;
    753 
    754     /// The number of parameters preceding this parameter in the
    755     /// function parameter scope in which it was declared.
    756     unsigned ParameterIndex : NumParameterIndexBits;
    757   };
    758 
    759   union {
    760     unsigned AllBits;
    761     VarDeclBitfields VarDeclBits;
    762     ParmVarDeclBitfields ParmVarDeclBits;
    763   };
    764 
    765   VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
    766           SourceLocation IdLoc, IdentifierInfo *Id,
    767           QualType T, TypeSourceInfo *TInfo, StorageClass SC,
    768           StorageClass SCAsWritten)
    769     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
    770     assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
    771     assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
    772     AllBits = 0;
    773     VarDeclBits.SClass = SC;
    774     VarDeclBits.SClassAsWritten = SCAsWritten;
    775     // Everything else is implicitly initialized to false.
    776   }
    777 
    778   typedef Redeclarable<VarDecl> redeclarable_base;
    779   virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
    780 
    781 public:
    782   typedef redeclarable_base::redecl_iterator redecl_iterator;
    783   redecl_iterator redecls_begin() const {
    784     return redeclarable_base::redecls_begin();
    785   }
    786   redecl_iterator redecls_end() const {
    787     return redeclarable_base::redecls_end();
    788   }
    789 
    790   static VarDecl *Create(ASTContext &C, DeclContext *DC,
    791                          SourceLocation StartLoc, SourceLocation IdLoc,
    792                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
    793                          StorageClass S, StorageClass SCAsWritten);
    794 
    795   virtual SourceRange getSourceRange() const;
    796 
    797   StorageClass getStorageClass() const {
    798     return (StorageClass) VarDeclBits.SClass;
    799   }
    800   StorageClass getStorageClassAsWritten() const {
    801     return (StorageClass) VarDeclBits.SClassAsWritten;
    802   }
    803   void setStorageClass(StorageClass SC);
    804   void setStorageClassAsWritten(StorageClass SC) {
    805     assert(isLegalForVariable(SC));
    806     VarDeclBits.SClassAsWritten = SC;
    807   }
    808 
    809   void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
    810   bool isThreadSpecified() const {
    811     return VarDeclBits.ThreadSpecified;
    812   }
    813 
    814   /// hasLocalStorage - Returns true if a variable with function scope
    815   ///  is a non-static local variable.
    816   bool hasLocalStorage() const {
    817     if (getStorageClass() == SC_None)
    818       return !isFileVarDecl();
    819 
    820     // Return true for:  Auto, Register.
    821     // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
    822 
    823     return getStorageClass() >= SC_Auto;
    824   }
    825 
    826   /// isStaticLocal - Returns true if a variable with function scope is a
    827   /// static local variable.
    828   bool isStaticLocal() const {
    829     return getStorageClass() == SC_Static && !isFileVarDecl();
    830   }
    831 
    832   /// hasExternStorage - Returns true if a variable has extern or
    833   /// __private_extern__ storage.
    834   bool hasExternalStorage() const {
    835     return getStorageClass() == SC_Extern ||
    836            getStorageClass() == SC_PrivateExtern;
    837   }
    838 
    839   /// hasGlobalStorage - Returns true for all variables that do not
    840   ///  have local storage.  This includs all global variables as well
    841   ///  as static variables declared within a function.
    842   bool hasGlobalStorage() const { return !hasLocalStorage(); }
    843 
    844   /// \brief Determines whether this variable is a variable with
    845   /// external, C linkage.
    846   bool isExternC() const;
    847 
    848   /// isLocalVarDecl - Returns true for local variable declarations
    849   /// other than parameters.  Note that this includes static variables
    850   /// inside of functions. It also includes variables inside blocks.
    851   ///
    852   ///   void foo() { int x; static int y; extern int z; }
    853   ///
    854   bool isLocalVarDecl() const {
    855     if (getKind() != Decl::Var)
    856       return false;
    857     if (const DeclContext *DC = getDeclContext())
    858       return DC->getRedeclContext()->isFunctionOrMethod();
    859     return false;
    860   }
    861 
    862   /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
    863   /// excludes variables declared in blocks.
    864   bool isFunctionOrMethodVarDecl() const {
    865     if (getKind() != Decl::Var)
    866       return false;
    867     const DeclContext *DC = getDeclContext()->getRedeclContext();
    868     return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
    869   }
    870 
    871   /// \brief Determines whether this is a static data member.
    872   ///
    873   /// This will only be true in C++, and applies to, e.g., the
    874   /// variable 'x' in:
    875   /// \code
    876   /// struct S {
    877   ///   static int x;
    878   /// };
    879   /// \endcode
    880   bool isStaticDataMember() const {
    881     // If it wasn't static, it would be a FieldDecl.
    882     return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
    883   }
    884 
    885   virtual VarDecl *getCanonicalDecl();
    886   const VarDecl *getCanonicalDecl() const {
    887     return const_cast<VarDecl*>(this)->getCanonicalDecl();
    888   }
    889 
    890   enum DefinitionKind {
    891     DeclarationOnly,      ///< This declaration is only a declaration.
    892     TentativeDefinition,  ///< This declaration is a tentative definition.
    893     Definition            ///< This declaration is definitely a definition.
    894   };
    895 
    896   /// \brief Check whether this declaration is a definition. If this could be
    897   /// a tentative definition (in C), don't check whether there's an overriding
    898   /// definition.
    899   DefinitionKind isThisDeclarationADefinition() const;
    900 
    901   /// \brief Check whether this variable is defined in this
    902   /// translation unit.
    903   DefinitionKind hasDefinition() const;
    904 
    905   /// \brief Get the tentative definition that acts as the real definition in
    906   /// a TU. Returns null if there is a proper definition available.
    907   VarDecl *getActingDefinition();
    908   const VarDecl *getActingDefinition() const {
    909     return const_cast<VarDecl*>(this)->getActingDefinition();
    910   }
    911 
    912   /// \brief Determine whether this is a tentative definition of a
    913   /// variable in C.
    914   bool isTentativeDefinitionNow() const;
    915 
    916   /// \brief Get the real (not just tentative) definition for this declaration.
    917   VarDecl *getDefinition();
    918   const VarDecl *getDefinition() const {
    919     return const_cast<VarDecl*>(this)->getDefinition();
    920   }
    921 
    922   /// \brief Determine whether this is or was instantiated from an out-of-line
    923   /// definition of a static data member.
    924   virtual bool isOutOfLine() const;
    925 
    926   /// \brief If this is a static data member, find its out-of-line definition.
    927   VarDecl *getOutOfLineDefinition();
    928 
    929   /// isFileVarDecl - Returns true for file scoped variable declaration.
    930   bool isFileVarDecl() const {
    931     if (getKind() != Decl::Var)
    932       return false;
    933 
    934     if (getDeclContext()->getRedeclContext()->isFileContext())
    935       return true;
    936 
    937     if (isStaticDataMember())
    938       return true;
    939 
    940     return false;
    941   }
    942 
    943   /// getAnyInitializer - Get the initializer for this variable, no matter which
    944   /// declaration it is attached to.
    945   const Expr *getAnyInitializer() const {
    946     const VarDecl *D;
    947     return getAnyInitializer(D);
    948   }
    949 
    950   /// getAnyInitializer - Get the initializer for this variable, no matter which
    951   /// declaration it is attached to. Also get that declaration.
    952   const Expr *getAnyInitializer(const VarDecl *&D) const;
    953 
    954   bool hasInit() const {
    955     return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
    956   }
    957   const Expr *getInit() const {
    958     if (Init.isNull())
    959       return 0;
    960 
    961     const Stmt *S = Init.dyn_cast<Stmt *>();
    962     if (!S) {
    963       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
    964         S = ES->Value;
    965     }
    966     return (const Expr*) S;
    967   }
    968   Expr *getInit() {
    969     if (Init.isNull())
    970       return 0;
    971 
    972     Stmt *S = Init.dyn_cast<Stmt *>();
    973     if (!S) {
    974       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
    975         S = ES->Value;
    976     }
    977 
    978     return (Expr*) S;
    979   }
    980 
    981   /// \brief Retrieve the address of the initializer expression.
    982   Stmt **getInitAddress() {
    983     if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
    984       return &ES->Value;
    985 
    986     // This union hack tip-toes around strict-aliasing rules.
    987     union {
    988       InitType *InitPtr;
    989       Stmt **StmtPtr;
    990     };
    991 
    992     InitPtr = &Init;
    993     return StmtPtr;
    994   }
    995 
    996   void setInit(Expr *I);
    997 
    998   /// \brief Determine whether this variable is a reference that
    999   /// extends the lifetime of its temporary initializer.
   1000   ///
   1001   /// A reference extends the lifetime of its temporary initializer if
   1002   /// it's initializer is an rvalue that would normally go out of scope
   1003   /// at the end of the initializer (a full expression). In such cases,
   1004   /// the reference itself takes ownership of the temporary, which will
   1005   /// be destroyed when the reference goes out of scope. For example:
   1006   ///
   1007   /// \code
   1008   /// const int &r = 1.0; // creates a temporary of type 'int'
   1009   /// \endcode
   1010   bool extendsLifetimeOfTemporary() const;
   1011 
   1012   EvaluatedStmt *EnsureEvaluatedStmt() const {
   1013     EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
   1014     if (!Eval) {
   1015       Stmt *S = Init.get<Stmt *>();
   1016       Eval = new (getASTContext()) EvaluatedStmt;
   1017       Eval->Value = S;
   1018       Init = Eval;
   1019     }
   1020     return Eval;
   1021   }
   1022 
   1023   /// \brief Check whether we are in the process of checking whether the
   1024   /// initializer can be evaluated.
   1025   bool isEvaluatingValue() const {
   1026     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
   1027       return Eval->IsEvaluating;
   1028 
   1029     return false;
   1030   }
   1031 
   1032   /// \brief Note that we now are checking whether the initializer can be
   1033   /// evaluated.
   1034   void setEvaluatingValue() const {
   1035     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
   1036     Eval->IsEvaluating = true;
   1037   }
   1038 
   1039   /// \brief Note that constant evaluation has computed the given
   1040   /// value for this variable's initializer.
   1041   void setEvaluatedValue(const APValue &Value) const {
   1042     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
   1043     Eval->IsEvaluating = false;
   1044     Eval->WasEvaluated = true;
   1045     Eval->Evaluated = Value;
   1046   }
   1047 
   1048   /// \brief Return the already-evaluated value of this variable's
   1049   /// initializer, or NULL if the value is not yet known. Returns pointer
   1050   /// to untyped APValue if the value could not be evaluated.
   1051   APValue *getEvaluatedValue() const {
   1052     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
   1053       if (Eval->WasEvaluated)
   1054         return &Eval->Evaluated;
   1055 
   1056     return 0;
   1057   }
   1058 
   1059   /// \brief Determines whether it is already known whether the
   1060   /// initializer is an integral constant expression or not.
   1061   bool isInitKnownICE() const {
   1062     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
   1063       return Eval->CheckedICE;
   1064 
   1065     return false;
   1066   }
   1067 
   1068   /// \brief Determines whether the initializer is an integral
   1069   /// constant expression.
   1070   ///
   1071   /// \pre isInitKnownICE()
   1072   bool isInitICE() const {
   1073     assert(isInitKnownICE() &&
   1074            "Check whether we already know that the initializer is an ICE");
   1075     return Init.get<EvaluatedStmt *>()->IsICE;
   1076   }
   1077 
   1078   /// \brief Check whether we are in the process of checking the initializer
   1079   /// is an integral constant expression.
   1080   bool isCheckingICE() const {
   1081     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
   1082       return Eval->CheckingICE;
   1083 
   1084     return false;
   1085   }
   1086 
   1087   /// \brief Note that we now are checking whether the initializer is an
   1088   /// integral constant expression.
   1089   void setCheckingICE() const {
   1090     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
   1091     Eval->CheckingICE = true;
   1092   }
   1093 
   1094   /// \brief Note that we now know whether the initializer is an
   1095   /// integral constant expression.
   1096   void setInitKnownICE(bool IsICE) const {
   1097     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
   1098     Eval->CheckingICE = false;
   1099     Eval->CheckedICE = true;
   1100     Eval->IsICE = IsICE;
   1101   }
   1102 
   1103   void setCXXDirectInitializer(bool T) { VarDeclBits.HasCXXDirectInit = T; }
   1104 
   1105   /// hasCXXDirectInitializer - If true, the initializer was a direct
   1106   /// initializer, e.g: "int x(1);". The Init expression will be the expression
   1107   /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
   1108   /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
   1109   /// by checking hasCXXDirectInitializer.
   1110   ///
   1111   bool hasCXXDirectInitializer() const {
   1112     return VarDeclBits.HasCXXDirectInit;
   1113   }
   1114 
   1115   /// \brief Determine whether this variable is the exception variable in a
   1116   /// C++ catch statememt or an Objective-C @catch statement.
   1117   bool isExceptionVariable() const {
   1118     return VarDeclBits.ExceptionVar;
   1119   }
   1120   void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
   1121 
   1122   /// \brief Determine whether this local variable can be used with the named
   1123   /// return value optimization (NRVO).
   1124   ///
   1125   /// The named return value optimization (NRVO) works by marking certain
   1126   /// non-volatile local variables of class type as NRVO objects. These
   1127   /// locals can be allocated within the return slot of their containing
   1128   /// function, in which case there is no need to copy the object to the
   1129   /// return slot when returning from the function. Within the function body,
   1130   /// each return that returns the NRVO object will have this variable as its
   1131   /// NRVO candidate.
   1132   bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
   1133   void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
   1134 
   1135   /// \brief Determine whether this variable is the for-range-declaration in
   1136   /// a C++0x for-range statement.
   1137   bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
   1138   void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
   1139 
   1140   /// \brief Determine whether this variable is an ARC pseudo-__strong
   1141   /// variable.  A pseudo-__strong variable has a __strong-qualified
   1142   /// type but does not actually retain the object written into it.
   1143   /// Generally such variables are also 'const' for safety.
   1144   bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
   1145   void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
   1146 
   1147   /// Whether this variable is (C++0x) constexpr.
   1148   bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
   1149   void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
   1150 
   1151   /// \brief If this variable is an instantiated static data member of a
   1152   /// class template specialization, returns the templated static data member
   1153   /// from which it was instantiated.
   1154   VarDecl *getInstantiatedFromStaticDataMember() const;
   1155 
   1156   /// \brief If this variable is a static data member, determine what kind of
   1157   /// template specialization or instantiation this is.
   1158   TemplateSpecializationKind getTemplateSpecializationKind() const;
   1159 
   1160   /// \brief If this variable is an instantiation of a static data member of a
   1161   /// class template specialization, retrieves the member specialization
   1162   /// information.
   1163   MemberSpecializationInfo *getMemberSpecializationInfo() const;
   1164 
   1165   /// \brief For a static data member that was instantiated from a static
   1166   /// data member of a class template, set the template specialiation kind.
   1167   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   1168                         SourceLocation PointOfInstantiation = SourceLocation());
   1169 
   1170   // Implement isa/cast/dyncast/etc.
   1171   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1172   static bool classof(const VarDecl *D) { return true; }
   1173   static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
   1174 };
   1175 
   1176 class ImplicitParamDecl : public VarDecl {
   1177 public:
   1178   static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
   1179                                    SourceLocation IdLoc, IdentifierInfo *Id,
   1180                                    QualType T);
   1181 
   1182   ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
   1183                     IdentifierInfo *Id, QualType Type)
   1184     : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
   1185               /*tinfo*/ 0, SC_None, SC_None) {
   1186     setImplicit();
   1187   }
   1188 
   1189   // Implement isa/cast/dyncast/etc.
   1190   static bool classof(const ImplicitParamDecl *D) { return true; }
   1191   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1192   static bool classofKind(Kind K) { return K == ImplicitParam; }
   1193 };
   1194 
   1195 /// ParmVarDecl - Represents a parameter to a function.
   1196 class ParmVarDecl : public VarDecl {
   1197 public:
   1198   enum { MaxFunctionScopeDepth = 255 };
   1199   enum { MaxFunctionScopeIndex = 255 };
   1200 
   1201 protected:
   1202   ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
   1203               SourceLocation IdLoc, IdentifierInfo *Id,
   1204               QualType T, TypeSourceInfo *TInfo,
   1205               StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
   1206     : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
   1207     assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
   1208     assert(ParmVarDeclBits.IsKNRPromoted == false);
   1209     assert(ParmVarDeclBits.IsObjCMethodParam == false);
   1210     setDefaultArg(DefArg);
   1211   }
   1212 
   1213 public:
   1214   static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
   1215                              SourceLocation StartLoc,
   1216                              SourceLocation IdLoc, IdentifierInfo *Id,
   1217                              QualType T, TypeSourceInfo *TInfo,
   1218                              StorageClass S, StorageClass SCAsWritten,
   1219                              Expr *DefArg);
   1220 
   1221   virtual SourceRange getSourceRange() const;
   1222 
   1223   void setObjCMethodScopeInfo(unsigned parameterIndex) {
   1224     ParmVarDeclBits.IsObjCMethodParam = true;
   1225     setParameterIndex(parameterIndex);
   1226   }
   1227 
   1228   void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
   1229     assert(!ParmVarDeclBits.IsObjCMethodParam);
   1230 
   1231     ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
   1232     assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!");
   1233 
   1234     setParameterIndex(parameterIndex);
   1235   }
   1236 
   1237   bool isObjCMethodParameter() const {
   1238     return ParmVarDeclBits.IsObjCMethodParam;
   1239   }
   1240 
   1241   unsigned getFunctionScopeDepth() const {
   1242     if (ParmVarDeclBits.IsObjCMethodParam) return 0;
   1243     return ParmVarDeclBits.ScopeDepthOrObjCQuals;
   1244   }
   1245 
   1246   /// Returns the index of this parameter in its prototype or method scope.
   1247   unsigned getFunctionScopeIndex() const {
   1248     return getParameterIndex();
   1249   }
   1250 
   1251   ObjCDeclQualifier getObjCDeclQualifier() const {
   1252     if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
   1253     return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
   1254   }
   1255   void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
   1256     assert(ParmVarDeclBits.IsObjCMethodParam);
   1257     ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
   1258   }
   1259 
   1260   /// True if the value passed to this parameter must undergo
   1261   /// K&R-style default argument promotion:
   1262   ///
   1263   /// C99 6.5.2.2.
   1264   ///   If the expression that denotes the called function has a type
   1265   ///   that does not include a prototype, the integer promotions are
   1266   ///   performed on each argument, and arguments that have type float
   1267   ///   are promoted to double.
   1268   bool isKNRPromoted() const {
   1269     return ParmVarDeclBits.IsKNRPromoted;
   1270   }
   1271   void setKNRPromoted(bool promoted) {
   1272     ParmVarDeclBits.IsKNRPromoted = promoted;
   1273   }
   1274 
   1275   Expr *getDefaultArg();
   1276   const Expr *getDefaultArg() const {
   1277     return const_cast<ParmVarDecl *>(this)->getDefaultArg();
   1278   }
   1279 
   1280   void setDefaultArg(Expr *defarg) {
   1281     Init = reinterpret_cast<Stmt *>(defarg);
   1282   }
   1283 
   1284   unsigned getNumDefaultArgTemporaries() const;
   1285   CXXTemporary *getDefaultArgTemporary(unsigned i);
   1286   const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
   1287     return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
   1288   }
   1289 
   1290   /// \brief Retrieve the source range that covers the entire default
   1291   /// argument.
   1292   SourceRange getDefaultArgRange() const;
   1293   void setUninstantiatedDefaultArg(Expr *arg) {
   1294     Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
   1295   }
   1296   Expr *getUninstantiatedDefaultArg() {
   1297     return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
   1298   }
   1299   const Expr *getUninstantiatedDefaultArg() const {
   1300     return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
   1301   }
   1302 
   1303   /// hasDefaultArg - Determines whether this parameter has a default argument,
   1304   /// either parsed or not.
   1305   bool hasDefaultArg() const {
   1306     return getInit() || hasUnparsedDefaultArg() ||
   1307       hasUninstantiatedDefaultArg();
   1308   }
   1309 
   1310   /// hasUnparsedDefaultArg - Determines whether this parameter has a
   1311   /// default argument that has not yet been parsed. This will occur
   1312   /// during the processing of a C++ class whose member functions have
   1313   /// default arguments, e.g.,
   1314   /// @code
   1315   ///   class X {
   1316   ///   public:
   1317   ///     void f(int x = 17); // x has an unparsed default argument now
   1318   ///   }; // x has a regular default argument now
   1319   /// @endcode
   1320   bool hasUnparsedDefaultArg() const {
   1321     return Init.is<UnparsedDefaultArgument*>();
   1322   }
   1323 
   1324   bool hasUninstantiatedDefaultArg() const {
   1325     return Init.is<UninstantiatedDefaultArgument*>();
   1326   }
   1327 
   1328   /// setUnparsedDefaultArg - Specify that this parameter has an
   1329   /// unparsed default argument. The argument will be replaced with a
   1330   /// real default argument via setDefaultArg when the class
   1331   /// definition enclosing the function declaration that owns this
   1332   /// default argument is completed.
   1333   void setUnparsedDefaultArg() {
   1334     Init = (UnparsedDefaultArgument *)0;
   1335   }
   1336 
   1337   bool hasInheritedDefaultArg() const {
   1338     return ParmVarDeclBits.HasInheritedDefaultArg;
   1339   }
   1340 
   1341   void setHasInheritedDefaultArg(bool I = true) {
   1342     ParmVarDeclBits.HasInheritedDefaultArg = I;
   1343   }
   1344 
   1345   QualType getOriginalType() const {
   1346     if (getTypeSourceInfo())
   1347       return getTypeSourceInfo()->getType();
   1348     return getType();
   1349   }
   1350 
   1351   /// \brief Determine whether this parameter is actually a function
   1352   /// parameter pack.
   1353   bool isParameterPack() const;
   1354 
   1355   /// setOwningFunction - Sets the function declaration that owns this
   1356   /// ParmVarDecl. Since ParmVarDecls are often created before the
   1357   /// FunctionDecls that own them, this routine is required to update
   1358   /// the DeclContext appropriately.
   1359   void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
   1360 
   1361   // Implement isa/cast/dyncast/etc.
   1362   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1363   static bool classof(const ParmVarDecl *D) { return true; }
   1364   static bool classofKind(Kind K) { return K == ParmVar; }
   1365 
   1366 private:
   1367   enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
   1368 
   1369   void setParameterIndex(unsigned parameterIndex) {
   1370     if (parameterIndex >= ParameterIndexSentinel) {
   1371       setParameterIndexLarge(parameterIndex);
   1372       return;
   1373     }
   1374 
   1375     ParmVarDeclBits.ParameterIndex = parameterIndex;
   1376     assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
   1377   }
   1378   unsigned getParameterIndex() const {
   1379     unsigned d = ParmVarDeclBits.ParameterIndex;
   1380     return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
   1381   }
   1382 
   1383   void setParameterIndexLarge(unsigned parameterIndex);
   1384   unsigned getParameterIndexLarge() const;
   1385 };
   1386 
   1387 /// FunctionDecl - An instance of this class is created to represent a
   1388 /// function declaration or definition.
   1389 ///
   1390 /// Since a given function can be declared several times in a program,
   1391 /// there may be several FunctionDecls that correspond to that
   1392 /// function. Only one of those FunctionDecls will be found when
   1393 /// traversing the list of declarations in the context of the
   1394 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
   1395 /// contains all of the information known about the function. Other,
   1396 /// previous declarations of the function are available via the
   1397 /// getPreviousDeclaration() chain.
   1398 class FunctionDecl : public DeclaratorDecl, public DeclContext,
   1399                      public Redeclarable<FunctionDecl> {
   1400 public:
   1401   typedef clang::StorageClass StorageClass;
   1402 
   1403   /// \brief The kind of templated function a FunctionDecl can be.
   1404   enum TemplatedKind {
   1405     TK_NonTemplate,
   1406     TK_FunctionTemplate,
   1407     TK_MemberSpecialization,
   1408     TK_FunctionTemplateSpecialization,
   1409     TK_DependentFunctionTemplateSpecialization
   1410   };
   1411 
   1412 private:
   1413   /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
   1414   /// parameters of this function.  This is null if a prototype or if there are
   1415   /// no formals.
   1416   ParmVarDecl **ParamInfo;
   1417 
   1418   LazyDeclStmtPtr Body;
   1419 
   1420   // FIXME: This can be packed into the bitfields in Decl.
   1421   // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
   1422   unsigned SClass : 2;
   1423   unsigned SClassAsWritten : 2;
   1424   bool IsInline : 1;
   1425   bool IsInlineSpecified : 1;
   1426   bool IsVirtualAsWritten : 1;
   1427   bool IsPure : 1;
   1428   bool HasInheritedPrototype : 1;
   1429   bool HasWrittenPrototype : 1;
   1430   bool IsDeleted : 1;
   1431   bool IsTrivial : 1; // sunk from CXXMethodDecl
   1432   bool IsDefaulted : 1; // sunk from CXXMethoDecl
   1433   bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
   1434   bool HasImplicitReturnZero : 1;
   1435   bool IsLateTemplateParsed : 1;
   1436   bool IsConstexpr : 1;
   1437 
   1438   /// \brief End part of this FunctionDecl's source range.
   1439   ///
   1440   /// We could compute the full range in getSourceRange(). However, when we're
   1441   /// dealing with a function definition deserialized from a PCH/AST file,
   1442   /// we can only compute the full range once the function body has been
   1443   /// de-serialized, so it's far better to have the (sometimes-redundant)
   1444   /// EndRangeLoc.
   1445   SourceLocation EndRangeLoc;
   1446 
   1447   /// \brief The template or declaration that this declaration
   1448   /// describes or was instantiated from, respectively.
   1449   ///
   1450   /// For non-templates, this value will be NULL. For function
   1451   /// declarations that describe a function template, this will be a
   1452   /// pointer to a FunctionTemplateDecl. For member functions
   1453   /// of class template specializations, this will be a MemberSpecializationInfo
   1454   /// pointer containing information about the specialization.
   1455   /// For function template specializations, this will be a
   1456   /// FunctionTemplateSpecializationInfo, which contains information about
   1457   /// the template being specialized and the template arguments involved in
   1458   /// that specialization.
   1459   llvm::PointerUnion4<FunctionTemplateDecl *,
   1460                       MemberSpecializationInfo *,
   1461                       FunctionTemplateSpecializationInfo *,
   1462                       DependentFunctionTemplateSpecializationInfo *>
   1463     TemplateOrSpecialization;
   1464 
   1465   /// DNLoc - Provides source/type location info for the
   1466   /// declaration name embedded in the DeclaratorDecl base class.
   1467   DeclarationNameLoc DNLoc;
   1468 
   1469   /// \brief Specify that this function declaration is actually a function
   1470   /// template specialization.
   1471   ///
   1472   /// \param C the ASTContext.
   1473   ///
   1474   /// \param Template the function template that this function template
   1475   /// specialization specializes.
   1476   ///
   1477   /// \param TemplateArgs the template arguments that produced this
   1478   /// function template specialization from the template.
   1479   ///
   1480   /// \param InsertPos If non-NULL, the position in the function template
   1481   /// specialization set where the function template specialization data will
   1482   /// be inserted.
   1483   ///
   1484   /// \param TSK the kind of template specialization this is.
   1485   ///
   1486   /// \param TemplateArgsAsWritten location info of template arguments.
   1487   ///
   1488   /// \param PointOfInstantiation point at which the function template
   1489   /// specialization was first instantiated.
   1490   void setFunctionTemplateSpecialization(ASTContext &C,
   1491                                          FunctionTemplateDecl *Template,
   1492                                        const TemplateArgumentList *TemplateArgs,
   1493                                          void *InsertPos,
   1494                                          TemplateSpecializationKind TSK,
   1495                           const TemplateArgumentListInfo *TemplateArgsAsWritten,
   1496                                          SourceLocation PointOfInstantiation);
   1497 
   1498   /// \brief Specify that this record is an instantiation of the
   1499   /// member function FD.
   1500   void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
   1501                                         TemplateSpecializationKind TSK);
   1502 
   1503   void setParams(ASTContext &C, llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
   1504 
   1505 protected:
   1506   FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
   1507                const DeclarationNameInfo &NameInfo,
   1508                QualType T, TypeSourceInfo *TInfo,
   1509                StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified,
   1510                bool isConstexprSpecified)
   1511     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
   1512                      StartLoc),
   1513       DeclContext(DK),
   1514       ParamInfo(0), Body(),
   1515       SClass(S), SClassAsWritten(SCAsWritten),
   1516       IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
   1517       IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
   1518       HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
   1519       IsDefaulted(false), IsExplicitlyDefaulted(false),
   1520       HasImplicitReturnZero(false), IsLateTemplateParsed(false),
   1521       IsConstexpr(isConstexprSpecified), EndRangeLoc(NameInfo.getEndLoc()),
   1522       TemplateOrSpecialization(),
   1523       DNLoc(NameInfo.getInfo()) {}
   1524 
   1525   typedef Redeclarable<FunctionDecl> redeclarable_base;
   1526   virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
   1527 
   1528 public:
   1529   typedef redeclarable_base::redecl_iterator redecl_iterator;
   1530   redecl_iterator redecls_begin() const {
   1531     return redeclarable_base::redecls_begin();
   1532   }
   1533   redecl_iterator redecls_end() const {
   1534     return redeclarable_base::redecls_end();
   1535   }
   1536 
   1537   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
   1538                               SourceLocation StartLoc, SourceLocation NLoc,
   1539                               DeclarationName N, QualType T,
   1540                               TypeSourceInfo *TInfo,
   1541                               StorageClass SC = SC_None,
   1542                               StorageClass SCAsWritten = SC_None,
   1543                               bool isInlineSpecified = false,
   1544                               bool hasWrittenPrototype = true,
   1545                               bool isConstexprSpecified = false) {
   1546     DeclarationNameInfo NameInfo(N, NLoc);
   1547     return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
   1548                                 SC, SCAsWritten,
   1549                                 isInlineSpecified, hasWrittenPrototype,
   1550                                 isConstexprSpecified);
   1551   }
   1552 
   1553   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
   1554                               SourceLocation StartLoc,
   1555                               const DeclarationNameInfo &NameInfo,
   1556                               QualType T, TypeSourceInfo *TInfo,
   1557                               StorageClass SC = SC_None,
   1558                               StorageClass SCAsWritten = SC_None,
   1559                               bool isInlineSpecified = false,
   1560                               bool hasWrittenPrototype = true,
   1561                               bool isConstexprSpecified = false);
   1562 
   1563   DeclarationNameInfo getNameInfo() const {
   1564     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
   1565   }
   1566 
   1567   virtual void getNameForDiagnostic(std::string &S,
   1568                                     const PrintingPolicy &Policy,
   1569                                     bool Qualified) const;
   1570 
   1571   void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
   1572 
   1573   virtual SourceRange getSourceRange() const;
   1574 
   1575   /// \brief Returns true if the function has a body (definition). The
   1576   /// function body might be in any of the (re-)declarations of this
   1577   /// function. The variant that accepts a FunctionDecl pointer will
   1578   /// set that function declaration to the actual declaration
   1579   /// containing the body (if there is one).
   1580   bool hasBody(const FunctionDecl *&Definition) const;
   1581 
   1582   virtual bool hasBody() const {
   1583     const FunctionDecl* Definition;
   1584     return hasBody(Definition);
   1585   }
   1586 
   1587   /// hasTrivialBody - Returns whether the function has a trivial body that does
   1588   /// not require any specific codegen.
   1589   bool hasTrivialBody() const;
   1590 
   1591   /// isDefined - Returns true if the function is defined at all, including
   1592   /// a deleted definition. Except for the behavior when the function is
   1593   /// deleted, behaves like hasBody.
   1594   bool isDefined(const FunctionDecl *&Definition) const;
   1595 
   1596   virtual bool isDefined() const {
   1597     const FunctionDecl* Definition;
   1598     return isDefined(Definition);
   1599   }
   1600 
   1601   /// getBody - Retrieve the body (definition) of the function. The
   1602   /// function body might be in any of the (re-)declarations of this
   1603   /// function. The variant that accepts a FunctionDecl pointer will
   1604   /// set that function declaration to the actual declaration
   1605   /// containing the body (if there is one).
   1606   /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
   1607   /// unnecessary AST de-serialization of the body.
   1608   Stmt *getBody(const FunctionDecl *&Definition) const;
   1609 
   1610   virtual Stmt *getBody() const {
   1611     const FunctionDecl* Definition;
   1612     return getBody(Definition);
   1613   }
   1614 
   1615   /// isThisDeclarationADefinition - Returns whether this specific
   1616   /// declaration of the function is also a definition. This does not
   1617   /// determine whether the function has been defined (e.g., in a
   1618   /// previous definition); for that information, use isDefined. Note
   1619   /// that this returns false for a defaulted function unless that function
   1620   /// has been implicitly defined (possibly as deleted).
   1621   bool isThisDeclarationADefinition() const {
   1622     return IsDeleted || Body || IsLateTemplateParsed;
   1623   }
   1624 
   1625   /// doesThisDeclarationHaveABody - Returns whether this specific
   1626   /// declaration of the function has a body - that is, if it is a non-
   1627   /// deleted definition.
   1628   bool doesThisDeclarationHaveABody() const {
   1629     return Body || IsLateTemplateParsed;
   1630   }
   1631 
   1632   void setBody(Stmt *B);
   1633   void setLazyBody(uint64_t Offset) { Body = Offset; }
   1634 
   1635   /// Whether this function is variadic.
   1636   bool isVariadic() const;
   1637 
   1638   /// Whether this function is marked as virtual explicitly.
   1639   bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
   1640   void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
   1641 
   1642   /// Whether this virtual function is pure, i.e. makes the containing class
   1643   /// abstract.
   1644   bool isPure() const { return IsPure; }
   1645   void setPure(bool P = true);
   1646 
   1647   /// Whether this templated function will be late parsed.
   1648   bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
   1649   void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
   1650 
   1651   /// Whether this function is "trivial" in some specialized C++ senses.
   1652   /// Can only be true for default constructors, copy constructors,
   1653   /// copy assignment operators, and destructors.  Not meaningful until
   1654   /// the class has been fully built by Sema.
   1655   bool isTrivial() const { return IsTrivial; }
   1656   void setTrivial(bool IT) { IsTrivial = IT; }
   1657 
   1658   /// Whether this function is defaulted per C++0x. Only valid for
   1659   /// special member functions.
   1660   bool isDefaulted() const { return IsDefaulted; }
   1661   void setDefaulted(bool D = true) { IsDefaulted = D; }
   1662 
   1663   /// Whether this function is explicitly defaulted per C++0x. Only valid
   1664   /// for special member functions.
   1665   bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
   1666   void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
   1667 
   1668   /// Whether falling off this function implicitly returns null/zero.
   1669   /// If a more specific implicit return value is required, front-ends
   1670   /// should synthesize the appropriate return statements.
   1671   bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
   1672   void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
   1673 
   1674   /// \brief Whether this function has a prototype, either because one
   1675   /// was explicitly written or because it was "inherited" by merging
   1676   /// a declaration without a prototype with a declaration that has a
   1677   /// prototype.
   1678   bool hasPrototype() const {
   1679     return HasWrittenPrototype || HasInheritedPrototype;
   1680   }
   1681 
   1682   bool hasWrittenPrototype() const { return HasWrittenPrototype; }
   1683 
   1684   /// \brief Whether this function inherited its prototype from a
   1685   /// previous declaration.
   1686   bool hasInheritedPrototype() const { return HasInheritedPrototype; }
   1687   void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
   1688 
   1689   /// Whether this is a (C++0x) constexpr function or constexpr constructor.
   1690   bool isConstexpr() const { return IsConstexpr; }
   1691   void setConstexpr(bool IC) { IsConstexpr = IC; }
   1692 
   1693   /// \brief Whether this function has been deleted.
   1694   ///
   1695   /// A function that is "deleted" (via the C++0x "= delete" syntax)
   1696   /// acts like a normal function, except that it cannot actually be
   1697   /// called or have its address taken. Deleted functions are
   1698   /// typically used in C++ overload resolution to attract arguments
   1699   /// whose type or lvalue/rvalue-ness would permit the use of a
   1700   /// different overload that would behave incorrectly. For example,
   1701   /// one might use deleted functions to ban implicit conversion from
   1702   /// a floating-point number to an Integer type:
   1703   ///
   1704   /// @code
   1705   /// struct Integer {
   1706   ///   Integer(long); // construct from a long
   1707   ///   Integer(double) = delete; // no construction from float or double
   1708   ///   Integer(long double) = delete; // no construction from long double
   1709   /// };
   1710   /// @endcode
   1711   // If a function is deleted, its first declaration must be.
   1712   bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
   1713   bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
   1714   void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
   1715 
   1716   /// \brief Determines whether this function is "main", which is the
   1717   /// entry point into an executable program.
   1718   bool isMain() const;
   1719 
   1720   /// \brief Determines whether this operator new or delete is one
   1721   /// of the reserved global placement operators:
   1722   ///    void *operator new(size_t, void *);
   1723   ///    void *operator new[](size_t, void *);
   1724   ///    void operator delete(void *, void *);
   1725   ///    void operator delete[](void *, void *);
   1726   /// These functions have special behavior under [new.delete.placement]:
   1727   ///    These functions are reserved, a C++ program may not define
   1728   ///    functions that displace the versions in the Standard C++ library.
   1729   ///    The provisions of [basic.stc.dynamic] do not apply to these
   1730   ///    reserved placement forms of operator new and operator delete.
   1731   ///
   1732   /// This function must be an allocation or deallocation function.
   1733   bool isReservedGlobalPlacementOperator() const;
   1734 
   1735   /// \brief Determines whether this function is a function with
   1736   /// external, C linkage.
   1737   bool isExternC() const;
   1738 
   1739   /// \brief Determines whether this is a global function.
   1740   bool isGlobal() const;
   1741 
   1742   void setPreviousDeclaration(FunctionDecl * PrevDecl);
   1743 
   1744   virtual const FunctionDecl *getCanonicalDecl() const;
   1745   virtual FunctionDecl *getCanonicalDecl();
   1746 
   1747   unsigned getBuiltinID() const;
   1748 
   1749   // Iterator access to formal parameters.
   1750   unsigned param_size() const { return getNumParams(); }
   1751   typedef ParmVarDecl **param_iterator;
   1752   typedef ParmVarDecl * const *param_const_iterator;
   1753 
   1754   param_iterator param_begin() { return ParamInfo; }
   1755   param_iterator param_end()   { return ParamInfo+param_size(); }
   1756 
   1757   param_const_iterator param_begin() const { return ParamInfo; }
   1758   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
   1759 
   1760   /// getNumParams - Return the number of parameters this function must have
   1761   /// based on its FunctionType.  This is the length of the ParamInfo array
   1762   /// after it has been created.
   1763   unsigned getNumParams() const;
   1764 
   1765   const ParmVarDecl *getParamDecl(unsigned i) const {
   1766     assert(i < getNumParams() && "Illegal param #");
   1767     return ParamInfo[i];
   1768   }
   1769   ParmVarDecl *getParamDecl(unsigned i) {
   1770     assert(i < getNumParams() && "Illegal param #");
   1771     return ParamInfo[i];
   1772   }
   1773   void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
   1774     setParams(getASTContext(), NewParamInfo);
   1775   }
   1776 
   1777   /// getMinRequiredArguments - Returns the minimum number of arguments
   1778   /// needed to call this function. This may be fewer than the number of
   1779   /// function parameters, if some of the parameters have default
   1780   /// arguments (in C++).
   1781   unsigned getMinRequiredArguments() const;
   1782 
   1783   QualType getResultType() const {
   1784     return getType()->getAs<FunctionType>()->getResultType();
   1785   }
   1786 
   1787   /// \brief Determine the type of an expression that calls this function.
   1788   QualType getCallResultType() const {
   1789     return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
   1790   }
   1791 
   1792   StorageClass getStorageClass() const { return StorageClass(SClass); }
   1793   void setStorageClass(StorageClass SC);
   1794 
   1795   StorageClass getStorageClassAsWritten() const {
   1796     return StorageClass(SClassAsWritten);
   1797   }
   1798 
   1799   /// \brief Determine whether the "inline" keyword was specified for this
   1800   /// function.
   1801   bool isInlineSpecified() const { return IsInlineSpecified; }
   1802 
   1803   /// Set whether the "inline" keyword was specified for this function.
   1804   void setInlineSpecified(bool I) {
   1805     IsInlineSpecified = I;
   1806     IsInline = I;
   1807   }
   1808 
   1809   /// Flag that this function is implicitly inline.
   1810   void setImplicitlyInline() {
   1811     IsInline = true;
   1812   }
   1813 
   1814   /// \brief Determine whether this function should be inlined, because it is
   1815   /// either marked "inline" or "constexpr" or is a member function of a class
   1816   /// that was defined in the class body.
   1817   bool isInlined() const;
   1818 
   1819   bool isInlineDefinitionExternallyVisible() const;
   1820 
   1821   bool doesDeclarationForceExternallyVisibleDefinition() const;
   1822 
   1823   /// isOverloadedOperator - Whether this function declaration
   1824   /// represents an C++ overloaded operator, e.g., "operator+".
   1825   bool isOverloadedOperator() const {
   1826     return getOverloadedOperator() != OO_None;
   1827   }
   1828 
   1829   OverloadedOperatorKind getOverloadedOperator() const;
   1830 
   1831   const IdentifierInfo *getLiteralIdentifier() const;
   1832 
   1833   /// \brief If this function is an instantiation of a member function
   1834   /// of a class template specialization, retrieves the function from
   1835   /// which it was instantiated.
   1836   ///
   1837   /// This routine will return non-NULL for (non-templated) member
   1838   /// functions of class templates and for instantiations of function
   1839   /// templates. For example, given:
   1840   ///
   1841   /// \code
   1842   /// template<typename T>
   1843   /// struct X {
   1844   ///   void f(T);
   1845   /// };
   1846   /// \endcode
   1847   ///
   1848   /// The declaration for X<int>::f is a (non-templated) FunctionDecl
   1849   /// whose parent is the class template specialization X<int>. For
   1850   /// this declaration, getInstantiatedFromFunction() will return
   1851   /// the FunctionDecl X<T>::A. When a complete definition of
   1852   /// X<int>::A is required, it will be instantiated from the
   1853   /// declaration returned by getInstantiatedFromMemberFunction().
   1854   FunctionDecl *getInstantiatedFromMemberFunction() const;
   1855 
   1856   /// \brief What kind of templated function this is.
   1857   TemplatedKind getTemplatedKind() const;
   1858 
   1859   /// \brief If this function is an instantiation of a member function of a
   1860   /// class template specialization, retrieves the member specialization
   1861   /// information.
   1862   MemberSpecializationInfo *getMemberSpecializationInfo() const;
   1863 
   1864   /// \brief Specify that this record is an instantiation of the
   1865   /// member function FD.
   1866   void setInstantiationOfMemberFunction(FunctionDecl *FD,
   1867                                         TemplateSpecializationKind TSK) {
   1868     setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
   1869   }
   1870 
   1871   /// \brief Retrieves the function template that is described by this
   1872   /// function declaration.
   1873   ///
   1874   /// Every function template is represented as a FunctionTemplateDecl
   1875   /// and a FunctionDecl (or something derived from FunctionDecl). The
   1876   /// former contains template properties (such as the template
   1877   /// parameter lists) while the latter contains the actual
   1878   /// description of the template's
   1879   /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
   1880   /// FunctionDecl that describes the function template,
   1881   /// getDescribedFunctionTemplate() retrieves the
   1882   /// FunctionTemplateDecl from a FunctionDecl.
   1883   FunctionTemplateDecl *getDescribedFunctionTemplate() const {
   1884     return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
   1885   }
   1886 
   1887   void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
   1888     TemplateOrSpecialization = Template;
   1889   }
   1890 
   1891   /// \brief Determine whether this function is a function template
   1892   /// specialization.
   1893   bool isFunctionTemplateSpecialization() const {
   1894     return getPrimaryTemplate() != 0;
   1895   }
   1896 
   1897   /// \brief Retrieve the class scope template pattern that this function
   1898   ///  template specialization is instantiated from.
   1899   FunctionDecl *getClassScopeSpecializationPattern() const;
   1900 
   1901   /// \brief If this function is actually a function template specialization,
   1902   /// retrieve information about this function template specialization.
   1903   /// Otherwise, returns NULL.
   1904   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
   1905     return TemplateOrSpecialization.
   1906              dyn_cast<FunctionTemplateSpecializationInfo*>();
   1907   }
   1908 
   1909   /// \brief Determines whether this function is a function template
   1910   /// specialization or a member of a class template specialization that can
   1911   /// be implicitly instantiated.
   1912   bool isImplicitlyInstantiable() const;
   1913 
   1914   /// \brief Retrieve the function declaration from which this function could
   1915   /// be instantiated, if it is an instantiation (rather than a non-template
   1916   /// or a specialization, for example).
   1917   FunctionDecl *getTemplateInstantiationPattern() const;
   1918 
   1919   /// \brief Retrieve the primary template that this function template
   1920   /// specialization either specializes or was instantiated from.
   1921   ///
   1922   /// If this function declaration is not a function template specialization,
   1923   /// returns NULL.
   1924   FunctionTemplateDecl *getPrimaryTemplate() const;
   1925 
   1926   /// \brief Retrieve the template arguments used to produce this function
   1927   /// template specialization from the primary template.
   1928   ///
   1929   /// If this function declaration is not a function template specialization,
   1930   /// returns NULL.
   1931   const TemplateArgumentList *getTemplateSpecializationArgs() const;
   1932 
   1933   /// \brief Retrieve the template argument list as written in the sources,
   1934   /// if any.
   1935   ///
   1936   /// If this function declaration is not a function template specialization
   1937   /// or if it had no explicit template argument list, returns NULL.
   1938   /// Note that it an explicit template argument list may be written empty,
   1939   /// e.g., template<> void foo<>(char* s);
   1940   const ASTTemplateArgumentListInfo*
   1941   getTemplateSpecializationArgsAsWritten() const;
   1942 
   1943   /// \brief Specify that this function declaration is actually a function
   1944   /// template specialization.
   1945   ///
   1946   /// \param Template the function template that this function template
   1947   /// specialization specializes.
   1948   ///
   1949   /// \param TemplateArgs the template arguments that produced this
   1950   /// function template specialization from the template.
   1951   ///
   1952   /// \param InsertPos If non-NULL, the position in the function template
   1953   /// specialization set where the function template specialization data will
   1954   /// be inserted.
   1955   ///
   1956   /// \param TSK the kind of template specialization this is.
   1957   ///
   1958   /// \param TemplateArgsAsWritten location info of template arguments.
   1959   ///
   1960   /// \param PointOfInstantiation point at which the function template
   1961   /// specialization was first instantiated.
   1962   void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
   1963                                       const TemplateArgumentList *TemplateArgs,
   1964                                          void *InsertPos,
   1965                     TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
   1966                     const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
   1967                     SourceLocation PointOfInstantiation = SourceLocation()) {
   1968     setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
   1969                                       InsertPos, TSK, TemplateArgsAsWritten,
   1970                                       PointOfInstantiation);
   1971   }
   1972 
   1973   /// \brief Specifies that this function declaration is actually a
   1974   /// dependent function template specialization.
   1975   void setDependentTemplateSpecialization(ASTContext &Context,
   1976                              const UnresolvedSetImpl &Templates,
   1977                       const TemplateArgumentListInfo &TemplateArgs);
   1978 
   1979   DependentFunctionTemplateSpecializationInfo *
   1980   getDependentSpecializationInfo() const {
   1981     return TemplateOrSpecialization.
   1982              dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
   1983   }
   1984 
   1985   /// \brief Determine what kind of template instantiation this function
   1986   /// represents.
   1987   TemplateSpecializationKind getTemplateSpecializationKind() const;
   1988 
   1989   /// \brief Determine what kind of template instantiation this function
   1990   /// represents.
   1991   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   1992                         SourceLocation PointOfInstantiation = SourceLocation());
   1993 
   1994   /// \brief Retrieve the (first) point of instantiation of a function template
   1995   /// specialization or a member of a class template specialization.
   1996   ///
   1997   /// \returns the first point of instantiation, if this function was
   1998   /// instantiated from a template; otherwise, returns an invalid source
   1999   /// location.
   2000   SourceLocation getPointOfInstantiation() const;
   2001 
   2002   /// \brief Determine whether this is or was instantiated from an out-of-line
   2003   /// definition of a member function.
   2004   virtual bool isOutOfLine() const;
   2005 
   2006   // Implement isa/cast/dyncast/etc.
   2007   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2008   static bool classof(const FunctionDecl *D) { return true; }
   2009   static bool classofKind(Kind K) {
   2010     return K >= firstFunction && K <= lastFunction;
   2011   }
   2012   static DeclContext *castToDeclContext(const FunctionDecl *D) {
   2013     return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
   2014   }
   2015   static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
   2016     return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
   2017   }
   2018 
   2019   friend class ASTDeclReader;
   2020   friend class ASTDeclWriter;
   2021 };
   2022 
   2023 
   2024 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
   2025 /// represent a member of a struct/union/class.
   2026 class FieldDecl : public DeclaratorDecl {
   2027   // FIXME: This can be packed into the bitfields in Decl.
   2028   bool Mutable : 1;
   2029   mutable unsigned CachedFieldIndex : 31;
   2030 
   2031   /// \brief A pointer to either the in-class initializer for this field (if
   2032   /// the boolean value is false), or the bit width expression for this bit
   2033   /// field (if the boolean value is true).
   2034   ///
   2035   /// We can safely combine these two because in-class initializers are not
   2036   /// permitted for bit-fields.
   2037   ///
   2038   /// If the boolean is false and the initializer is null, then this field has
   2039   /// an in-class initializer which has not yet been parsed and attached.
   2040   llvm::PointerIntPair<Expr *, 1, bool> InitializerOrBitWidth;
   2041 protected:
   2042   FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
   2043             SourceLocation IdLoc, IdentifierInfo *Id,
   2044             QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
   2045             bool HasInit)
   2046     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
   2047       Mutable(Mutable), CachedFieldIndex(0),
   2048       InitializerOrBitWidth(BW, !HasInit) {
   2049     assert(!(BW && HasInit) && "got initializer for bitfield");
   2050   }
   2051 
   2052 public:
   2053   static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
   2054                            SourceLocation StartLoc, SourceLocation IdLoc,
   2055                            IdentifierInfo *Id, QualType T,
   2056                            TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
   2057                            bool HasInit);
   2058 
   2059   /// getFieldIndex - Returns the index of this field within its record,
   2060   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
   2061   unsigned getFieldIndex() const;
   2062 
   2063   /// isMutable - Determines whether this field is mutable (C++ only).
   2064   bool isMutable() const { return Mutable; }
   2065 
   2066   /// \brief Set whether this field is mutable (C++ only).
   2067   void setMutable(bool M) { Mutable = M; }
   2068 
   2069   /// isBitfield - Determines whether this field is a bitfield.
   2070   bool isBitField() const {
   2071     return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer();
   2072   }
   2073 
   2074   /// @brief Determines whether this is an unnamed bitfield.
   2075   bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
   2076 
   2077   /// isAnonymousStructOrUnion - Determines whether this field is a
   2078   /// representative for an anonymous struct or union. Such fields are
   2079   /// unnamed and are implicitly generated by the implementation to
   2080   /// store the data for the anonymous union or struct.
   2081   bool isAnonymousStructOrUnion() const;
   2082 
   2083   Expr *getBitWidth() const {
   2084     return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
   2085   }
   2086   unsigned getBitWidthValue(const ASTContext &Ctx) const;
   2087   void setBitWidth(Expr *BW) {
   2088     assert(!InitializerOrBitWidth.getPointer() &&
   2089            "bit width or initializer already set");
   2090     InitializerOrBitWidth.setPointer(BW);
   2091     InitializerOrBitWidth.setInt(1);
   2092   }
   2093   /// removeBitWidth - Remove the bitfield width from this member.
   2094   void removeBitWidth() {
   2095     assert(isBitField() && "no bit width to remove");
   2096     InitializerOrBitWidth.setPointer(0);
   2097   }
   2098 
   2099   /// hasInClassInitializer - Determine whether this member has a C++0x in-class
   2100   /// initializer.
   2101   bool hasInClassInitializer() const {
   2102     return !InitializerOrBitWidth.getInt();
   2103   }
   2104   /// getInClassInitializer - Get the C++0x in-class initializer for this
   2105   /// member, or null if one has not been set. If a valid declaration has an
   2106   /// in-class initializer, but this returns null, then we have not parsed and
   2107   /// attached it yet.
   2108   Expr *getInClassInitializer() const {
   2109     return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
   2110   }
   2111   /// setInClassInitializer - Set the C++0x in-class initializer for this member.
   2112   void setInClassInitializer(Expr *Init);
   2113   /// removeInClassInitializer - Remove the C++0x in-class initializer from this
   2114   /// member.
   2115   void removeInClassInitializer() {
   2116     assert(!InitializerOrBitWidth.getInt() && "no initializer to remove");
   2117     InitializerOrBitWidth.setPointer(0);
   2118     InitializerOrBitWidth.setInt(1);
   2119   }
   2120 
   2121   /// getParent - Returns the parent of this field declaration, which
   2122   /// is the struct in which this method is defined.
   2123   const RecordDecl *getParent() const {
   2124     return cast<RecordDecl>(getDeclContext());
   2125   }
   2126 
   2127   RecordDecl *getParent() {
   2128     return cast<RecordDecl>(getDeclContext());
   2129   }
   2130 
   2131   SourceRange getSourceRange() const;
   2132 
   2133   // Implement isa/cast/dyncast/etc.
   2134   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2135   static bool classof(const FieldDecl *D) { return true; }
   2136   static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
   2137 };
   2138 
   2139 /// EnumConstantDecl - An instance of this object exists for each enum constant
   2140 /// that is defined.  For example, in "enum X {a,b}", each of a/b are
   2141 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
   2142 /// TagType for the X EnumDecl.
   2143 class EnumConstantDecl : public ValueDecl {
   2144   Stmt *Init; // an integer constant expression
   2145   llvm::APSInt Val; // The value.
   2146 protected:
   2147   EnumConstantDecl(DeclContext *DC, SourceLocation L,
   2148                    IdentifierInfo *Id, QualType T, Expr *E,
   2149                    const llvm::APSInt &V)
   2150     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
   2151 
   2152 public:
   2153 
   2154   static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
   2155                                   SourceLocation L, IdentifierInfo *Id,
   2156                                   QualType T, Expr *E,
   2157                                   const llvm::APSInt &V);
   2158 
   2159   const Expr *getInitExpr() const { return (const Expr*) Init; }
   2160   Expr *getInitExpr() { return (Expr*) Init; }
   2161   const llvm::APSInt &getInitVal() const { return Val; }
   2162 
   2163   void setInitExpr(Expr *E) { Init = (Stmt*) E; }
   2164   void setInitVal(const llvm::APSInt &V) { Val = V; }
   2165 
   2166   SourceRange getSourceRange() const;
   2167 
   2168   // Implement isa/cast/dyncast/etc.
   2169   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2170   static bool classof(const EnumConstantDecl *D) { return true; }
   2171   static bool classofKind(Kind K) { return K == EnumConstant; }
   2172 
   2173   friend class StmtIteratorBase;
   2174 };
   2175 
   2176 /// IndirectFieldDecl - An instance of this class is created to represent a
   2177 /// field injected from an anonymous union/struct into the parent scope.
   2178 /// IndirectFieldDecl are always implicit.
   2179 class IndirectFieldDecl : public ValueDecl {
   2180   NamedDecl **Chaining;
   2181   unsigned ChainingSize;
   2182 
   2183   IndirectFieldDecl(DeclContext *DC, SourceLocation L,
   2184                     DeclarationName N, QualType T,
   2185                     NamedDecl **CH, unsigned CHS)
   2186     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
   2187 
   2188 public:
   2189   static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
   2190                                    SourceLocation L, IdentifierInfo *Id,
   2191                                    QualType T, NamedDecl **CH, unsigned CHS);
   2192 
   2193   typedef NamedDecl * const *chain_iterator;
   2194   chain_iterator chain_begin() const { return Chaining; }
   2195   chain_iterator chain_end() const  { return Chaining+ChainingSize; }
   2196 
   2197   unsigned getChainingSize() const { return ChainingSize; }
   2198 
   2199   FieldDecl *getAnonField() const {
   2200     assert(ChainingSize >= 2);
   2201     return cast<FieldDecl>(Chaining[ChainingSize - 1]);
   2202   }
   2203 
   2204   VarDecl *getVarDecl() const {
   2205     assert(ChainingSize >= 2);
   2206     return dyn_cast<VarDecl>(*chain_begin());
   2207   }
   2208 
   2209   // Implement isa/cast/dyncast/etc.
   2210   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2211   static bool classof(const IndirectFieldDecl *D) { return true; }
   2212   static bool classofKind(Kind K) { return K == IndirectField; }
   2213   friend class ASTDeclReader;
   2214 };
   2215 
   2216 /// TypeDecl - Represents a declaration of a type.
   2217 ///
   2218 class TypeDecl : public NamedDecl {
   2219   /// TypeForDecl - This indicates the Type object that represents
   2220   /// this TypeDecl.  It is a cache maintained by
   2221   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
   2222   /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
   2223   mutable const Type *TypeForDecl;
   2224   /// LocStart - The start of the source range for this declaration.
   2225   SourceLocation LocStart;
   2226   friend class ASTContext;
   2227   friend class DeclContext;
   2228   friend class TagDecl;
   2229   friend class TemplateTypeParmDecl;
   2230   friend class TagType;
   2231 
   2232 protected:
   2233   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
   2234            SourceLocation StartL = SourceLocation())
   2235     : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
   2236 
   2237 public:
   2238   // Low-level accessor
   2239   const Type *getTypeForDecl() const { return TypeForDecl; }
   2240   void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
   2241 
   2242   SourceLocation getLocStart() const { return LocStart; }
   2243   void setLocStart(SourceLocation L) { LocStart = L; }
   2244   virtual SourceRange getSourceRange() const {
   2245     if (LocStart.isValid())
   2246       return SourceRange(LocStart, getLocation());
   2247     else
   2248       return SourceRange(getLocation());
   2249   }
   2250 
   2251   // Implement isa/cast/dyncast/etc.
   2252   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2253   static bool classof(const TypeDecl *D) { return true; }
   2254   static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
   2255 };
   2256 
   2257 
   2258 /// Base class for declarations which introduce a typedef-name.
   2259 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
   2260   /// UnderlyingType - This is the type the typedef is set to.
   2261   TypeSourceInfo *TInfo;
   2262 
   2263 protected:
   2264   TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
   2265                   SourceLocation IdLoc, IdentifierInfo *Id,
   2266                   TypeSourceInfo *TInfo)
   2267     : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
   2268 
   2269   typedef Redeclarable<TypedefNameDecl> redeclarable_base;
   2270   virtual TypedefNameDecl *getNextRedeclaration() {
   2271     return RedeclLink.getNext();
   2272   }
   2273 
   2274 public:
   2275   typedef redeclarable_base::redecl_iterator redecl_iterator;
   2276   redecl_iterator redecls_begin() const {
   2277     return redeclarable_base::redecls_begin();
   2278   }
   2279   redecl_iterator redecls_end() const {
   2280     return redeclarable_base::redecls_end();
   2281   }
   2282 
   2283   TypeSourceInfo *getTypeSourceInfo() const {
   2284     return TInfo;
   2285   }
   2286 
   2287   /// Retrieves the canonical declaration of this typedef-name.
   2288   TypedefNameDecl *getCanonicalDecl() {
   2289     return getFirstDeclaration();
   2290   }
   2291   const TypedefNameDecl *getCanonicalDecl() const {
   2292     return getFirstDeclaration();
   2293   }
   2294 
   2295   QualType getUnderlyingType() const {
   2296     return TInfo->getType();
   2297   }
   2298   void setTypeSourceInfo(TypeSourceInfo *newType) {
   2299     TInfo = newType;
   2300   }
   2301 
   2302   // Implement isa/cast/dyncast/etc.
   2303   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2304   static bool classof(const TypedefNameDecl *D) { return true; }
   2305   static bool classofKind(Kind K) {
   2306     return K >= firstTypedefName && K <= lastTypedefName;
   2307   }
   2308 };
   2309 
   2310 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
   2311 /// type specifier.
   2312 class TypedefDecl : public TypedefNameDecl {
   2313   TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
   2314               IdentifierInfo *Id, TypeSourceInfo *TInfo)
   2315     : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
   2316 
   2317 public:
   2318   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
   2319                              SourceLocation StartLoc, SourceLocation IdLoc,
   2320                              IdentifierInfo *Id, TypeSourceInfo *TInfo);
   2321 
   2322   SourceRange getSourceRange() const;
   2323 
   2324   // Implement isa/cast/dyncast/etc.
   2325   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2326   static bool classof(const TypedefDecl *D) { return true; }
   2327   static bool classofKind(Kind K) { return K == Typedef; }
   2328 };
   2329 
   2330 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
   2331 /// alias-declaration.
   2332 class TypeAliasDecl : public TypedefNameDecl {
   2333   TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
   2334                 IdentifierInfo *Id, TypeSourceInfo *TInfo)
   2335     : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
   2336 
   2337 public:
   2338   static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
   2339                                SourceLocation StartLoc, SourceLocation IdLoc,
   2340                                IdentifierInfo *Id, TypeSourceInfo *TInfo);
   2341 
   2342   SourceRange getSourceRange() const;
   2343 
   2344   // Implement isa/cast/dyncast/etc.
   2345   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2346   static bool classof(const TypeAliasDecl *D) { return true; }
   2347   static bool classofKind(Kind K) { return K == TypeAlias; }
   2348 };
   2349 
   2350 /// TagDecl - Represents the declaration of a struct/union/class/enum.
   2351 class TagDecl
   2352   : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
   2353 public:
   2354   // This is really ugly.
   2355   typedef TagTypeKind TagKind;
   2356 
   2357 private:
   2358   // FIXME: This can be packed into the bitfields in Decl.
   2359   /// TagDeclKind - The TagKind enum.
   2360   unsigned TagDeclKind : 2;
   2361 
   2362   /// IsCompleteDefinition - True if this is a definition ("struct foo
   2363   /// {};"), false if it is a declaration ("struct foo;").  It is not
   2364   /// a definition until the definition has been fully processed.
   2365   bool IsCompleteDefinition : 1;
   2366 
   2367   /// IsBeingDefined - True if this is currently being defined.
   2368   bool IsBeingDefined : 1;
   2369 
   2370   /// IsEmbeddedInDeclarator - True if this tag declaration is
   2371   /// "embedded" (i.e., defined or declared for the very first time)
   2372   /// in the syntax of a declarator.
   2373   bool IsEmbeddedInDeclarator : 1;
   2374 
   2375   /// /brief True if this tag is free standing, e.g. "struct foo;".
   2376   bool IsFreeStanding : 1;
   2377 
   2378 protected:
   2379   // These are used by (and only defined for) EnumDecl.
   2380   unsigned NumPositiveBits : 8;
   2381   unsigned NumNegativeBits : 8;
   2382 
   2383   /// IsScoped - True if this tag declaration is a scoped enumeration. Only
   2384   /// possible in C++0x mode.
   2385   bool IsScoped : 1;
   2386   /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
   2387   /// then this is true if the scoped enum was declared using the class
   2388   /// tag, false if it was declared with the struct tag. No meaning is
   2389   /// associated if this tag declaration is not a scoped enum.
   2390   bool IsScopedUsingClassTag : 1;
   2391 
   2392   /// IsFixed - True if this is an enumeration with fixed underlying type. Only
   2393   /// possible in C++0x mode.
   2394   bool IsFixed : 1;
   2395 
   2396 private:
   2397   SourceLocation RBraceLoc;
   2398 
   2399   // A struct representing syntactic qualifier info,
   2400   // to be used for the (uncommon) case of out-of-line declarations.
   2401   typedef QualifierInfo ExtInfo;
   2402 
   2403   /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
   2404   /// is qualified, it points to the qualifier info (nns and range);
   2405   /// otherwise, if the tag declaration is anonymous and it is part of
   2406   /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
   2407   /// otherwise, it is a null (TypedefNameDecl) pointer.
   2408   llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
   2409 
   2410   bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
   2411   ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
   2412   const ExtInfo *getExtInfo() const {
   2413     return TypedefNameDeclOrQualifier.get<ExtInfo*>();
   2414   }
   2415 
   2416 protected:
   2417   TagDecl(Kind DK, TagKind TK, DeclContext *DC,
   2418           SourceLocation L, IdentifierInfo *Id,
   2419           TagDecl *PrevDecl, SourceLocation StartL)
   2420     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
   2421       TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
   2422     assert((DK != Enum || TK == TTK_Enum) &&
   2423            "EnumDecl not matched with TTK_Enum");
   2424     TagDeclKind = TK;
   2425     IsCompleteDefinition = false;
   2426     IsBeingDefined = false;
   2427     IsEmbeddedInDeclarator = false;
   2428     IsFreeStanding = false;
   2429     setPreviousDeclaration(PrevDecl);
   2430   }
   2431 
   2432   typedef Redeclarable<TagDecl> redeclarable_base;
   2433   virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
   2434 
   2435   /// @brief Completes the definition of this tag declaration.
   2436   ///
   2437   /// This is a helper function for derived classes.
   2438   void completeDefinition();
   2439 
   2440 public:
   2441   typedef redeclarable_base::redecl_iterator redecl_iterator;
   2442   redecl_iterator redecls_begin() const {
   2443     return redeclarable_base::redecls_begin();
   2444   }
   2445   redecl_iterator redecls_end() const {
   2446     return redeclarable_base::redecls_end();
   2447   }
   2448 
   2449   SourceLocation getRBraceLoc() const { return RBraceLoc; }
   2450   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
   2451 
   2452   /// getInnerLocStart - Return SourceLocation representing start of source
   2453   /// range ignoring outer template declarations.
   2454   SourceLocation getInnerLocStart() const { return getLocStart(); }
   2455 
   2456   /// getOuterLocStart - Return SourceLocation representing start of source
   2457   /// range taking into account any outer template declarations.
   2458   SourceLocation getOuterLocStart() const;
   2459   virtual SourceRange getSourceRange() const;
   2460 
   2461   virtual TagDecl* getCanonicalDecl();
   2462   const TagDecl* getCanonicalDecl() const {
   2463     return const_cast<TagDecl*>(this)->getCanonicalDecl();
   2464   }
   2465 
   2466   /// isThisDeclarationADefinition() - Return true if this declaration
   2467   /// is a completion definintion of the type.  Provided for consistency.
   2468   bool isThisDeclarationADefinition() const {
   2469     return isCompleteDefinition();
   2470   }
   2471 
   2472   /// isCompleteDefinition - Return true if this decl has its body
   2473   /// fully specified.
   2474   bool isCompleteDefinition() const {
   2475     return IsCompleteDefinition;
   2476   }
   2477 
   2478   /// isBeingDefined - Return true if this decl is currently being defined.
   2479   bool isBeingDefined() const {
   2480     return IsBeingDefined;
   2481   }
   2482 
   2483   bool isEmbeddedInDeclarator() const {
   2484     return IsEmbeddedInDeclarator;
   2485   }
   2486   void setEmbeddedInDeclarator(bool isInDeclarator) {
   2487     IsEmbeddedInDeclarator = isInDeclarator;
   2488   }
   2489 
   2490   bool isFreeStanding() const { return IsFreeStanding; }
   2491   void setFreeStanding(bool isFreeStanding = true) {
   2492     IsFreeStanding = isFreeStanding;
   2493   }
   2494 
   2495   /// \brief Whether this declaration declares a type that is
   2496   /// dependent, i.e., a type that somehow depends on template
   2497   /// parameters.
   2498   bool isDependentType() const { return isDependentContext(); }
   2499 
   2500   /// @brief Starts the definition of this tag declaration.
   2501   ///
   2502   /// This method should be invoked at the beginning of the definition
   2503   /// of this tag declaration. It will set the tag type into a state
   2504   /// where it is in the process of being defined.
   2505   void startDefinition();
   2506 
   2507   /// getDefinition - Returns the TagDecl that actually defines this
   2508   ///  struct/union/class/enum.  When determining whether or not a
   2509   ///  struct/union/class/enum has a definition, one should use this
   2510   ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
   2511   ///  whether or not a specific TagDecl is defining declaration, not
   2512   ///  whether or not the struct/union/class/enum type is defined.
   2513   ///  This method returns NULL if there is no TagDecl that defines
   2514   ///  the struct/union/class/enum.
   2515   TagDecl *getDefinition() const;
   2516 
   2517   void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
   2518 
   2519   const char *getKindName() const {
   2520     return TypeWithKeyword::getTagTypeKindName(getTagKind());
   2521   }
   2522 
   2523   TagKind getTagKind() const {
   2524     return TagKind(TagDeclKind);
   2525   }
   2526 
   2527   void setTagKind(TagKind TK) { TagDeclKind = TK; }
   2528 
   2529   bool isStruct() const { return getTagKind() == TTK_Struct; }
   2530   bool isClass()  const { return getTagKind() == TTK_Class; }
   2531   bool isUnion()  const { return getTagKind() == TTK_Union; }
   2532   bool isEnum()   const { return getTagKind() == TTK_Enum; }
   2533 
   2534   TypedefNameDecl *getTypedefNameForAnonDecl() const {
   2535     return hasExtInfo() ? 0 : TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
   2536   }
   2537 
   2538   void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
   2539 
   2540   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
   2541   /// declaration, if it was present in the source.
   2542   NestedNameSpecifier *getQualifier() const {
   2543     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
   2544                         : 0;
   2545   }
   2546 
   2547   /// \brief Retrieve the nested-name-specifier (with source-location
   2548   /// information) that qualifies the name of this declaration, if it was
   2549   /// present in the source.
   2550   NestedNameSpecifierLoc getQualifierLoc() const {
   2551     return hasExtInfo() ? getExtInfo()->QualifierLoc
   2552                         : NestedNameSpecifierLoc();
   2553   }
   2554 
   2555   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
   2556 
   2557   unsigned getNumTemplateParameterLists() const {
   2558     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
   2559   }
   2560   TemplateParameterList *getTemplateParameterList(unsigned i) const {
   2561     assert(i < getNumTemplateParameterLists());
   2562     return getExtInfo()->TemplParamLists[i];
   2563   }
   2564   void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
   2565                                      TemplateParameterList **TPLists);
   2566 
   2567   // Implement isa/cast/dyncast/etc.
   2568   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2569   static bool classof(const TagDecl *D) { return true; }
   2570   static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
   2571 
   2572   static DeclContext *castToDeclContext(const TagDecl *D) {
   2573     return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
   2574   }
   2575   static TagDecl *castFromDeclContext(const DeclContext *DC) {
   2576     return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
   2577   }
   2578 
   2579   friend class ASTDeclReader;
   2580   friend class ASTDeclWriter;
   2581 };
   2582 
   2583 /// EnumDecl - Represents an enum.  As an extension, we allow forward-declared
   2584 /// enums.
   2585 class EnumDecl : public TagDecl {
   2586   /// IntegerType - This represent the integer type that the enum corresponds
   2587   /// to for code generation purposes.  Note that the enumerator constants may
   2588   /// have a different type than this does.
   2589   ///
   2590   /// If the underlying integer type was explicitly stated in the source
   2591   /// code, this is a TypeSourceInfo* for that type. Otherwise this type
   2592   /// was automatically deduced somehow, and this is a Type*.
   2593   ///
   2594   /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
   2595   /// some cases it won't.
   2596   ///
   2597   /// The underlying type of an enumeration never has any qualifiers, so
   2598   /// we can get away with just storing a raw Type*, and thus save an
   2599   /// extra pointer when TypeSourceInfo is needed.
   2600 
   2601   llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
   2602 
   2603   /// PromotionType - The integer type that values of this type should
   2604   /// promote to.  In C, enumerators are generally of an integer type
   2605   /// directly, but gcc-style large enumerators (and all enumerators
   2606   /// in C++) are of the enum type instead.
   2607   QualType PromotionType;
   2608 
   2609   /// \brief If the enumeration was instantiated from an enumeration
   2610   /// within a class or function template, this pointer refers to the
   2611   /// enumeration declared within the template.
   2612   EnumDecl *InstantiatedFrom;
   2613 
   2614   // The number of positive and negative bits required by the
   2615   // enumerators are stored in the SubclassBits field.
   2616   enum {
   2617     NumBitsWidth = 8,
   2618     NumBitsMask = (1 << NumBitsWidth) - 1
   2619   };
   2620 
   2621   EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
   2622            IdentifierInfo *Id, EnumDecl *PrevDecl,
   2623            bool Scoped, bool ScopedUsingClassTag, bool Fixed)
   2624     : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
   2625       InstantiatedFrom(0) {
   2626     assert(Scoped || !ScopedUsingClassTag);
   2627     IntegerType = (const Type*)0;
   2628     NumNegativeBits = 0;
   2629     NumPositiveBits = 0;
   2630     IsScoped = Scoped;
   2631     IsScopedUsingClassTag = ScopedUsingClassTag;
   2632     IsFixed = Fixed;
   2633   }
   2634 public:
   2635   EnumDecl *getCanonicalDecl() {
   2636     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
   2637   }
   2638   const EnumDecl *getCanonicalDecl() const {
   2639     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
   2640   }
   2641 
   2642   const EnumDecl *getPreviousDeclaration() const {
   2643     return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
   2644   }
   2645   EnumDecl *getPreviousDeclaration() {
   2646     return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
   2647   }
   2648 
   2649   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
   2650                           SourceLocation StartLoc, SourceLocation IdLoc,
   2651                           IdentifierInfo *Id, EnumDecl *PrevDecl,
   2652                           bool IsScoped, bool IsScopedUsingClassTag,
   2653                           bool IsFixed);
   2654   static EnumDecl *Create(ASTContext &C, EmptyShell Empty);
   2655 
   2656   /// completeDefinition - When created, the EnumDecl corresponds to a
   2657   /// forward-declared enum. This method is used to mark the
   2658   /// declaration as being defined; it's enumerators have already been
   2659   /// added (via DeclContext::addDecl). NewType is the new underlying
   2660   /// type of the enumeration type.
   2661   void completeDefinition(QualType NewType,
   2662                           QualType PromotionType,
   2663                           unsigned NumPositiveBits,
   2664                           unsigned NumNegativeBits);
   2665 
   2666   // enumerator_iterator - Iterates through the enumerators of this
   2667   // enumeration.
   2668   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
   2669 
   2670   enumerator_iterator enumerator_begin() const {
   2671     const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
   2672     if (!E)
   2673       E = this;
   2674     return enumerator_iterator(E->decls_begin());
   2675   }
   2676 
   2677   enumerator_iterator enumerator_end() const {
   2678     const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
   2679     if (!E)
   2680       E = this;
   2681     return enumerator_iterator(E->decls_end());
   2682   }
   2683 
   2684   /// getPromotionType - Return the integer type that enumerators
   2685   /// should promote to.
   2686   QualType getPromotionType() const { return PromotionType; }
   2687 
   2688   /// \brief Set the promotion type.
   2689   void setPromotionType(QualType T) { PromotionType = T; }
   2690 
   2691   /// getIntegerType - Return the integer type this enum decl corresponds to.
   2692   /// This returns a null qualtype for an enum forward definition.
   2693   QualType getIntegerType() const {
   2694     if (!IntegerType)
   2695       return QualType();
   2696     if (const Type* T = IntegerType.dyn_cast<const Type*>())
   2697       return QualType(T, 0);
   2698     return IntegerType.get<TypeSourceInfo*>()->getType();
   2699   }
   2700 
   2701   /// \brief Set the underlying integer type.
   2702   void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
   2703 
   2704   /// \brief Set the underlying integer type source info.
   2705   void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
   2706 
   2707   /// \brief Return the type source info for the underlying integer type,
   2708   /// if no type source info exists, return 0.
   2709   TypeSourceInfo* getIntegerTypeSourceInfo() const {
   2710     return IntegerType.dyn_cast<TypeSourceInfo*>();
   2711   }
   2712 
   2713   /// \brief Returns the width in bits required to store all the
   2714   /// non-negative enumerators of this enum.
   2715   unsigned getNumPositiveBits() const {
   2716     return NumPositiveBits;
   2717   }
   2718   void setNumPositiveBits(unsigned Num) {
   2719     NumPositiveBits = Num;
   2720     assert(NumPositiveBits == Num && "can't store this bitcount");
   2721   }
   2722 
   2723   /// \brief Returns the width in bits required to store all the
   2724   /// negative enumerators of this enum.  These widths include
   2725   /// the rightmost leading 1;  that is:
   2726   ///
   2727   /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
   2728   /// ------------------------     -------     -----------------
   2729   ///                       -1     1111111                     1
   2730   ///                      -10     1110110                     5
   2731   ///                     -101     1001011                     8
   2732   unsigned getNumNegativeBits() const {
   2733     return NumNegativeBits;
   2734   }
   2735   void setNumNegativeBits(unsigned Num) {
   2736     NumNegativeBits = Num;
   2737   }
   2738 
   2739   /// \brief Returns true if this is a C++0x scoped enumeration.
   2740   bool isScoped() const {
   2741     return IsScoped;
   2742   }
   2743 
   2744   /// \brief Returns true if this is a C++0x scoped enumeration.
   2745   bool isScopedUsingClassTag() const {
   2746     return IsScopedUsingClassTag;
   2747   }
   2748 
   2749   /// \brief Returns true if this is a C++0x enumeration with fixed underlying
   2750   /// type.
   2751   bool isFixed() const {
   2752     return IsFixed;
   2753   }
   2754 
   2755   /// \brief Returns true if this can be considered a complete type.
   2756   bool isComplete() const {
   2757     return isCompleteDefinition() || isFixed();
   2758   }
   2759 
   2760   /// \brief Returns the enumeration (declared within the template)
   2761   /// from which this enumeration type was instantiated, or NULL if
   2762   /// this enumeration was not instantiated from any template.
   2763   EnumDecl *getInstantiatedFromMemberEnum() const {
   2764     return InstantiatedFrom;
   2765   }
   2766 
   2767   void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
   2768 
   2769   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2770   static bool classof(const EnumDecl *D) { return true; }
   2771   static bool classofKind(Kind K) { return K == Enum; }
   2772 
   2773   friend class ASTDeclReader;
   2774 };
   2775 
   2776 
   2777 /// RecordDecl - Represents a struct/union/class.  For example:
   2778 ///   struct X;                  // Forward declaration, no "body".
   2779 ///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
   2780 /// This decl will be marked invalid if *any* members are invalid.
   2781 ///
   2782 class RecordDecl : public TagDecl {
   2783   // FIXME: This can be packed into the bitfields in Decl.
   2784   /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
   2785   /// array member (e.g. int X[]) or if this union contains a struct that does.
   2786   /// If so, this cannot be contained in arrays or other structs as a member.
   2787   bool HasFlexibleArrayMember : 1;
   2788 
   2789   /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
   2790   /// or union.
   2791   bool AnonymousStructOrUnion : 1;
   2792 
   2793   /// HasObjectMember - This is true if this struct has at least one member
   2794   /// containing an object.
   2795   bool HasObjectMember : 1;
   2796 
   2797   /// \brief Whether the field declarations of this record have been loaded
   2798   /// from external storage. To avoid unnecessary deserialization of
   2799   /// methods/nested types we allow deserialization of just the fields
   2800   /// when needed.
   2801   mutable bool LoadedFieldsFromExternalStorage : 1;
   2802   friend class DeclContext;
   2803 
   2804 protected:
   2805   RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
   2806              SourceLocation StartLoc, SourceLocation IdLoc,
   2807              IdentifierInfo *Id, RecordDecl *PrevDecl);
   2808 
   2809 public:
   2810   static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
   2811                             SourceLocation StartLoc, SourceLocation IdLoc,
   2812                             IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
   2813   static RecordDecl *Create(const ASTContext &C, EmptyShell Empty);
   2814 
   2815   const RecordDecl *getPreviousDeclaration() const {
   2816     return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
   2817   }
   2818   RecordDecl *getPreviousDeclaration() {
   2819     return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
   2820   }
   2821 
   2822   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
   2823   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
   2824 
   2825   /// isAnonymousStructOrUnion - Whether this is an anonymous struct
   2826   /// or union. To be an anonymous struct or union, it must have been
   2827   /// declared without a name and there must be no objects of this
   2828   /// type declared, e.g.,
   2829   /// @code
   2830   ///   union { int i; float f; };
   2831   /// @endcode
   2832   /// is an anonymous union but neither of the following are:
   2833   /// @code
   2834   ///  union X { int i; float f; };
   2835   ///  union { int i; float f; } obj;
   2836   /// @endcode
   2837   bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
   2838   void setAnonymousStructOrUnion(bool Anon) {
   2839     AnonymousStructOrUnion = Anon;
   2840   }
   2841 
   2842   bool hasObjectMember() const { return HasObjectMember; }
   2843   void setHasObjectMember (bool val) { HasObjectMember = val; }
   2844 
   2845   /// \brief Determines whether this declaration represents the
   2846   /// injected class name.
   2847   ///
   2848   /// The injected class name in C++ is the name of the class that
   2849   /// appears inside the class itself. For example:
   2850   ///
   2851   /// \code
   2852   /// struct C {
   2853   ///   // C is implicitly declared here as a synonym for the class name.
   2854   /// };
   2855   ///
   2856   /// C::C c; // same as "C c;"
   2857   /// \endcode
   2858   bool isInjectedClassName() const;
   2859 
   2860   /// getDefinition - Returns the RecordDecl that actually defines
   2861   ///  this struct/union/class.  When determining whether or not a
   2862   ///  struct/union/class is completely defined, one should use this
   2863   ///  method as opposed to 'isCompleteDefinition'.
   2864   ///  'isCompleteDefinition' indicates whether or not a specific
   2865   ///  RecordDecl is a completed definition, not whether or not the
   2866   ///  record type is defined.  This method returns NULL if there is
   2867   ///  no RecordDecl that defines the struct/union/tag.
   2868   RecordDecl *getDefinition() const {
   2869     return cast_or_null<RecordDecl>(TagDecl::getDefinition());
   2870   }
   2871 
   2872   // Iterator access to field members. The field iterator only visits
   2873   // the non-static data members of this class, ignoring any static
   2874   // data members, functions, constructors, destructors, etc.
   2875   typedef specific_decl_iterator<FieldDecl> field_iterator;
   2876 
   2877   field_iterator field_begin() const;
   2878 
   2879   field_iterator field_end() const {
   2880     return field_iterator(decl_iterator());
   2881   }
   2882 
   2883   // field_empty - Whether there are any fields (non-static data
   2884   // members) in this record.
   2885   bool field_empty() const {
   2886     return field_begin() == field_end();
   2887   }
   2888 
   2889   /// completeDefinition - Notes that the definition of this type is
   2890   /// now complete.
   2891   virtual void completeDefinition();
   2892 
   2893   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2894   static bool classof(const RecordDecl *D) { return true; }
   2895   static bool classofKind(Kind K) {
   2896     return K >= firstRecord && K <= lastRecord;
   2897   }
   2898 
   2899 private:
   2900   /// \brief Deserialize just the fields.
   2901   void LoadFieldsFromExternalStorage() const;
   2902 };
   2903 
   2904 class FileScopeAsmDecl : public Decl {
   2905   StringLiteral *AsmString;
   2906   SourceLocation RParenLoc;
   2907   FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
   2908                    SourceLocation StartL, SourceLocation EndL)
   2909     : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
   2910 public:
   2911   static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
   2912                                   StringLiteral *Str, SourceLocation AsmLoc,
   2913                                   SourceLocation RParenLoc);
   2914 
   2915   SourceLocation getAsmLoc() const { return getLocation(); }
   2916   SourceLocation getRParenLoc() const { return RParenLoc; }
   2917   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
   2918   SourceRange getSourceRange() const {
   2919     return SourceRange(getAsmLoc(), getRParenLoc());
   2920   }
   2921 
   2922   const StringLiteral *getAsmString() const { return AsmString; }
   2923   StringLiteral *getAsmString() { return AsmString; }
   2924   void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
   2925 
   2926   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2927   static bool classof(const FileScopeAsmDecl *D) { return true; }
   2928   static bool classofKind(Kind K) { return K == FileScopeAsm; }
   2929 };
   2930 
   2931 /// BlockDecl - This represents a block literal declaration, which is like an
   2932 /// unnamed FunctionDecl.  For example:
   2933 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
   2934 ///
   2935 class BlockDecl : public Decl, public DeclContext {
   2936 public:
   2937   /// A class which contains all the information about a particular
   2938   /// captured value.
   2939   class Capture {
   2940     enum {
   2941       flag_isByRef = 0x1,
   2942       flag_isNested = 0x2
   2943     };
   2944 
   2945     /// The variable being captured.
   2946     llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
   2947 
   2948     /// The copy expression, expressed in terms of a DeclRef (or
   2949     /// BlockDeclRef) to the captured variable.  Only required if the
   2950     /// variable has a C++ class type.
   2951     Expr *CopyExpr;
   2952 
   2953   public:
   2954     Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
   2955       : VariableAndFlags(variable,
   2956                   (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
   2957         CopyExpr(copy) {}
   2958 
   2959     /// The variable being captured.
   2960     VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
   2961 
   2962     /// Whether this is a "by ref" capture, i.e. a capture of a __block
   2963     /// variable.
   2964     bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
   2965 
   2966     /// Whether this is a nested capture, i.e. the variable captured
   2967     /// is not from outside the immediately enclosing function/block.
   2968     bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
   2969 
   2970     bool hasCopyExpr() const { return CopyExpr != 0; }
   2971     Expr *getCopyExpr() const { return CopyExpr; }
   2972     void setCopyExpr(Expr *e) { CopyExpr = e; }
   2973   };
   2974 
   2975 private:
   2976   // FIXME: This can be packed into the bitfields in Decl.
   2977   bool IsVariadic : 1;
   2978   bool CapturesCXXThis : 1;
   2979   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
   2980   /// parameters of this function.  This is null if a prototype or if there are
   2981   /// no formals.
   2982   ParmVarDecl **ParamInfo;
   2983   unsigned NumParams;
   2984 
   2985   Stmt *Body;
   2986   TypeSourceInfo *SignatureAsWritten;
   2987 
   2988   Capture *Captures;
   2989   unsigned NumCaptures;
   2990 
   2991 protected:
   2992   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
   2993     : Decl(Block, DC, CaretLoc), DeclContext(Block),
   2994       IsVariadic(false), CapturesCXXThis(false),
   2995       ParamInfo(0), NumParams(0), Body(0),
   2996       SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
   2997 
   2998 public:
   2999   static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
   3000 
   3001   SourceLocation getCaretLocation() const { return getLocation(); }
   3002 
   3003   bool isVariadic() const { return IsVariadic; }
   3004   void setIsVariadic(bool value) { IsVariadic = value; }
   3005 
   3006   CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
   3007   Stmt *getBody() const { return (Stmt*) Body; }
   3008   void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
   3009 
   3010   void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
   3011   TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
   3012 
   3013   // Iterator access to formal parameters.
   3014   unsigned param_size() const { return getNumParams(); }
   3015   typedef ParmVarDecl **param_iterator;
   3016   typedef ParmVarDecl * const *param_const_iterator;
   3017 
   3018   bool param_empty() const { return NumParams == 0; }
   3019   param_iterator param_begin()  { return ParamInfo; }
   3020   param_iterator param_end()   { return ParamInfo+param_size(); }
   3021 
   3022   param_const_iterator param_begin() const { return ParamInfo; }
   3023   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
   3024 
   3025   unsigned getNumParams() const { return NumParams; }
   3026   const ParmVarDecl *getParamDecl(unsigned i) const {
   3027     assert(i < getNumParams() && "Illegal param #");
   3028     return ParamInfo[i];
   3029   }
   3030   ParmVarDecl *getParamDecl(unsigned i) {
   3031     assert(i < getNumParams() && "Illegal param #");
   3032     return ParamInfo[i];
   3033   }
   3034   void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
   3035 
   3036   /// hasCaptures - True if this block (or its nested blocks) captures
   3037   /// anything of local storage from its enclosing scopes.
   3038   bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
   3039 
   3040   /// getNumCaptures - Returns the number of captured variables.
   3041   /// Does not include an entry for 'this'.
   3042   unsigned getNumCaptures() const { return NumCaptures; }
   3043 
   3044   typedef const Capture *capture_iterator;
   3045   typedef const Capture *capture_const_iterator;
   3046   capture_iterator capture_begin() { return Captures; }
   3047   capture_iterator capture_end() { return Captures + NumCaptures; }
   3048   capture_const_iterator capture_begin() const { return Captures; }
   3049   capture_const_iterator capture_end() const { return Captures + NumCaptures; }
   3050 
   3051   bool capturesCXXThis() const { return CapturesCXXThis; }
   3052 
   3053   bool capturesVariable(const VarDecl *var) const;
   3054 
   3055   void setCaptures(ASTContext &Context,
   3056                    const Capture *begin,
   3057                    const Capture *end,
   3058                    bool capturesCXXThis);
   3059 
   3060   virtual SourceRange getSourceRange() const;
   3061 
   3062   // Implement isa/cast/dyncast/etc.
   3063   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   3064   static bool classof(const BlockDecl *D) { return true; }
   3065   static bool classofKind(Kind K) { return K == Block; }
   3066   static DeclContext *castToDeclContext(const BlockDecl *D) {
   3067     return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
   3068   }
   3069   static BlockDecl *castFromDeclContext(const DeclContext *DC) {
   3070     return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
   3071   }
   3072 };
   3073 
   3074 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
   3075 /// into a diagnostic with <<.
   3076 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   3077                                            const NamedDecl* ND) {
   3078   DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
   3079                   DiagnosticsEngine::ak_nameddecl);
   3080   return DB;
   3081 }
   3082 
   3083 template<typename decl_type>
   3084 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
   3085   // Note: This routine is implemented here because we need both NamedDecl
   3086   // and Redeclarable to be defined.
   3087 
   3088   decl_type *First;
   3089 
   3090   if (PrevDecl) {
   3091     // Point to previous. Make sure that this is actually the most recent
   3092     // redeclaration, or we can build invalid chains. If the most recent
   3093     // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
   3094     RedeclLink = PreviousDeclLink(llvm::cast<decl_type>(
   3095                                                         PrevDecl->getMostRecentDeclaration()));
   3096     First = PrevDecl->getFirstDeclaration();
   3097     assert(First->RedeclLink.NextIsLatest() && "Expected first");
   3098   } else {
   3099     // Make this first.
   3100     First = static_cast<decl_type*>(this);
   3101   }
   3102 
   3103   // First one will point to this one as latest.
   3104   First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
   3105   if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
   3106     ND->ClearLinkageCache();
   3107 }
   3108 
   3109 }  // end namespace clang
   3110 
   3111 #endif
   3112