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