Bug Summary

File:lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp
Warning:line 142, column 31
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-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/ExpressionParser/Clang -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/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-14/lib/clang/14.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-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -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-deprecated-register -Wno-vla-extension -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -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-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

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

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

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- 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 an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <memory>
35#include <new>
36#include <string>
37#include <system_error>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class ErrorSuccess;
45
46/// Base class for error info classes. Do not extend this directly: Extend
47/// the ErrorInfo template subclass instead.
48class ErrorInfoBase {
49public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
68
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86private:
87 virtual void anchor();
88
89 static char ID;
90};
91
92/// Lightweight error class with error context and mandatory checking.
93///
94/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95/// are represented by setting the pointer to a ErrorInfoBase subclass
96/// instance containing information describing the failure. Success is
97/// represented by a null pointer value.
98///
99/// Instances of Error also contains a 'Checked' flag, which must be set
100/// before the destructor is called, otherwise the destructor will trigger a
101/// runtime error. This enforces at runtime the requirement that all Error
102/// instances be checked or returned to the caller.
103///
104/// There are two ways to set the checked flag, depending on what state the
105/// Error instance is in. For Error instances indicating success, it
106/// is sufficient to invoke the boolean conversion operator. E.g.:
107///
108/// @code{.cpp}
109/// Error foo(<...>);
110///
111/// if (auto E = foo(<...>))
112/// return E; // <- Return E if it is in the error state.
113/// // We have verified that E was in the success state. It can now be safely
114/// // destroyed.
115/// @endcode
116///
117/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118/// without testing the return value will raise a runtime error, even if foo
119/// returns success.
120///
121/// For Error instances representing failure, you must use either the
122/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123///
124/// @code{.cpp}
125/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126/// // Custom error info.
127/// };
128///
129/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130///
131/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132/// auto NewE =
133/// handleErrors(E,
134/// [](const MyErrorInfo &M) {
135/// // Deal with the error.
136/// },
137/// [](std::unique_ptr<OtherError> M) -> Error {
138/// if (canHandle(*M)) {
139/// // handle error.
140/// return Error::success();
141/// }
142/// // Couldn't handle this error instance. Pass it up the stack.
143/// return Error(std::move(M));
144/// );
145/// // Note - we must check or return NewE in case any of the handlers
146/// // returned a new error.
147/// @endcode
148///
149/// The handleAllErrors function is identical to handleErrors, except
150/// that it has a void return type, and requires all errors to be handled and
151/// no new errors be returned. It prevents errors (assuming they can all be
152/// handled) from having to be bubbled all the way to the top-level.
153///
154/// *All* Error instances must be checked before destruction, even if
155/// they're moved-assigned or constructed from Success values that have already
156/// been checked. This enforces checking through all levels of the call stack.
157class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
158 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
159 // to add to the error list. It can't rely on handleErrors for this, since
160 // handleErrors does not support ErrorList handlers.
161 friend class ErrorList;
162
163 // handleErrors needs to be able to set the Checked flag.
164 template <typename... HandlerTs>
165 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166
167 // Expected<T> needs to be able to steal the payload when constructed from an
168 // error.
169 template <typename T> friend class Expected;
170
171 // wrap needs to be able to steal the payload.
172 friend LLVMErrorRef wrap(Error);
173
174protected:
175 /// Create a success value. Prefer using 'Error::success()' for readability
176 Error() {
177 setPtr(nullptr);
178 setChecked(false);
179 }
180
181public:
182 /// Create a success value.
183 static ErrorSuccess success();
184
185 // Errors are not copy-constructable.
186 Error(const Error &Other) = delete;
187
188 /// Move-construct an error value. The newly constructed error is considered
189 /// unchecked, even if the source error had been checked. The original error
190 /// becomes a checked Success value, regardless of its original state.
191 Error(Error &&Other) {
192 setChecked(true);
193 *this = std::move(Other);
194 }
195
196 /// Create an error value. Prefer using the 'make_error' function, but
197 /// this constructor can be useful when "re-throwing" errors from handlers.
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
200 setChecked(false);
201 }
202
203 // Errors are not copy-assignable.
204 Error &operator=(const Error &Other) = delete;
205
206 /// Move-assign an error value. The current error must represent success, you
207 /// you cannot overwrite an unhandled error. The current error is then
208 /// considered unchecked. The source error becomes a checked success value,
209 /// regardless of its original state.
210 Error &operator=(Error &&Other) {
211 // Don't allow overwriting of unchecked values.
212 assertIsChecked();
213 setPtr(Other.getPtr());
214
215 // This Error is unchecked, even if the source error was checked.
216 setChecked(false);
217
218 // Null out Other's payload and set its checked bit.
219 Other.setPtr(nullptr);
220 Other.setChecked(true);
221
222 return *this;
223 }
224
225 /// Destroy a Error. Fails with a call to abort() if the error is
226 /// unchecked.
227 ~Error() {
228 assertIsChecked();
229 delete getPtr();
230 }
231
232 /// Bool conversion. Returns true if this Error is in a failure state,
233 /// and false if it is in an accept state. If the error is in a Success state
234 /// it will be considered checked.
235 explicit operator bool() {
236 setChecked(getPtr() == nullptr);
237 return getPtr() != nullptr;
238 }
239
240 /// Check whether one error is a subclass of another.
241 template <typename ErrT> bool isA() const {
242 return getPtr() && getPtr()->isA(ErrT::classID());
243 }
244
245 /// Returns the dynamic class id of this error, or null if this is a success
246 /// value.
247 const void* dynamicClassID() const {
248 if (!getPtr())
249 return nullptr;
250 return getPtr()->dynamicClassID();
251 }
252
253private:
254#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
255 // assertIsChecked() happens very frequently, but under normal circumstances
256 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
257 // of debug prints can cause the function to be too large for inlining. So
258 // it's important that we define this function out of line so that it can't be
259 // inlined.
260 [[noreturn]] void fatalUncheckedError() const;
261#endif
262
263 void assertIsChecked() {
264#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
265 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
266 fatalUncheckedError();
267#endif
268 }
269
270 ErrorInfoBase *getPtr() const {
271#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
272 return reinterpret_cast<ErrorInfoBase*>(
273 reinterpret_cast<uintptr_t>(Payload) &
274 ~static_cast<uintptr_t>(0x1));
275#else
276 return Payload;
277#endif
278 }
279
280 void setPtr(ErrorInfoBase *EI) {
281#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
282 Payload = reinterpret_cast<ErrorInfoBase*>(
283 (reinterpret_cast<uintptr_t>(EI) &
284 ~static_cast<uintptr_t>(0x1)) |
285 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
286#else
287 Payload = EI;
288#endif
289 }
290
291 bool getChecked() const {
292#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
293 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
294#else
295 return true;
296#endif
297 }
298
299 void setChecked(bool V) {
300#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
301 Payload = reinterpret_cast<ErrorInfoBase*>(
302 (reinterpret_cast<uintptr_t>(Payload) &
303 ~static_cast<uintptr_t>(0x1)) |
304 (V ? 0 : 1));
305#endif
306 }
307
308 std::unique_ptr<ErrorInfoBase> takePayload() {
309 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
310 setPtr(nullptr);
311 setChecked(true);
312 return Tmp;
313 }
314
315 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
316 if (auto *P = E.getPtr())
317 P->log(OS);
318 else
319 OS << "success";
320 return OS;
321 }
322
323 ErrorInfoBase *Payload = nullptr;
324};
325
326/// Subclass of Error for the sole purpose of identifying the success path in
327/// the type system. This allows to catch invalid conversion to Expected<T> at
328/// compile time.
329class ErrorSuccess final : public Error {};
330
331inline ErrorSuccess Error::success() { return ErrorSuccess(); }
332
333/// Make a Error instance representing failure using the given error info
334/// type.
335template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
336 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
337}
338
339/// Base class for user error types. Users should declare their error types
340/// like:
341///
342/// class MyError : public ErrorInfo<MyError> {
343/// ....
344/// };
345///
346/// This class provides an implementation of the ErrorInfoBase::kind
347/// method, which is used by the Error RTTI system.
348template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
349class ErrorInfo : public ParentErrT {
350public:
351 using ParentErrT::ParentErrT; // inherit constructors
352
353 static const void *classID() { return &ThisErrT::ID; }
354
355 const void *dynamicClassID() const override { return &ThisErrT::ID; }
356
357 bool isA(const void *const ClassID) const override {
358 return ClassID == classID() || ParentErrT::isA(ClassID);
359 }
360};
361
362/// Special ErrorInfo subclass representing a list of ErrorInfos.
363/// Instances of this class are constructed by joinError.
364class ErrorList final : public ErrorInfo<ErrorList> {
365 // handleErrors needs to be able to iterate the payload list of an
366 // ErrorList.
367 template <typename... HandlerTs>
368 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
369
370 // joinErrors is implemented in terms of join.
371 friend Error joinErrors(Error, Error);
372
373public:
374 void log(raw_ostream &OS) const override {
375 OS << "Multiple errors:\n";
376 for (const auto &ErrPayload : Payloads) {
377 ErrPayload->log(OS);
378 OS << "\n";
379 }
380 }
381
382 std::error_code convertToErrorCode() const override;
383
384 // Used by ErrorInfo::classID.
385 static char ID;
386
387private:
388 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
389 std::unique_ptr<ErrorInfoBase> Payload2) {
390 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&(static_cast <bool> (!Payload1->isA<ErrorList>
() && !Payload2->isA<ErrorList>() &&
"ErrorList constructor payloads should be singleton errors")
? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "llvm/include/llvm/Support/Error.h", 391, __extension__ __PRETTY_FUNCTION__
))
391 "ErrorList constructor payloads should be singleton errors")(static_cast <bool> (!Payload1->isA<ErrorList>
() && !Payload2->isA<ErrorList>() &&
"ErrorList constructor payloads should be singleton errors")
? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "llvm/include/llvm/Support/Error.h", 391, __extension__ __PRETTY_FUNCTION__
))
;
392 Payloads.push_back(std::move(Payload1));
393 Payloads.push_back(std::move(Payload2));
394 }
395
396 static Error join(Error E1, Error E2) {
397 if (!E1)
398 return E2;
399 if (!E2)
400 return E1;
401 if (E1.isA<ErrorList>()) {
402 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
403 if (E2.isA<ErrorList>()) {
404 auto E2Payload = E2.takePayload();
405 auto &E2List = static_cast<ErrorList &>(*E2Payload);
406 for (auto &Payload : E2List.Payloads)
407 E1List.Payloads.push_back(std::move(Payload));
408 } else
409 E1List.Payloads.push_back(E2.takePayload());
410
411 return E1;
412 }
413 if (E2.isA<ErrorList>()) {
414 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
415 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
416 return E2;
417 }
418 return Error(std::unique_ptr<ErrorList>(
419 new ErrorList(E1.takePayload(), E2.takePayload())));
420 }
421
422 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
423};
424
425/// Concatenate errors. The resulting Error is unchecked, and contains the
426/// ErrorInfo(s), if any, contained in E1, followed by the
427/// ErrorInfo(s), if any, contained in E2.
428inline Error joinErrors(Error E1, Error E2) {
429 return ErrorList::join(std::move(E1), std::move(E2));
430}
431
432/// Tagged union holding either a T or a Error.
433///
434/// This class parallels ErrorOr, but replaces error_code with Error. Since
435/// Error cannot be copied, this class replaces getError() with
436/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
437/// error class type.
438///
439/// Example usage of 'Expected<T>' as a function return type:
440///
441/// @code{.cpp}
442/// Expected<int> myDivide(int A, int B) {
443/// if (B == 0) {
444/// // return an Error
445/// return createStringError(inconvertibleErrorCode(),
446/// "B must not be zero!");
447/// }
448/// // return an integer
449/// return A / B;
450/// }
451/// @endcode
452///
453/// Checking the results of to a function returning 'Expected<T>':
454/// @code{.cpp}
455/// if (auto E = Result.takeError()) {
456/// // We must consume the error. Typically one of:
457/// // - return the error to our caller
458/// // - toString(), when logging
459/// // - consumeError(), to silently swallow the error
460/// // - handleErrors(), to distinguish error types
461/// errs() << "Problem with division " << toString(std::move(E)) << "\n";
462/// return;
463/// }
464/// // use the result
465/// outs() << "The answer is " << *Result << "\n";
466/// @endcode
467///
468/// For unit-testing a function returning an 'Expceted<T>', see the
469/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
470
471template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
472 template <class T1> friend class ExpectedAsOutParameter;
473 template <class OtherT> friend class Expected;
474
475 static constexpr bool isRef = std::is_reference<T>::value;
476
477 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
478
479 using error_type = std::unique_ptr<ErrorInfoBase>;
480
481public:
482 using storage_type = std::conditional_t<isRef, wrap, T>;
483 using value_type = T;
484
485private:
486 using reference = std::remove_reference_t<T> &;
487 using const_reference = const std::remove_reference_t<T> &;
488 using pointer = std::remove_reference_t<T> *;
489 using const_pointer = const std::remove_reference_t<T> *;
490
491public:
492 /// Create an Expected<T> error value from the given Error.
493 Expected(Error Err)
494 : HasError(true)
495#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
496 // Expected is unchecked upon construction in Debug builds.
497 , Unchecked(true)
498#endif
499 {
500 assert(Err && "Cannot create Expected<T> from Error success value.")(static_cast <bool> (Err && "Cannot create Expected<T> from Error success value."
) ? void (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "llvm/include/llvm/Support/Error.h", 500, __extension__ __PRETTY_FUNCTION__
))
;
501 new (getErrorStorage()) error_type(Err.takePayload());
502 }
503
504 /// Forbid to convert from Error::success() implicitly, this avoids having
505 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
506 /// but triggers the assertion above.
507 Expected(ErrorSuccess) = delete;
508
509 /// Create an Expected<T> success value from the given OtherT value, which
510 /// must be convertible to T.
511 template <typename OtherT>
512 Expected(OtherT &&Val,
513 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr)
514 : HasError(false)
515#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
516 // Expected is unchecked upon construction in Debug builds.
517 ,
518 Unchecked(true)
519#endif
520 {
521 new (getStorage()) storage_type(std::forward<OtherT>(Val));
522 }
523
524 /// Move construct an Expected<T> value.
525 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
526
527 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
528 /// must be convertible to T.
529 template <class OtherT>
530 Expected(
531 Expected<OtherT> &&Other,
532 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) {
533 moveConstruct(std::move(Other));
534 }
535
536 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
537 /// isn't convertible to T.
538 template <class OtherT>
539 explicit Expected(
540 Expected<OtherT> &&Other,
541 std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) {
542 moveConstruct(std::move(Other));
543 }
544
545 /// Move-assign from another Expected<T>.
546 Expected &operator=(Expected &&Other) {
547 moveAssign(std::move(Other));
548 return *this;
549 }
550
551 /// Destroy an Expected<T>.
552 ~Expected() {
553 assertIsChecked();
554 if (!HasError)
555 getStorage()->~storage_type();
556 else
557 getErrorStorage()->~error_type();
558 }
559
560 /// Return false if there is an error.
561 explicit operator bool() {
562#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
563 Unchecked = HasError;
564#endif
565 return !HasError;
27
Assuming field 'HasError' is false, which participates in a condition later
28
Returning the value 1, which participates in a condition later
566 }
567
568 /// Returns a reference to the stored T value.
569 reference get() {
570 assertIsChecked();
571 return *getStorage();
572 }
573
574 /// Returns a const reference to the stored T value.
575 const_reference get() const {
576 assertIsChecked();
577 return const_cast<Expected<T> *>(this)->get();
578 }
579
580 /// Returns \a takeError() after moving the held T (if any) into \p V.
581 template <class OtherT>
582 Error moveInto(OtherT &Value,
583 std::enable_if_t<std::is_assignable<OtherT &, T &&>::value> * =
584 nullptr) && {
585 if (*this)
586 Value = std::move(get());
587 return takeError();
588 }
589
590 /// Check that this Expected<T> is an error of type ErrT.
591 template <typename ErrT> bool errorIsA() const {
592 return HasError && (*getErrorStorage())->template isA<ErrT>();
593 }
594
595 /// Take ownership of the stored error.
596 /// After calling this the Expected<T> is in an indeterminate state that can
597 /// only be safely destructed. No further calls (beside the destructor) should
598 /// be made on the Expected<T> value.
599 Error takeError() {
600#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
601 Unchecked = false;
602#endif
603 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
604 }
605
606 /// Returns a pointer to the stored T value.
607 pointer operator->() {
608 assertIsChecked();
609 return toPointer(getStorage());
610 }
611
612 /// Returns a const pointer to the stored T value.
613 const_pointer operator->() const {
614 assertIsChecked();
615 return toPointer(getStorage());
616 }
617
618 /// Returns a reference to the stored T value.
619 reference operator*() {
620 assertIsChecked();
621 return *getStorage();
622 }
623
624 /// Returns a const reference to the stored T value.
625 const_reference operator*() const {
626 assertIsChecked();
627 return *getStorage();
628 }
629
630private:
631 template <class T1>
632 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
633 return &a == &b;
634 }
635
636 template <class T1, class T2>
637 static bool compareThisIfSameType(const T1 &, const T2 &) {
638 return false;
639 }
640
641 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
642 HasError = Other.HasError;
643#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
644 Unchecked = true;
645 Other.Unchecked = false;
646#endif
647
648 if (!HasError)
649 new (getStorage()) storage_type(std::move(*Other.getStorage()));
650 else
651 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
652 }
653
654 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
655 assertIsChecked();
656
657 if (compareThisIfSameType(*this, Other))
658 return;
659
660 this->~Expected();
661 new (this) Expected(std::move(Other));
662 }
663
664 pointer toPointer(pointer Val) { return Val; }
665
666 const_pointer toPointer(const_pointer Val) const { return Val; }
667
668 pointer toPointer(wrap *Val) { return &Val->get(); }
669
670 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
671
672 storage_type *getStorage() {
673 assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!"
) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "llvm/include/llvm/Support/Error.h", 673, __extension__ __PRETTY_FUNCTION__
))
;
674 return reinterpret_cast<storage_type *>(&TStorage);
675 }
676
677 const storage_type *getStorage() const {
678 assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!"
) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "llvm/include/llvm/Support/Error.h", 678, __extension__ __PRETTY_FUNCTION__
))
;
679 return reinterpret_cast<const storage_type *>(&TStorage);
680 }
681
682 error_type *getErrorStorage() {
683 assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!"
) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "llvm/include/llvm/Support/Error.h", 683, __extension__ __PRETTY_FUNCTION__
))
;
684 return reinterpret_cast<error_type *>(&ErrorStorage);
685 }
686
687 const error_type *getErrorStorage() const {
688 assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!"
) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "llvm/include/llvm/Support/Error.h", 688, __extension__ __PRETTY_FUNCTION__
))
;
689 return reinterpret_cast<const error_type *>(&ErrorStorage);
690 }
691
692 // Used by ExpectedAsOutParameter to reset the checked flag.
693 void setUnchecked() {
694#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
695 Unchecked = true;
696#endif
697 }
698
699#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
700 [[noreturn]] LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) void fatalUncheckedExpected() const {
701 dbgs() << "Expected<T> must be checked before access or destruction.\n";
702 if (HasError) {
703 dbgs() << "Unchecked Expected<T> contained error:\n";
704 (*getErrorStorage())->log(dbgs());
705 } else
706 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
707 "values in success mode must still be checked prior to being "
708 "destroyed).\n";
709 abort();
710 }
711#endif
712
713 void assertIsChecked() const {
714#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
715 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
716 fatalUncheckedExpected();
717#endif
718 }
719
720 union {
721 AlignedCharArrayUnion<storage_type> TStorage;
722 AlignedCharArrayUnion<error_type> ErrorStorage;
723 };
724 bool HasError : 1;
725#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
726 bool Unchecked : 1;
727#endif
728};
729
730/// Report a serious error, calling any installed error handler. See
731/// ErrorHandling.h.
732[[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true);
733
734/// Report a fatal error if Err is a failure value.
735///
736/// This function can be used to wrap calls to fallible functions ONLY when it
737/// is known that the Error will always be a success value. E.g.
738///
739/// @code{.cpp}
740/// // foo only attempts the fallible operation if DoFallibleOperation is
741/// // true. If DoFallibleOperation is false then foo always returns
742/// // Error::success().
743/// Error foo(bool DoFallibleOperation);
744///
745/// cantFail(foo(false));
746/// @endcode
747inline void cantFail(Error Err, const char *Msg = nullptr) {
748 if (Err) {
749 if (!Msg)
750 Msg = "Failure value returned from cantFail wrapped call";
751#ifndef NDEBUG
752 std::string Str;
753 raw_string_ostream OS(Str);
754 OS << Msg << "\n" << Err;
755 Msg = OS.str().c_str();
756#endif
757 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h"
, 757)
;
758 }
759}
760
761/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
762/// returns the contained value.
763///
764/// This function can be used to wrap calls to fallible functions ONLY when it
765/// is known that the Error will always be a success value. E.g.
766///
767/// @code{.cpp}
768/// // foo only attempts the fallible operation if DoFallibleOperation is
769/// // true. If DoFallibleOperation is false then foo always returns an int.
770/// Expected<int> foo(bool DoFallibleOperation);
771///
772/// int X = cantFail(foo(false));
773/// @endcode
774template <typename T>
775T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
776 if (ValOrErr)
777 return std::move(*ValOrErr);
778 else {
779 if (!Msg)
780 Msg = "Failure value returned from cantFail wrapped call";
781#ifndef NDEBUG
782 std::string Str;
783 raw_string_ostream OS(Str);
784 auto E = ValOrErr.takeError();
785 OS << Msg << "\n" << E;
786 Msg = OS.str().c_str();
787#endif
788 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h"
, 788)
;
789 }
790}
791
792/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
793/// returns the contained reference.
794///
795/// This function can be used to wrap calls to fallible functions ONLY when it
796/// is known that the Error will always be a success value. E.g.
797///
798/// @code{.cpp}
799/// // foo only attempts the fallible operation if DoFallibleOperation is
800/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
801/// Expected<Bar&> foo(bool DoFallibleOperation);
802///
803/// Bar &X = cantFail(foo(false));
804/// @endcode
805template <typename T>
806T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
807 if (ValOrErr)
808 return *ValOrErr;
809 else {
810 if (!Msg)
811 Msg = "Failure value returned from cantFail wrapped call";
812#ifndef NDEBUG
813 std::string Str;
814 raw_string_ostream OS(Str);
815 auto E = ValOrErr.takeError();
816 OS << Msg << "\n" << E;
817 Msg = OS.str().c_str();
818#endif
819 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h"
, 819)
;
820 }
821}
822
823/// Helper for testing applicability of, and applying, handlers for
824/// ErrorInfo types.
825template <typename HandlerT>
826class ErrorHandlerTraits
827 : public ErrorHandlerTraits<decltype(
828 &std::remove_reference<HandlerT>::type::operator())> {};
829
830// Specialization functions of the form 'Error (const ErrT&)'.
831template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
832public:
833 static bool appliesTo(const ErrorInfoBase &E) {
834 return E.template isA<ErrT>();
835 }
836
837 template <typename HandlerT>
838 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
839 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 839, __extension__ __PRETTY_FUNCTION__
))
;
840 return H(static_cast<ErrT &>(*E));
841 }
842};
843
844// Specialization functions of the form 'void (const ErrT&)'.
845template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
846public:
847 static bool appliesTo(const ErrorInfoBase &E) {
848 return E.template isA<ErrT>();
849 }
850
851 template <typename HandlerT>
852 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
853 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 853, __extension__ __PRETTY_FUNCTION__
))
;
854 H(static_cast<ErrT &>(*E));
855 return Error::success();
856 }
857};
858
859/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
860template <typename ErrT>
861class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
862public:
863 static bool appliesTo(const ErrorInfoBase &E) {
864 return E.template isA<ErrT>();
865 }
866
867 template <typename HandlerT>
868 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
869 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 869, __extension__ __PRETTY_FUNCTION__
))
;
870 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
871 return H(std::move(SubE));
872 }
873};
874
875/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
876template <typename ErrT>
877class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
878public:
879 static bool appliesTo(const ErrorInfoBase &E) {
880 return E.template isA<ErrT>();
881 }
882
883 template <typename HandlerT>
884 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
885 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 885, __extension__ __PRETTY_FUNCTION__
))
;
886 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
887 H(std::move(SubE));
888 return Error::success();
889 }
890};
891
892// Specialization for member functions of the form 'RetT (const ErrT&)'.
893template <typename C, typename RetT, typename ErrT>
894class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
895 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
896
897// Specialization for member functions of the form 'RetT (const ErrT&) const'.
898template <typename C, typename RetT, typename ErrT>
899class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
900 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
901
902// Specialization for member functions of the form 'RetT (const ErrT&)'.
903template <typename C, typename RetT, typename ErrT>
904class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
905 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
906
907// Specialization for member functions of the form 'RetT (const ErrT&) const'.
908template <typename C, typename RetT, typename ErrT>
909class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
910 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
911
912/// Specialization for member functions of the form
913/// 'RetT (std::unique_ptr<ErrT>)'.
914template <typename C, typename RetT, typename ErrT>
915class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
916 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
917
918/// Specialization for member functions of the form
919/// 'RetT (std::unique_ptr<ErrT>) const'.
920template <typename C, typename RetT, typename ErrT>
921class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
922 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
923
924inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
925 return Error(std::move(Payload));
926}
927
928template <typename HandlerT, typename... HandlerTs>
929Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
930 HandlerT &&Handler, HandlerTs &&... Handlers) {
931 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
932 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
933 std::move(Payload));
934 return handleErrorImpl(std::move(Payload),
935 std::forward<HandlerTs>(Handlers)...);
936}
937
938/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
939/// unhandled errors (or Errors returned by handlers) are re-concatenated and
940/// returned.
941/// Because this function returns an error, its result must also be checked
942/// or returned. If you intend to handle all errors use handleAllErrors
943/// (which returns void, and will abort() on unhandled errors) instead.
944template <typename... HandlerTs>
945Error handleErrors(Error E, HandlerTs &&... Hs) {
946 if (!E)
947 return Error::success();
948
949 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
950
951 if (Payload->isA<ErrorList>()) {
952 ErrorList &List = static_cast<ErrorList &>(*Payload);
953 Error R;
954 for (auto &P : List.Payloads)
955 R = ErrorList::join(
956 std::move(R),
957 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
958 return R;
959 }
960
961 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
962}
963
964/// Behaves the same as handleErrors, except that by contract all errors
965/// *must* be handled by the given handlers (i.e. there must be no remaining
966/// errors after running the handlers, or llvm_unreachable is called).
967template <typename... HandlerTs>
968void handleAllErrors(Error E, HandlerTs &&... Handlers) {
969 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
970}
971
972/// Check that E is a non-error, then drop it.
973/// If E is an error, llvm_unreachable will be called.
974inline void handleAllErrors(Error E) {
975 cantFail(std::move(E));
976}
977
978/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
979///
980/// If the incoming value is a success value it is returned unmodified. If it
981/// is a failure value then it the contained error is passed to handleErrors.
982/// If handleErrors is able to handle the error then the RecoveryPath functor
983/// is called to supply the final result. If handleErrors is not able to
984/// handle all errors then the unhandled errors are returned.
985///
986/// This utility enables the follow pattern:
987///
988/// @code{.cpp}
989/// enum FooStrategy { Aggressive, Conservative };
990/// Expected<Foo> foo(FooStrategy S);
991///
992/// auto ResultOrErr =
993/// handleExpected(
994/// foo(Aggressive),
995/// []() { return foo(Conservative); },
996/// [](AggressiveStrategyError&) {
997/// // Implicitly conusme this - we'll recover by using a conservative
998/// // strategy.
999/// });
1000///
1001/// @endcode
1002template <typename T, typename RecoveryFtor, typename... HandlerTs>
1003Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
1004 HandlerTs &&... Handlers) {
1005 if (ValOrErr)
1006 return ValOrErr;
1007
1008 if (auto Err = handleErrors(ValOrErr.takeError(),
1009 std::forward<HandlerTs>(Handlers)...))
1010 return std::move(Err);
1011
1012 return RecoveryPath();
1013}
1014
1015/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1016/// will be printed before the first one is logged. A newline will be printed
1017/// after each error.
1018///
1019/// This function is compatible with the helpers from Support/WithColor.h. You
1020/// can pass any of them as the OS. Please consider using them instead of
1021/// including 'error: ' in the ErrorBanner.
1022///
1023/// This is useful in the base level of your program to allow clean termination
1024/// (allowing clean deallocation of resources, etc.), while reporting error
1025/// information to the user.
1026void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
1027
1028/// Write all error messages (if any) in E to a string. The newline character
1029/// is used to separate error messages.
1030inline std::string toString(Error E) {
1031 SmallVector<std::string, 2> Errors;
1032 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
1033 Errors.push_back(EI.message());
1034 });
1035 return join(Errors.begin(), Errors.end(), "\n");
1036}
1037
1038/// Consume a Error without doing anything. This method should be used
1039/// only where an error can be considered a reasonable and expected return
1040/// value.
1041///
1042/// Uses of this method are potentially indicative of design problems: If it's
1043/// legitimate to do nothing while processing an "error", the error-producer
1044/// might be more clearly refactored to return an Optional<T>.
1045inline void consumeError(Error Err) {
1046 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1047}
1048
1049/// Convert an Expected to an Optional without doing anything. This method
1050/// should be used only where an error can be considered a reasonable and
1051/// expected return value.
1052///
1053/// Uses of this method are potentially indicative of problems: perhaps the
1054/// error should be propagated further, or the error-producer should just
1055/// return an Optional in the first place.
1056template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) {
1057 if (E)
1058 return std::move(*E);
1059 consumeError(E.takeError());
1060 return None;
1061}
1062
1063/// Helper for converting an Error to a bool.
1064///
1065/// This method returns true if Err is in an error state, or false if it is
1066/// in a success state. Puts Err in a checked state in both cases (unlike
1067/// Error::operator bool(), which only does this for success states).
1068inline bool errorToBool(Error Err) {
1069 bool IsError = static_cast<bool>(Err);
1070 if (IsError)
1071 consumeError(std::move(Err));
1072 return IsError;
1073}
1074
1075/// Helper for Errors used as out-parameters.
1076///
1077/// This helper is for use with the Error-as-out-parameter idiom, where an error
1078/// is passed to a function or method by reference, rather than being returned.
1079/// In such cases it is helpful to set the checked bit on entry to the function
1080/// so that the error can be written to (unchecked Errors abort on assignment)
1081/// and clear the checked bit on exit so that clients cannot accidentally forget
1082/// to check the result. This helper performs these actions automatically using
1083/// RAII:
1084///
1085/// @code{.cpp}
1086/// Result foo(Error &Err) {
1087/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1088/// // <body of foo>
1089/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1090/// }
1091/// @endcode
1092///
1093/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1094/// used with optional Errors (Error pointers that are allowed to be null). If
1095/// ErrorAsOutParameter took an Error reference, an instance would have to be
1096/// created inside every condition that verified that Error was non-null. By
1097/// taking an Error pointer we can just create one instance at the top of the
1098/// function.
1099class ErrorAsOutParameter {
1100public:
1101 ErrorAsOutParameter(Error *Err) : Err(Err) {
1102 // Raise the checked bit if Err is success.
1103 if (Err)
1104 (void)!!*Err;
1105 }
1106
1107 ~ErrorAsOutParameter() {
1108 // Clear the checked bit.
1109 if (Err && !*Err)
1110 *Err = Error::success();
1111 }
1112
1113private:
1114 Error *Err;
1115};
1116
1117/// Helper for Expected<T>s used as out-parameters.
1118///
1119/// See ErrorAsOutParameter.
1120template <typename T>
1121class ExpectedAsOutParameter {
1122public:
1123 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1124 : ValOrErr(ValOrErr) {
1125 if (ValOrErr)
1126 (void)!!*ValOrErr;
1127 }
1128
1129 ~ExpectedAsOutParameter() {
1130 if (ValOrErr)
1131 ValOrErr->setUnchecked();
1132 }
1133
1134private:
1135 Expected<T> *ValOrErr;
1136};
1137
1138/// This class wraps a std::error_code in a Error.
1139///
1140/// This is useful if you're writing an interface that returns a Error
1141/// (or Expected) and you want to call code that still returns
1142/// std::error_codes.
1143class ECError : public ErrorInfo<ECError> {
1144 friend Error errorCodeToError(std::error_code);
1145
1146 virtual void anchor() override;
1147
1148public:
1149 void setErrorCode(std::error_code EC) { this->EC = EC; }
1150 std::error_code convertToErrorCode() const override { return EC; }
1151 void log(raw_ostream &OS) const override { OS << EC.message(); }
1152
1153 // Used by ErrorInfo::classID.
1154 static char ID;
1155
1156protected:
1157 ECError() = default;
1158 ECError(std::error_code EC) : EC(EC) {}
1159
1160 std::error_code EC;
1161};
1162
1163/// The value returned by this function can be returned from convertToErrorCode
1164/// for Error values where no sensible translation to std::error_code exists.
1165/// It should only be used in this situation, and should never be used where a
1166/// sensible conversion to std::error_code is available, as attempts to convert
1167/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1168/// error to try to convert such a value).
1169std::error_code inconvertibleErrorCode();
1170
1171/// Helper for converting an std::error_code to a Error.
1172Error errorCodeToError(std::error_code EC);
1173
1174/// Helper for converting an ECError to a std::error_code.
1175///
1176/// This method requires that Err be Error() or an ECError, otherwise it
1177/// will trigger a call to abort().
1178std::error_code errorToErrorCode(Error Err);
1179
1180/// Convert an ErrorOr<T> to an Expected<T>.
1181template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1182 if (auto EC = EO.getError())
1183 return errorCodeToError(EC);
1184 return std::move(*EO);
1185}
1186
1187/// Convert an Expected<T> to an ErrorOr<T>.
1188template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1189 if (auto Err = E.takeError())
1190 return errorToErrorCode(std::move(Err));
1191 return std::move(*E);
1192}
1193
1194/// This class wraps a string in an Error.
1195///
1196/// StringError is useful in cases where the client is not expected to be able
1197/// to consume the specific error message programmatically (for example, if the
1198/// error message is to be presented to the user).
1199///
1200/// StringError can also be used when additional information is to be printed
1201/// along with a error_code message. Depending on the constructor called, this
1202/// class can either display:
1203/// 1. the error_code message (ECError behavior)
1204/// 2. a string
1205/// 3. the error_code message and a string
1206///
1207/// These behaviors are useful when subtyping is required; for example, when a
1208/// specific library needs an explicit error type. In the example below,
1209/// PDBError is derived from StringError:
1210///
1211/// @code{.cpp}
1212/// Expected<int> foo() {
1213/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1214/// "Additional information");
1215/// }
1216/// @endcode
1217///
1218class StringError : public ErrorInfo<StringError> {
1219public:
1220 static char ID;
1221
1222 // Prints EC + S and converts to EC
1223 StringError(std::error_code EC, const Twine &S = Twine());
1224
1225 // Prints S and converts to EC
1226 StringError(const Twine &S, std::error_code EC);
1227
1228 void log(raw_ostream &OS) const override;
1229 std::error_code convertToErrorCode() const override;
1230
1231 const std::string &getMessage() const { return Msg; }
1232
1233private:
1234 std::string Msg;
1235 std::error_code EC;
1236 const bool PrintMsgOnly = false;
1237};
1238
1239/// Create formatted StringError object.
1240template <typename... Ts>
1241inline Error createStringError(std::error_code EC, char const *Fmt,
1242 const Ts &... Vals) {
1243 std::string Buffer;
1244 raw_string_ostream Stream(Buffer);
1245 Stream << format(Fmt, Vals...);
1246 return make_error<StringError>(Stream.str(), EC);
1247}
1248
1249Error createStringError(std::error_code EC, char const *Msg);
1250
1251inline Error createStringError(std::error_code EC, const Twine &S) {
1252 return createStringError(EC, S.str().c_str());
1253}
1254
1255template <typename... Ts>
1256inline Error createStringError(std::errc EC, char const *Fmt,
1257 const Ts &... Vals) {
1258 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1259}
1260
1261/// This class wraps a filename and another Error.
1262///
1263/// In some cases, an error needs to live along a 'source' name, in order to
1264/// show more detailed information to the user.
1265class FileError final : public ErrorInfo<FileError> {
1266
1267 friend Error createFileError(const Twine &, Error);
1268 friend Error createFileError(const Twine &, size_t, Error);
1269
1270public:
1271 void log(raw_ostream &OS) const override {
1272 assert(Err && "Trying to log after takeError().")(static_cast <bool> (Err && "Trying to log after takeError()."
) ? void (0) : __assert_fail ("Err && \"Trying to log after takeError().\""
, "llvm/include/llvm/Support/Error.h", 1272, __extension__ __PRETTY_FUNCTION__
))
;
1273 OS << "'" << FileName << "': ";
1274 if (Line.hasValue())
1275 OS << "line " << Line.getValue() << ": ";
1276 Err->log(OS);
1277 }
1278
1279 std::string messageWithoutFileInfo() const {
1280 std::string Msg;
1281 raw_string_ostream OS(Msg);
1282 Err->log(OS);
1283 return OS.str();
1284 }
1285
1286 StringRef getFileName() { return FileName; }
1287
1288 Error takeError() { return Error(std::move(Err)); }
1289
1290 std::error_code convertToErrorCode() const override;
1291
1292 // Used by ErrorInfo::classID.
1293 static char ID;
1294
1295private:
1296 FileError(const Twine &F, Optional<size_t> LineNum,
1297 std::unique_ptr<ErrorInfoBase> E) {
1298 assert(E && "Cannot create FileError from Error success value.")(static_cast <bool> (E && "Cannot create FileError from Error success value."
) ? void (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\""
, "llvm/include/llvm/Support/Error.h", 1298, __extension__ __PRETTY_FUNCTION__
))
;
1299 FileName = F.str();
1300 Err = std::move(E);
1301 Line = std::move(LineNum);
1302 }
1303
1304 static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1305 std::unique_ptr<ErrorInfoBase> Payload;
1306 handleAllErrors(std::move(E),
1307 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1308 Payload = std::move(EIB);
1309 return Error::success();
1310 });
1311 return Error(
1312 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1313 }
1314
1315 std::string FileName;
1316 Optional<size_t> Line;
1317 std::unique_ptr<ErrorInfoBase> Err;
1318};
1319
1320/// Concatenate a source file path and/or name with an Error. The resulting
1321/// Error is unchecked.
1322inline Error createFileError(const Twine &F, Error E) {
1323 return FileError::build(F, Optional<size_t>(), std::move(E));
1324}
1325
1326/// Concatenate a source file path and/or name with line number and an Error.
1327/// The resulting Error is unchecked.
1328inline Error createFileError(const Twine &F, size_t Line, Error E) {
1329 return FileError::build(F, Optional<size_t>(Line), std::move(E));
1330}
1331
1332/// Concatenate a source file path and/or name with a std::error_code
1333/// to form an Error object.
1334inline Error createFileError(const Twine &F, std::error_code EC) {
1335 return createFileError(F, errorCodeToError(EC));
1336}
1337
1338/// Concatenate a source file path and/or name with line number and
1339/// std::error_code to form an Error object.
1340inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1341 return createFileError(F, Line, errorCodeToError(EC));
1342}
1343
1344Error createFileError(const Twine &F, ErrorSuccess) = delete;
1345
1346/// Helper for check-and-exit error handling.
1347///
1348/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1349///
1350class ExitOnError {
1351public:
1352 /// Create an error on exit helper.
1353 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1354 : Banner(std::move(Banner)),
1355 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1356
1357 /// Set the banner string for any errors caught by operator().
1358 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1359
1360 /// Set the exit-code mapper function.
1361 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1362 this->GetExitCode = std::move(GetExitCode);
1363 }
1364
1365 /// Check Err. If it's in a failure state log the error(s) and exit.
1366 void operator()(Error Err) const { checkError(std::move(Err)); }
1367
1368 /// Check E. If it's in a success state then return the contained value. If
1369 /// it's in a failure state log the error(s) and exit.
1370 template <typename T> T operator()(Expected<T> &&E) const {
1371 checkError(E.takeError());
1372 return std::move(*E);
1373 }
1374
1375 /// Check E. If it's in a success state then return the contained reference. If
1376 /// it's in a failure state log the error(s) and exit.
1377 template <typename T> T& operator()(Expected<T&> &&E) const {
1378 checkError(E.takeError());
1379 return *E;
1380 }
1381
1382private:
1383 void checkError(Error Err) const {
1384 if (Err) {
1385 int ExitCode = GetExitCode(Err);
1386 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1387 exit(ExitCode);
1388 }
1389 }
1390
1391 std::string Banner;
1392 std::function<int(const Error &)> GetExitCode;
1393};
1394
1395/// Conversion from Error to LLVMErrorRef for C error bindings.
1396inline LLVMErrorRef wrap(Error Err) {
1397 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1398}
1399
1400/// Conversion from LLVMErrorRef to Error for C error bindings.
1401inline Error unwrap(LLVMErrorRef ErrRef) {
1402 return Error(std::unique_ptr<ErrorInfoBase>(
1403 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1404}
1405
1406} // end namespace llvm
1407
1408#endif // LLVM_SUPPORT_ERROR_H