Home | History | Annotate | Download | only in AST
      1 //===-- DeclBase.h - Base 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 and DeclContext interfaces.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_AST_DECLBASE_H
     15 #define LLVM_CLANG_AST_DECLBASE_H
     16 
     17 #include "clang/AST/AttrIterator.h"
     18 #include "clang/AST/DeclarationName.h"
     19 #include "clang/Basic/Linkage.h"
     20 #include "clang/Basic/Specifiers.h"
     21 #include "llvm/ADT/PointerUnion.h"
     22 #include "llvm/Support/Compiler.h"
     23 #include "llvm/Support/PrettyStackTrace.h"
     24 
     25 namespace clang {
     26 class ASTMutationListener;
     27 class BlockDecl;
     28 class CXXRecordDecl;
     29 class CompoundStmt;
     30 class DeclContext;
     31 class DeclarationName;
     32 class DependentDiagnostic;
     33 class EnumDecl;
     34 class FunctionDecl;
     35 class LinkageComputer;
     36 class LinkageSpecDecl;
     37 class Module;
     38 class NamedDecl;
     39 class NamespaceDecl;
     40 class ObjCCategoryDecl;
     41 class ObjCCategoryImplDecl;
     42 class ObjCContainerDecl;
     43 class ObjCImplDecl;
     44 class ObjCImplementationDecl;
     45 class ObjCInterfaceDecl;
     46 class ObjCMethodDecl;
     47 class ObjCProtocolDecl;
     48 struct PrintingPolicy;
     49 class Stmt;
     50 class StoredDeclsMap;
     51 class TranslationUnitDecl;
     52 class UsingDirectiveDecl;
     53 }
     54 
     55 namespace llvm {
     56 // DeclContext* is only 4-byte aligned on 32-bit systems.
     57 template<>
     58   class PointerLikeTypeTraits<clang::DeclContext*> {
     59   typedef clang::DeclContext* PT;
     60 public:
     61   static inline void *getAsVoidPointer(PT P) { return P; }
     62   static inline PT getFromVoidPointer(void *P) {
     63     return static_cast<PT>(P);
     64   }
     65   enum { NumLowBitsAvailable = 2 };
     66 };
     67 }
     68 
     69 namespace clang {
     70 
     71   /// \brief Captures the result of checking the availability of a
     72   /// declaration.
     73   enum AvailabilityResult {
     74     AR_Available = 0,
     75     AR_NotYetIntroduced,
     76     AR_Deprecated,
     77     AR_Unavailable
     78   };
     79 
     80 /// Decl - This represents one declaration (or definition), e.g. a variable,
     81 /// typedef, function, struct, etc.
     82 ///
     83 class Decl {
     84 public:
     85   /// \brief Lists the kind of concrete classes of Decl.
     86   enum Kind {
     87 #define DECL(DERIVED, BASE) DERIVED,
     88 #define ABSTRACT_DECL(DECL)
     89 #define DECL_RANGE(BASE, START, END) \
     90         first##BASE = START, last##BASE = END,
     91 #define LAST_DECL_RANGE(BASE, START, END) \
     92         first##BASE = START, last##BASE = END
     93 #include "clang/AST/DeclNodes.inc"
     94   };
     95 
     96   /// \brief A placeholder type used to construct an empty shell of a
     97   /// decl-derived type that will be filled in later (e.g., by some
     98   /// deserialization method).
     99   struct EmptyShell { };
    100 
    101   /// IdentifierNamespace - The different namespaces in which
    102   /// declarations may appear.  According to C99 6.2.3, there are
    103   /// four namespaces, labels, tags, members and ordinary
    104   /// identifiers.  C++ describes lookup completely differently:
    105   /// certain lookups merely "ignore" certain kinds of declarations,
    106   /// usually based on whether the declaration is of a type, etc.
    107   ///
    108   /// These are meant as bitmasks, so that searches in
    109   /// C++ can look into the "tag" namespace during ordinary lookup.
    110   ///
    111   /// Decl currently provides 15 bits of IDNS bits.
    112   enum IdentifierNamespace {
    113     /// Labels, declared with 'x:' and referenced with 'goto x'.
    114     IDNS_Label               = 0x0001,
    115 
    116     /// Tags, declared with 'struct foo;' and referenced with
    117     /// 'struct foo'.  All tags are also types.  This is what
    118     /// elaborated-type-specifiers look for in C.
    119     IDNS_Tag                 = 0x0002,
    120 
    121     /// Types, declared with 'struct foo', typedefs, etc.
    122     /// This is what elaborated-type-specifiers look for in C++,
    123     /// but note that it's ill-formed to find a non-tag.
    124     IDNS_Type                = 0x0004,
    125 
    126     /// Members, declared with object declarations within tag
    127     /// definitions.  In C, these can only be found by "qualified"
    128     /// lookup in member expressions.  In C++, they're found by
    129     /// normal lookup.
    130     IDNS_Member              = 0x0008,
    131 
    132     /// Namespaces, declared with 'namespace foo {}'.
    133     /// Lookup for nested-name-specifiers find these.
    134     IDNS_Namespace           = 0x0010,
    135 
    136     /// Ordinary names.  In C, everything that's not a label, tag,
    137     /// or member ends up here.
    138     IDNS_Ordinary            = 0x0020,
    139 
    140     /// Objective C \@protocol.
    141     IDNS_ObjCProtocol        = 0x0040,
    142 
    143     /// This declaration is a friend function.  A friend function
    144     /// declaration is always in this namespace but may also be in
    145     /// IDNS_Ordinary if it was previously declared.
    146     IDNS_OrdinaryFriend      = 0x0080,
    147 
    148     /// This declaration is a friend class.  A friend class
    149     /// declaration is always in this namespace but may also be in
    150     /// IDNS_Tag|IDNS_Type if it was previously declared.
    151     IDNS_TagFriend           = 0x0100,
    152 
    153     /// This declaration is a using declaration.  A using declaration
    154     /// *introduces* a number of other declarations into the current
    155     /// scope, and those declarations use the IDNS of their targets,
    156     /// but the actual using declarations go in this namespace.
    157     IDNS_Using               = 0x0200,
    158 
    159     /// This declaration is a C++ operator declared in a non-class
    160     /// context.  All such operators are also in IDNS_Ordinary.
    161     /// C++ lexical operator lookup looks for these.
    162     IDNS_NonMemberOperator   = 0x0400
    163   };
    164 
    165   /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
    166   /// parameter types in method declarations.  Other than remembering
    167   /// them and mangling them into the method's signature string, these
    168   /// are ignored by the compiler; they are consumed by certain
    169   /// remote-messaging frameworks.
    170   ///
    171   /// in, inout, and out are mutually exclusive and apply only to
    172   /// method parameters.  bycopy and byref are mutually exclusive and
    173   /// apply only to method parameters (?).  oneway applies only to
    174   /// results.  All of these expect their corresponding parameter to
    175   /// have a particular type.  None of this is currently enforced by
    176   /// clang.
    177   ///
    178   /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
    179   enum ObjCDeclQualifier {
    180     OBJC_TQ_None = 0x0,
    181     OBJC_TQ_In = 0x1,
    182     OBJC_TQ_Inout = 0x2,
    183     OBJC_TQ_Out = 0x4,
    184     OBJC_TQ_Bycopy = 0x8,
    185     OBJC_TQ_Byref = 0x10,
    186     OBJC_TQ_Oneway = 0x20
    187   };
    188 
    189 protected:
    190   // Enumeration values used in the bits stored in NextInContextAndBits.
    191   enum {
    192     /// \brief Whether this declaration is a top-level declaration (function,
    193     /// global variable, etc.) that is lexically inside an objc container
    194     /// definition.
    195     TopLevelDeclInObjCContainerFlag = 0x01,
    196 
    197     /// \brief Whether this declaration is private to the module in which it was
    198     /// defined.
    199     ModulePrivateFlag = 0x02
    200   };
    201 
    202   /// \brief The next declaration within the same lexical
    203   /// DeclContext. These pointers form the linked list that is
    204   /// traversed via DeclContext's decls_begin()/decls_end().
    205   ///
    206   /// The extra two bits are used for the TopLevelDeclInObjCContainer and
    207   /// ModulePrivate bits.
    208   llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
    209 
    210 private:
    211   friend class DeclContext;
    212 
    213   struct MultipleDC {
    214     DeclContext *SemanticDC;
    215     DeclContext *LexicalDC;
    216   };
    217 
    218 
    219   /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
    220   /// For declarations that don't contain C++ scope specifiers, it contains
    221   /// the DeclContext where the Decl was declared.
    222   /// For declarations with C++ scope specifiers, it contains a MultipleDC*
    223   /// with the context where it semantically belongs (SemanticDC) and the
    224   /// context where it was lexically declared (LexicalDC).
    225   /// e.g.:
    226   ///
    227   ///   namespace A {
    228   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
    229   ///   }
    230   ///   void A::f(); // SemanticDC == namespace 'A'
    231   ///                // LexicalDC == global namespace
    232   llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
    233 
    234   inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
    235   inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
    236   inline MultipleDC *getMultipleDC() const {
    237     return DeclCtx.get<MultipleDC*>();
    238   }
    239   inline DeclContext *getSemanticDC() const {
    240     return DeclCtx.get<DeclContext*>();
    241   }
    242 
    243   /// Loc - The location of this decl.
    244   SourceLocation Loc;
    245 
    246   /// DeclKind - This indicates which class this is.
    247   unsigned DeclKind : 8;
    248 
    249   /// InvalidDecl - This indicates a semantic error occurred.
    250   unsigned InvalidDecl :  1;
    251 
    252   /// HasAttrs - This indicates whether the decl has attributes or not.
    253   unsigned HasAttrs : 1;
    254 
    255   /// Implicit - Whether this declaration was implicitly generated by
    256   /// the implementation rather than explicitly written by the user.
    257   unsigned Implicit : 1;
    258 
    259   /// \brief Whether this declaration was "used", meaning that a definition is
    260   /// required.
    261   unsigned Used : 1;
    262 
    263   /// \brief Whether this declaration was "referenced".
    264   /// The difference with 'Used' is whether the reference appears in a
    265   /// evaluated context or not, e.g. functions used in uninstantiated templates
    266   /// are regarded as "referenced" but not "used".
    267   unsigned Referenced : 1;
    268 
    269   /// \brief Whether statistic collection is enabled.
    270   static bool StatisticsEnabled;
    271 
    272 protected:
    273   /// Access - Used by C++ decls for the access specifier.
    274   // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
    275   unsigned Access : 2;
    276   friend class CXXClassMemberWrapper;
    277 
    278   /// \brief Whether this declaration was loaded from an AST file.
    279   unsigned FromASTFile : 1;
    280 
    281   /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
    282   /// because it is was loaded from an AST file is either module-private or
    283   /// because its submodule has not been made visible.
    284   unsigned Hidden : 1;
    285 
    286   /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
    287   unsigned IdentifierNamespace : 12;
    288 
    289   /// \brief If 0, we have not computed the linkage of this declaration.
    290   /// Otherwise, it is the linkage + 1.
    291   mutable unsigned CacheValidAndLinkage : 3;
    292 
    293   friend class ASTDeclWriter;
    294   friend class ASTDeclReader;
    295   friend class ASTReader;
    296   friend class LinkageComputer;
    297 
    298   template<typename decl_type> friend class Redeclarable;
    299 
    300 private:
    301   void CheckAccessDeclContext() const;
    302 
    303 protected:
    304 
    305   Decl(Kind DK, DeclContext *DC, SourceLocation L)
    306     : NextInContextAndBits(), DeclCtx(DC),
    307       Loc(L), DeclKind(DK), InvalidDecl(0),
    308       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
    309       Access(AS_none), FromASTFile(0), Hidden(0),
    310       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
    311       CacheValidAndLinkage(0)
    312   {
    313     if (StatisticsEnabled) add(DK);
    314   }
    315 
    316   Decl(Kind DK, EmptyShell Empty)
    317     : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
    318       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
    319       Access(AS_none), FromASTFile(0), Hidden(0),
    320       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
    321       CacheValidAndLinkage(0)
    322   {
    323     if (StatisticsEnabled) add(DK);
    324   }
    325 
    326   virtual ~Decl();
    327 
    328   /// \brief Allocate memory for a deserialized declaration.
    329   ///
    330   /// This routine must be used to allocate memory for any declaration that is
    331   /// deserialized from a module file.
    332   ///
    333   /// \param Context The context in which we will allocate memory.
    334   /// \param ID The global ID of the deserialized declaration.
    335   /// \param Size The size of the allocated object.
    336   static void *AllocateDeserializedDecl(const ASTContext &Context,
    337                                         unsigned ID,
    338                                         unsigned Size);
    339 
    340   /// \brief Update a potentially out-of-date declaration.
    341   void updateOutOfDate(IdentifierInfo &II) const;
    342 
    343   Linkage getCachedLinkage() const {
    344     return Linkage(CacheValidAndLinkage - 1);
    345   }
    346 
    347   void setCachedLinkage(Linkage L) const {
    348     CacheValidAndLinkage = L + 1;
    349   }
    350 
    351   bool hasCachedLinkage() const {
    352     return CacheValidAndLinkage;
    353   }
    354 
    355 public:
    356 
    357   /// \brief Source range that this declaration covers.
    358   virtual SourceRange getSourceRange() const LLVM_READONLY {
    359     return SourceRange(getLocation(), getLocation());
    360   }
    361   SourceLocation getLocStart() const LLVM_READONLY {
    362     return getSourceRange().getBegin();
    363   }
    364   SourceLocation getLocEnd() const LLVM_READONLY {
    365     return getSourceRange().getEnd();
    366   }
    367 
    368   SourceLocation getLocation() const { return Loc; }
    369   void setLocation(SourceLocation L) { Loc = L; }
    370 
    371   Kind getKind() const { return static_cast<Kind>(DeclKind); }
    372   const char *getDeclKindName() const;
    373 
    374   Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
    375   const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
    376 
    377   DeclContext *getDeclContext() {
    378     if (isInSemaDC())
    379       return getSemanticDC();
    380     return getMultipleDC()->SemanticDC;
    381   }
    382   const DeclContext *getDeclContext() const {
    383     return const_cast<Decl*>(this)->getDeclContext();
    384   }
    385 
    386   /// Find the innermost non-closure ancestor of this declaration,
    387   /// walking up through blocks, lambdas, etc.  If that ancestor is
    388   /// not a code context (!isFunctionOrMethod()), returns null.
    389   ///
    390   /// A declaration may be its own non-closure context.
    391   Decl *getNonClosureContext();
    392   const Decl *getNonClosureContext() const {
    393     return const_cast<Decl*>(this)->getNonClosureContext();
    394   }
    395 
    396   TranslationUnitDecl *getTranslationUnitDecl();
    397   const TranslationUnitDecl *getTranslationUnitDecl() const {
    398     return const_cast<Decl*>(this)->getTranslationUnitDecl();
    399   }
    400 
    401   bool isInAnonymousNamespace() const;
    402 
    403   ASTContext &getASTContext() const LLVM_READONLY;
    404 
    405   void setAccess(AccessSpecifier AS) {
    406     Access = AS;
    407 #ifndef NDEBUG
    408     CheckAccessDeclContext();
    409 #endif
    410   }
    411 
    412   AccessSpecifier getAccess() const {
    413 #ifndef NDEBUG
    414     CheckAccessDeclContext();
    415 #endif
    416     return AccessSpecifier(Access);
    417   }
    418 
    419   /// \brief Retrieve the access specifier for this declaration, even though
    420   /// it may not yet have been properly set.
    421   AccessSpecifier getAccessUnsafe() const {
    422     return AccessSpecifier(Access);
    423   }
    424 
    425   bool hasAttrs() const { return HasAttrs; }
    426   void setAttrs(const AttrVec& Attrs) {
    427     return setAttrsImpl(Attrs, getASTContext());
    428   }
    429   AttrVec &getAttrs() {
    430     return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
    431   }
    432   const AttrVec &getAttrs() const;
    433   void dropAttrs();
    434 
    435   void addAttr(Attr *A) {
    436     if (hasAttrs())
    437       getAttrs().push_back(A);
    438     else
    439       setAttrs(AttrVec(1, A));
    440   }
    441 
    442   typedef AttrVec::const_iterator attr_iterator;
    443 
    444   // FIXME: Do not rely on iterators having comparable singular values.
    445   //        Note that this should error out if they do not.
    446   attr_iterator attr_begin() const {
    447     return hasAttrs() ? getAttrs().begin() : 0;
    448   }
    449   attr_iterator attr_end() const {
    450     return hasAttrs() ? getAttrs().end() : 0;
    451   }
    452 
    453   template <typename T>
    454   void dropAttr() {
    455     if (!HasAttrs) return;
    456 
    457     AttrVec &Vec = getAttrs();
    458     Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
    459 
    460     if (Vec.empty())
    461       HasAttrs = false;
    462   }
    463 
    464   template <typename T>
    465   specific_attr_iterator<T> specific_attr_begin() const {
    466     return specific_attr_iterator<T>(attr_begin());
    467   }
    468   template <typename T>
    469   specific_attr_iterator<T> specific_attr_end() const {
    470     return specific_attr_iterator<T>(attr_end());
    471   }
    472 
    473   template<typename T> T *getAttr() const {
    474     return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0;
    475   }
    476   template<typename T> bool hasAttr() const {
    477     return hasAttrs() && hasSpecificAttr<T>(getAttrs());
    478   }
    479 
    480   /// getMaxAlignment - return the maximum alignment specified by attributes
    481   /// on this decl, 0 if there are none.
    482   unsigned getMaxAlignment() const;
    483 
    484   /// setInvalidDecl - Indicates the Decl had a semantic error. This
    485   /// allows for graceful error recovery.
    486   void setInvalidDecl(bool Invalid = true);
    487   bool isInvalidDecl() const { return (bool) InvalidDecl; }
    488 
    489   /// isImplicit - Indicates whether the declaration was implicitly
    490   /// generated by the implementation. If false, this declaration
    491   /// was written explicitly in the source code.
    492   bool isImplicit() const { return Implicit; }
    493   void setImplicit(bool I = true) { Implicit = I; }
    494 
    495   /// \brief Whether this declaration was used, meaning that a definition
    496   /// is required.
    497   ///
    498   /// \param CheckUsedAttr When true, also consider the "used" attribute
    499   /// (in addition to the "used" bit set by \c setUsed()) when determining
    500   /// whether the function is used.
    501   bool isUsed(bool CheckUsedAttr = true) const;
    502 
    503   void setUsed(bool U = true) { Used = U; }
    504 
    505   /// \brief Whether this declaration was referenced.
    506   bool isReferenced() const;
    507 
    508   void setReferenced(bool R = true) { Referenced = R; }
    509 
    510   /// \brief Whether this declaration is a top-level declaration (function,
    511   /// global variable, etc.) that is lexically inside an objc container
    512   /// definition.
    513   bool isTopLevelDeclInObjCContainer() const {
    514     return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
    515   }
    516 
    517   void setTopLevelDeclInObjCContainer(bool V = true) {
    518     unsigned Bits = NextInContextAndBits.getInt();
    519     if (V)
    520       Bits |= TopLevelDeclInObjCContainerFlag;
    521     else
    522       Bits &= ~TopLevelDeclInObjCContainerFlag;
    523     NextInContextAndBits.setInt(Bits);
    524   }
    525 
    526   /// \brief Whether this declaration was marked as being private to the
    527   /// module in which it was defined.
    528   bool isModulePrivate() const {
    529     return NextInContextAndBits.getInt() & ModulePrivateFlag;
    530   }
    531 
    532 protected:
    533   /// \brief Specify whether this declaration was marked as being private
    534   /// to the module in which it was defined.
    535   void setModulePrivate(bool MP = true) {
    536     unsigned Bits = NextInContextAndBits.getInt();
    537     if (MP)
    538       Bits |= ModulePrivateFlag;
    539     else
    540       Bits &= ~ModulePrivateFlag;
    541     NextInContextAndBits.setInt(Bits);
    542   }
    543 
    544   /// \brief Set the owning module ID.
    545   void setOwningModuleID(unsigned ID) {
    546     assert(isFromASTFile() && "Only works on a deserialized declaration");
    547     *((unsigned*)this - 2) = ID;
    548   }
    549 
    550 public:
    551 
    552   /// \brief Determine the availability of the given declaration.
    553   ///
    554   /// This routine will determine the most restrictive availability of
    555   /// the given declaration (e.g., preferring 'unavailable' to
    556   /// 'deprecated').
    557   ///
    558   /// \param Message If non-NULL and the result is not \c
    559   /// AR_Available, will be set to a (possibly empty) message
    560   /// describing why the declaration has not been introduced, is
    561   /// deprecated, or is unavailable.
    562   AvailabilityResult getAvailability(std::string *Message = 0) const;
    563 
    564   /// \brief Determine whether this declaration is marked 'deprecated'.
    565   ///
    566   /// \param Message If non-NULL and the declaration is deprecated,
    567   /// this will be set to the message describing why the declaration
    568   /// was deprecated (which may be empty).
    569   bool isDeprecated(std::string *Message = 0) const {
    570     return getAvailability(Message) == AR_Deprecated;
    571   }
    572 
    573   /// \brief Determine whether this declaration is marked 'unavailable'.
    574   ///
    575   /// \param Message If non-NULL and the declaration is unavailable,
    576   /// this will be set to the message describing why the declaration
    577   /// was made unavailable (which may be empty).
    578   bool isUnavailable(std::string *Message = 0) const {
    579     return getAvailability(Message) == AR_Unavailable;
    580   }
    581 
    582   /// \brief Determine whether this is a weak-imported symbol.
    583   ///
    584   /// Weak-imported symbols are typically marked with the
    585   /// 'weak_import' attribute, but may also be marked with an
    586   /// 'availability' attribute where we're targing a platform prior to
    587   /// the introduction of this feature.
    588   bool isWeakImported() const;
    589 
    590   /// \brief Determines whether this symbol can be weak-imported,
    591   /// e.g., whether it would be well-formed to add the weak_import
    592   /// attribute.
    593   ///
    594   /// \param IsDefinition Set to \c true to indicate that this
    595   /// declaration cannot be weak-imported because it has a definition.
    596   bool canBeWeakImported(bool &IsDefinition) const;
    597 
    598   /// \brief Determine whether this declaration came from an AST file (such as
    599   /// a precompiled header or module) rather than having been parsed.
    600   bool isFromASTFile() const { return FromASTFile; }
    601 
    602   /// \brief Retrieve the global declaration ID associated with this
    603   /// declaration, which specifies where in the
    604   unsigned getGlobalID() const {
    605     if (isFromASTFile())
    606       return *((const unsigned*)this - 1);
    607     return 0;
    608   }
    609 
    610   /// \brief Retrieve the global ID of the module that owns this particular
    611   /// declaration.
    612   unsigned getOwningModuleID() const {
    613     if (isFromASTFile())
    614       return *((const unsigned*)this - 2);
    615 
    616     return 0;
    617   }
    618 
    619 private:
    620   Module *getOwningModuleSlow() const;
    621 
    622 public:
    623   Module *getOwningModule() const {
    624     if (!isFromASTFile())
    625       return 0;
    626 
    627     return getOwningModuleSlow();
    628   }
    629 
    630   unsigned getIdentifierNamespace() const {
    631     return IdentifierNamespace;
    632   }
    633   bool isInIdentifierNamespace(unsigned NS) const {
    634     return getIdentifierNamespace() & NS;
    635   }
    636   static unsigned getIdentifierNamespaceForKind(Kind DK);
    637 
    638   bool hasTagIdentifierNamespace() const {
    639     return isTagIdentifierNamespace(getIdentifierNamespace());
    640   }
    641   static bool isTagIdentifierNamespace(unsigned NS) {
    642     // TagDecls have Tag and Type set and may also have TagFriend.
    643     return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
    644   }
    645 
    646   /// getLexicalDeclContext - The declaration context where this Decl was
    647   /// lexically declared (LexicalDC). May be different from
    648   /// getDeclContext() (SemanticDC).
    649   /// e.g.:
    650   ///
    651   ///   namespace A {
    652   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
    653   ///   }
    654   ///   void A::f(); // SemanticDC == namespace 'A'
    655   ///                // LexicalDC == global namespace
    656   DeclContext *getLexicalDeclContext() {
    657     if (isInSemaDC())
    658       return getSemanticDC();
    659     return getMultipleDC()->LexicalDC;
    660   }
    661   const DeclContext *getLexicalDeclContext() const {
    662     return const_cast<Decl*>(this)->getLexicalDeclContext();
    663   }
    664 
    665   virtual bool isOutOfLine() const {
    666     return getLexicalDeclContext() != getDeclContext();
    667   }
    668 
    669   /// setDeclContext - Set both the semantic and lexical DeclContext
    670   /// to DC.
    671   void setDeclContext(DeclContext *DC);
    672 
    673   void setLexicalDeclContext(DeclContext *DC);
    674 
    675   /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
    676   /// scoped decl is defined outside the current function or method.  This is
    677   /// roughly global variables and functions, but also handles enums (which
    678   /// could be defined inside or outside a function etc).
    679   bool isDefinedOutsideFunctionOrMethod() const {
    680     return getParentFunctionOrMethod() == 0;
    681   }
    682 
    683   /// \brief If this decl is defined inside a function/method/block it returns
    684   /// the corresponding DeclContext, otherwise it returns null.
    685   const DeclContext *getParentFunctionOrMethod() const;
    686   DeclContext *getParentFunctionOrMethod() {
    687     return const_cast<DeclContext*>(
    688                     const_cast<const Decl*>(this)->getParentFunctionOrMethod());
    689   }
    690 
    691   /// \brief Retrieves the "canonical" declaration of the given declaration.
    692   virtual Decl *getCanonicalDecl() { return this; }
    693   const Decl *getCanonicalDecl() const {
    694     return const_cast<Decl*>(this)->getCanonicalDecl();
    695   }
    696 
    697   /// \brief Whether this particular Decl is a canonical one.
    698   bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
    699 
    700 protected:
    701   /// \brief Returns the next redeclaration or itself if this is the only decl.
    702   ///
    703   /// Decl subclasses that can be redeclared should override this method so that
    704   /// Decl::redecl_iterator can iterate over them.
    705   virtual Decl *getNextRedeclaration() { return this; }
    706 
    707   /// \brief Implementation of getPreviousDecl(), to be overridden by any
    708   /// subclass that has a redeclaration chain.
    709   virtual Decl *getPreviousDeclImpl() { return 0; }
    710 
    711   /// \brief Implementation of getMostRecentDecl(), to be overridden by any
    712   /// subclass that has a redeclaration chain.
    713   virtual Decl *getMostRecentDeclImpl() { return this; }
    714 
    715 public:
    716   /// \brief Iterates through all the redeclarations of the same decl.
    717   class redecl_iterator {
    718     /// Current - The current declaration.
    719     Decl *Current;
    720     Decl *Starter;
    721 
    722   public:
    723     typedef Decl *value_type;
    724     typedef const value_type &reference;
    725     typedef const value_type *pointer;
    726     typedef std::forward_iterator_tag iterator_category;
    727     typedef std::ptrdiff_t difference_type;
    728 
    729     redecl_iterator() : Current(0) { }
    730     explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
    731 
    732     reference operator*() const { return Current; }
    733     value_type operator->() const { return Current; }
    734 
    735     redecl_iterator& operator++() {
    736       assert(Current && "Advancing while iterator has reached end");
    737       // Get either previous decl or latest decl.
    738       Decl *Next = Current->getNextRedeclaration();
    739       assert(Next && "Should return next redeclaration or itself, never null!");
    740       Current = (Next != Starter ? Next : 0);
    741       return *this;
    742     }
    743 
    744     redecl_iterator operator++(int) {
    745       redecl_iterator tmp(*this);
    746       ++(*this);
    747       return tmp;
    748     }
    749 
    750     friend bool operator==(redecl_iterator x, redecl_iterator y) {
    751       return x.Current == y.Current;
    752     }
    753     friend bool operator!=(redecl_iterator x, redecl_iterator y) {
    754       return x.Current != y.Current;
    755     }
    756   };
    757 
    758   /// \brief Returns iterator for all the redeclarations of the same decl.
    759   /// It will iterate at least once (when this decl is the only one).
    760   redecl_iterator redecls_begin() const {
    761     return redecl_iterator(const_cast<Decl*>(this));
    762   }
    763   redecl_iterator redecls_end() const { return redecl_iterator(); }
    764 
    765   /// \brief Retrieve the previous declaration that declares the same entity
    766   /// as this declaration, or NULL if there is no previous declaration.
    767   Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
    768 
    769   /// \brief Retrieve the most recent declaration that declares the same entity
    770   /// as this declaration, or NULL if there is no previous declaration.
    771   const Decl *getPreviousDecl() const {
    772     return const_cast<Decl *>(this)->getPreviousDeclImpl();
    773   }
    774 
    775   /// \brief Retrieve the most recent declaration that declares the same entity
    776   /// as this declaration (which may be this declaration).
    777   Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
    778 
    779   /// \brief Retrieve the most recent declaration that declares the same entity
    780   /// as this declaration (which may be this declaration).
    781   const Decl *getMostRecentDecl() const {
    782     return const_cast<Decl *>(this)->getMostRecentDeclImpl();
    783   }
    784 
    785   /// getBody - If this Decl represents a declaration for a body of code,
    786   ///  such as a function or method definition, this method returns the
    787   ///  top-level Stmt* of that body.  Otherwise this method returns null.
    788   virtual Stmt* getBody() const { return 0; }
    789 
    790   /// \brief Returns true if this \c Decl represents a declaration for a body of
    791   /// code, such as a function or method definition.
    792   /// Note that \c hasBody can also return true if any redeclaration of this
    793   /// \c Decl represents a declaration for a body of code.
    794   virtual bool hasBody() const { return getBody() != 0; }
    795 
    796   /// getBodyRBrace - Gets the right brace of the body, if a body exists.
    797   /// This works whether the body is a CompoundStmt or a CXXTryStmt.
    798   SourceLocation getBodyRBrace() const;
    799 
    800   // global temp stats (until we have a per-module visitor)
    801   static void add(Kind k);
    802   static void EnableStatistics();
    803   static void PrintStats();
    804 
    805   /// isTemplateParameter - Determines whether this declaration is a
    806   /// template parameter.
    807   bool isTemplateParameter() const;
    808 
    809   /// isTemplateParameter - Determines whether this declaration is a
    810   /// template parameter pack.
    811   bool isTemplateParameterPack() const;
    812 
    813   /// \brief Whether this declaration is a parameter pack.
    814   bool isParameterPack() const;
    815 
    816   /// \brief returns true if this declaration is a template
    817   bool isTemplateDecl() const;
    818 
    819   /// \brief Whether this declaration is a function or function template.
    820   bool isFunctionOrFunctionTemplate() const;
    821 
    822   /// \brief Changes the namespace of this declaration to reflect that it's
    823   /// the object of a friend declaration.
    824   ///
    825   /// These declarations appear in the lexical context of the friending
    826   /// class, but in the semantic context of the actual entity.  This property
    827   /// applies only to a specific decl object;  other redeclarations of the
    828   /// same entity may not (and probably don't) share this property.
    829   void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
    830     unsigned OldNS = IdentifierNamespace;
    831     assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
    832                      IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
    833            "namespace includes neither ordinary nor tag");
    834     assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
    835                        IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
    836            "namespace includes other than ordinary or tag");
    837 
    838     Decl *Prev = getPreviousDecl();
    839     IdentifierNamespace = 0;
    840     if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
    841       IdentifierNamespace |= IDNS_TagFriend;
    842       if (PerformFriendInjection ||
    843           (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
    844         IdentifierNamespace |= IDNS_Tag | IDNS_Type;
    845     }
    846 
    847     if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) {
    848       IdentifierNamespace |= IDNS_OrdinaryFriend;
    849       if (PerformFriendInjection ||
    850           (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
    851         IdentifierNamespace |= IDNS_Ordinary;
    852     }
    853   }
    854 
    855   enum FriendObjectKind {
    856     FOK_None,      ///< Not a friend object.
    857     FOK_Declared,  ///< A friend of a previously-declared entity.
    858     FOK_Undeclared ///< A friend of a previously-undeclared entity.
    859   };
    860 
    861   /// \brief Determines whether this declaration is the object of a
    862   /// friend declaration and, if so, what kind.
    863   ///
    864   /// There is currently no direct way to find the associated FriendDecl.
    865   FriendObjectKind getFriendObjectKind() const {
    866     unsigned mask =
    867         (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
    868     if (!mask) return FOK_None;
    869     return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
    870                                                              : FOK_Undeclared);
    871   }
    872 
    873   /// Specifies that this declaration is a C++ overloaded non-member.
    874   void setNonMemberOperator() {
    875     assert(getKind() == Function || getKind() == FunctionTemplate);
    876     assert((IdentifierNamespace & IDNS_Ordinary) &&
    877            "visible non-member operators should be in ordinary namespace");
    878     IdentifierNamespace |= IDNS_NonMemberOperator;
    879   }
    880 
    881   static bool classofKind(Kind K) { return true; }
    882   static DeclContext *castToDeclContext(const Decl *);
    883   static Decl *castFromDeclContext(const DeclContext *);
    884 
    885   void print(raw_ostream &Out, unsigned Indentation = 0,
    886              bool PrintInstantiation = false) const;
    887   void print(raw_ostream &Out, const PrintingPolicy &Policy,
    888              unsigned Indentation = 0, bool PrintInstantiation = false) const;
    889   static void printGroup(Decl** Begin, unsigned NumDecls,
    890                          raw_ostream &Out, const PrintingPolicy &Policy,
    891                          unsigned Indentation = 0);
    892   // Debuggers don't usually respect default arguments.
    893   LLVM_ATTRIBUTE_USED void dump() const;
    894   // Same as dump(), but forces color printing.
    895   LLVM_ATTRIBUTE_USED void dumpColor() const;
    896   void dump(raw_ostream &Out) const;
    897   // Debuggers don't usually respect default arguments.
    898   LLVM_ATTRIBUTE_USED void dumpXML() const;
    899   void dumpXML(raw_ostream &OS) const;
    900 
    901 private:
    902   void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
    903   void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
    904                            ASTContext &Ctx);
    905 
    906 protected:
    907   ASTMutationListener *getASTMutationListener() const;
    908 };
    909 
    910 /// \brief Determine whether two declarations declare the same entity.
    911 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
    912   if (!D1 || !D2)
    913     return false;
    914 
    915   if (D1 == D2)
    916     return true;
    917 
    918   return D1->getCanonicalDecl() == D2->getCanonicalDecl();
    919 }
    920 
    921 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
    922 /// doing something to a specific decl.
    923 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
    924   const Decl *TheDecl;
    925   SourceLocation Loc;
    926   SourceManager &SM;
    927   const char *Message;
    928 public:
    929   PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
    930                        SourceManager &sm, const char *Msg)
    931   : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
    932 
    933   virtual void print(raw_ostream &OS) const;
    934 };
    935 
    936 typedef llvm::MutableArrayRef<NamedDecl*> DeclContextLookupResult;
    937 
    938 typedef ArrayRef<NamedDecl *> DeclContextLookupConstResult;
    939 
    940 /// DeclContext - This is used only as base class of specific decl types that
    941 /// can act as declaration contexts. These decls are (only the top classes
    942 /// that directly derive from DeclContext are mentioned, not their subclasses):
    943 ///
    944 ///   TranslationUnitDecl
    945 ///   NamespaceDecl
    946 ///   FunctionDecl
    947 ///   TagDecl
    948 ///   ObjCMethodDecl
    949 ///   ObjCContainerDecl
    950 ///   LinkageSpecDecl
    951 ///   BlockDecl
    952 ///
    953 class DeclContext {
    954   /// DeclKind - This indicates which class this is.
    955   unsigned DeclKind : 8;
    956 
    957   /// \brief Whether this declaration context also has some external
    958   /// storage that contains additional declarations that are lexically
    959   /// part of this context.
    960   mutable bool ExternalLexicalStorage : 1;
    961 
    962   /// \brief Whether this declaration context also has some external
    963   /// storage that contains additional declarations that are visible
    964   /// in this context.
    965   mutable bool ExternalVisibleStorage : 1;
    966 
    967   /// \brief Whether this declaration context has had external visible
    968   /// storage added since the last lookup. In this case, \c LookupPtr's
    969   /// invariant may not hold and needs to be fixed before we perform
    970   /// another lookup.
    971   mutable bool NeedToReconcileExternalVisibleStorage : 1;
    972 
    973   /// \brief Pointer to the data structure used to lookup declarations
    974   /// within this context (or a DependentStoredDeclsMap if this is a
    975   /// dependent context), and a bool indicating whether we have lazily
    976   /// omitted any declarations from the map. We maintain the invariant
    977   /// that, if the map contains an entry for a DeclarationName (and we
    978   /// haven't lazily omitted anything), then it contains all relevant
    979   /// entries for that name.
    980   mutable llvm::PointerIntPair<StoredDeclsMap*, 1, bool> LookupPtr;
    981 
    982 protected:
    983   /// FirstDecl - The first declaration stored within this declaration
    984   /// context.
    985   mutable Decl *FirstDecl;
    986 
    987   /// LastDecl - The last declaration stored within this declaration
    988   /// context. FIXME: We could probably cache this value somewhere
    989   /// outside of the DeclContext, to reduce the size of DeclContext by
    990   /// another pointer.
    991   mutable Decl *LastDecl;
    992 
    993   friend class ExternalASTSource;
    994   friend class ASTDeclReader;
    995   friend class ASTWriter;
    996 
    997   /// \brief Build up a chain of declarations.
    998   ///
    999   /// \returns the first/last pair of declarations.
   1000   static std::pair<Decl *, Decl *>
   1001   BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
   1002 
   1003   DeclContext(Decl::Kind K)
   1004       : DeclKind(K), ExternalLexicalStorage(false),
   1005         ExternalVisibleStorage(false),
   1006         NeedToReconcileExternalVisibleStorage(false), LookupPtr(0, false),
   1007         FirstDecl(0), LastDecl(0) {}
   1008 
   1009 public:
   1010   ~DeclContext();
   1011 
   1012   Decl::Kind getDeclKind() const {
   1013     return static_cast<Decl::Kind>(DeclKind);
   1014   }
   1015   const char *getDeclKindName() const;
   1016 
   1017   /// getParent - Returns the containing DeclContext.
   1018   DeclContext *getParent() {
   1019     return cast<Decl>(this)->getDeclContext();
   1020   }
   1021   const DeclContext *getParent() const {
   1022     return const_cast<DeclContext*>(this)->getParent();
   1023   }
   1024 
   1025   /// getLexicalParent - Returns the containing lexical DeclContext. May be
   1026   /// different from getParent, e.g.:
   1027   ///
   1028   ///   namespace A {
   1029   ///      struct S;
   1030   ///   }
   1031   ///   struct A::S {}; // getParent() == namespace 'A'
   1032   ///                   // getLexicalParent() == translation unit
   1033   ///
   1034   DeclContext *getLexicalParent() {
   1035     return cast<Decl>(this)->getLexicalDeclContext();
   1036   }
   1037   const DeclContext *getLexicalParent() const {
   1038     return const_cast<DeclContext*>(this)->getLexicalParent();
   1039   }
   1040 
   1041   DeclContext *getLookupParent();
   1042 
   1043   const DeclContext *getLookupParent() const {
   1044     return const_cast<DeclContext*>(this)->getLookupParent();
   1045   }
   1046 
   1047   ASTContext &getParentASTContext() const {
   1048     return cast<Decl>(this)->getASTContext();
   1049   }
   1050 
   1051   bool isClosure() const {
   1052     return DeclKind == Decl::Block;
   1053   }
   1054 
   1055   bool isObjCContainer() const {
   1056     switch (DeclKind) {
   1057         case Decl::ObjCCategory:
   1058         case Decl::ObjCCategoryImpl:
   1059         case Decl::ObjCImplementation:
   1060         case Decl::ObjCInterface:
   1061         case Decl::ObjCProtocol:
   1062             return true;
   1063     }
   1064     return false;
   1065   }
   1066 
   1067   bool isFunctionOrMethod() const {
   1068     switch (DeclKind) {
   1069     case Decl::Block:
   1070     case Decl::Captured:
   1071     case Decl::ObjCMethod:
   1072       return true;
   1073     default:
   1074       return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
   1075     }
   1076   }
   1077 
   1078   bool isFileContext() const {
   1079     return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
   1080   }
   1081 
   1082   bool isTranslationUnit() const {
   1083     return DeclKind == Decl::TranslationUnit;
   1084   }
   1085 
   1086   bool isRecord() const {
   1087     return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
   1088   }
   1089 
   1090   bool isNamespace() const {
   1091     return DeclKind == Decl::Namespace;
   1092   }
   1093 
   1094   bool isInlineNamespace() const;
   1095 
   1096   /// \brief Determines whether this context is dependent on a
   1097   /// template parameter.
   1098   bool isDependentContext() const;
   1099 
   1100   /// isTransparentContext - Determines whether this context is a
   1101   /// "transparent" context, meaning that the members declared in this
   1102   /// context are semantically declared in the nearest enclosing
   1103   /// non-transparent (opaque) context but are lexically declared in
   1104   /// this context. For example, consider the enumerators of an
   1105   /// enumeration type:
   1106   /// @code
   1107   /// enum E {
   1108   ///   Val1
   1109   /// };
   1110   /// @endcode
   1111   /// Here, E is a transparent context, so its enumerator (Val1) will
   1112   /// appear (semantically) that it is in the same context of E.
   1113   /// Examples of transparent contexts include: enumerations (except for
   1114   /// C++0x scoped enums), and C++ linkage specifications.
   1115   bool isTransparentContext() const;
   1116 
   1117   /// \brief Determine whether this declaration context is equivalent
   1118   /// to the declaration context DC.
   1119   bool Equals(const DeclContext *DC) const {
   1120     return DC && this->getPrimaryContext() == DC->getPrimaryContext();
   1121   }
   1122 
   1123   /// \brief Determine whether this declaration context encloses the
   1124   /// declaration context DC.
   1125   bool Encloses(const DeclContext *DC) const;
   1126 
   1127   /// \brief Find the nearest non-closure ancestor of this context,
   1128   /// i.e. the innermost semantic parent of this context which is not
   1129   /// a closure.  A context may be its own non-closure ancestor.
   1130   Decl *getNonClosureAncestor();
   1131   const Decl *getNonClosureAncestor() const {
   1132     return const_cast<DeclContext*>(this)->getNonClosureAncestor();
   1133   }
   1134 
   1135   /// getPrimaryContext - There may be many different
   1136   /// declarations of the same entity (including forward declarations
   1137   /// of classes, multiple definitions of namespaces, etc.), each with
   1138   /// a different set of declarations. This routine returns the
   1139   /// "primary" DeclContext structure, which will contain the
   1140   /// information needed to perform name lookup into this context.
   1141   DeclContext *getPrimaryContext();
   1142   const DeclContext *getPrimaryContext() const {
   1143     return const_cast<DeclContext*>(this)->getPrimaryContext();
   1144   }
   1145 
   1146   /// getRedeclContext - Retrieve the context in which an entity conflicts with
   1147   /// other entities of the same name, or where it is a redeclaration if the
   1148   /// two entities are compatible. This skips through transparent contexts.
   1149   DeclContext *getRedeclContext();
   1150   const DeclContext *getRedeclContext() const {
   1151     return const_cast<DeclContext *>(this)->getRedeclContext();
   1152   }
   1153 
   1154   /// \brief Retrieve the nearest enclosing namespace context.
   1155   DeclContext *getEnclosingNamespaceContext();
   1156   const DeclContext *getEnclosingNamespaceContext() const {
   1157     return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
   1158   }
   1159 
   1160   /// \brief Test if this context is part of the enclosing namespace set of
   1161   /// the context NS, as defined in C++0x [namespace.def]p9. If either context
   1162   /// isn't a namespace, this is equivalent to Equals().
   1163   ///
   1164   /// The enclosing namespace set of a namespace is the namespace and, if it is
   1165   /// inline, its enclosing namespace, recursively.
   1166   bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
   1167 
   1168   /// \brief Collects all of the declaration contexts that are semantically
   1169   /// connected to this declaration context.
   1170   ///
   1171   /// For declaration contexts that have multiple semantically connected but
   1172   /// syntactically distinct contexts, such as C++ namespaces, this routine
   1173   /// retrieves the complete set of such declaration contexts in source order.
   1174   /// For example, given:
   1175   ///
   1176   /// \code
   1177   /// namespace N {
   1178   ///   int x;
   1179   /// }
   1180   /// namespace N {
   1181   ///   int y;
   1182   /// }
   1183   /// \endcode
   1184   ///
   1185   /// The \c Contexts parameter will contain both definitions of N.
   1186   ///
   1187   /// \param Contexts Will be cleared and set to the set of declaration
   1188   /// contexts that are semanticaly connected to this declaration context,
   1189   /// in source order, including this context (which may be the only result,
   1190   /// for non-namespace contexts).
   1191   void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
   1192 
   1193   /// decl_iterator - Iterates through the declarations stored
   1194   /// within this context.
   1195   class decl_iterator {
   1196     /// Current - The current declaration.
   1197     Decl *Current;
   1198 
   1199   public:
   1200     typedef Decl *value_type;
   1201     typedef const value_type &reference;
   1202     typedef const value_type *pointer;
   1203     typedef std::forward_iterator_tag iterator_category;
   1204     typedef std::ptrdiff_t            difference_type;
   1205 
   1206     decl_iterator() : Current(0) { }
   1207     explicit decl_iterator(Decl *C) : Current(C) { }
   1208 
   1209     reference operator*() const { return Current; }
   1210     // This doesn't meet the iterator requirements, but it's convenient
   1211     value_type operator->() const { return Current; }
   1212 
   1213     decl_iterator& operator++() {
   1214       Current = Current->getNextDeclInContext();
   1215       return *this;
   1216     }
   1217 
   1218     decl_iterator operator++(int) {
   1219       decl_iterator tmp(*this);
   1220       ++(*this);
   1221       return tmp;
   1222     }
   1223 
   1224     friend bool operator==(decl_iterator x, decl_iterator y) {
   1225       return x.Current == y.Current;
   1226     }
   1227     friend bool operator!=(decl_iterator x, decl_iterator y) {
   1228       return x.Current != y.Current;
   1229     }
   1230   };
   1231 
   1232   /// decls_begin/decls_end - Iterate over the declarations stored in
   1233   /// this context.
   1234   decl_iterator decls_begin() const;
   1235   decl_iterator decls_end() const { return decl_iterator(); }
   1236   bool decls_empty() const;
   1237 
   1238   /// noload_decls_begin/end - Iterate over the declarations stored in this
   1239   /// context that are currently loaded; don't attempt to retrieve anything
   1240   /// from an external source.
   1241   decl_iterator noload_decls_begin() const;
   1242   decl_iterator noload_decls_end() const { return decl_iterator(); }
   1243 
   1244   /// specific_decl_iterator - Iterates over a subrange of
   1245   /// declarations stored in a DeclContext, providing only those that
   1246   /// are of type SpecificDecl (or a class derived from it). This
   1247   /// iterator is used, for example, to provide iteration over just
   1248   /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
   1249   template<typename SpecificDecl>
   1250   class specific_decl_iterator {
   1251     /// Current - The current, underlying declaration iterator, which
   1252     /// will either be NULL or will point to a declaration of
   1253     /// type SpecificDecl.
   1254     DeclContext::decl_iterator Current;
   1255 
   1256     /// SkipToNextDecl - Advances the current position up to the next
   1257     /// declaration of type SpecificDecl that also meets the criteria
   1258     /// required by Acceptable.
   1259     void SkipToNextDecl() {
   1260       while (*Current && !isa<SpecificDecl>(*Current))
   1261         ++Current;
   1262     }
   1263 
   1264   public:
   1265     typedef SpecificDecl *value_type;
   1266     // TODO: Add reference and pointer typedefs (with some appropriate proxy
   1267     // type) if we ever have a need for them.
   1268     typedef void reference;
   1269     typedef void pointer;
   1270     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
   1271       difference_type;
   1272     typedef std::forward_iterator_tag iterator_category;
   1273 
   1274     specific_decl_iterator() : Current() { }
   1275 
   1276     /// specific_decl_iterator - Construct a new iterator over a
   1277     /// subset of the declarations the range [C,
   1278     /// end-of-declarations). If A is non-NULL, it is a pointer to a
   1279     /// member function of SpecificDecl that should return true for
   1280     /// all of the SpecificDecl instances that will be in the subset
   1281     /// of iterators. For example, if you want Objective-C instance
   1282     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
   1283     /// &ObjCMethodDecl::isInstanceMethod.
   1284     explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
   1285       SkipToNextDecl();
   1286     }
   1287 
   1288     value_type operator*() const { return cast<SpecificDecl>(*Current); }
   1289     // This doesn't meet the iterator requirements, but it's convenient
   1290     value_type operator->() const { return **this; }
   1291 
   1292     specific_decl_iterator& operator++() {
   1293       ++Current;
   1294       SkipToNextDecl();
   1295       return *this;
   1296     }
   1297 
   1298     specific_decl_iterator operator++(int) {
   1299       specific_decl_iterator tmp(*this);
   1300       ++(*this);
   1301       return tmp;
   1302     }
   1303 
   1304     friend bool operator==(const specific_decl_iterator& x,
   1305                            const specific_decl_iterator& y) {
   1306       return x.Current == y.Current;
   1307     }
   1308 
   1309     friend bool operator!=(const specific_decl_iterator& x,
   1310                            const specific_decl_iterator& y) {
   1311       return x.Current != y.Current;
   1312     }
   1313   };
   1314 
   1315   /// \brief Iterates over a filtered subrange of declarations stored
   1316   /// in a DeclContext.
   1317   ///
   1318   /// This iterator visits only those declarations that are of type
   1319   /// SpecificDecl (or a class derived from it) and that meet some
   1320   /// additional run-time criteria. This iterator is used, for
   1321   /// example, to provide access to the instance methods within an
   1322   /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
   1323   /// Acceptable = ObjCMethodDecl::isInstanceMethod).
   1324   template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
   1325   class filtered_decl_iterator {
   1326     /// Current - The current, underlying declaration iterator, which
   1327     /// will either be NULL or will point to a declaration of
   1328     /// type SpecificDecl.
   1329     DeclContext::decl_iterator Current;
   1330 
   1331     /// SkipToNextDecl - Advances the current position up to the next
   1332     /// declaration of type SpecificDecl that also meets the criteria
   1333     /// required by Acceptable.
   1334     void SkipToNextDecl() {
   1335       while (*Current &&
   1336              (!isa<SpecificDecl>(*Current) ||
   1337               (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
   1338         ++Current;
   1339     }
   1340 
   1341   public:
   1342     typedef SpecificDecl *value_type;
   1343     // TODO: Add reference and pointer typedefs (with some appropriate proxy
   1344     // type) if we ever have a need for them.
   1345     typedef void reference;
   1346     typedef void pointer;
   1347     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
   1348       difference_type;
   1349     typedef std::forward_iterator_tag iterator_category;
   1350 
   1351     filtered_decl_iterator() : Current() { }
   1352 
   1353     /// filtered_decl_iterator - Construct a new iterator over a
   1354     /// subset of the declarations the range [C,
   1355     /// end-of-declarations). If A is non-NULL, it is a pointer to a
   1356     /// member function of SpecificDecl that should return true for
   1357     /// all of the SpecificDecl instances that will be in the subset
   1358     /// of iterators. For example, if you want Objective-C instance
   1359     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
   1360     /// &ObjCMethodDecl::isInstanceMethod.
   1361     explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
   1362       SkipToNextDecl();
   1363     }
   1364 
   1365     value_type operator*() const { return cast<SpecificDecl>(*Current); }
   1366     value_type operator->() const { return cast<SpecificDecl>(*Current); }
   1367 
   1368     filtered_decl_iterator& operator++() {
   1369       ++Current;
   1370       SkipToNextDecl();
   1371       return *this;
   1372     }
   1373 
   1374     filtered_decl_iterator operator++(int) {
   1375       filtered_decl_iterator tmp(*this);
   1376       ++(*this);
   1377       return tmp;
   1378     }
   1379 
   1380     friend bool operator==(const filtered_decl_iterator& x,
   1381                            const filtered_decl_iterator& y) {
   1382       return x.Current == y.Current;
   1383     }
   1384 
   1385     friend bool operator!=(const filtered_decl_iterator& x,
   1386                            const filtered_decl_iterator& y) {
   1387       return x.Current != y.Current;
   1388     }
   1389   };
   1390 
   1391   /// @brief Add the declaration D into this context.
   1392   ///
   1393   /// This routine should be invoked when the declaration D has first
   1394   /// been declared, to place D into the context where it was
   1395   /// (lexically) defined. Every declaration must be added to one
   1396   /// (and only one!) context, where it can be visited via
   1397   /// [decls_begin(), decls_end()). Once a declaration has been added
   1398   /// to its lexical context, the corresponding DeclContext owns the
   1399   /// declaration.
   1400   ///
   1401   /// If D is also a NamedDecl, it will be made visible within its
   1402   /// semantic context via makeDeclVisibleInContext.
   1403   void addDecl(Decl *D);
   1404 
   1405   /// @brief Add the declaration D into this context, but suppress
   1406   /// searches for external declarations with the same name.
   1407   ///
   1408   /// Although analogous in function to addDecl, this removes an
   1409   /// important check.  This is only useful if the Decl is being
   1410   /// added in response to an external search; in all other cases,
   1411   /// addDecl() is the right function to use.
   1412   /// See the ASTImporter for use cases.
   1413   void addDeclInternal(Decl *D);
   1414 
   1415   /// @brief Add the declaration D to this context without modifying
   1416   /// any lookup tables.
   1417   ///
   1418   /// This is useful for some operations in dependent contexts where
   1419   /// the semantic context might not be dependent;  this basically
   1420   /// only happens with friends.
   1421   void addHiddenDecl(Decl *D);
   1422 
   1423   /// @brief Removes a declaration from this context.
   1424   void removeDecl(Decl *D);
   1425 
   1426   /// @brief Checks whether a declaration is in this context.
   1427   bool containsDecl(Decl *D) const;
   1428 
   1429   /// lookup_iterator - An iterator that provides access to the results
   1430   /// of looking up a name within this context.
   1431   typedef NamedDecl **lookup_iterator;
   1432 
   1433   /// lookup_const_iterator - An iterator that provides non-mutable
   1434   /// access to the results of lookup up a name within this context.
   1435   typedef NamedDecl * const * lookup_const_iterator;
   1436 
   1437   typedef DeclContextLookupResult lookup_result;
   1438   typedef DeclContextLookupConstResult lookup_const_result;
   1439 
   1440   /// lookup - Find the declarations (if any) with the given Name in
   1441   /// this context. Returns a range of iterators that contains all of
   1442   /// the declarations with this name, with object, function, member,
   1443   /// and enumerator names preceding any tag name. Note that this
   1444   /// routine will not look into parent contexts.
   1445   lookup_result lookup(DeclarationName Name);
   1446   lookup_const_result lookup(DeclarationName Name) const {
   1447     return const_cast<DeclContext*>(this)->lookup(Name);
   1448   }
   1449 
   1450   /// \brief Find the declarations with the given name that are visible
   1451   /// within this context; don't attempt to retrieve anything from an
   1452   /// external source.
   1453   lookup_result noload_lookup(DeclarationName Name);
   1454 
   1455   /// \brief A simplistic name lookup mechanism that performs name lookup
   1456   /// into this declaration context without consulting the external source.
   1457   ///
   1458   /// This function should almost never be used, because it subverts the
   1459   /// usual relationship between a DeclContext and the external source.
   1460   /// See the ASTImporter for the (few, but important) use cases.
   1461   ///
   1462   /// FIXME: This is very inefficient; replace uses of it with uses of
   1463   /// noload_lookup.
   1464   void localUncachedLookup(DeclarationName Name,
   1465                            SmallVectorImpl<NamedDecl *> &Results);
   1466 
   1467   /// @brief Makes a declaration visible within this context.
   1468   ///
   1469   /// This routine makes the declaration D visible to name lookup
   1470   /// within this context and, if this is a transparent context,
   1471   /// within its parent contexts up to the first enclosing
   1472   /// non-transparent context. Making a declaration visible within a
   1473   /// context does not transfer ownership of a declaration, and a
   1474   /// declaration can be visible in many contexts that aren't its
   1475   /// lexical context.
   1476   ///
   1477   /// If D is a redeclaration of an existing declaration that is
   1478   /// visible from this context, as determined by
   1479   /// NamedDecl::declarationReplaces, the previous declaration will be
   1480   /// replaced with D.
   1481   void makeDeclVisibleInContext(NamedDecl *D);
   1482 
   1483   /// all_lookups_iterator - An iterator that provides a view over the results
   1484   /// of looking up every possible name.
   1485   class all_lookups_iterator;
   1486 
   1487   /// \brief Iterators over all possible lookups within this context.
   1488   all_lookups_iterator lookups_begin() const;
   1489   all_lookups_iterator lookups_end() const;
   1490 
   1491   /// \brief Iterators over all possible lookups within this context that are
   1492   /// currently loaded; don't attempt to retrieve anything from an external
   1493   /// source.
   1494   all_lookups_iterator noload_lookups_begin() const;
   1495   all_lookups_iterator noload_lookups_end() const;
   1496 
   1497   /// udir_iterator - Iterates through the using-directives stored
   1498   /// within this context.
   1499   typedef UsingDirectiveDecl * const * udir_iterator;
   1500 
   1501   typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
   1502 
   1503   udir_iterator_range getUsingDirectives() const;
   1504 
   1505   udir_iterator using_directives_begin() const {
   1506     return getUsingDirectives().first;
   1507   }
   1508 
   1509   udir_iterator using_directives_end() const {
   1510     return getUsingDirectives().second;
   1511   }
   1512 
   1513   // These are all defined in DependentDiagnostic.h.
   1514   class ddiag_iterator;
   1515   inline ddiag_iterator ddiag_begin() const;
   1516   inline ddiag_iterator ddiag_end() const;
   1517 
   1518   // Low-level accessors
   1519 
   1520   /// \brief Mark the lookup table as needing to be built.  This should be
   1521   /// used only if setHasExternalLexicalStorage() has been called on any
   1522   /// decl context for which this is the primary context.
   1523   void setMustBuildLookupTable() {
   1524     LookupPtr.setInt(true);
   1525   }
   1526 
   1527   /// \brief Retrieve the internal representation of the lookup structure.
   1528   /// This may omit some names if we are lazily building the structure.
   1529   StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
   1530 
   1531   /// \brief Ensure the lookup structure is fully-built and return it.
   1532   StoredDeclsMap *buildLookup();
   1533 
   1534   /// \brief Whether this DeclContext has external storage containing
   1535   /// additional declarations that are lexically in this context.
   1536   bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
   1537 
   1538   /// \brief State whether this DeclContext has external storage for
   1539   /// declarations lexically in this context.
   1540   void setHasExternalLexicalStorage(bool ES = true) {
   1541     ExternalLexicalStorage = ES;
   1542   }
   1543 
   1544   /// \brief Whether this DeclContext has external storage containing
   1545   /// additional declarations that are visible in this context.
   1546   bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
   1547 
   1548   /// \brief State whether this DeclContext has external storage for
   1549   /// declarations visible in this context.
   1550   void setHasExternalVisibleStorage(bool ES = true) {
   1551     ExternalVisibleStorage = ES;
   1552     if (ES && LookupPtr.getPointer())
   1553       NeedToReconcileExternalVisibleStorage = true;
   1554   }
   1555 
   1556   /// \brief Determine whether the given declaration is stored in the list of
   1557   /// declarations lexically within this context.
   1558   bool isDeclInLexicalTraversal(const Decl *D) const {
   1559     return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
   1560                  D == LastDecl);
   1561   }
   1562 
   1563   static bool classof(const Decl *D);
   1564   static bool classof(const DeclContext *D) { return true; }
   1565 
   1566   LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
   1567   LLVM_ATTRIBUTE_USED void dumpLookups() const;
   1568   LLVM_ATTRIBUTE_USED void dumpLookups(llvm::raw_ostream &OS) const;
   1569 
   1570 private:
   1571   void reconcileExternalVisibleStorage();
   1572   void LoadLexicalDeclsFromExternalStorage() const;
   1573 
   1574   /// @brief Makes a declaration visible within this context, but
   1575   /// suppresses searches for external declarations with the same
   1576   /// name.
   1577   ///
   1578   /// Analogous to makeDeclVisibleInContext, but for the exclusive
   1579   /// use of addDeclInternal().
   1580   void makeDeclVisibleInContextInternal(NamedDecl *D);
   1581 
   1582   friend class DependentDiagnostic;
   1583   StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
   1584 
   1585   template<decl_iterator (DeclContext::*Begin)() const,
   1586            decl_iterator (DeclContext::*End)() const>
   1587   void buildLookupImpl(DeclContext *DCtx);
   1588   void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
   1589                                          bool Rediscoverable);
   1590   void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
   1591 };
   1592 
   1593 inline bool Decl::isTemplateParameter() const {
   1594   return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
   1595          getKind() == TemplateTemplateParm;
   1596 }
   1597 
   1598 // Specialization selected when ToTy is not a known subclass of DeclContext.
   1599 template <class ToTy,
   1600           bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
   1601 struct cast_convert_decl_context {
   1602   static const ToTy *doit(const DeclContext *Val) {
   1603     return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
   1604   }
   1605 
   1606   static ToTy *doit(DeclContext *Val) {
   1607     return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
   1608   }
   1609 };
   1610 
   1611 // Specialization selected when ToTy is a known subclass of DeclContext.
   1612 template <class ToTy>
   1613 struct cast_convert_decl_context<ToTy, true> {
   1614   static const ToTy *doit(const DeclContext *Val) {
   1615     return static_cast<const ToTy*>(Val);
   1616   }
   1617 
   1618   static ToTy *doit(DeclContext *Val) {
   1619     return static_cast<ToTy*>(Val);
   1620   }
   1621 };
   1622 
   1623 
   1624 } // end clang.
   1625 
   1626 namespace llvm {
   1627 
   1628 /// isa<T>(DeclContext*)
   1629 template <typename To>
   1630 struct isa_impl<To, ::clang::DeclContext> {
   1631   static bool doit(const ::clang::DeclContext &Val) {
   1632     return To::classofKind(Val.getDeclKind());
   1633   }
   1634 };
   1635 
   1636 /// cast<T>(DeclContext*)
   1637 template<class ToTy>
   1638 struct cast_convert_val<ToTy,
   1639                         const ::clang::DeclContext,const ::clang::DeclContext> {
   1640   static const ToTy &doit(const ::clang::DeclContext &Val) {
   1641     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
   1642   }
   1643 };
   1644 template<class ToTy>
   1645 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
   1646   static ToTy &doit(::clang::DeclContext &Val) {
   1647     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
   1648   }
   1649 };
   1650 template<class ToTy>
   1651 struct cast_convert_val<ToTy,
   1652                      const ::clang::DeclContext*, const ::clang::DeclContext*> {
   1653   static const ToTy *doit(const ::clang::DeclContext *Val) {
   1654     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
   1655   }
   1656 };
   1657 template<class ToTy>
   1658 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
   1659   static ToTy *doit(::clang::DeclContext *Val) {
   1660     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
   1661   }
   1662 };
   1663 
   1664 /// Implement cast_convert_val for Decl -> DeclContext conversions.
   1665 template<class FromTy>
   1666 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
   1667   static ::clang::DeclContext &doit(const FromTy &Val) {
   1668     return *FromTy::castToDeclContext(&Val);
   1669   }
   1670 };
   1671 
   1672 template<class FromTy>
   1673 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
   1674   static ::clang::DeclContext *doit(const FromTy *Val) {
   1675     return FromTy::castToDeclContext(Val);
   1676   }
   1677 };
   1678 
   1679 template<class FromTy>
   1680 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
   1681   static const ::clang::DeclContext &doit(const FromTy &Val) {
   1682     return *FromTy::castToDeclContext(&Val);
   1683   }
   1684 };
   1685 
   1686 template<class FromTy>
   1687 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
   1688   static const ::clang::DeclContext *doit(const FromTy *Val) {
   1689     return FromTy::castToDeclContext(Val);
   1690   }
   1691 };
   1692 
   1693 } // end namespace llvm
   1694 
   1695 #endif
   1696