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