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

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