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

source code of clang/include/clang/AST/DeclBase.h