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