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