]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/DeclBase.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303291, and update
[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 "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 Retrieve the version of the target platform in which this
620   /// declaration was introduced.
621   ///
622   /// \returns An empty version tuple if this declaration has no 'introduced'
623   /// availability attributes, or the version tuple that's specified in the
624   /// attribute otherwise.
625   VersionTuple getVersionIntroduced() const;
626
627   /// \brief Determine whether this declaration is marked 'deprecated'.
628   ///
629   /// \param Message If non-NULL and the declaration is deprecated,
630   /// this will be set to the message describing why the declaration
631   /// was deprecated (which may be empty).
632   bool isDeprecated(std::string *Message = nullptr) const {
633     return getAvailability(Message) == AR_Deprecated;
634   }
635
636   /// \brief Determine whether this declaration is marked 'unavailable'.
637   ///
638   /// \param Message If non-NULL and the declaration is unavailable,
639   /// this will be set to the message describing why the declaration
640   /// was made unavailable (which may be empty).
641   bool isUnavailable(std::string *Message = nullptr) const {
642     return getAvailability(Message) == AR_Unavailable;
643   }
644
645   /// \brief Determine whether this is a weak-imported symbol.
646   ///
647   /// Weak-imported symbols are typically marked with the
648   /// 'weak_import' attribute, but may also be marked with an
649   /// 'availability' attribute where we're targing a platform prior to
650   /// the introduction of this feature.
651   bool isWeakImported() const;
652
653   /// \brief Determines whether this symbol can be weak-imported,
654   /// e.g., whether it would be well-formed to add the weak_import
655   /// attribute.
656   ///
657   /// \param IsDefinition Set to \c true to indicate that this
658   /// declaration cannot be weak-imported because it has a definition.
659   bool canBeWeakImported(bool &IsDefinition) const;
660
661   /// \brief Determine whether this declaration came from an AST file (such as
662   /// a precompiled header or module) rather than having been parsed.
663   bool isFromASTFile() const { return FromASTFile; }
664
665   /// \brief Retrieve the global declaration ID associated with this
666   /// declaration, which specifies where this Decl was loaded from.
667   unsigned getGlobalID() const {
668     if (isFromASTFile())
669       return *((const unsigned*)this - 1);
670     return 0;
671   }
672
673   /// \brief Retrieve the global ID of the module that owns this particular
674   /// declaration.
675   unsigned getOwningModuleID() const {
676     if (isFromASTFile())
677       return *((const unsigned*)this - 2);
678     return 0;
679   }
680
681 private:
682   Module *getOwningModuleSlow() const;
683 protected:
684   bool hasLocalOwningModuleStorage() const;
685
686 public:
687   /// \brief Get the imported owning module, if this decl is from an imported
688   /// (non-local) module.
689   Module *getImportedOwningModule() const {
690     if (!isFromASTFile())
691       return nullptr;
692
693     return getOwningModuleSlow();
694   }
695
696   /// \brief Get the local owning module, if known. Returns nullptr if owner is
697   /// not yet known or declaration is not from a module.
698   Module *getLocalOwningModule() const {
699     if (isFromASTFile() || !Hidden)
700       return nullptr;
701     return reinterpret_cast<Module *const *>(this)[-1];
702   }
703   void setLocalOwningModule(Module *M) {
704     assert(!isFromASTFile() && Hidden && hasLocalOwningModuleStorage() &&
705            "should not have a cached owning module");
706     reinterpret_cast<Module **>(this)[-1] = M;
707   }
708
709   Module *getOwningModule() const {
710     return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
711   }
712
713   /// \brief Determine whether this declaration is hidden from name lookup.
714   bool isHidden() const { return Hidden; }
715
716   /// \brief Set whether this declaration is hidden from name lookup.
717   void setHidden(bool Hide) {
718     assert((!Hide || isFromASTFile() || hasLocalOwningModuleStorage()) &&
719            "declaration with no owning module can't be hidden");
720     Hidden = Hide;
721   }
722
723   unsigned getIdentifierNamespace() const {
724     return IdentifierNamespace;
725   }
726   bool isInIdentifierNamespace(unsigned NS) const {
727     return getIdentifierNamespace() & NS;
728   }
729   static unsigned getIdentifierNamespaceForKind(Kind DK);
730
731   bool hasTagIdentifierNamespace() const {
732     return isTagIdentifierNamespace(getIdentifierNamespace());
733   }
734   static bool isTagIdentifierNamespace(unsigned NS) {
735     // TagDecls have Tag and Type set and may also have TagFriend.
736     return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
737   }
738
739   /// getLexicalDeclContext - The declaration context where this Decl was
740   /// lexically declared (LexicalDC). May be different from
741   /// getDeclContext() (SemanticDC).
742   /// e.g.:
743   ///
744   ///   namespace A {
745   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
746   ///   }
747   ///   void A::f(); // SemanticDC == namespace 'A'
748   ///                // LexicalDC == global namespace
749   DeclContext *getLexicalDeclContext() {
750     if (isInSemaDC())
751       return getSemanticDC();
752     return getMultipleDC()->LexicalDC;
753   }
754   const DeclContext *getLexicalDeclContext() const {
755     return const_cast<Decl*>(this)->getLexicalDeclContext();
756   }
757
758   /// Determine whether this declaration is declared out of line (outside its
759   /// semantic context).
760   virtual bool isOutOfLine() const;
761
762   /// setDeclContext - Set both the semantic and lexical DeclContext
763   /// to DC.
764   void setDeclContext(DeclContext *DC);
765
766   void setLexicalDeclContext(DeclContext *DC);
767
768   /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
769   /// scoped decl is defined outside the current function or method.  This is
770   /// roughly global variables and functions, but also handles enums (which
771   /// could be defined inside or outside a function etc).
772   bool isDefinedOutsideFunctionOrMethod() const {
773     return getParentFunctionOrMethod() == nullptr;
774   }
775
776   /// \brief Returns true if this declaration lexically is inside a function.
777   /// It recognizes non-defining declarations as well as members of local
778   /// classes:
779   /// \code
780   ///     void foo() { void bar(); }
781   ///     void foo2() { class ABC { void bar(); }; }
782   /// \endcode
783   bool isLexicallyWithinFunctionOrMethod() const;
784
785   /// \brief If this decl is defined inside a function/method/block it returns
786   /// the corresponding DeclContext, otherwise it returns null.
787   const DeclContext *getParentFunctionOrMethod() const;
788   DeclContext *getParentFunctionOrMethod() {
789     return const_cast<DeclContext*>(
790                     const_cast<const Decl*>(this)->getParentFunctionOrMethod());
791   }
792
793   /// \brief Retrieves the "canonical" declaration of the given declaration.
794   virtual Decl *getCanonicalDecl() { return this; }
795   const Decl *getCanonicalDecl() const {
796     return const_cast<Decl*>(this)->getCanonicalDecl();
797   }
798
799   /// \brief Whether this particular Decl is a canonical one.
800   bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
801   
802 protected:
803   /// \brief Returns the next redeclaration or itself if this is the only decl.
804   ///
805   /// Decl subclasses that can be redeclared should override this method so that
806   /// Decl::redecl_iterator can iterate over them.
807   virtual Decl *getNextRedeclarationImpl() { return this; }
808
809   /// \brief Implementation of getPreviousDecl(), to be overridden by any
810   /// subclass that has a redeclaration chain.
811   virtual Decl *getPreviousDeclImpl() { return nullptr; }
812
813   /// \brief Implementation of getMostRecentDecl(), to be overridden by any
814   /// subclass that has a redeclaration chain.
815   virtual Decl *getMostRecentDeclImpl() { return this; }
816
817 public:
818   /// \brief Iterates through all the redeclarations of the same decl.
819   class redecl_iterator {
820     /// Current - The current declaration.
821     Decl *Current;
822     Decl *Starter;
823
824   public:
825     typedef Decl *value_type;
826     typedef const value_type &reference;
827     typedef const value_type *pointer;
828     typedef std::forward_iterator_tag iterator_category;
829     typedef std::ptrdiff_t difference_type;
830
831     redecl_iterator() : Current(nullptr) { }
832     explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
833
834     reference operator*() const { return Current; }
835     value_type operator->() const { return Current; }
836
837     redecl_iterator& operator++() {
838       assert(Current && "Advancing while iterator has reached end");
839       // Get either previous decl or latest decl.
840       Decl *Next = Current->getNextRedeclarationImpl();
841       assert(Next && "Should return next redeclaration or itself, never null!");
842       Current = (Next != Starter) ? Next : nullptr;
843       return *this;
844     }
845
846     redecl_iterator operator++(int) {
847       redecl_iterator tmp(*this);
848       ++(*this);
849       return tmp;
850     }
851
852     friend bool operator==(redecl_iterator x, redecl_iterator y) {
853       return x.Current == y.Current;
854     }
855     friend bool operator!=(redecl_iterator x, redecl_iterator y) {
856       return x.Current != y.Current;
857     }
858   };
859
860   typedef llvm::iterator_range<redecl_iterator> redecl_range;
861
862   /// \brief Returns an iterator range for all the redeclarations of the same
863   /// decl. It will iterate at least once (when this decl is the only one).
864   redecl_range redecls() const {
865     return redecl_range(redecls_begin(), redecls_end());
866   }
867
868   redecl_iterator redecls_begin() const {
869     return redecl_iterator(const_cast<Decl *>(this));
870   }
871   redecl_iterator redecls_end() const { return redecl_iterator(); }
872
873   /// \brief Retrieve the previous declaration that declares the same entity
874   /// as this declaration, or NULL if there is no previous declaration.
875   Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
876   
877   /// \brief Retrieve the most recent declaration that declares the same entity
878   /// as this declaration, or NULL if there is no previous declaration.
879   const Decl *getPreviousDecl() const { 
880     return const_cast<Decl *>(this)->getPreviousDeclImpl();
881   }
882
883   /// \brief True if this is the first declaration in its redeclaration chain.
884   bool isFirstDecl() const {
885     return getPreviousDecl() == nullptr;
886   }
887
888   /// \brief Retrieve the most recent declaration that declares the same entity
889   /// as this declaration (which may be this declaration).
890   Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
891
892   /// \brief Retrieve the most recent declaration that declares the same entity
893   /// as this declaration (which may be this declaration).
894   const Decl *getMostRecentDecl() const { 
895     return const_cast<Decl *>(this)->getMostRecentDeclImpl();
896   }
897
898   /// getBody - If this Decl represents a declaration for a body of code,
899   ///  such as a function or method definition, this method returns the
900   ///  top-level Stmt* of that body.  Otherwise this method returns null.
901   virtual Stmt* getBody() const { return nullptr; }
902
903   /// \brief Returns true if this \c Decl represents a declaration for a body of
904   /// code, such as a function or method definition.
905   /// Note that \c hasBody can also return true if any redeclaration of this
906   /// \c Decl represents a declaration for a body of code.
907   virtual bool hasBody() const { return getBody() != nullptr; }
908
909   /// getBodyRBrace - Gets the right brace of the body, if a body exists.
910   /// This works whether the body is a CompoundStmt or a CXXTryStmt.
911   SourceLocation getBodyRBrace() const;
912
913   // global temp stats (until we have a per-module visitor)
914   static void add(Kind k);
915   static void EnableStatistics();
916   static void PrintStats();
917
918   /// isTemplateParameter - Determines whether this declaration is a
919   /// template parameter.
920   bool isTemplateParameter() const;
921
922   /// isTemplateParameter - Determines whether this declaration is a
923   /// template parameter pack.
924   bool isTemplateParameterPack() const;
925
926   /// \brief Whether this declaration is a parameter pack.
927   bool isParameterPack() const;
928
929   /// \brief returns true if this declaration is a template
930   bool isTemplateDecl() const;
931
932   /// \brief Whether this declaration is a function or function template.
933   bool isFunctionOrFunctionTemplate() const {
934     return (DeclKind >= Decl::firstFunction &&
935             DeclKind <= Decl::lastFunction) ||
936            DeclKind == FunctionTemplate;
937   }
938
939   /// \brief If this is a declaration that describes some template, this
940   /// method returns that template declaration.
941   TemplateDecl *getDescribedTemplate() const;
942
943   /// \brief Returns the function itself, or the templated function if this is a
944   /// function template.
945   FunctionDecl *getAsFunction() LLVM_READONLY;
946
947   const FunctionDecl *getAsFunction() const {
948     return const_cast<Decl *>(this)->getAsFunction();
949   }
950
951   /// \brief Changes the namespace of this declaration to reflect that it's
952   /// a function-local extern declaration.
953   ///
954   /// These declarations appear in the lexical context of the extern
955   /// declaration, but in the semantic context of the enclosing namespace
956   /// scope.
957   void setLocalExternDecl() {
958     assert((IdentifierNamespace == IDNS_Ordinary ||
959             IdentifierNamespace == IDNS_OrdinaryFriend) &&
960            "namespace is not ordinary");
961
962     Decl *Prev = getPreviousDecl();
963     IdentifierNamespace &= ~IDNS_Ordinary;
964
965     IdentifierNamespace |= IDNS_LocalExtern;
966     if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
967       IdentifierNamespace |= IDNS_Ordinary;
968   }
969
970   /// \brief Determine whether this is a block-scope declaration with linkage.
971   /// This will either be a local variable declaration declared 'extern', or a
972   /// local function declaration.
973   bool isLocalExternDecl() {
974     return IdentifierNamespace & IDNS_LocalExtern;
975   }
976
977   /// \brief Changes the namespace of this declaration to reflect that it's
978   /// the object of a friend declaration.
979   ///
980   /// These declarations appear in the lexical context of the friending
981   /// class, but in the semantic context of the actual entity.  This property
982   /// applies only to a specific decl object;  other redeclarations of the
983   /// same entity may not (and probably don't) share this property.
984   void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
985     unsigned OldNS = IdentifierNamespace;
986     assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
987                      IDNS_TagFriend | IDNS_OrdinaryFriend |
988                      IDNS_LocalExtern)) &&
989            "namespace includes neither ordinary nor tag");
990     assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
991                        IDNS_TagFriend | IDNS_OrdinaryFriend |
992                        IDNS_LocalExtern)) &&
993            "namespace includes other than ordinary or tag");
994
995     Decl *Prev = getPreviousDecl();
996     IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
997
998     if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
999       IdentifierNamespace |= IDNS_TagFriend;
1000       if (PerformFriendInjection ||
1001           (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1002         IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1003     }
1004
1005     if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
1006       IdentifierNamespace |= IDNS_OrdinaryFriend;
1007       if (PerformFriendInjection ||
1008           (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1009         IdentifierNamespace |= IDNS_Ordinary;
1010     }
1011   }
1012
1013   enum FriendObjectKind {
1014     FOK_None,      ///< Not a friend object.
1015     FOK_Declared,  ///< A friend of a previously-declared entity.
1016     FOK_Undeclared ///< A friend of a previously-undeclared entity.
1017   };
1018
1019   /// \brief Determines whether this declaration is the object of a
1020   /// friend declaration and, if so, what kind.
1021   ///
1022   /// There is currently no direct way to find the associated FriendDecl.
1023   FriendObjectKind getFriendObjectKind() const {
1024     unsigned mask =
1025         (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1026     if (!mask) return FOK_None;
1027     return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1028                                                              : FOK_Undeclared);
1029   }
1030
1031   /// Specifies that this declaration is a C++ overloaded non-member.
1032   void setNonMemberOperator() {
1033     assert(getKind() == Function || getKind() == FunctionTemplate);
1034     assert((IdentifierNamespace & IDNS_Ordinary) &&
1035            "visible non-member operators should be in ordinary namespace");
1036     IdentifierNamespace |= IDNS_NonMemberOperator;
1037   }
1038
1039   static bool classofKind(Kind K) { return true; }
1040   static DeclContext *castToDeclContext(const Decl *);
1041   static Decl *castFromDeclContext(const DeclContext *);
1042
1043   void print(raw_ostream &Out, unsigned Indentation = 0,
1044              bool PrintInstantiation = false) const;
1045   void print(raw_ostream &Out, const PrintingPolicy &Policy,
1046              unsigned Indentation = 0, bool PrintInstantiation = false) const;
1047   static void printGroup(Decl** Begin, unsigned NumDecls,
1048                          raw_ostream &Out, const PrintingPolicy &Policy,
1049                          unsigned Indentation = 0);
1050   // Debuggers don't usually respect default arguments.
1051   void dump() const;
1052   // Same as dump(), but forces color printing.
1053   void dumpColor() const;
1054   void dump(raw_ostream &Out, bool Deserialize = false) const;
1055
1056   /// \brief Looks through the Decl's underlying type to extract a FunctionType
1057   /// when possible. Will return null if the type underlying the Decl does not
1058   /// have a FunctionType.
1059   const FunctionType *getFunctionType(bool BlocksToo = true) const;
1060
1061 private:
1062   void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1063   void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1064                            ASTContext &Ctx);
1065
1066 protected:
1067   ASTMutationListener *getASTMutationListener() const;
1068 };
1069
1070 /// \brief Determine whether two declarations declare the same entity.
1071 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1072   if (!D1 || !D2)
1073     return false;
1074   
1075   if (D1 == D2)
1076     return true;
1077   
1078   return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1079 }
1080   
1081 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1082 /// doing something to a specific decl.
1083 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1084   const Decl *TheDecl;
1085   SourceLocation Loc;
1086   SourceManager &SM;
1087   const char *Message;
1088 public:
1089   PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1090                        SourceManager &sm, const char *Msg)
1091   : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1092
1093   void print(raw_ostream &OS) const override;
1094 };
1095
1096 /// \brief The results of name lookup within a DeclContext. This is either a
1097 /// single result (with no stable storage) or a collection of results (with
1098 /// stable storage provided by the lookup table).
1099 class DeclContextLookupResult {
1100   typedef ArrayRef<NamedDecl *> ResultTy;
1101   ResultTy Result;
1102   // If there is only one lookup result, it would be invalidated by
1103   // reallocations of the name table, so store it separately.
1104   NamedDecl *Single;
1105
1106   static NamedDecl *const SingleElementDummyList;
1107
1108 public:
1109   DeclContextLookupResult() : Result(), Single() {}
1110   DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1111       : Result(Result), Single() {}
1112   DeclContextLookupResult(NamedDecl *Single)
1113       : Result(SingleElementDummyList), Single(Single) {}
1114
1115   class iterator;
1116   typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1117                                       std::random_access_iterator_tag,
1118                                       NamedDecl *const> IteratorBase;
1119   class iterator : public IteratorBase {
1120     value_type SingleElement;
1121
1122   public:
1123     iterator() : IteratorBase(), SingleElement() {}
1124     explicit iterator(pointer Pos, value_type Single = nullptr)
1125         : IteratorBase(Pos), SingleElement(Single) {}
1126
1127     reference operator*() const {
1128       return SingleElement ? SingleElement : IteratorBase::operator*();
1129     }
1130   };
1131   typedef iterator const_iterator;
1132   typedef iterator::pointer pointer;
1133   typedef iterator::reference reference;
1134
1135   iterator begin() const { return iterator(Result.begin(), Single); }
1136   iterator end() const { return iterator(Result.end(), Single); }
1137
1138   bool empty() const { return Result.empty(); }
1139   pointer data() const { return Single ? &Single : Result.data(); }
1140   size_t size() const { return Single ? 1 : Result.size(); }
1141   reference front() const { return Single ? Single : Result.front(); }
1142   reference back() const { return Single ? Single : Result.back(); }
1143   reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1144
1145   // FIXME: Remove this from the interface
1146   DeclContextLookupResult slice(size_t N) const {
1147     DeclContextLookupResult Sliced = Result.slice(N);
1148     Sliced.Single = Single;
1149     return Sliced;
1150   }
1151 };
1152
1153 /// DeclContext - This is used only as base class of specific decl types that
1154 /// can act as declaration contexts. These decls are (only the top classes
1155 /// that directly derive from DeclContext are mentioned, not their subclasses):
1156 ///
1157 ///   TranslationUnitDecl
1158 ///   NamespaceDecl
1159 ///   FunctionDecl
1160 ///   TagDecl
1161 ///   ObjCMethodDecl
1162 ///   ObjCContainerDecl
1163 ///   LinkageSpecDecl
1164 ///   ExportDecl
1165 ///   BlockDecl
1166 ///   OMPDeclareReductionDecl
1167 ///
1168 class DeclContext {
1169   /// DeclKind - This indicates which class this is.
1170   unsigned DeclKind : 8;
1171
1172   /// \brief Whether this declaration context also has some external
1173   /// storage that contains additional declarations that are lexically
1174   /// part of this context.
1175   mutable bool ExternalLexicalStorage : 1;
1176
1177   /// \brief Whether this declaration context also has some external
1178   /// storage that contains additional declarations that are visible
1179   /// in this context.
1180   mutable bool ExternalVisibleStorage : 1;
1181
1182   /// \brief Whether this declaration context has had external visible
1183   /// storage added since the last lookup. In this case, \c LookupPtr's
1184   /// invariant may not hold and needs to be fixed before we perform
1185   /// another lookup.
1186   mutable bool NeedToReconcileExternalVisibleStorage : 1;
1187
1188   /// \brief If \c true, this context may have local lexical declarations
1189   /// that are missing from the lookup table.
1190   mutable bool HasLazyLocalLexicalLookups : 1;
1191
1192   /// \brief If \c true, the external source may have lexical declarations
1193   /// that are missing from the lookup table.
1194   mutable bool HasLazyExternalLexicalLookups : 1;
1195
1196   /// \brief If \c true, lookups should only return identifier from
1197   /// DeclContext scope (for example TranslationUnit). Used in
1198   /// LookupQualifiedName()
1199   mutable bool UseQualifiedLookup : 1;
1200
1201   /// \brief Pointer to the data structure used to lookup declarations
1202   /// within this context (or a DependentStoredDeclsMap if this is a
1203   /// dependent context). We maintain the invariant that, if the map
1204   /// contains an entry for a DeclarationName (and we haven't lazily
1205   /// omitted anything), then it contains all relevant entries for that
1206   /// name (modulo the hasExternalDecls() flag).
1207   mutable StoredDeclsMap *LookupPtr;
1208
1209 protected:
1210   /// FirstDecl - The first declaration stored within this declaration
1211   /// context.
1212   mutable Decl *FirstDecl;
1213
1214   /// LastDecl - The last declaration stored within this declaration
1215   /// context. FIXME: We could probably cache this value somewhere
1216   /// outside of the DeclContext, to reduce the size of DeclContext by
1217   /// another pointer.
1218   mutable Decl *LastDecl;
1219
1220   friend class ExternalASTSource;
1221   friend class ASTDeclReader;
1222   friend class ASTWriter;
1223
1224   /// \brief Build up a chain of declarations.
1225   ///
1226   /// \returns the first/last pair of declarations.
1227   static std::pair<Decl *, Decl *>
1228   BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1229
1230   DeclContext(Decl::Kind K)
1231       : DeclKind(K), ExternalLexicalStorage(false),
1232         ExternalVisibleStorage(false),
1233         NeedToReconcileExternalVisibleStorage(false),
1234         HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1235         UseQualifiedLookup(false),
1236         LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
1237
1238 public:
1239   ~DeclContext();
1240
1241   Decl::Kind getDeclKind() const {
1242     return static_cast<Decl::Kind>(DeclKind);
1243   }
1244   const char *getDeclKindName() const;
1245
1246   /// getParent - Returns the containing DeclContext.
1247   DeclContext *getParent() {
1248     return cast<Decl>(this)->getDeclContext();
1249   }
1250   const DeclContext *getParent() const {
1251     return const_cast<DeclContext*>(this)->getParent();
1252   }
1253
1254   /// getLexicalParent - Returns the containing lexical DeclContext. May be
1255   /// different from getParent, e.g.:
1256   ///
1257   ///   namespace A {
1258   ///      struct S;
1259   ///   }
1260   ///   struct A::S {}; // getParent() == namespace 'A'
1261   ///                   // getLexicalParent() == translation unit
1262   ///
1263   DeclContext *getLexicalParent() {
1264     return cast<Decl>(this)->getLexicalDeclContext();
1265   }
1266   const DeclContext *getLexicalParent() const {
1267     return const_cast<DeclContext*>(this)->getLexicalParent();
1268   }
1269
1270   DeclContext *getLookupParent();
1271
1272   const DeclContext *getLookupParent() const {
1273     return const_cast<DeclContext*>(this)->getLookupParent();
1274   }
1275
1276   ASTContext &getParentASTContext() const {
1277     return cast<Decl>(this)->getASTContext();
1278   }
1279
1280   bool isClosure() const {
1281     return DeclKind == Decl::Block;
1282   }
1283
1284   bool isObjCContainer() const {
1285     switch (DeclKind) {
1286         case Decl::ObjCCategory:
1287         case Decl::ObjCCategoryImpl:
1288         case Decl::ObjCImplementation:
1289         case Decl::ObjCInterface:
1290         case Decl::ObjCProtocol:
1291             return true;
1292     }
1293     return false;
1294   }
1295
1296   bool isFunctionOrMethod() const {
1297     switch (DeclKind) {
1298     case Decl::Block:
1299     case Decl::Captured:
1300     case Decl::ObjCMethod:
1301       return true;
1302     default:
1303       return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1304     }
1305   }
1306
1307   /// \brief Test whether the context supports looking up names.
1308   bool isLookupContext() const {
1309     return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1310            DeclKind != Decl::Export;
1311   }
1312
1313   bool isFileContext() const {
1314     return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1315   }
1316
1317   bool isTranslationUnit() const {
1318     return DeclKind == Decl::TranslationUnit;
1319   }
1320
1321   bool isRecord() const {
1322     return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1323   }
1324
1325   bool isNamespace() const {
1326     return DeclKind == Decl::Namespace;
1327   }
1328
1329   bool isStdNamespace() const;
1330
1331   bool isInlineNamespace() const;
1332
1333   /// \brief Determines whether this context is dependent on a
1334   /// template parameter.
1335   bool isDependentContext() const;
1336
1337   /// isTransparentContext - Determines whether this context is a
1338   /// "transparent" context, meaning that the members declared in this
1339   /// context are semantically declared in the nearest enclosing
1340   /// non-transparent (opaque) context but are lexically declared in
1341   /// this context. For example, consider the enumerators of an
1342   /// enumeration type:
1343   /// @code
1344   /// enum E {
1345   ///   Val1
1346   /// };
1347   /// @endcode
1348   /// Here, E is a transparent context, so its enumerator (Val1) will
1349   /// appear (semantically) that it is in the same context of E.
1350   /// Examples of transparent contexts include: enumerations (except for
1351   /// C++0x scoped enums), and C++ linkage specifications.
1352   bool isTransparentContext() const;
1353
1354   /// \brief Determines whether this context or some of its ancestors is a
1355   /// linkage specification context that specifies C linkage.
1356   bool isExternCContext() const;
1357
1358   /// \brief Retrieve the nearest enclosing C linkage specification context.
1359   const LinkageSpecDecl *getExternCContext() const;
1360
1361   /// \brief Determines whether this context or some of its ancestors is a
1362   /// linkage specification context that specifies C++ linkage.
1363   bool isExternCXXContext() const;
1364
1365   /// \brief Determine whether this declaration context is equivalent
1366   /// to the declaration context DC.
1367   bool Equals(const DeclContext *DC) const {
1368     return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1369   }
1370
1371   /// \brief Determine whether this declaration context encloses the
1372   /// declaration context DC.
1373   bool Encloses(const DeclContext *DC) const;
1374
1375   /// \brief Find the nearest non-closure ancestor of this context,
1376   /// i.e. the innermost semantic parent of this context which is not
1377   /// a closure.  A context may be its own non-closure ancestor.
1378   Decl *getNonClosureAncestor();
1379   const Decl *getNonClosureAncestor() const {
1380     return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1381   }
1382
1383   /// getPrimaryContext - There may be many different
1384   /// declarations of the same entity (including forward declarations
1385   /// of classes, multiple definitions of namespaces, etc.), each with
1386   /// a different set of declarations. This routine returns the
1387   /// "primary" DeclContext structure, which will contain the
1388   /// information needed to perform name lookup into this context.
1389   DeclContext *getPrimaryContext();
1390   const DeclContext *getPrimaryContext() const {
1391     return const_cast<DeclContext*>(this)->getPrimaryContext();
1392   }
1393
1394   /// getRedeclContext - Retrieve the context in which an entity conflicts with
1395   /// other entities of the same name, or where it is a redeclaration if the
1396   /// two entities are compatible. This skips through transparent contexts.
1397   DeclContext *getRedeclContext();
1398   const DeclContext *getRedeclContext() const {
1399     return const_cast<DeclContext *>(this)->getRedeclContext();
1400   }
1401
1402   /// \brief Retrieve the nearest enclosing namespace context.
1403   DeclContext *getEnclosingNamespaceContext();
1404   const DeclContext *getEnclosingNamespaceContext() const {
1405     return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1406   }
1407
1408   /// \brief Retrieve the outermost lexically enclosing record context.
1409   RecordDecl *getOuterLexicalRecordContext();
1410   const RecordDecl *getOuterLexicalRecordContext() const {
1411     return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1412   }
1413
1414   /// \brief Test if this context is part of the enclosing namespace set of
1415   /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1416   /// isn't a namespace, this is equivalent to Equals().
1417   ///
1418   /// The enclosing namespace set of a namespace is the namespace and, if it is
1419   /// inline, its enclosing namespace, recursively.
1420   bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1421
1422   /// \brief Collects all of the declaration contexts that are semantically
1423   /// connected to this declaration context.
1424   ///
1425   /// For declaration contexts that have multiple semantically connected but
1426   /// syntactically distinct contexts, such as C++ namespaces, this routine 
1427   /// retrieves the complete set of such declaration contexts in source order.
1428   /// For example, given:
1429   ///
1430   /// \code
1431   /// namespace N {
1432   ///   int x;
1433   /// }
1434   /// namespace N {
1435   ///   int y;
1436   /// }
1437   /// \endcode
1438   ///
1439   /// The \c Contexts parameter will contain both definitions of N.
1440   ///
1441   /// \param Contexts Will be cleared and set to the set of declaration
1442   /// contexts that are semanticaly connected to this declaration context,
1443   /// in source order, including this context (which may be the only result,
1444   /// for non-namespace contexts).
1445   void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1446
1447   /// decl_iterator - Iterates through the declarations stored
1448   /// within this context.
1449   class decl_iterator {
1450     /// Current - The current declaration.
1451     Decl *Current;
1452
1453   public:
1454     typedef Decl *value_type;
1455     typedef const value_type &reference;
1456     typedef const value_type *pointer;
1457     typedef std::forward_iterator_tag iterator_category;
1458     typedef std::ptrdiff_t            difference_type;
1459
1460     decl_iterator() : Current(nullptr) { }
1461     explicit decl_iterator(Decl *C) : Current(C) { }
1462
1463     reference operator*() const { return Current; }
1464     // This doesn't meet the iterator requirements, but it's convenient
1465     value_type operator->() const { return Current; }
1466
1467     decl_iterator& operator++() {
1468       Current = Current->getNextDeclInContext();
1469       return *this;
1470     }
1471
1472     decl_iterator operator++(int) {
1473       decl_iterator tmp(*this);
1474       ++(*this);
1475       return tmp;
1476     }
1477
1478     friend bool operator==(decl_iterator x, decl_iterator y) {
1479       return x.Current == y.Current;
1480     }
1481     friend bool operator!=(decl_iterator x, decl_iterator y) {
1482       return x.Current != y.Current;
1483     }
1484   };
1485
1486   typedef llvm::iterator_range<decl_iterator> decl_range;
1487
1488   /// decls_begin/decls_end - Iterate over the declarations stored in
1489   /// this context.
1490   decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1491   decl_iterator decls_begin() const;
1492   decl_iterator decls_end() const { return decl_iterator(); }
1493   bool decls_empty() const;
1494
1495   /// noload_decls_begin/end - Iterate over the declarations stored in this
1496   /// context that are currently loaded; don't attempt to retrieve anything
1497   /// from an external source.
1498   decl_range noload_decls() const {
1499     return decl_range(noload_decls_begin(), noload_decls_end());
1500   }
1501   decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1502   decl_iterator noload_decls_end() const { return decl_iterator(); }
1503
1504   /// specific_decl_iterator - Iterates over a subrange of
1505   /// declarations stored in a DeclContext, providing only those that
1506   /// are of type SpecificDecl (or a class derived from it). This
1507   /// iterator is used, for example, to provide iteration over just
1508   /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1509   template<typename SpecificDecl>
1510   class specific_decl_iterator {
1511     /// Current - The current, underlying declaration iterator, which
1512     /// will either be NULL or will point to a declaration of
1513     /// type SpecificDecl.
1514     DeclContext::decl_iterator Current;
1515
1516     /// SkipToNextDecl - Advances the current position up to the next
1517     /// declaration of type SpecificDecl that also meets the criteria
1518     /// required by Acceptable.
1519     void SkipToNextDecl() {
1520       while (*Current && !isa<SpecificDecl>(*Current))
1521         ++Current;
1522     }
1523
1524   public:
1525     typedef SpecificDecl *value_type;
1526     // TODO: Add reference and pointer typedefs (with some appropriate proxy
1527     // type) if we ever have a need for them.
1528     typedef void reference;
1529     typedef void pointer;
1530     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1531       difference_type;
1532     typedef std::forward_iterator_tag iterator_category;
1533
1534     specific_decl_iterator() : Current() { }
1535
1536     /// specific_decl_iterator - Construct a new iterator over a
1537     /// subset of the declarations the range [C,
1538     /// end-of-declarations). If A is non-NULL, it is a pointer to a
1539     /// member function of SpecificDecl that should return true for
1540     /// all of the SpecificDecl instances that will be in the subset
1541     /// of iterators. For example, if you want Objective-C instance
1542     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1543     /// &ObjCMethodDecl::isInstanceMethod.
1544     explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1545       SkipToNextDecl();
1546     }
1547
1548     value_type operator*() const { return cast<SpecificDecl>(*Current); }
1549     // This doesn't meet the iterator requirements, but it's convenient
1550     value_type operator->() const { return **this; }
1551
1552     specific_decl_iterator& operator++() {
1553       ++Current;
1554       SkipToNextDecl();
1555       return *this;
1556     }
1557
1558     specific_decl_iterator operator++(int) {
1559       specific_decl_iterator tmp(*this);
1560       ++(*this);
1561       return tmp;
1562     }
1563
1564     friend bool operator==(const specific_decl_iterator& x,
1565                            const specific_decl_iterator& y) {
1566       return x.Current == y.Current;
1567     }
1568
1569     friend bool operator!=(const specific_decl_iterator& x,
1570                            const specific_decl_iterator& y) {
1571       return x.Current != y.Current;
1572     }
1573   };
1574
1575   /// \brief Iterates over a filtered subrange of declarations stored
1576   /// in a DeclContext.
1577   ///
1578   /// This iterator visits only those declarations that are of type
1579   /// SpecificDecl (or a class derived from it) and that meet some
1580   /// additional run-time criteria. This iterator is used, for
1581   /// example, to provide access to the instance methods within an
1582   /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1583   /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1584   template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1585   class filtered_decl_iterator {
1586     /// Current - The current, underlying declaration iterator, which
1587     /// will either be NULL or will point to a declaration of
1588     /// type SpecificDecl.
1589     DeclContext::decl_iterator Current;
1590
1591     /// SkipToNextDecl - Advances the current position up to the next
1592     /// declaration of type SpecificDecl that also meets the criteria
1593     /// required by Acceptable.
1594     void SkipToNextDecl() {
1595       while (*Current &&
1596              (!isa<SpecificDecl>(*Current) ||
1597               (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1598         ++Current;
1599     }
1600
1601   public:
1602     typedef SpecificDecl *value_type;
1603     // TODO: Add reference and pointer typedefs (with some appropriate proxy
1604     // type) if we ever have a need for them.
1605     typedef void reference;
1606     typedef void pointer;
1607     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1608       difference_type;
1609     typedef std::forward_iterator_tag iterator_category;
1610
1611     filtered_decl_iterator() : Current() { }
1612
1613     /// filtered_decl_iterator - Construct a new iterator over a
1614     /// subset of the declarations the range [C,
1615     /// end-of-declarations). If A is non-NULL, it is a pointer to a
1616     /// member function of SpecificDecl that should return true for
1617     /// all of the SpecificDecl instances that will be in the subset
1618     /// of iterators. For example, if you want Objective-C instance
1619     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1620     /// &ObjCMethodDecl::isInstanceMethod.
1621     explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1622       SkipToNextDecl();
1623     }
1624
1625     value_type operator*() const { return cast<SpecificDecl>(*Current); }
1626     value_type operator->() const { return cast<SpecificDecl>(*Current); }
1627
1628     filtered_decl_iterator& operator++() {
1629       ++Current;
1630       SkipToNextDecl();
1631       return *this;
1632     }
1633
1634     filtered_decl_iterator operator++(int) {
1635       filtered_decl_iterator tmp(*this);
1636       ++(*this);
1637       return tmp;
1638     }
1639
1640     friend bool operator==(const filtered_decl_iterator& x,
1641                            const filtered_decl_iterator& y) {
1642       return x.Current == y.Current;
1643     }
1644
1645     friend bool operator!=(const filtered_decl_iterator& x,
1646                            const filtered_decl_iterator& y) {
1647       return x.Current != y.Current;
1648     }
1649   };
1650
1651   /// @brief Add the declaration D into this context.
1652   ///
1653   /// This routine should be invoked when the declaration D has first
1654   /// been declared, to place D into the context where it was
1655   /// (lexically) defined. Every declaration must be added to one
1656   /// (and only one!) context, where it can be visited via
1657   /// [decls_begin(), decls_end()). Once a declaration has been added
1658   /// to its lexical context, the corresponding DeclContext owns the
1659   /// declaration.
1660   ///
1661   /// If D is also a NamedDecl, it will be made visible within its
1662   /// semantic context via makeDeclVisibleInContext.
1663   void addDecl(Decl *D);
1664
1665   /// @brief Add the declaration D into this context, but suppress
1666   /// searches for external declarations with the same name.
1667   ///
1668   /// Although analogous in function to addDecl, this removes an
1669   /// important check.  This is only useful if the Decl is being
1670   /// added in response to an external search; in all other cases,
1671   /// addDecl() is the right function to use.
1672   /// See the ASTImporter for use cases.
1673   void addDeclInternal(Decl *D);
1674
1675   /// @brief Add the declaration D to this context without modifying
1676   /// any lookup tables.
1677   ///
1678   /// This is useful for some operations in dependent contexts where
1679   /// the semantic context might not be dependent;  this basically
1680   /// only happens with friends.
1681   void addHiddenDecl(Decl *D);
1682
1683   /// @brief Removes a declaration from this context.
1684   void removeDecl(Decl *D);
1685     
1686   /// @brief Checks whether a declaration is in this context.
1687   bool containsDecl(Decl *D) const;
1688
1689   typedef DeclContextLookupResult lookup_result;
1690   typedef lookup_result::iterator lookup_iterator;
1691
1692   /// lookup - Find the declarations (if any) with the given Name in
1693   /// this context. Returns a range of iterators that contains all of
1694   /// the declarations with this name, with object, function, member,
1695   /// and enumerator names preceding any tag name. Note that this
1696   /// routine will not look into parent contexts.
1697   lookup_result lookup(DeclarationName Name) const;
1698
1699   /// \brief Find the declarations with the given name that are visible
1700   /// within this context; don't attempt to retrieve anything from an
1701   /// external source.
1702   lookup_result noload_lookup(DeclarationName Name);
1703
1704   /// \brief A simplistic name lookup mechanism that performs name lookup
1705   /// into this declaration context without consulting the external source.
1706   ///
1707   /// This function should almost never be used, because it subverts the
1708   /// usual relationship between a DeclContext and the external source.
1709   /// See the ASTImporter for the (few, but important) use cases.
1710   ///
1711   /// FIXME: This is very inefficient; replace uses of it with uses of
1712   /// noload_lookup.
1713   void localUncachedLookup(DeclarationName Name,
1714                            SmallVectorImpl<NamedDecl *> &Results);
1715
1716   /// @brief Makes a declaration visible within this context.
1717   ///
1718   /// This routine makes the declaration D visible to name lookup
1719   /// within this context and, if this is a transparent context,
1720   /// within its parent contexts up to the first enclosing
1721   /// non-transparent context. Making a declaration visible within a
1722   /// context does not transfer ownership of a declaration, and a
1723   /// declaration can be visible in many contexts that aren't its
1724   /// lexical context.
1725   ///
1726   /// If D is a redeclaration of an existing declaration that is
1727   /// visible from this context, as determined by
1728   /// NamedDecl::declarationReplaces, the previous declaration will be
1729   /// replaced with D.
1730   void makeDeclVisibleInContext(NamedDecl *D);
1731
1732   /// all_lookups_iterator - An iterator that provides a view over the results
1733   /// of looking up every possible name.
1734   class all_lookups_iterator;
1735
1736   typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1737
1738   lookups_range lookups() const;
1739   lookups_range noload_lookups() const;
1740
1741   /// \brief Iterators over all possible lookups within this context.
1742   all_lookups_iterator lookups_begin() const;
1743   all_lookups_iterator lookups_end() const;
1744
1745   /// \brief Iterators over all possible lookups within this context that are
1746   /// currently loaded; don't attempt to retrieve anything from an external
1747   /// source.
1748   all_lookups_iterator noload_lookups_begin() const;
1749   all_lookups_iterator noload_lookups_end() const;
1750
1751   struct udir_iterator;
1752   typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1753                                       std::random_access_iterator_tag,
1754                                       UsingDirectiveDecl *> udir_iterator_base;
1755   struct udir_iterator : udir_iterator_base {
1756     udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1757     UsingDirectiveDecl *operator*() const;
1758   };
1759
1760   typedef llvm::iterator_range<udir_iterator> udir_range;
1761
1762   udir_range using_directives() const;
1763
1764   // These are all defined in DependentDiagnostic.h.
1765   class ddiag_iterator;
1766   typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1767
1768   inline ddiag_range ddiags() const;
1769
1770   // Low-level accessors
1771
1772   /// \brief Mark that there are external lexical declarations that we need
1773   /// to include in our lookup table (and that are not available as external
1774   /// visible lookups). These extra lookup results will be found by walking
1775   /// the lexical declarations of this context. This should be used only if
1776   /// setHasExternalLexicalStorage() has been called on any decl context for
1777   /// which this is the primary context.
1778   void setMustBuildLookupTable() {
1779     assert(this == getPrimaryContext() &&
1780            "should only be called on primary context");
1781     HasLazyExternalLexicalLookups = true;
1782   }
1783
1784   /// \brief Retrieve the internal representation of the lookup structure.
1785   /// This may omit some names if we are lazily building the structure.
1786   StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1787
1788   /// \brief Ensure the lookup structure is fully-built and return it.
1789   StoredDeclsMap *buildLookup();
1790
1791   /// \brief Whether this DeclContext has external storage containing
1792   /// additional declarations that are lexically in this context.
1793   bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1794
1795   /// \brief State whether this DeclContext has external storage for
1796   /// declarations lexically in this context.
1797   void setHasExternalLexicalStorage(bool ES = true) {
1798     ExternalLexicalStorage = ES;
1799   }
1800
1801   /// \brief Whether this DeclContext has external storage containing
1802   /// additional declarations that are visible in this context.
1803   bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1804
1805   /// \brief State whether this DeclContext has external storage for
1806   /// declarations visible in this context.
1807   void setHasExternalVisibleStorage(bool ES = true) {
1808     ExternalVisibleStorage = ES;
1809     if (ES && LookupPtr)
1810       NeedToReconcileExternalVisibleStorage = true;
1811   }
1812
1813   /// \brief Determine whether the given declaration is stored in the list of
1814   /// declarations lexically within this context.
1815   bool isDeclInLexicalTraversal(const Decl *D) const {
1816     return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || 
1817                  D == LastDecl);
1818   }
1819
1820   bool setUseQualifiedLookup(bool use = true) {
1821     bool old_value = UseQualifiedLookup;
1822     UseQualifiedLookup = use;
1823     return old_value;
1824   }
1825
1826   bool shouldUseQualifiedLookup() const {
1827     return UseQualifiedLookup;
1828   }
1829
1830   static bool classof(const Decl *D);
1831   static bool classof(const DeclContext *D) { return true; }
1832
1833   void dumpDeclContext() const;
1834   void dumpLookups() const;
1835   void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
1836                    bool Deserialize = false) const;
1837
1838 private:
1839   void reconcileExternalVisibleStorage() const;
1840   bool LoadLexicalDeclsFromExternalStorage() const;
1841
1842   /// @brief Makes a declaration visible within this context, but
1843   /// suppresses searches for external declarations with the same
1844   /// name.
1845   ///
1846   /// Analogous to makeDeclVisibleInContext, but for the exclusive
1847   /// use of addDeclInternal().
1848   void makeDeclVisibleInContextInternal(NamedDecl *D);
1849
1850   friend class DependentDiagnostic;
1851   StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1852
1853   void buildLookupImpl(DeclContext *DCtx, bool Internal);
1854   void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1855                                          bool Rediscoverable);
1856   void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1857 };
1858
1859 inline bool Decl::isTemplateParameter() const {
1860   return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1861          getKind() == TemplateTemplateParm;
1862 }
1863
1864 // Specialization selected when ToTy is not a known subclass of DeclContext.
1865 template <class ToTy,
1866           bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1867 struct cast_convert_decl_context {
1868   static const ToTy *doit(const DeclContext *Val) {
1869     return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1870   }
1871
1872   static ToTy *doit(DeclContext *Val) {
1873     return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1874   }
1875 };
1876
1877 // Specialization selected when ToTy is a known subclass of DeclContext.
1878 template <class ToTy>
1879 struct cast_convert_decl_context<ToTy, true> {
1880   static const ToTy *doit(const DeclContext *Val) {
1881     return static_cast<const ToTy*>(Val);
1882   }
1883
1884   static ToTy *doit(DeclContext *Val) {
1885     return static_cast<ToTy*>(Val);
1886   }
1887 };
1888
1889
1890 } // end clang.
1891
1892 namespace llvm {
1893
1894 /// isa<T>(DeclContext*)
1895 template <typename To>
1896 struct isa_impl<To, ::clang::DeclContext> {
1897   static bool doit(const ::clang::DeclContext &Val) {
1898     return To::classofKind(Val.getDeclKind());
1899   }
1900 };
1901
1902 /// cast<T>(DeclContext*)
1903 template<class ToTy>
1904 struct cast_convert_val<ToTy,
1905                         const ::clang::DeclContext,const ::clang::DeclContext> {
1906   static const ToTy &doit(const ::clang::DeclContext &Val) {
1907     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1908   }
1909 };
1910 template<class ToTy>
1911 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1912   static ToTy &doit(::clang::DeclContext &Val) {
1913     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1914   }
1915 };
1916 template<class ToTy>
1917 struct cast_convert_val<ToTy,
1918                      const ::clang::DeclContext*, const ::clang::DeclContext*> {
1919   static const ToTy *doit(const ::clang::DeclContext *Val) {
1920     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1921   }
1922 };
1923 template<class ToTy>
1924 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1925   static ToTy *doit(::clang::DeclContext *Val) {
1926     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1927   }
1928 };
1929
1930 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1931 template<class FromTy>
1932 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1933   static ::clang::DeclContext &doit(const FromTy &Val) {
1934     return *FromTy::castToDeclContext(&Val);
1935   }
1936 };
1937
1938 template<class FromTy>
1939 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1940   static ::clang::DeclContext *doit(const FromTy *Val) {
1941     return FromTy::castToDeclContext(Val);
1942   }
1943 };
1944
1945 template<class FromTy>
1946 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1947   static const ::clang::DeclContext &doit(const FromTy &Val) {
1948     return *FromTy::castToDeclContext(&Val);
1949   }
1950 };
1951
1952 template<class FromTy>
1953 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1954   static const ::clang::DeclContext *doit(const FromTy *Val) {
1955     return FromTy::castToDeclContext(Val);
1956   }
1957 };
1958
1959 } // end namespace llvm
1960
1961 #endif