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