Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp
Warning:line 131, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CxxModuleHandler.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/ExpressionParser/Clang -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Plugins/ExpressionParser/Clang -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

1//===-- CxxModuleHandler.cpp ----------------------------------------------===//
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#include "Plugins/ExpressionParser/Clang/CxxModuleHandler.h"
10#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
11
12#include "lldb/Utility/LLDBLog.h"
13#include "lldb/Utility/Log.h"
14#include "clang/Sema/Lookup.h"
15#include "llvm/Support/Error.h"
16
17using namespace lldb_private;
18using namespace clang;
19
20CxxModuleHandler::CxxModuleHandler(ASTImporter &importer, ASTContext *target)
21 : m_importer(&importer),
22 m_sema(TypeSystemClang::GetASTContext(target)->getSema()) {
23
24 std::initializer_list<const char *> supported_names = {
25 // containers
26 "array",
27 "deque",
28 "forward_list",
29 "list",
30 "queue",
31 "stack",
32 "vector",
33 // pointers
34 "shared_ptr",
35 "unique_ptr",
36 "weak_ptr",
37 // iterator
38 "move_iterator",
39 "__wrap_iter",
40 // utility
41 "allocator",
42 "pair",
43 };
44 m_supported_templates.insert(supported_names.begin(), supported_names.end());
45}
46
47/// Builds a list of scopes that point into the given context.
48///
49/// \param sema The sema that will be using the scopes.
50/// \param ctxt The context that the scope should look into.
51/// \param result A list of scopes. The scopes need to be freed by the caller
52/// (except the TUScope which is owned by the sema).
53static void makeScopes(Sema &sema, DeclContext *ctxt,
54 std::vector<Scope *> &result) {
55 // FIXME: The result should be a list of unique_ptrs, but the TUScope makes
56 // this currently impossible as it's owned by the Sema.
57
58 if (auto parent = ctxt->getParent()) {
59 makeScopes(sema, parent, result);
60
61 Scope *scope =
62 new Scope(result.back(), Scope::DeclScope, sema.getDiagnostics());
63 scope->setEntity(ctxt);
64 result.push_back(scope);
65 } else
66 result.push_back(sema.TUScope);
67}
68
69/// Uses the Sema to look up the given name in the given DeclContext.
70static std::unique_ptr<LookupResult>
71emulateLookupInCtxt(Sema &sema, llvm::StringRef name, DeclContext *ctxt) {
72 IdentifierInfo &ident = sema.getASTContext().Idents.get(name);
73
74 std::unique_ptr<LookupResult> lookup_result;
75 lookup_result = std::make_unique<LookupResult>(sema, DeclarationName(&ident),
76 SourceLocation(),
77 Sema::LookupOrdinaryName);
78
79 // Usually during parsing we already encountered the scopes we would use. But
80 // here don't have these scopes so we have to emulate the behavior of the
81 // Sema during parsing.
82 std::vector<Scope *> scopes;
83 makeScopes(sema, ctxt, scopes);
84
85 // Now actually perform the lookup with the sema.
86 sema.LookupName(*lookup_result, scopes.back());
87
88 // Delete all the allocated scopes beside the translation unit scope (which
89 // has depth 0).
90 for (Scope *s : scopes)
91 if (s->getDepth() != 0)
92 delete s;
93
94 return lookup_result;
95}
96
97/// Error class for handling problems when finding a certain DeclContext.
98struct MissingDeclContext : public llvm::ErrorInfo<MissingDeclContext> {
99
100 static char ID;
101
102 MissingDeclContext(DeclContext *context, std::string error)
103 : m_context(context), m_error(error) {}
104
105 DeclContext *m_context;
106 std::string m_error;
107
108 void log(llvm::raw_ostream &OS) const override {
109 OS << llvm::formatv("error when reconstructing context of kind {0}:{1}",
110 m_context->getDeclKindName(), m_error);
111 }
112
113 std::error_code convertToErrorCode() const override {
114 return llvm::inconvertibleErrorCode();
115 }
116};
117
118char MissingDeclContext::ID = 0;
119
120/// Given a foreign decl context, this function finds the equivalent local
121/// decl context in the ASTContext of the given Sema. Potentially deserializes
122/// decls from the 'std' module if necessary.
123static llvm::Expected<DeclContext *>
124getEqualLocalDeclContext(Sema &sema, DeclContext *foreign_ctxt) {
125
126 // Inline namespaces don't matter for lookups, so let's skip them.
127 while (foreign_ctxt && foreign_ctxt->isInlineNamespace())
24
Assuming 'foreign_ctxt' is null
128 foreign_ctxt = foreign_ctxt->getParent();
129
130 // If the foreign context is the TU, we just return the local TU.
131 if (foreign_ctxt->isTranslationUnit())
25
Called C++ object pointer is null
132 return sema.getASTContext().getTranslationUnitDecl();
133
134 // Recursively find/build the parent DeclContext.
135 llvm::Expected<DeclContext *> parent =
136 getEqualLocalDeclContext(sema, foreign_ctxt->getParent());
137 if (!parent)
138 return parent;
139
140 // We currently only support building namespaces.
141 if (foreign_ctxt->isNamespace()) {
142 NamedDecl *ns = llvm::cast<NamedDecl>(foreign_ctxt);
143 llvm::StringRef ns_name = ns->getName();
144
145 auto lookup_result = emulateLookupInCtxt(sema, ns_name, *parent);
146 for (NamedDecl *named_decl : *lookup_result) {
147 if (DeclContext *DC = llvm::dyn_cast<DeclContext>(named_decl))
148 return DC->getPrimaryContext();
149 }
150 return llvm::make_error<MissingDeclContext>(
151 foreign_ctxt,
152 "Couldn't find namespace " + ns->getQualifiedNameAsString());
153 }
154
155 return llvm::make_error<MissingDeclContext>(foreign_ctxt, "Unknown context ");
156}
157
158/// Returns true iff tryInstantiateStdTemplate supports instantiating a template
159/// with the given template arguments.
160static bool templateArgsAreSupported(ArrayRef<TemplateArgument> a) {
161 for (const TemplateArgument &arg : a) {
162 switch (arg.getKind()) {
163 case TemplateArgument::Type:
164 case TemplateArgument::Integral:
165 break;
166 default:
167 // TemplateArgument kind hasn't been handled yet.
168 return false;
169 }
170 }
171 return true;
172}
173
174/// Constructor function for Clang declarations. Ensures that the created
175/// declaration is registered with the ASTImporter.
176template <typename T, typename... Args>
177T *createDecl(ASTImporter &importer, Decl *from_d, Args &&... args) {
178 T *to_d = T::Create(std::forward<Args>(args)...);
179 importer.RegisterImportedDecl(from_d, to_d);
180 return to_d;
181}
182
183llvm::Optional<Decl *> CxxModuleHandler::tryInstantiateStdTemplate(Decl *d) {
184 Log *log = GetLog(LLDBLog::Expressions);
185
186 // If we don't have a template to instiantiate, then there is nothing to do.
187 auto td = dyn_cast<ClassTemplateSpecializationDecl>(d);
3
Assuming 'd' is a 'ClassTemplateSpecializationDecl'
188 if (!td
3.1
'td' is non-null
3.1
'td' is non-null
3.1
'td' is non-null
)
4
Taking false branch
189 return llvm::None;
190
191 // We only care about templates in the std namespace.
192 if (!td->getDeclContext()->isStdNamespace())
5
Assuming the condition is false
6
Taking false branch
193 return llvm::None;
194
195 // We have a list of supported template names.
196 if (!m_supported_templates.contains(td->getName()))
7
Assuming the condition is false
8
Taking false branch
197 return llvm::None;
198
199 // Early check if we even support instantiating this template. We do this
200 // before we import anything into the target AST.
201 auto &foreign_args = td->getTemplateInstantiationArgs();
202 if (!templateArgsAreSupported(foreign_args.asArray()))
9
Taking false branch
203 return llvm::None;
204
205 // Find the local DeclContext that corresponds to the DeclContext of our
206 // decl we want to import.
207 llvm::Expected<DeclContext *> to_context =
208 getEqualLocalDeclContext(*m_sema, td->getDeclContext());
10
Calling 'Decl::getDeclContext'
21
Returning from 'Decl::getDeclContext'
22
Passing value via 2nd parameter 'foreign_ctxt'
23
Calling 'getEqualLocalDeclContext'
209 if (!to_context) {
210 LLDB_LOG_ERROR(log, to_context.takeError(),do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
211 "Got error while searching equal local DeclContext for decl "do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
212 "'{1}':\n{0}",do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
213 td->getName())do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
214 return llvm::None;
215 }
216
217 // Look up the template in our local context.
218 std::unique_ptr<LookupResult> lookup =
219 emulateLookupInCtxt(*m_sema, td->getName(), *to_context);
220
221 ClassTemplateDecl *new_class_template = nullptr;
222 for (auto LD : *lookup) {
223 if ((new_class_template = dyn_cast<ClassTemplateDecl>(LD)))
224 break;
225 }
226 if (!new_class_template)
227 return llvm::None;
228
229 // Import the foreign template arguments.
230 llvm::SmallVector<TemplateArgument, 4> imported_args;
231
232 // If this logic is changed, also update templateArgsAreSupported.
233 for (const TemplateArgument &arg : foreign_args.asArray()) {
234 switch (arg.getKind()) {
235 case TemplateArgument::Type: {
236 llvm::Expected<QualType> type = m_importer->Import(arg.getAsType());
237 if (!type) {
238 LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (type.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Couldn't import type: {0}"); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
239 return llvm::None;
240 }
241 imported_args.push_back(TemplateArgument(*type));
242 break;
243 }
244 case TemplateArgument::Integral: {
245 llvm::APSInt integral = arg.getAsIntegral();
246 llvm::Expected<QualType> type =
247 m_importer->Import(arg.getIntegralType());
248 if (!type) {
249 LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (type.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Couldn't import type: {0}"); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
250 return llvm::None;
251 }
252 imported_args.push_back(
253 TemplateArgument(d->getASTContext(), integral, *type));
254 break;
255 }
256 default:
257 assert(false && "templateArgsAreSupported not updated?")(static_cast <bool> (false && "templateArgsAreSupported not updated?"
) ? void (0) : __assert_fail ("false && \"templateArgsAreSupported not updated?\""
, "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, 257, __extension__ __PRETTY_FUNCTION__))
;
258 }
259 }
260
261 // Find the class template specialization declaration that
262 // corresponds to these arguments.
263 void *InsertPos = nullptr;
264 ClassTemplateSpecializationDecl *result =
265 new_class_template->findSpecialization(imported_args, InsertPos);
266
267 if (result) {
268 // We found an existing specialization in the module that fits our arguments
269 // so we can treat it as the result and register it with the ASTImporter.
270 m_importer->RegisterImportedDecl(d, result);
271 return result;
272 }
273
274 // Instantiate the template.
275 result = createDecl<ClassTemplateSpecializationDecl>(
276 *m_importer, d, m_sema->getASTContext(),
277 new_class_template->getTemplatedDecl()->getTagKind(),
278 new_class_template->getDeclContext(),
279 new_class_template->getTemplatedDecl()->getLocation(),
280 new_class_template->getLocation(), new_class_template, imported_args,
281 nullptr);
282
283 new_class_template->AddSpecialization(result, InsertPos);
284 if (new_class_template->isOutOfLine())
285 result->setLexicalDeclContext(
286 new_class_template->getLexicalDeclContext());
287 return result;
288}
289
290llvm::Optional<Decl *> CxxModuleHandler::Import(Decl *d) {
291 if (!isValid())
1
Taking false branch
292 return {};
293
294 return tryInstantiateStdTemplate(d);
2
Calling 'CxxModuleHandler::tryInstantiateStdTemplate'
295}

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include/clang/AST/DeclBase.h

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

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- 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/// \file
10/// This file defines the PointerUnion class, which is a discriminated union of
11/// pointer types.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_POINTERUNION_H
16#define LLVM_ADT_POINTERUNION_H
17
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/PointerLikeTypeTraits.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <cstdint>
26
27namespace llvm {
28
29namespace pointer_union_detail {
30 /// Determine the number of bits required to store integers with values < n.
31 /// This is ceil(log2(n)).
32 constexpr int bitsRequired(unsigned n) {
33 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
34 }
35
36 template <typename... Ts> constexpr int lowBitsAvailable() {
37 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
38 }
39
40 /// Find the first type in a list of types.
41 template <typename T, typename...> struct GetFirstType {
42 using type = T;
43 };
44
45 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
46 /// for the template arguments.
47 template <typename ...PTs> class PointerUnionUIntTraits {
48 public:
49 static inline void *getAsVoidPointer(void *P) { return P; }
50 static inline void *getFromVoidPointer(void *P) { return P; }
51 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
52 };
53
54 template <typename Derived, typename ValTy, int I, typename ...Types>
55 class PointerUnionMembers;
56
57 template <typename Derived, typename ValTy, int I>
58 class PointerUnionMembers<Derived, ValTy, I> {
59 protected:
60 ValTy Val;
61 PointerUnionMembers() = default;
62 PointerUnionMembers(ValTy Val) : Val(Val) {}
63
64 friend struct PointerLikeTypeTraits<Derived>;
65 };
66
67 template <typename Derived, typename ValTy, int I, typename Type,
68 typename ...Types>
69 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
70 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
71 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
72 public:
73 using Base::Base;
74 PointerUnionMembers() = default;
75 PointerUnionMembers(Type V)
76 : Base(ValTy(const_cast<void *>(
77 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
78 I)) {}
79
80 using Base::operator=;
81 Derived &operator=(Type V) {
82 this->Val = ValTy(
83 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
84 I);
85 return static_cast<Derived &>(*this);
86 };
87 };
88}
89
90/// A discriminated union of two or more pointer types, with the discriminator
91/// in the low bit of the pointer.
92///
93/// This implementation is extremely efficient in space due to leveraging the
94/// low bits of the pointer, while exposing a natural and type-safe API.
95///
96/// Common use patterns would be something like this:
97/// PointerUnion<int*, float*> P;
98/// P = (int*)0;
99/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
100/// X = P.get<int*>(); // ok.
101/// Y = P.get<float*>(); // runtime assertion failure.
102/// Z = P.get<double*>(); // compile time failure.
103/// P = (float*)0;
104/// Y = P.get<float*>(); // ok.
105/// X = P.get<int*>(); // runtime assertion failure.
106/// PointerUnion<int*, int*> Q; // compile time failure.
107template <typename... PTs>
108class PointerUnion
109 : public pointer_union_detail::PointerUnionMembers<
110 PointerUnion<PTs...>,
111 PointerIntPair<
112 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
113 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
114 0, PTs...> {
115 static_assert(TypesAreDistinct<PTs...>::value,
116 "PointerUnion alternative types cannot be repeated");
117 // The first type is special because we want to directly cast a pointer to a
118 // default-initialized union to a pointer to the first type. But we don't
119 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
120 // because it's much more convenient to have a name for the whole pack. So
121 // split off the first type here.
122 using First = TypeAtIndex<0, PTs...>;
123 using Base = typename PointerUnion::PointerUnionMembers;
124
125public:
126 PointerUnion() = default;
127
128 PointerUnion(std::nullptr_t) : PointerUnion() {}
129 using Base::Base;
130
131 /// Test if the pointer held in the union is null, regardless of
132 /// which type it is.
133 bool isNull() const { return !this->Val.getPointer(); }
134
135 explicit operator bool() const { return !isNull(); }
136
137 /// Test if the Union currently holds the type matching T.
138 template <typename T> bool is() const {
139 return this->Val.getInt() == FirstIndexOfType<T, PTs...>::value;
140 }
141
142 /// Returns the value of the specified pointer type.
143 ///
144 /// If the specified pointer type is incorrect, assert.
145 template <typename T> T get() const {
146 assert(is<T>() && "Invalid accessor called")(static_cast <bool> (is<T>() && "Invalid accessor called"
) ? void (0) : __assert_fail ("is<T>() && \"Invalid accessor called\""
, "llvm/include/llvm/ADT/PointerUnion.h", 146, __extension__ __PRETTY_FUNCTION__
))
;
14
'?' condition is true
147 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
15
Passing value via 1st parameter 'P'
16
Returning pointer
148 }
149
150 /// Returns the current pointer if it is of the specified pointer type,
151 /// otherwise returns null.
152 template <typename T> T dyn_cast() const {
153 if (is<T>())
154 return get<T>();
155 return T();
156 }
157
158 /// If the union is set to the first pointer type get an address pointing to
159 /// it.
160 First const *getAddrOfPtr1() const {
161 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
162 }
163
164 /// If the union is set to the first pointer type get an address pointing to
165 /// it.
166 First *getAddrOfPtr1() {
167 assert(is<First>() && "Val is not the first pointer")(static_cast <bool> (is<First>() && "Val is not the first pointer"
) ? void (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "llvm/include/llvm/ADT/PointerUnion.h", 167, __extension__ __PRETTY_FUNCTION__
))
;
168 assert((static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 171, __extension__ __PRETTY_FUNCTION__
))
169 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 171, __extension__ __PRETTY_FUNCTION__
))
170 this->Val.getPointer() &&(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 171, __extension__ __PRETTY_FUNCTION__
))
171 "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 171, __extension__ __PRETTY_FUNCTION__
))
;
172 return const_cast<First *>(
173 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
174 }
175
176 /// Assignment from nullptr which just clears the union.
177 const PointerUnion &operator=(std::nullptr_t) {
178 this->Val.initWithPointer(nullptr);
179 return *this;
180 }
181
182 /// Assignment from elements of the union.
183 using Base::operator=;
184
185 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
186 static inline PointerUnion getFromOpaqueValue(void *VP) {
187 PointerUnion V;
188 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
189 return V;
190 }
191};
192
193template <typename ...PTs>
194bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
195 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
196}
197
198template <typename ...PTs>
199bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
200 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
201}
202
203template <typename ...PTs>
204bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
205 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
206}
207
208// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
209// # low bits available = min(PT1bits,PT2bits)-1.
210template <typename ...PTs>
211struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
212 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
213 return P.getOpaqueValue();
214 }
215
216 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
217 return PointerUnion<PTs...>::getFromOpaqueValue(P);
218 }
219
220 // The number of bits available are the min of the pointer types minus the
221 // bits needed for the discriminator.
222 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
223 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
224};
225
226// Teach DenseMap how to use PointerUnions as keys.
227template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
228 using Union = PointerUnion<PTs...>;
229 using FirstInfo =
230 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
231
232 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
233
234 static inline Union getTombstoneKey() {
235 return Union(FirstInfo::getTombstoneKey());
236 }
237
238 static unsigned getHashValue(const Union &UnionVal) {
239 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
240 return DenseMapInfo<intptr_t>::getHashValue(key);
241 }
242
243 static bool isEqual(const Union &LHS, const Union &RHS) {
244 return LHS == RHS;
245 }
246};
247
248} // end namespace llvm
249
250#endif // LLVM_ADT_POINTERUNION_H