Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
Warning:line 1079, column 11
1st function call argument is an uninitialized value

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 MetadataLoader.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Bitcode/Reader -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Bitcode/Reader/MetadataLoader.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Bitcode/Reader/MetadataLoader.cpp

1//===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
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 "MetadataLoader.h"
10#include "ValueList.h"
11
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/ArrayRef.h"
14#include "llvm/ADT/BitmaskEnum.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/STLFunctionalExtras.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/ADT/ilist_iterator.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/BinaryFormat/Dwarf.h"
28#include "llvm/Bitcode/BitcodeReader.h"
29#include "llvm/Bitcode/LLVMBitCodes.h"
30#include "llvm/Bitstream/BitstreamReader.h"
31#include "llvm/IR/AutoUpgrade.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DebugInfoMetadata.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalObject.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Instruction.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/TrackingMDRef.h"
44#include "llvm/IR/Type.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/type_traits.h"
50
51#include <algorithm>
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <deque>
56#include <iterator>
57#include <limits>
58#include <string>
59#include <tuple>
60#include <type_traits>
61#include <utility>
62#include <vector>
63namespace llvm {
64class Argument;
65}
66
67using namespace llvm;
68
69#define DEBUG_TYPE"bitcode-reader" "bitcode-reader"
70
71STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded")static llvm::Statistic NumMDStringLoaded = {"bitcode-reader",
"NumMDStringLoaded", "Number of MDStrings loaded"}
;
72STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created")static llvm::Statistic NumMDNodeTemporary = {"bitcode-reader"
, "NumMDNodeTemporary", "Number of MDNode::Temporary created"
}
;
73STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded")static llvm::Statistic NumMDRecordLoaded = {"bitcode-reader",
"NumMDRecordLoaded", "Number of Metadata records loaded"}
;
74
75/// Flag whether we need to import full type definitions for ThinLTO.
76/// Currently needed for Darwin and LLDB.
77static cl::opt<bool> ImportFullTypeDefinitions(
78 "import-full-type-definitions", cl::init(false), cl::Hidden,
79 cl::desc("Import full type definitions for ThinLTO."));
80
81static cl::opt<bool> DisableLazyLoading(
82 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
83 cl::desc("Force disable the lazy-loading on-demand of metadata when "
84 "loading bitcode for importing."));
85
86namespace {
87
88static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
89
90class BitcodeReaderMetadataList {
91 /// Array of metadata references.
92 ///
93 /// Don't use std::vector here. Some versions of libc++ copy (instead of
94 /// move) on resize, and TrackingMDRef is very expensive to copy.
95 SmallVector<TrackingMDRef, 1> MetadataPtrs;
96
97 /// The set of indices in MetadataPtrs above of forward references that were
98 /// generated.
99 SmallDenseSet<unsigned, 1> ForwardReference;
100
101 /// The set of indices in MetadataPtrs above of Metadata that need to be
102 /// resolved.
103 SmallDenseSet<unsigned, 1> UnresolvedNodes;
104
105 /// Structures for resolving old type refs.
106 struct {
107 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
108 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
109 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
110 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
111 } OldTypeRefs;
112
113 LLVMContext &Context;
114
115 /// Maximum number of valid references. Forward references exceeding the
116 /// maximum must be invalid.
117 unsigned RefsUpperBound;
118
119public:
120 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
121 : Context(C),
122 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
123 RefsUpperBound)) {}
124
125 // vector compatibility methods
126 unsigned size() const { return MetadataPtrs.size(); }
127 void resize(unsigned N) { MetadataPtrs.resize(N); }
128 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
129 void clear() { MetadataPtrs.clear(); }
130 Metadata *back() const { return MetadataPtrs.back(); }
131 void pop_back() { MetadataPtrs.pop_back(); }
132 bool empty() const { return MetadataPtrs.empty(); }
133
134 Metadata *operator[](unsigned i) const {
135 assert(i < MetadataPtrs.size())(static_cast <bool> (i < MetadataPtrs.size()) ? void
(0) : __assert_fail ("i < MetadataPtrs.size()", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 135, __extension__ __PRETTY_FUNCTION__))
;
136 return MetadataPtrs[i];
137 }
138
139 Metadata *lookup(unsigned I) const {
140 if (I < MetadataPtrs.size())
31
Taking false branch
141 return MetadataPtrs[I];
142 return nullptr;
32
Returning null pointer, which participates in a condition later
143 }
144
145 void shrinkTo(unsigned N) {
146 assert(N <= size() && "Invalid shrinkTo request!")(static_cast <bool> (N <= size() && "Invalid shrinkTo request!"
) ? void (0) : __assert_fail ("N <= size() && \"Invalid shrinkTo request!\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 146, __extension__
__PRETTY_FUNCTION__))
;
147 assert(ForwardReference.empty() && "Unexpected forward refs")(static_cast <bool> (ForwardReference.empty() &&
"Unexpected forward refs") ? void (0) : __assert_fail ("ForwardReference.empty() && \"Unexpected forward refs\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 147, __extension__
__PRETTY_FUNCTION__))
;
148 assert(UnresolvedNodes.empty() && "Unexpected unresolved node")(static_cast <bool> (UnresolvedNodes.empty() &&
"Unexpected unresolved node") ? void (0) : __assert_fail ("UnresolvedNodes.empty() && \"Unexpected unresolved node\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 148, __extension__
__PRETTY_FUNCTION__))
;
149 MetadataPtrs.resize(N);
150 }
151
152 /// Return the given metadata, creating a replaceable forward reference if
153 /// necessary.
154 Metadata *getMetadataFwdRef(unsigned Idx);
155
156 /// Return the given metadata only if it is fully resolved.
157 ///
158 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
159 /// would give \c false.
160 Metadata *getMetadataIfResolved(unsigned Idx);
161
162 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
163 void assignValue(Metadata *MD, unsigned Idx);
164 void tryToResolveCycles();
165 bool hasFwdRefs() const { return !ForwardReference.empty(); }
166 int getNextFwdRef() {
167 assert(hasFwdRefs())(static_cast <bool> (hasFwdRefs()) ? void (0) : __assert_fail
("hasFwdRefs()", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 167, __extension__ __PRETTY_FUNCTION__))
;
168 return *ForwardReference.begin();
169 }
170
171 /// Upgrade a type that had an MDString reference.
172 void addTypeRef(MDString &UUID, DICompositeType &CT);
173
174 /// Upgrade a type that had an MDString reference.
175 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
176
177 /// Upgrade a type ref array that may have MDString references.
178 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
179
180private:
181 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
182};
183
184void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
185 if (auto *MDN = dyn_cast<MDNode>(MD))
186 if (!MDN->isResolved())
187 UnresolvedNodes.insert(Idx);
188
189 if (Idx == size()) {
190 push_back(MD);
191 return;
192 }
193
194 if (Idx >= size())
195 resize(Idx + 1);
196
197 TrackingMDRef &OldMD = MetadataPtrs[Idx];
198 if (!OldMD) {
199 OldMD.reset(MD);
200 return;
201 }
202
203 // If there was a forward reference to this value, replace it.
204 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
205 PrevMD->replaceAllUsesWith(MD);
206 ForwardReference.erase(Idx);
207}
208
209Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
210 // Bail out for a clearly invalid value.
211 if (Idx >= RefsUpperBound)
212 return nullptr;
213
214 if (Idx >= size())
215 resize(Idx + 1);
216
217 if (Metadata *MD = MetadataPtrs[Idx])
218 return MD;
219
220 // Track forward refs to be resolved later.
221 ForwardReference.insert(Idx);
222
223 // Create and return a placeholder, which will later be RAUW'd.
224 ++NumMDNodeTemporary;
225 Metadata *MD = MDNode::getTemporary(Context, None).release();
226 MetadataPtrs[Idx].reset(MD);
227 return MD;
228}
229
230Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
231 Metadata *MD = lookup(Idx);
232 if (auto *N = dyn_cast_or_null<MDNode>(MD))
233 if (!N->isResolved())
234 return nullptr;
235 return MD;
236}
237
238MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
239 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
240}
241
242void BitcodeReaderMetadataList::tryToResolveCycles() {
243 if (!ForwardReference.empty())
244 // Still forward references... can't resolve cycles.
245 return;
246
247 // Give up on finding a full definition for any forward decls that remain.
248 for (const auto &Ref : OldTypeRefs.FwdDecls)
249 OldTypeRefs.Final.insert(Ref);
250 OldTypeRefs.FwdDecls.clear();
251
252 // Upgrade from old type ref arrays. In strange cases, this could add to
253 // OldTypeRefs.Unknown.
254 for (const auto &Array : OldTypeRefs.Arrays)
255 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
256 OldTypeRefs.Arrays.clear();
257
258 // Replace old string-based type refs with the resolved node, if possible.
259 // If we haven't seen the node, leave it to the verifier to complain about
260 // the invalid string reference.
261 for (const auto &Ref : OldTypeRefs.Unknown) {
262 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
263 Ref.second->replaceAllUsesWith(CT);
264 else
265 Ref.second->replaceAllUsesWith(Ref.first);
266 }
267 OldTypeRefs.Unknown.clear();
268
269 if (UnresolvedNodes.empty())
270 // Nothing to do.
271 return;
272
273 // Resolve any cycles.
274 for (unsigned I : UnresolvedNodes) {
275 auto &MD = MetadataPtrs[I];
276 auto *N = dyn_cast_or_null<MDNode>(MD);
277 if (!N)
278 continue;
279
280 assert(!N->isTemporary() && "Unexpected forward reference")(static_cast <bool> (!N->isTemporary() && "Unexpected forward reference"
) ? void (0) : __assert_fail ("!N->isTemporary() && \"Unexpected forward reference\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 280, __extension__
__PRETTY_FUNCTION__))
;
281 N->resolveCycles();
282 }
283
284 // Make sure we return early again until there's another unresolved ref.
285 UnresolvedNodes.clear();
286}
287
288void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
289 DICompositeType &CT) {
290 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID")(static_cast <bool> (CT.getRawIdentifier() == &UUID
&& "Mismatched UUID") ? void (0) : __assert_fail ("CT.getRawIdentifier() == &UUID && \"Mismatched UUID\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 290, __extension__
__PRETTY_FUNCTION__))
;
291 if (CT.isForwardDecl())
292 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
293 else
294 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
295}
296
297Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
298 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
299 if (LLVM_LIKELY(!UUID)__builtin_expect((bool)(!UUID), true))
300 return MaybeUUID;
301
302 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
303 return CT;
304
305 auto &Ref = OldTypeRefs.Unknown[UUID];
306 if (!Ref)
307 Ref = MDNode::getTemporary(Context, None);
308 return Ref.get();
309}
310
311Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
312 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
313 if (!Tuple || Tuple->isDistinct())
314 return MaybeTuple;
315
316 // Look through the array immediately if possible.
317 if (!Tuple->isTemporary())
318 return resolveTypeRefArray(Tuple);
319
320 // Create and return a placeholder to use for now. Eventually
321 // resolveTypeRefArrays() will be resolve this forward reference.
322 OldTypeRefs.Arrays.emplace_back(
323 std::piecewise_construct, std::forward_as_tuple(Tuple),
324 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
325 return OldTypeRefs.Arrays.back().second.get();
326}
327
328Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
329 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
330 if (!Tuple || Tuple->isDistinct())
331 return MaybeTuple;
332
333 // Look through the DITypeRefArray, upgrading each DIType *.
334 SmallVector<Metadata *, 32> Ops;
335 Ops.reserve(Tuple->getNumOperands());
336 for (Metadata *MD : Tuple->operands())
337 Ops.push_back(upgradeTypeRef(MD));
338
339 return MDTuple::get(Context, Ops);
340}
341
342namespace {
343
344class PlaceholderQueue {
345 // Placeholders would thrash around when moved, so store in a std::deque
346 // instead of some sort of vector.
347 std::deque<DistinctMDOperandPlaceholder> PHs;
348
349public:
350 ~PlaceholderQueue() {
351 assert(empty() &&(static_cast <bool> (empty() && "PlaceholderQueue hasn't been flushed before being destroyed"
) ? void (0) : __assert_fail ("empty() && \"PlaceholderQueue hasn't been flushed before being destroyed\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 352, __extension__
__PRETTY_FUNCTION__))
352 "PlaceholderQueue hasn't been flushed before being destroyed")(static_cast <bool> (empty() && "PlaceholderQueue hasn't been flushed before being destroyed"
) ? void (0) : __assert_fail ("empty() && \"PlaceholderQueue hasn't been flushed before being destroyed\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 352, __extension__
__PRETTY_FUNCTION__))
;
353 }
354 bool empty() const { return PHs.empty(); }
355 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
356 void flush(BitcodeReaderMetadataList &MetadataList);
357
358 /// Return the list of temporaries nodes in the queue, these need to be
359 /// loaded before we can flush the queue.
360 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
361 DenseSet<unsigned> &Temporaries) {
362 for (auto &PH : PHs) {
363 auto ID = PH.getID();
364 auto *MD = MetadataList.lookup(ID);
365 if (!MD) {
366 Temporaries.insert(ID);
367 continue;
368 }
369 auto *N = dyn_cast_or_null<MDNode>(MD);
370 if (N && N->isTemporary())
371 Temporaries.insert(ID);
372 }
373 }
374};
375
376} // end anonymous namespace
377
378DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
379 PHs.emplace_back(ID);
380 return PHs.back();
381}
382
383void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
384 while (!PHs.empty()) {
385 auto *MD = MetadataList.lookup(PHs.front().getID());
386 assert(MD && "Flushing placeholder on unassigned MD")(static_cast <bool> (MD && "Flushing placeholder on unassigned MD"
) ? void (0) : __assert_fail ("MD && \"Flushing placeholder on unassigned MD\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 386, __extension__
__PRETTY_FUNCTION__))
;
387#ifndef NDEBUG
388 if (auto *MDN = dyn_cast<MDNode>(MD))
389 assert(MDN->isResolved() &&(static_cast <bool> (MDN->isResolved() && "Flushing Placeholder while cycles aren't resolved"
) ? void (0) : __assert_fail ("MDN->isResolved() && \"Flushing Placeholder while cycles aren't resolved\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 390, __extension__
__PRETTY_FUNCTION__))
390 "Flushing Placeholder while cycles aren't resolved")(static_cast <bool> (MDN->isResolved() && "Flushing Placeholder while cycles aren't resolved"
) ? void (0) : __assert_fail ("MDN->isResolved() && \"Flushing Placeholder while cycles aren't resolved\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 390, __extension__
__PRETTY_FUNCTION__))
;
391#endif
392 PHs.front().replaceUseWith(MD);
393 PHs.pop_front();
394 }
395}
396
397} // anonymous namespace
398
399static Error error(const Twine &Message) {
400 return make_error<StringError>(
401 Message, make_error_code(BitcodeError::CorruptedBitcode));
402}
403
404class MetadataLoader::MetadataLoaderImpl {
405 BitcodeReaderMetadataList MetadataList;
406 BitcodeReaderValueList &ValueList;
407 BitstreamCursor &Stream;
408 LLVMContext &Context;
409 Module &TheModule;
410 std::function<Type *(unsigned)> getTypeByID;
411
412 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
413 /// to keep around the right "context" (Abbrev list) to be able to jump in
414 /// the middle of the metadata block and load any record.
415 BitstreamCursor IndexCursor;
416
417 /// Index that keeps track of MDString values.
418 std::vector<StringRef> MDStringRef;
419
420 /// On-demand loading of a single MDString. Requires the index above to be
421 /// populated.
422 MDString *lazyLoadOneMDString(unsigned Idx);
423
424 /// Index that keeps track of where to find a metadata record in the stream.
425 std::vector<uint64_t> GlobalMetadataBitPosIndex;
426
427 /// Cursor position of the start of the global decl attachments, to enable
428 /// loading using the index built for lazy loading, instead of forward
429 /// references.
430 uint64_t GlobalDeclAttachmentPos = 0;
431
432#ifndef NDEBUG
433 /// Baisic correctness check that we end up parsing all of the global decl
434 /// attachments.
435 unsigned NumGlobalDeclAttachSkipped = 0;
436 unsigned NumGlobalDeclAttachParsed = 0;
437#endif
438
439 /// Load the global decl attachments, using the index built for lazy loading.
440 Expected<bool> loadGlobalDeclAttachments();
441
442 /// Populate the index above to enable lazily loading of metadata, and load
443 /// the named metadata as well as the transitively referenced global
444 /// Metadata.
445 Expected<bool> lazyLoadModuleMetadataBlock();
446
447 /// On-demand loading of a single metadata. Requires the index above to be
448 /// populated.
449 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
450
451 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
452 // point from SP to CU after a block is completly parsed.
453 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
454
455 /// Functions that need to be matched with subprograms when upgrading old
456 /// metadata.
457 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
458
459 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
460 DenseMap<unsigned, unsigned> MDKindMap;
461
462 bool StripTBAA = false;
463 bool HasSeenOldLoopTags = false;
464 bool NeedUpgradeToDIGlobalVariableExpression = false;
465 bool NeedDeclareExpressionUpgrade = false;
466
467 /// True if metadata is being parsed for a module being ThinLTO imported.
468 bool IsImporting = false;
469
470 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
471 PlaceholderQueue &Placeholders, StringRef Blob,
472 unsigned &NextMetadataNo);
473 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
474 function_ref<void(StringRef)> CallBack);
475 Error parseGlobalObjectAttachment(GlobalObject &GO,
476 ArrayRef<uint64_t> Record);
477 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
478
479 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
480
481 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
482 void upgradeCUSubprograms() {
483 for (auto CU_SP : CUSubprograms)
484 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
485 for (auto &Op : SPs->operands())
486 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
487 SP->replaceUnit(CU_SP.first);
488 CUSubprograms.clear();
489 }
490
491 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
492 void upgradeCUVariables() {
493 if (!NeedUpgradeToDIGlobalVariableExpression)
494 return;
495
496 // Upgrade list of variables attached to the CUs.
497 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
498 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
499 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
500 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
501 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
502 if (auto *GV =
503 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
504 auto *DGVE = DIGlobalVariableExpression::getDistinct(
505 Context, GV, DIExpression::get(Context, {}));
506 GVs->replaceOperandWith(I, DGVE);
507 }
508 }
509
510 // Upgrade variables attached to globals.
511 for (auto &GV : TheModule.globals()) {
512 SmallVector<MDNode *, 1> MDs;
513 GV.getMetadata(LLVMContext::MD_dbg, MDs);
514 GV.eraseMetadata(LLVMContext::MD_dbg);
515 for (auto *MD : MDs)
516 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
517 auto *DGVE = DIGlobalVariableExpression::getDistinct(
518 Context, DGV, DIExpression::get(Context, {}));
519 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
520 } else
521 GV.addMetadata(LLVMContext::MD_dbg, *MD);
522 }
523 }
524
525 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
526 /// describes a function argument.
527 void upgradeDeclareExpressions(Function &F) {
528 if (!NeedDeclareExpressionUpgrade)
529 return;
530
531 for (auto &BB : F)
532 for (auto &I : BB)
533 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
534 if (auto *DIExpr = DDI->getExpression())
535 if (DIExpr->startsWithDeref() &&
536 isa_and_nonnull<Argument>(DDI->getAddress())) {
537 SmallVector<uint64_t, 8> Ops;
538 Ops.append(std::next(DIExpr->elements_begin()),
539 DIExpr->elements_end());
540 DDI->setExpression(DIExpression::get(Context, Ops));
541 }
542 }
543
544 /// Upgrade the expression from previous versions.
545 Error upgradeDIExpression(uint64_t FromVersion,
546 MutableArrayRef<uint64_t> &Expr,
547 SmallVectorImpl<uint64_t> &Buffer) {
548 auto N = Expr.size();
549 switch (FromVersion) {
550 default:
551 return error("Invalid record");
552 case 0:
553 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
554 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
555 LLVM_FALLTHROUGH[[gnu::fallthrough]];
556 case 1:
557 // Move DW_OP_deref to the end.
558 if (N && Expr[0] == dwarf::DW_OP_deref) {
559 auto End = Expr.end();
560 if (Expr.size() >= 3 &&
561 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
562 End = std::prev(End, 3);
563 std::move(std::next(Expr.begin()), End, Expr.begin());
564 *std::prev(End) = dwarf::DW_OP_deref;
565 }
566 NeedDeclareExpressionUpgrade = true;
567 LLVM_FALLTHROUGH[[gnu::fallthrough]];
568 case 2: {
569 // Change DW_OP_plus to DW_OP_plus_uconst.
570 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
571 auto SubExpr = ArrayRef<uint64_t>(Expr);
572 while (!SubExpr.empty()) {
573 // Skip past other operators with their operands
574 // for this version of the IR, obtained from
575 // from historic DIExpression::ExprOperand::getSize().
576 size_t HistoricSize;
577 switch (SubExpr.front()) {
578 default:
579 HistoricSize = 1;
580 break;
581 case dwarf::DW_OP_constu:
582 case dwarf::DW_OP_minus:
583 case dwarf::DW_OP_plus:
584 HistoricSize = 2;
585 break;
586 case dwarf::DW_OP_LLVM_fragment:
587 HistoricSize = 3;
588 break;
589 }
590
591 // If the expression is malformed, make sure we don't
592 // copy more elements than we should.
593 HistoricSize = std::min(SubExpr.size(), HistoricSize);
594 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
595
596 switch (SubExpr.front()) {
597 case dwarf::DW_OP_plus:
598 Buffer.push_back(dwarf::DW_OP_plus_uconst);
599 Buffer.append(Args.begin(), Args.end());
600 break;
601 case dwarf::DW_OP_minus:
602 Buffer.push_back(dwarf::DW_OP_constu);
603 Buffer.append(Args.begin(), Args.end());
604 Buffer.push_back(dwarf::DW_OP_minus);
605 break;
606 default:
607 Buffer.push_back(*SubExpr.begin());
608 Buffer.append(Args.begin(), Args.end());
609 break;
610 }
611
612 // Continue with remaining elements.
613 SubExpr = SubExpr.slice(HistoricSize);
614 }
615 Expr = MutableArrayRef<uint64_t>(Buffer);
616 LLVM_FALLTHROUGH[[gnu::fallthrough]];
617 }
618 case 3:
619 // Up-to-date!
620 break;
621 }
622
623 return Error::success();
624 }
625
626 void upgradeDebugInfo() {
627 upgradeCUSubprograms();
628 upgradeCUVariables();
629 }
630
631public:
632 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
633 BitcodeReaderValueList &ValueList,
634 std::function<Type *(unsigned)> getTypeByID,
635 bool IsImporting)
636 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
637 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
638 TheModule(TheModule), getTypeByID(std::move(getTypeByID)),
639 IsImporting(IsImporting) {}
640
641 Error parseMetadata(bool ModuleLevel);
642
643 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
644
645 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
646 if (ID < MDStringRef.size())
20
Assuming the condition is false
21
Taking false branch
647 return lazyLoadOneMDString(ID);
648 if (auto *MD
21.1
'MD' is null
21.1
'MD' is null
= MetadataList.lookup(ID))
22
Taking false branch
649 return MD;
650 // If lazy-loading is enabled, we try recursively to load the operand
651 // instead of creating a temporary.
652 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
23
Assuming the condition is true
24
Taking true branch
653 PlaceholderQueue Placeholders;
654 lazyLoadOneMetadata(ID, Placeholders);
25
Calling 'MetadataLoaderImpl::lazyLoadOneMetadata'
655 resolveForwardRefsAndPlaceholders(Placeholders);
656 return MetadataList.lookup(ID);
657 }
658 return MetadataList.getMetadataFwdRef(ID);
659 }
660
661 DISubprogram *lookupSubprogramForFunction(Function *F) {
662 return FunctionsWithSPs.lookup(F);
663 }
664
665 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
666
667 Error parseMetadataAttachment(Function &F,
668 ArrayRef<Instruction *> InstructionList);
669
670 Error parseMetadataKinds();
671
672 void setStripTBAA(bool Value) { StripTBAA = Value; }
673 bool isStrippingTBAA() const { return StripTBAA; }
674
675 unsigned size() const { return MetadataList.size(); }
676 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
677 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
678};
679
680Expected<bool>
681MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
682 IndexCursor = Stream;
683 SmallVector<uint64_t, 64> Record;
684 GlobalDeclAttachmentPos = 0;
685 // Get the abbrevs, and preload record positions to make them lazy-loadable.
686 while (true) {
687 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
688 BitstreamEntry Entry;
689 if (Error E =
690 IndexCursor
691 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
692 .moveInto(Entry))
693 return std::move(E);
694
695 switch (Entry.Kind) {
696 case BitstreamEntry::SubBlock: // Handled for us already.
697 case BitstreamEntry::Error:
698 return error("Malformed block");
699 case BitstreamEntry::EndBlock: {
700 return true;
701 }
702 case BitstreamEntry::Record: {
703 // The interesting case.
704 ++NumMDRecordLoaded;
705 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
706 unsigned Code;
707 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
708 return std::move(E);
709 switch (Code) {
710 case bitc::METADATA_STRINGS: {
711 // Rewind and parse the strings.
712 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
713 return std::move(Err);
714 StringRef Blob;
715 Record.clear();
716 if (Expected<unsigned> MaybeRecord =
717 IndexCursor.readRecord(Entry.ID, Record, &Blob))
718 ;
719 else
720 return MaybeRecord.takeError();
721 unsigned NumStrings = Record[0];
722 MDStringRef.reserve(NumStrings);
723 auto IndexNextMDString = [&](StringRef Str) {
724 MDStringRef.push_back(Str);
725 };
726 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
727 return std::move(Err);
728 break;
729 }
730 case bitc::METADATA_INDEX_OFFSET: {
731 // This is the offset to the index, when we see this we skip all the
732 // records and load only an index to these.
733 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
734 return std::move(Err);
735 Record.clear();
736 if (Expected<unsigned> MaybeRecord =
737 IndexCursor.readRecord(Entry.ID, Record))
738 ;
739 else
740 return MaybeRecord.takeError();
741 if (Record.size() != 2)
742 return error("Invalid record");
743 auto Offset = Record[0] + (Record[1] << 32);
744 auto BeginPos = IndexCursor.GetCurrentBitNo();
745 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
746 return std::move(Err);
747 Expected<BitstreamEntry> MaybeEntry =
748 IndexCursor.advanceSkippingSubblocks(
749 BitstreamCursor::AF_DontPopBlockAtEnd);
750 if (!MaybeEntry)
751 return MaybeEntry.takeError();
752 Entry = MaybeEntry.get();
753 assert(Entry.Kind == BitstreamEntry::Record &&(static_cast <bool> (Entry.Kind == BitstreamEntry::Record
&& "Corrupted bitcode: Expected `Record` when trying to find the "
"Metadata index") ? void (0) : __assert_fail ("Entry.Kind == BitstreamEntry::Record && \"Corrupted bitcode: Expected `Record` when trying to find the \" \"Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 755, __extension__
__PRETTY_FUNCTION__))
754 "Corrupted bitcode: Expected `Record` when trying to find the "(static_cast <bool> (Entry.Kind == BitstreamEntry::Record
&& "Corrupted bitcode: Expected `Record` when trying to find the "
"Metadata index") ? void (0) : __assert_fail ("Entry.Kind == BitstreamEntry::Record && \"Corrupted bitcode: Expected `Record` when trying to find the \" \"Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 755, __extension__
__PRETTY_FUNCTION__))
755 "Metadata index")(static_cast <bool> (Entry.Kind == BitstreamEntry::Record
&& "Corrupted bitcode: Expected `Record` when trying to find the "
"Metadata index") ? void (0) : __assert_fail ("Entry.Kind == BitstreamEntry::Record && \"Corrupted bitcode: Expected `Record` when trying to find the \" \"Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 755, __extension__
__PRETTY_FUNCTION__))
;
756 Record.clear();
757 if (Expected<unsigned> MaybeCode =
758 IndexCursor.readRecord(Entry.ID, Record))
759 assert(MaybeCode.get() == bitc::METADATA_INDEX &&(static_cast <bool> (MaybeCode.get() == bitc::METADATA_INDEX
&& "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
"find the Metadata index") ? void (0) : __assert_fail ("MaybeCode.get() == bitc::METADATA_INDEX && \"Corrupted bitcode: Expected `METADATA_INDEX` when trying to \" \"find the Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 761, __extension__
__PRETTY_FUNCTION__))
760 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "(static_cast <bool> (MaybeCode.get() == bitc::METADATA_INDEX
&& "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
"find the Metadata index") ? void (0) : __assert_fail ("MaybeCode.get() == bitc::METADATA_INDEX && \"Corrupted bitcode: Expected `METADATA_INDEX` when trying to \" \"find the Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 761, __extension__
__PRETTY_FUNCTION__))
761 "find the Metadata index")(static_cast <bool> (MaybeCode.get() == bitc::METADATA_INDEX
&& "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
"find the Metadata index") ? void (0) : __assert_fail ("MaybeCode.get() == bitc::METADATA_INDEX && \"Corrupted bitcode: Expected `METADATA_INDEX` when trying to \" \"find the Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 761, __extension__
__PRETTY_FUNCTION__))
;
762 else
763 return MaybeCode.takeError();
764 // Delta unpack
765 auto CurrentValue = BeginPos;
766 GlobalMetadataBitPosIndex.reserve(Record.size());
767 for (auto &Elt : Record) {
768 CurrentValue += Elt;
769 GlobalMetadataBitPosIndex.push_back(CurrentValue);
770 }
771 break;
772 }
773 case bitc::METADATA_INDEX:
774 // We don't expect to get there, the Index is loaded when we encounter
775 // the offset.
776 return error("Corrupted Metadata block");
777 case bitc::METADATA_NAME: {
778 // Named metadata need to be materialized now and aren't deferred.
779 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
780 return std::move(Err);
781 Record.clear();
782
783 unsigned Code;
784 if (Expected<unsigned> MaybeCode =
785 IndexCursor.readRecord(Entry.ID, Record)) {
786 Code = MaybeCode.get();
787 assert(Code == bitc::METADATA_NAME)(static_cast <bool> (Code == bitc::METADATA_NAME) ? void
(0) : __assert_fail ("Code == bitc::METADATA_NAME", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 787, __extension__ __PRETTY_FUNCTION__))
;
788 } else
789 return MaybeCode.takeError();
790
791 // Read name of the named metadata.
792 SmallString<8> Name(Record.begin(), Record.end());
793 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
794 Code = MaybeCode.get();
795 else
796 return MaybeCode.takeError();
797
798 // Named Metadata comes in two parts, we expect the name to be followed
799 // by the node
800 Record.clear();
801 if (Expected<unsigned> MaybeNextBitCode =
802 IndexCursor.readRecord(Code, Record))
803 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE)(static_cast <bool> (MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE
) ? void (0) : __assert_fail ("MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 803, __extension__
__PRETTY_FUNCTION__))
;
804 else
805 return MaybeNextBitCode.takeError();
806
807 // Read named metadata elements.
808 unsigned Size = Record.size();
809 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
810 for (unsigned i = 0; i != Size; ++i) {
811 // FIXME: We could use a placeholder here, however NamedMDNode are
812 // taking MDNode as operand and not using the Metadata infrastructure.
813 // It is acknowledged by 'TODO: Inherit from Metadata' in the
814 // NamedMDNode class definition.
815 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
816 assert(MD && "Invalid metadata: expect fwd ref to MDNode")(static_cast <bool> (MD && "Invalid metadata: expect fwd ref to MDNode"
) ? void (0) : __assert_fail ("MD && \"Invalid metadata: expect fwd ref to MDNode\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 816, __extension__
__PRETTY_FUNCTION__))
;
817 NMD->addOperand(MD);
818 }
819 break;
820 }
821 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
822 if (!GlobalDeclAttachmentPos)
823 GlobalDeclAttachmentPos = SavedPos;
824#ifndef NDEBUG
825 NumGlobalDeclAttachSkipped++;
826#endif
827 break;
828 }
829 case bitc::METADATA_KIND:
830 case bitc::METADATA_STRING_OLD:
831 case bitc::METADATA_OLD_FN_NODE:
832 case bitc::METADATA_OLD_NODE:
833 case bitc::METADATA_VALUE:
834 case bitc::METADATA_DISTINCT_NODE:
835 case bitc::METADATA_NODE:
836 case bitc::METADATA_LOCATION:
837 case bitc::METADATA_GENERIC_DEBUG:
838 case bitc::METADATA_SUBRANGE:
839 case bitc::METADATA_ENUMERATOR:
840 case bitc::METADATA_BASIC_TYPE:
841 case bitc::METADATA_STRING_TYPE:
842 case bitc::METADATA_DERIVED_TYPE:
843 case bitc::METADATA_COMPOSITE_TYPE:
844 case bitc::METADATA_SUBROUTINE_TYPE:
845 case bitc::METADATA_MODULE:
846 case bitc::METADATA_FILE:
847 case bitc::METADATA_COMPILE_UNIT:
848 case bitc::METADATA_SUBPROGRAM:
849 case bitc::METADATA_LEXICAL_BLOCK:
850 case bitc::METADATA_LEXICAL_BLOCK_FILE:
851 case bitc::METADATA_NAMESPACE:
852 case bitc::METADATA_COMMON_BLOCK:
853 case bitc::METADATA_MACRO:
854 case bitc::METADATA_MACRO_FILE:
855 case bitc::METADATA_TEMPLATE_TYPE:
856 case bitc::METADATA_TEMPLATE_VALUE:
857 case bitc::METADATA_GLOBAL_VAR:
858 case bitc::METADATA_LOCAL_VAR:
859 case bitc::METADATA_LABEL:
860 case bitc::METADATA_EXPRESSION:
861 case bitc::METADATA_OBJC_PROPERTY:
862 case bitc::METADATA_IMPORTED_ENTITY:
863 case bitc::METADATA_GLOBAL_VAR_EXPR:
864 case bitc::METADATA_GENERIC_SUBRANGE:
865 // We don't expect to see any of these, if we see one, give up on
866 // lazy-loading and fallback.
867 MDStringRef.clear();
868 GlobalMetadataBitPosIndex.clear();
869 return false;
870 }
871 break;
872 }
873 }
874 }
875}
876
877// Load the global decl attachments after building the lazy loading index.
878// We don't load them "lazily" - all global decl attachments must be
879// parsed since they aren't materialized on demand. However, by delaying
880// their parsing until after the index is created, we can use the index
881// instead of creating temporaries.
882Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
883 // Nothing to do if we didn't find any of these metadata records.
884 if (!GlobalDeclAttachmentPos)
885 return true;
886 // Use a temporary cursor so that we don't mess up the main Stream cursor or
887 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
888 BitstreamCursor TempCursor = Stream;
889 SmallVector<uint64_t, 64> Record;
890 // Jump to the position before the first global decl attachment, so we can
891 // scan for the first BitstreamEntry record.
892 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
893 return std::move(Err);
894 while (true) {
895 BitstreamEntry Entry;
896 if (Error E =
897 TempCursor
898 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
899 .moveInto(Entry))
900 return std::move(E);
901
902 switch (Entry.Kind) {
903 case BitstreamEntry::SubBlock: // Handled for us already.
904 case BitstreamEntry::Error:
905 return error("Malformed block");
906 case BitstreamEntry::EndBlock:
907 // Check that we parsed them all.
908 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed)(static_cast <bool> (NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed
) ? void (0) : __assert_fail ("NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 908, __extension__
__PRETTY_FUNCTION__))
;
909 return true;
910 case BitstreamEntry::Record:
911 break;
912 }
913 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
914 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
915 if (!MaybeCode)
916 return MaybeCode.takeError();
917 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
918 // Anything other than a global decl attachment signals the end of
919 // these records. Check that we parsed them all.
920 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed)(static_cast <bool> (NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed
) ? void (0) : __assert_fail ("NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 920, __extension__
__PRETTY_FUNCTION__))
;
921 return true;
922 }
923#ifndef NDEBUG
924 NumGlobalDeclAttachParsed++;
925#endif
926 // FIXME: we need to do this early because we don't materialize global
927 // value explicitly.
928 if (Error Err = TempCursor.JumpToBit(CurrentPos))
929 return std::move(Err);
930 Record.clear();
931 if (Expected<unsigned> MaybeRecord =
932 TempCursor.readRecord(Entry.ID, Record))
933 ;
934 else
935 return MaybeRecord.takeError();
936 if (Record.size() % 2 == 0)
937 return error("Invalid record");
938 unsigned ValueID = Record[0];
939 if (ValueID >= ValueList.size())
940 return error("Invalid record");
941 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
942 // Need to save and restore the current position since
943 // parseGlobalObjectAttachment will resolve all forward references which
944 // would require parsing from locations stored in the index.
945 CurrentPos = TempCursor.GetCurrentBitNo();
946 if (Error Err = parseGlobalObjectAttachment(
947 *GO, ArrayRef<uint64_t>(Record).slice(1)))
948 return std::move(Err);
949 if (Error Err = TempCursor.JumpToBit(CurrentPos))
950 return std::move(Err);
951 }
952 }
953}
954
955/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
956/// module level metadata.
957Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
958 if (!ModuleLevel && MetadataList.hasFwdRefs())
959 return error("Invalid metadata: fwd refs into function blocks");
960
961 // Record the entry position so that we can jump back here and efficiently
962 // skip the whole block in case we lazy-load.
963 auto EntryPos = Stream.GetCurrentBitNo();
964
965 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
966 return Err;
967
968 SmallVector<uint64_t, 64> Record;
969 PlaceholderQueue Placeholders;
970
971 // We lazy-load module-level metadata: we build an index for each record, and
972 // then load individual record as needed, starting with the named metadata.
973 if (ModuleLevel && IsImporting && MetadataList.empty() &&
974 !DisableLazyLoading) {
975 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
976 if (!SuccessOrErr)
977 return SuccessOrErr.takeError();
978 if (SuccessOrErr.get()) {
979 // An index was successfully created and we will be able to load metadata
980 // on-demand.
981 MetadataList.resize(MDStringRef.size() +
982 GlobalMetadataBitPosIndex.size());
983
984 // Now that we have built the index, load the global decl attachments
985 // that were deferred during that process. This avoids creating
986 // temporaries.
987 SuccessOrErr = loadGlobalDeclAttachments();
988 if (!SuccessOrErr)
989 return SuccessOrErr.takeError();
990 assert(SuccessOrErr.get())(static_cast <bool> (SuccessOrErr.get()) ? void (0) : __assert_fail
("SuccessOrErr.get()", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 990, __extension__ __PRETTY_FUNCTION__))
;
991
992 // Reading the named metadata created forward references and/or
993 // placeholders, that we flush here.
994 resolveForwardRefsAndPlaceholders(Placeholders);
995 upgradeDebugInfo();
996 // Return at the beginning of the block, since it is easy to skip it
997 // entirely from there.
998 Stream.ReadBlockEnd(); // Pop the abbrev block context.
999 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1000 return Err;
1001 if (Error Err = Stream.SkipBlock()) {
1002 // FIXME this drops the error on the floor, which
1003 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1004 consumeError(std::move(Err));
1005 return Error::success();
1006 }
1007 return Error::success();
1008 }
1009 // Couldn't load an index, fallback to loading all the block "old-style".
1010 }
1011
1012 unsigned NextMetadataNo = MetadataList.size();
1013
1014 // Read all the records.
1015 while (true) {
1016 BitstreamEntry Entry;
1017 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1018 return E;
1019
1020 switch (Entry.Kind) {
1021 case BitstreamEntry::SubBlock: // Handled for us already.
1022 case BitstreamEntry::Error:
1023 return error("Malformed block");
1024 case BitstreamEntry::EndBlock:
1025 resolveForwardRefsAndPlaceholders(Placeholders);
1026 upgradeDebugInfo();
1027 return Error::success();
1028 case BitstreamEntry::Record:
1029 // The interesting case.
1030 break;
1031 }
1032
1033 // Read a record.
1034 Record.clear();
1035 StringRef Blob;
1036 ++NumMDRecordLoaded;
1037 if (Expected<unsigned> MaybeCode =
1038 Stream.readRecord(Entry.ID, Record, &Blob)) {
1039 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1040 Blob, NextMetadataNo))
1041 return Err;
1042 } else
1043 return MaybeCode.takeError();
1044 }
1045}
1046
1047MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1048 ++NumMDStringLoaded;
1049 if (Metadata *MD = MetadataList.lookup(ID))
1050 return cast<MDString>(MD);
1051 auto MDS = MDString::get(Context, MDStringRef[ID]);
1052 MetadataList.assignValue(MDS, ID);
1053 return MDS;
1054}
1055
1056void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1057 unsigned ID, PlaceholderQueue &Placeholders) {
1058 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size())(static_cast <bool> (ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex
.size()) ? void (0) : __assert_fail ("ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size()"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1058, __extension__
__PRETTY_FUNCTION__))
;
26
Assuming the condition is true
27
'?' condition is true
1059 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString")(static_cast <bool> (ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString") ? void (0) : __assert_fail
("ID >= MDStringRef.size() && \"Unexpected lazy-loading of MDString\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1059, __extension__
__PRETTY_FUNCTION__))
;
28
Assuming the condition is true
29
'?' condition is true
1060 // Lookup first if the metadata hasn't already been loaded.
1061 if (auto *MD
33.1
'MD' is null
33.1
'MD' is null
= MetadataList.lookup(ID)) {
30
Calling 'BitcodeReaderMetadataList::lookup'
33
Returning from 'BitcodeReaderMetadataList::lookup'
34
Taking false branch
1062 auto *N = cast<MDNode>(MD);
1063 if (!N->isTemporary())
1064 return;
1065 }
1066 SmallVector<uint64_t, 64> Record;
1067 StringRef Blob;
1068 if (Error Err = IndexCursor.JumpToBit(
35
Assuming the condition is false
36
Taking false branch
1069 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1070 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1071 Twine(toString(std::move(Err))));
1072 BitstreamEntry Entry;
1073 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
37
Calling 'Expected::moveInto'
40
Returning from 'Expected::moveInto'
41
Assuming the condition is false
42
Taking false branch
1074 // FIXME this drops the error on the floor.
1075 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1076 Twine(toString(std::move(E))));
1077 ++NumMDRecordLoaded;
1078 if (Expected<unsigned> MaybeCode =
1079 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
43
1st function call argument is an uninitialized value
1080 if (Error Err =
1081 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1082 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1083 Twine(toString(std::move(Err))));
1084 } else
1085 report_fatal_error("Can't lazyload MD: " +
1086 Twine(toString(MaybeCode.takeError())));
1087}
1088
1089/// Ensure that all forward-references and placeholders are resolved.
1090/// Iteratively lazy-loading metadata on-demand if needed.
1091void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1092 PlaceholderQueue &Placeholders) {
1093 DenseSet<unsigned> Temporaries;
1094 while (true) {
1095 // Populate Temporaries with the placeholders that haven't been loaded yet.
1096 Placeholders.getTemporaries(MetadataList, Temporaries);
1097
1098 // If we don't have any temporary, or FwdReference, we're done!
1099 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1100 break;
1101
1102 // First, load all the temporaries. This can add new placeholders or
1103 // forward references.
1104 for (auto ID : Temporaries)
1105 lazyLoadOneMetadata(ID, Placeholders);
1106 Temporaries.clear();
1107
1108 // Second, load the forward-references. This can also add new placeholders
1109 // or forward references.
1110 while (MetadataList.hasFwdRefs())
1111 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1112 }
1113 // At this point we don't have any forward reference remaining, or temporary
1114 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1115 // as resolved.
1116 MetadataList.tryToResolveCycles();
1117
1118 // Finally, everything is in place, we can replace the placeholders operands
1119 // with the final node they refer to.
1120 Placeholders.flush(MetadataList);
1121}
1122
1123Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1124 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1125 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1126
1127 bool IsDistinct = false;
1128 auto getMD = [&](unsigned ID) -> Metadata * {
1129 if (ID < MDStringRef.size())
1130 return lazyLoadOneMDString(ID);
1131 if (!IsDistinct) {
1132 if (auto *MD = MetadataList.lookup(ID))
1133 return MD;
1134 // If lazy-loading is enabled, we try recursively to load the operand
1135 // instead of creating a temporary.
1136 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1137 // Create a temporary for the node that is referencing the operand we
1138 // will lazy-load. It is needed before recursing in case there are
1139 // uniquing cycles.
1140 MetadataList.getMetadataFwdRef(NextMetadataNo);
1141 lazyLoadOneMetadata(ID, Placeholders);
1142 return MetadataList.lookup(ID);
1143 }
1144 // Return a temporary.
1145 return MetadataList.getMetadataFwdRef(ID);
1146 }
1147 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1148 return MD;
1149 return &Placeholders.getPlaceholderOp(ID);
1150 };
1151 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1152 if (ID)
1153 return getMD(ID - 1);
1154 return nullptr;
1155 };
1156 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1157 if (ID)
1158 return MetadataList.getMetadataFwdRef(ID - 1);
1159 return nullptr;
1160 };
1161 auto getMDString = [&](unsigned ID) -> MDString * {
1162 // This requires that the ID is not really a forward reference. In
1163 // particular, the MDString must already have been resolved.
1164 auto MDS = getMDOrNull(ID);
1165 return cast_or_null<MDString>(MDS);
1166 };
1167
1168 // Support for old type refs.
1169 auto getDITypeRefOrNull = [&](unsigned ID) {
1170 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1171 };
1172
1173#define GET_OR_DISTINCT(CLASS, ARGS) \
1174 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1175
1176 switch (Code) {
1177 default: // Default behavior: ignore.
1178 break;
1179 case bitc::METADATA_NAME: {
1180 // Read name of the named metadata.
1181 SmallString<8> Name(Record.begin(), Record.end());
1182 Record.clear();
1183 if (Error E = Stream.ReadCode().moveInto(Code))
1184 return E;
1185
1186 ++NumMDRecordLoaded;
1187 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1188 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1189 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1190 } else
1191 return MaybeNextBitCode.takeError();
1192
1193 // Read named metadata elements.
1194 unsigned Size = Record.size();
1195 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1196 for (unsigned i = 0; i != Size; ++i) {
1197 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1198 if (!MD)
1199 return error("Invalid named metadata: expect fwd ref to MDNode");
1200 NMD->addOperand(MD);
1201 }
1202 break;
1203 }
1204 case bitc::METADATA_OLD_FN_NODE: {
1205 // Deprecated, but still needed to read old bitcode files.
1206 // This is a LocalAsMetadata record, the only type of function-local
1207 // metadata.
1208 if (Record.size() % 2 == 1)
1209 return error("Invalid record");
1210
1211 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1212 // to be legal, but there's no upgrade path.
1213 auto dropRecord = [&] {
1214 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
1215 NextMetadataNo++;
1216 };
1217 if (Record.size() != 2) {
1218 dropRecord();
1219 break;
1220 }
1221
1222 unsigned TyID = Record[0];
1223 Type *Ty = getTypeByID(TyID);
1224 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1225 dropRecord();
1226 break;
1227 }
1228
1229 MetadataList.assignValue(
1230 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty, TyID)),
1231 NextMetadataNo);
1232 NextMetadataNo++;
1233 break;
1234 }
1235 case bitc::METADATA_OLD_NODE: {
1236 // Deprecated, but still needed to read old bitcode files.
1237 if (Record.size() % 2 == 1)
1238 return error("Invalid record");
1239
1240 unsigned Size = Record.size();
1241 SmallVector<Metadata *, 8> Elts;
1242 for (unsigned i = 0; i != Size; i += 2) {
1243 unsigned TyID = Record[i];
1244 Type *Ty = getTypeByID(TyID);
1245 if (!Ty)
1246 return error("Invalid record");
1247 if (Ty->isMetadataTy())
1248 Elts.push_back(getMD(Record[i + 1]));
1249 else if (!Ty->isVoidTy()) {
1250 auto *MD = ValueAsMetadata::get(
1251 ValueList.getValueFwdRef(Record[i + 1], Ty, TyID));
1252 assert(isa<ConstantAsMetadata>(MD) &&(static_cast <bool> (isa<ConstantAsMetadata>(MD) &&
"Expected non-function-local metadata") ? void (0) : __assert_fail
("isa<ConstantAsMetadata>(MD) && \"Expected non-function-local metadata\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1253, __extension__
__PRETTY_FUNCTION__))
1253 "Expected non-function-local metadata")(static_cast <bool> (isa<ConstantAsMetadata>(MD) &&
"Expected non-function-local metadata") ? void (0) : __assert_fail
("isa<ConstantAsMetadata>(MD) && \"Expected non-function-local metadata\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1253, __extension__
__PRETTY_FUNCTION__))
;
1254 Elts.push_back(MD);
1255 } else
1256 Elts.push_back(nullptr);
1257 }
1258 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1259 NextMetadataNo++;
1260 break;
1261 }
1262 case bitc::METADATA_VALUE: {
1263 if (Record.size() != 2)
1264 return error("Invalid record");
1265
1266 unsigned TyID = Record[0];
1267 Type *Ty = getTypeByID(TyID);
1268 if (Ty->isMetadataTy() || Ty->isVoidTy())
1269 return error("Invalid record");
1270
1271 MetadataList.assignValue(
1272 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty, TyID)),
1273 NextMetadataNo);
1274 NextMetadataNo++;
1275 break;
1276 }
1277 case bitc::METADATA_DISTINCT_NODE:
1278 IsDistinct = true;
1279 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1280 case bitc::METADATA_NODE: {
1281 SmallVector<Metadata *, 8> Elts;
1282 Elts.reserve(Record.size());
1283 for (unsigned ID : Record)
1284 Elts.push_back(getMDOrNull(ID));
1285 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1286 : MDNode::get(Context, Elts),
1287 NextMetadataNo);
1288 NextMetadataNo++;
1289 break;
1290 }
1291 case bitc::METADATA_LOCATION: {
1292 if (Record.size() != 5 && Record.size() != 6)
1293 return error("Invalid record");
1294
1295 IsDistinct = Record[0];
1296 unsigned Line = Record[1];
1297 unsigned Column = Record[2];
1298 Metadata *Scope = getMD(Record[3]);
1299 Metadata *InlinedAt = getMDOrNull(Record[4]);
1300 bool ImplicitCode = Record.size() == 6 && Record[5];
1301 MetadataList.assignValue(
1302 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1303 ImplicitCode)),
1304 NextMetadataNo);
1305 NextMetadataNo++;
1306 break;
1307 }
1308 case bitc::METADATA_GENERIC_DEBUG: {
1309 if (Record.size() < 4)
1310 return error("Invalid record");
1311
1312 IsDistinct = Record[0];
1313 unsigned Tag = Record[1];
1314 unsigned Version = Record[2];
1315
1316 if (Tag >= 1u << 16 || Version != 0)
1317 return error("Invalid record");
1318
1319 auto *Header = getMDString(Record[3]);
1320 SmallVector<Metadata *, 8> DwarfOps;
1321 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1322 DwarfOps.push_back(getMDOrNull(Record[I]));
1323 MetadataList.assignValue(
1324 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1325 NextMetadataNo);
1326 NextMetadataNo++;
1327 break;
1328 }
1329 case bitc::METADATA_SUBRANGE: {
1330 Metadata *Val = nullptr;
1331 // Operand 'count' is interpreted as:
1332 // - Signed integer (version 0)
1333 // - Metadata node (version 1)
1334 // Operand 'lowerBound' is interpreted as:
1335 // - Signed integer (version 0 and 1)
1336 // - Metadata node (version 2)
1337 // Operands 'upperBound' and 'stride' are interpreted as:
1338 // - Metadata node (version 2)
1339 switch (Record[0] >> 1) {
1340 case 0:
1341 Val = GET_OR_DISTINCT(DISubrange,
1342 (Context, Record[1], unrotateSign(Record[2])));
1343 break;
1344 case 1:
1345 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1346 unrotateSign(Record[2])));
1347 break;
1348 case 2:
1349 Val = GET_OR_DISTINCT(
1350 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1351 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1352 break;
1353 default:
1354 return error("Invalid record: Unsupported version of DISubrange");
1355 }
1356
1357 MetadataList.assignValue(Val, NextMetadataNo);
1358 IsDistinct = Record[0] & 1;
1359 NextMetadataNo++;
1360 break;
1361 }
1362 case bitc::METADATA_GENERIC_SUBRANGE: {
1363 Metadata *Val = nullptr;
1364 Val = GET_OR_DISTINCT(DIGenericSubrange,
1365 (Context, getMDOrNull(Record[1]),
1366 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1367 getMDOrNull(Record[4])));
1368
1369 MetadataList.assignValue(Val, NextMetadataNo);
1370 IsDistinct = Record[0] & 1;
1371 NextMetadataNo++;
1372 break;
1373 }
1374 case bitc::METADATA_ENUMERATOR: {
1375 if (Record.size() < 3)
1376 return error("Invalid record");
1377
1378 IsDistinct = Record[0] & 1;
1379 bool IsUnsigned = Record[0] & 2;
1380 bool IsBigInt = Record[0] & 4;
1381 APInt Value;
1382
1383 if (IsBigInt) {
1384 const uint64_t BitWidth = Record[1];
1385 const size_t NumWords = Record.size() - 3;
1386 Value = readWideAPInt(makeArrayRef(&Record[3], NumWords), BitWidth);
1387 } else
1388 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1389
1390 MetadataList.assignValue(
1391 GET_OR_DISTINCT(DIEnumerator,
1392 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1393 NextMetadataNo);
1394 NextMetadataNo++;
1395 break;
1396 }
1397 case bitc::METADATA_BASIC_TYPE: {
1398 if (Record.size() < 6 || Record.size() > 7)
1399 return error("Invalid record");
1400
1401 IsDistinct = Record[0];
1402 DINode::DIFlags Flags = (Record.size() > 6)
1403 ? static_cast<DINode::DIFlags>(Record[6])
1404 : DINode::FlagZero;
1405
1406 MetadataList.assignValue(
1407 GET_OR_DISTINCT(DIBasicType,
1408 (Context, Record[1], getMDString(Record[2]), Record[3],
1409 Record[4], Record[5], Flags)),
1410 NextMetadataNo);
1411 NextMetadataNo++;
1412 break;
1413 }
1414 case bitc::METADATA_STRING_TYPE: {
1415 if (Record.size() > 9 || Record.size() < 8)
1416 return error("Invalid record");
1417
1418 IsDistinct = Record[0];
1419 bool SizeIs8 = Record.size() == 8;
1420 // StringLocationExp (i.e. Record[5]) is added at a later time
1421 // than the other fields. The code here enables backward compatibility.
1422 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1423 unsigned Offset = SizeIs8 ? 5 : 6;
1424 MetadataList.assignValue(
1425 GET_OR_DISTINCT(DIStringType,
1426 (Context, Record[1], getMDString(Record[2]),
1427 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1428 StringLocationExp, Record[Offset], Record[Offset + 1],
1429 Record[Offset + 2])),
1430 NextMetadataNo);
1431 NextMetadataNo++;
1432 break;
1433 }
1434 case bitc::METADATA_DERIVED_TYPE: {
1435 if (Record.size() < 12 || Record.size() > 14)
1436 return error("Invalid record");
1437
1438 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1439 // that there is no DWARF address space associated with DIDerivedType.
1440 Optional<unsigned> DWARFAddressSpace;
1441 if (Record.size() > 12 && Record[12])
1442 DWARFAddressSpace = Record[12] - 1;
1443
1444 Metadata *Annotations = nullptr;
1445 if (Record.size() > 13 && Record[13])
1446 Annotations = getMDOrNull(Record[13]);
1447
1448 IsDistinct = Record[0];
1449 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1450 MetadataList.assignValue(
1451 GET_OR_DISTINCT(DIDerivedType,
1452 (Context, Record[1], getMDString(Record[2]),
1453 getMDOrNull(Record[3]), Record[4],
1454 getDITypeRefOrNull(Record[5]),
1455 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1456 Record[9], DWARFAddressSpace, Flags,
1457 getDITypeRefOrNull(Record[11]), Annotations)),
1458 NextMetadataNo);
1459 NextMetadataNo++;
1460 break;
1461 }
1462 case bitc::METADATA_COMPOSITE_TYPE: {
1463 if (Record.size() < 16 || Record.size() > 22)
1464 return error("Invalid record");
1465
1466 // If we have a UUID and this is not a forward declaration, lookup the
1467 // mapping.
1468 IsDistinct = Record[0] & 0x1;
1469 bool IsNotUsedInTypeRef = Record[0] >= 2;
1470 unsigned Tag = Record[1];
1471 MDString *Name = getMDString(Record[2]);
1472 Metadata *File = getMDOrNull(Record[3]);
1473 unsigned Line = Record[4];
1474 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1475 Metadata *BaseType = nullptr;
1476 uint64_t SizeInBits = Record[7];
1477 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1478 return error("Alignment value is too large");
1479 uint32_t AlignInBits = Record[8];
1480 uint64_t OffsetInBits = 0;
1481 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1482 Metadata *Elements = nullptr;
1483 unsigned RuntimeLang = Record[12];
1484 Metadata *VTableHolder = nullptr;
1485 Metadata *TemplateParams = nullptr;
1486 Metadata *Discriminator = nullptr;
1487 Metadata *DataLocation = nullptr;
1488 Metadata *Associated = nullptr;
1489 Metadata *Allocated = nullptr;
1490 Metadata *Rank = nullptr;
1491 Metadata *Annotations = nullptr;
1492 auto *Identifier = getMDString(Record[15]);
1493 // If this module is being parsed so that it can be ThinLTO imported
1494 // into another module, composite types only need to be imported
1495 // as type declarations (unless full type definitions requested).
1496 // Create type declarations up front to save memory. Also, buildODRType
1497 // handles the case where this is type ODRed with a definition needed
1498 // by the importing module, in which case the existing definition is
1499 // used.
1500 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1501 (Tag == dwarf::DW_TAG_enumeration_type ||
1502 Tag == dwarf::DW_TAG_class_type ||
1503 Tag == dwarf::DW_TAG_structure_type ||
1504 Tag == dwarf::DW_TAG_union_type)) {
1505 Flags = Flags | DINode::FlagFwdDecl;
1506 if (Name) {
1507 // This is a hack around preserving template parameters for simplified
1508 // template names - it should probably be replaced with a
1509 // DICompositeType flag specifying whether template parameters are
1510 // required on declarations of this type.
1511 StringRef NameStr = Name->getString();
1512 if (!NameStr.contains('<') || NameStr.startswith("_STN|"))
1513 TemplateParams = getMDOrNull(Record[14]);
1514 }
1515 } else {
1516 BaseType = getDITypeRefOrNull(Record[6]);
1517 OffsetInBits = Record[9];
1518 Elements = getMDOrNull(Record[11]);
1519 VTableHolder = getDITypeRefOrNull(Record[13]);
1520 TemplateParams = getMDOrNull(Record[14]);
1521 if (Record.size() > 16)
1522 Discriminator = getMDOrNull(Record[16]);
1523 if (Record.size() > 17)
1524 DataLocation = getMDOrNull(Record[17]);
1525 if (Record.size() > 19) {
1526 Associated = getMDOrNull(Record[18]);
1527 Allocated = getMDOrNull(Record[19]);
1528 }
1529 if (Record.size() > 20) {
1530 Rank = getMDOrNull(Record[20]);
1531 }
1532 if (Record.size() > 21) {
1533 Annotations = getMDOrNull(Record[21]);
1534 }
1535 }
1536 DICompositeType *CT = nullptr;
1537 if (Identifier)
1538 CT = DICompositeType::buildODRType(
1539 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1540 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1541 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1542 Allocated, Rank, Annotations);
1543
1544 // Create a node if we didn't get a lazy ODR type.
1545 if (!CT)
1546 CT = GET_OR_DISTINCT(DICompositeType,
1547 (Context, Tag, Name, File, Line, Scope, BaseType,
1548 SizeInBits, AlignInBits, OffsetInBits, Flags,
1549 Elements, RuntimeLang, VTableHolder, TemplateParams,
1550 Identifier, Discriminator, DataLocation, Associated,
1551 Allocated, Rank, Annotations));
1552 if (!IsNotUsedInTypeRef && Identifier)
1553 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1554
1555 MetadataList.assignValue(CT, NextMetadataNo);
1556 NextMetadataNo++;
1557 break;
1558 }
1559 case bitc::METADATA_SUBROUTINE_TYPE: {
1560 if (Record.size() < 3 || Record.size() > 4)
1561 return error("Invalid record");
1562 bool IsOldTypeRefArray = Record[0] < 2;
1563 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1564
1565 IsDistinct = Record[0] & 0x1;
1566 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1567 Metadata *Types = getMDOrNull(Record[2]);
1568 if (LLVM_UNLIKELY(IsOldTypeRefArray)__builtin_expect((bool)(IsOldTypeRefArray), false))
1569 Types = MetadataList.upgradeTypeRefArray(Types);
1570
1571 MetadataList.assignValue(
1572 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1573 NextMetadataNo);
1574 NextMetadataNo++;
1575 break;
1576 }
1577
1578 case bitc::METADATA_MODULE: {
1579 if (Record.size() < 5 || Record.size() > 9)
1580 return error("Invalid record");
1581
1582 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1583 IsDistinct = Record[0];
1584 MetadataList.assignValue(
1585 GET_OR_DISTINCT(
1586 DIModule,
1587 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1588 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1589 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1590 getMDString(Record[4 + Offset]),
1591 Record.size() <= 7 ? 0 : Record[7],
1592 Record.size() <= 8 ? false : Record[8])),
1593 NextMetadataNo);
1594 NextMetadataNo++;
1595 break;
1596 }
1597
1598 case bitc::METADATA_FILE: {
1599 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1600 return error("Invalid record");
1601
1602 IsDistinct = Record[0];
1603 Optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1604 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1605 // is not present. This matches up with the old internal representation,
1606 // and the old encoding for CSK_None in the ChecksumKind. The new
1607 // representation reserves the value 0 in the ChecksumKind to continue to
1608 // encode None in a backwards-compatible way.
1609 if (Record.size() > 4 && Record[3] && Record[4])
1610 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1611 getMDString(Record[4]));
1612 MetadataList.assignValue(
1613 GET_OR_DISTINCT(
1614 DIFile,
1615 (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum,
1616 Record.size() > 5 ? Optional<MDString *>(getMDString(Record[5]))
1617 : None)),
1618 NextMetadataNo);
1619 NextMetadataNo++;
1620 break;
1621 }
1622 case bitc::METADATA_COMPILE_UNIT: {
1623 if (Record.size() < 14 || Record.size() > 22)
1624 return error("Invalid record");
1625
1626 // Ignore Record[0], which indicates whether this compile unit is
1627 // distinct. It's always distinct.
1628 IsDistinct = true;
1629 auto *CU = DICompileUnit::getDistinct(
1630 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1631 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1632 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1633 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1634 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1635 Record.size() <= 14 ? 0 : Record[14],
1636 Record.size() <= 16 ? true : Record[16],
1637 Record.size() <= 17 ? false : Record[17],
1638 Record.size() <= 18 ? 0 : Record[18],
1639 Record.size() <= 19 ? false : Record[19],
1640 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1641 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1642
1643 MetadataList.assignValue(CU, NextMetadataNo);
1644 NextMetadataNo++;
1645
1646 // Move the Upgrade the list of subprograms.
1647 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1648 CUSubprograms.push_back({CU, SPs});
1649 break;
1650 }
1651 case bitc::METADATA_SUBPROGRAM: {
1652 if (Record.size() < 18 || Record.size() > 21)
1653 return error("Invalid record");
1654
1655 bool HasSPFlags = Record[0] & 4;
1656
1657 DINode::DIFlags Flags;
1658 DISubprogram::DISPFlags SPFlags;
1659 if (!HasSPFlags)
1660 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1661 else {
1662 Flags = static_cast<DINode::DIFlags>(Record[11]);
1663 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1664 }
1665
1666 // Support for old metadata when
1667 // subprogram specific flags are placed in DIFlags.
1668 const unsigned DIFlagMainSubprogram = 1 << 21;
1669 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
1670 if (HasOldMainSubprogramFlag)
1671 // Remove old DIFlagMainSubprogram from DIFlags.
1672 // Note: This assumes that any future use of bit 21 defaults to it
1673 // being 0.
1674 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1675
1676 if (HasOldMainSubprogramFlag && HasSPFlags)
1677 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1678 else if (!HasSPFlags)
1679 SPFlags = DISubprogram::toSPFlags(
1680 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
1681 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
1682 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
1683
1684 // All definitions should be distinct.
1685 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1686 // Version 1 has a Function as Record[15].
1687 // Version 2 has removed Record[15].
1688 // Version 3 has the Unit as Record[15].
1689 // Version 4 added thisAdjustment.
1690 // Version 5 repacked flags into DISPFlags, changing many element numbers.
1691 bool HasUnit = Record[0] & 2;
1692 if (!HasSPFlags && HasUnit && Record.size() < 19)
1693 return error("Invalid record");
1694 if (HasSPFlags && !HasUnit)
1695 return error("Invalid record");
1696 // Accommodate older formats.
1697 bool HasFn = false;
1698 bool HasThisAdj = true;
1699 bool HasThrownTypes = true;
1700 bool HasAnnotations = false;
1701 bool HasTargetFuncName = false;
1702 unsigned OffsetA = 0;
1703 unsigned OffsetB = 0;
1704 if (!HasSPFlags) {
1705 OffsetA = 2;
1706 OffsetB = 2;
1707 if (Record.size() >= 19) {
1708 HasFn = !HasUnit;
1709 OffsetB++;
1710 }
1711 HasThisAdj = Record.size() >= 20;
1712 HasThrownTypes = Record.size() >= 21;
1713 } else {
1714 HasAnnotations = Record.size() >= 19;
1715 HasTargetFuncName = Record.size() >= 20;
1716 }
1717 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1718 DISubprogram *SP = GET_OR_DISTINCT(
1719 DISubprogram,
1720 (Context,
1721 getDITypeRefOrNull(Record[1]), // scope
1722 getMDString(Record[2]), // name
1723 getMDString(Record[3]), // linkageName
1724 getMDOrNull(Record[4]), // file
1725 Record[5], // line
1726 getMDOrNull(Record[6]), // type
1727 Record[7 + OffsetA], // scopeLine
1728 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
1729 Record[10 + OffsetA], // virtualIndex
1730 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
1731 Flags, // flags
1732 SPFlags, // SPFlags
1733 HasUnit ? CUorFn : nullptr, // unit
1734 getMDOrNull(Record[13 + OffsetB]), // templateParams
1735 getMDOrNull(Record[14 + OffsetB]), // declaration
1736 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
1737 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1738 : nullptr, // thrownTypes
1739 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1740 : nullptr, // annotations
1741 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
1742 : nullptr // targetFuncName
1743 ));
1744 MetadataList.assignValue(SP, NextMetadataNo);
1745 NextMetadataNo++;
1746
1747 // Upgrade sp->function mapping to function->sp mapping.
1748 if (HasFn) {
1749 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1750 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1751 if (F->isMaterializable())
1752 // Defer until materialized; unmaterialized functions may not have
1753 // metadata.
1754 FunctionsWithSPs[F] = SP;
1755 else if (!F->empty())
1756 F->setSubprogram(SP);
1757 }
1758 }
1759 break;
1760 }
1761 case bitc::METADATA_LEXICAL_BLOCK: {
1762 if (Record.size() != 5)
1763 return error("Invalid record");
1764
1765 IsDistinct = Record[0];
1766 MetadataList.assignValue(
1767 GET_OR_DISTINCT(DILexicalBlock,
1768 (Context, getMDOrNull(Record[1]),
1769 getMDOrNull(Record[2]), Record[3], Record[4])),
1770 NextMetadataNo);
1771 NextMetadataNo++;
1772 break;
1773 }
1774 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1775 if (Record.size() != 4)
1776 return error("Invalid record");
1777
1778 IsDistinct = Record[0];
1779 MetadataList.assignValue(
1780 GET_OR_DISTINCT(DILexicalBlockFile,
1781 (Context, getMDOrNull(Record[1]),
1782 getMDOrNull(Record[2]), Record[3])),
1783 NextMetadataNo);
1784 NextMetadataNo++;
1785 break;
1786 }
1787 case bitc::METADATA_COMMON_BLOCK: {
1788 IsDistinct = Record[0] & 1;
1789 MetadataList.assignValue(
1790 GET_OR_DISTINCT(DICommonBlock,
1791 (Context, getMDOrNull(Record[1]),
1792 getMDOrNull(Record[2]), getMDString(Record[3]),
1793 getMDOrNull(Record[4]), Record[5])),
1794 NextMetadataNo);
1795 NextMetadataNo++;
1796 break;
1797 }
1798 case bitc::METADATA_NAMESPACE: {
1799 // Newer versions of DINamespace dropped file and line.
1800 MDString *Name;
1801 if (Record.size() == 3)
1802 Name = getMDString(Record[2]);
1803 else if (Record.size() == 5)
1804 Name = getMDString(Record[3]);
1805 else
1806 return error("Invalid record");
1807
1808 IsDistinct = Record[0] & 1;
1809 bool ExportSymbols = Record[0] & 2;
1810 MetadataList.assignValue(
1811 GET_OR_DISTINCT(DINamespace,
1812 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1813 NextMetadataNo);
1814 NextMetadataNo++;
1815 break;
1816 }
1817 case bitc::METADATA_MACRO: {
1818 if (Record.size() != 5)
1819 return error("Invalid record");
1820
1821 IsDistinct = Record[0];
1822 MetadataList.assignValue(
1823 GET_OR_DISTINCT(DIMacro,
1824 (Context, Record[1], Record[2], getMDString(Record[3]),
1825 getMDString(Record[4]))),
1826 NextMetadataNo);
1827 NextMetadataNo++;
1828 break;
1829 }
1830 case bitc::METADATA_MACRO_FILE: {
1831 if (Record.size() != 5)
1832 return error("Invalid record");
1833
1834 IsDistinct = Record[0];
1835 MetadataList.assignValue(
1836 GET_OR_DISTINCT(DIMacroFile,
1837 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1838 getMDOrNull(Record[4]))),
1839 NextMetadataNo);
1840 NextMetadataNo++;
1841 break;
1842 }
1843 case bitc::METADATA_TEMPLATE_TYPE: {
1844 if (Record.size() < 3 || Record.size() > 4)
1845 return error("Invalid record");
1846
1847 IsDistinct = Record[0];
1848 MetadataList.assignValue(
1849 GET_OR_DISTINCT(DITemplateTypeParameter,
1850 (Context, getMDString(Record[1]),
1851 getDITypeRefOrNull(Record[2]),
1852 (Record.size() == 4) ? getMDOrNull(Record[3])
1853 : getMDOrNull(false))),
1854 NextMetadataNo);
1855 NextMetadataNo++;
1856 break;
1857 }
1858 case bitc::METADATA_TEMPLATE_VALUE: {
1859 if (Record.size() < 5 || Record.size() > 6)
1860 return error("Invalid record");
1861
1862 IsDistinct = Record[0];
1863
1864 MetadataList.assignValue(
1865 GET_OR_DISTINCT(
1866 DITemplateValueParameter,
1867 (Context, Record[1], getMDString(Record[2]),
1868 getDITypeRefOrNull(Record[3]),
1869 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
1870 (Record.size() == 6) ? getMDOrNull(Record[5])
1871 : getMDOrNull(Record[4]))),
1872 NextMetadataNo);
1873 NextMetadataNo++;
1874 break;
1875 }
1876 case bitc::METADATA_GLOBAL_VAR: {
1877 if (Record.size() < 11 || Record.size() > 13)
1878 return error("Invalid record");
1879
1880 IsDistinct = Record[0] & 1;
1881 unsigned Version = Record[0] >> 1;
1882
1883 if (Version == 2) {
1884 Metadata *Annotations = nullptr;
1885 if (Record.size() > 12)
1886 Annotations = getMDOrNull(Record[12]);
1887
1888 MetadataList.assignValue(
1889 GET_OR_DISTINCT(DIGlobalVariable,
1890 (Context, getMDOrNull(Record[1]),
1891 getMDString(Record[2]), getMDString(Record[3]),
1892 getMDOrNull(Record[4]), Record[5],
1893 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1894 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1895 Record[11], Annotations)),
1896 NextMetadataNo);
1897
1898 NextMetadataNo++;
1899 } else if (Version == 1) {
1900 // No upgrade necessary. A null field will be introduced to indicate
1901 // that no parameter information is available.
1902 MetadataList.assignValue(
1903 GET_OR_DISTINCT(
1904 DIGlobalVariable,
1905 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1906 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1907 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1908 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
1909 NextMetadataNo);
1910
1911 NextMetadataNo++;
1912 } else if (Version == 0) {
1913 // Upgrade old metadata, which stored a global variable reference or a
1914 // ConstantInt here.
1915 NeedUpgradeToDIGlobalVariableExpression = true;
1916 Metadata *Expr = getMDOrNull(Record[9]);
1917 uint32_t AlignInBits = 0;
1918 if (Record.size() > 11) {
1919 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1920 return error("Alignment value is too large");
1921 AlignInBits = Record[11];
1922 }
1923 GlobalVariable *Attach = nullptr;
1924 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1925 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1926 Attach = GV;
1927 Expr = nullptr;
1928 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1929 Expr = DIExpression::get(Context,
1930 {dwarf::DW_OP_constu, CI->getZExtValue(),
1931 dwarf::DW_OP_stack_value});
1932 } else {
1933 Expr = nullptr;
1934 }
1935 }
1936 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1937 DIGlobalVariable,
1938 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1939 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1940 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1941 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
1942
1943 DIGlobalVariableExpression *DGVE = nullptr;
1944 if (Attach || Expr)
1945 DGVE = DIGlobalVariableExpression::getDistinct(
1946 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
1947 if (Attach)
1948 Attach->addDebugInfo(DGVE);
1949
1950 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1951 MetadataList.assignValue(MDNode, NextMetadataNo);
1952 NextMetadataNo++;
1953 } else
1954 return error("Invalid record");
1955
1956 break;
1957 }
1958 case bitc::METADATA_LOCAL_VAR: {
1959 // 10th field is for the obseleted 'inlinedAt:' field.
1960 if (Record.size() < 8 || Record.size() > 10)
1961 return error("Invalid record");
1962
1963 IsDistinct = Record[0] & 1;
1964 bool HasAlignment = Record[0] & 2;
1965 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1966 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1967 // this is newer version of record which doesn't have artificial tag.
1968 bool HasTag = !HasAlignment && Record.size() > 8;
1969 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1970 uint32_t AlignInBits = 0;
1971 Metadata *Annotations = nullptr;
1972 if (HasAlignment) {
1973 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1974 return error("Alignment value is too large");
1975 AlignInBits = Record[8];
1976 if (Record.size() > 9)
1977 Annotations = getMDOrNull(Record[9]);
1978 }
1979
1980 MetadataList.assignValue(
1981 GET_OR_DISTINCT(DILocalVariable,
1982 (Context, getMDOrNull(Record[1 + HasTag]),
1983 getMDString(Record[2 + HasTag]),
1984 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1985 getDITypeRefOrNull(Record[5 + HasTag]),
1986 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
1987 NextMetadataNo);
1988 NextMetadataNo++;
1989 break;
1990 }
1991 case bitc::METADATA_LABEL: {
1992 if (Record.size() != 5)
1993 return error("Invalid record");
1994
1995 IsDistinct = Record[0] & 1;
1996 MetadataList.assignValue(
1997 GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
1998 getMDString(Record[2]),
1999 getMDOrNull(Record[3]), Record[4])),
2000 NextMetadataNo);
2001 NextMetadataNo++;
2002 break;
2003 }
2004 case bitc::METADATA_EXPRESSION: {
2005 if (Record.size() < 1)
2006 return error("Invalid record");
2007
2008 IsDistinct = Record[0] & 1;
2009 uint64_t Version = Record[0] >> 1;
2010 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2011
2012 SmallVector<uint64_t, 6> Buffer;
2013 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2014 return Err;
2015
2016 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2017 NextMetadataNo);
2018 NextMetadataNo++;
2019 break;
2020 }
2021 case bitc::METADATA_GLOBAL_VAR_EXPR: {
2022 if (Record.size() != 3)
2023 return error("Invalid record");
2024
2025 IsDistinct = Record[0];
2026 Metadata *Expr = getMDOrNull(Record[2]);
2027 if (!Expr)
2028 Expr = DIExpression::get(Context, {});
2029 MetadataList.assignValue(
2030 GET_OR_DISTINCT(DIGlobalVariableExpression,
2031 (Context, getMDOrNull(Record[1]), Expr)),
2032 NextMetadataNo);
2033 NextMetadataNo++;
2034 break;
2035 }
2036 case bitc::METADATA_OBJC_PROPERTY: {
2037 if (Record.size() != 8)
2038 return error("Invalid record");
2039
2040 IsDistinct = Record[0];
2041 MetadataList.assignValue(
2042 GET_OR_DISTINCT(DIObjCProperty,
2043 (Context, getMDString(Record[1]),
2044 getMDOrNull(Record[2]), Record[3],
2045 getMDString(Record[4]), getMDString(Record[5]),
2046 Record[6], getDITypeRefOrNull(Record[7]))),
2047 NextMetadataNo);
2048 NextMetadataNo++;
2049 break;
2050 }
2051 case bitc::METADATA_IMPORTED_ENTITY: {
2052 if (Record.size() < 6 || Record.size() > 8)
2053 return error("Invalid DIImportedEntity record");
2054
2055 IsDistinct = Record[0];
2056 bool HasFile = (Record.size() >= 7);
2057 bool HasElements = (Record.size() >= 8);
2058 MetadataList.assignValue(
2059 GET_OR_DISTINCT(DIImportedEntity,
2060 (Context, Record[1], getMDOrNull(Record[2]),
2061 getDITypeRefOrNull(Record[3]),
2062 HasFile ? getMDOrNull(Record[6]) : nullptr,
2063 HasFile ? Record[4] : 0, getMDString(Record[5]),
2064 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2065 NextMetadataNo);
2066 NextMetadataNo++;
2067 break;
2068 }
2069 case bitc::METADATA_STRING_OLD: {
2070 std::string String(Record.begin(), Record.end());
2071
2072 // Test for upgrading !llvm.loop.
2073 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2074 ++NumMDStringLoaded;
2075 Metadata *MD = MDString::get(Context, String);
2076 MetadataList.assignValue(MD, NextMetadataNo);
2077 NextMetadataNo++;
2078 break;
2079 }
2080 case bitc::METADATA_STRINGS: {
2081 auto CreateNextMDString = [&](StringRef Str) {
2082 ++NumMDStringLoaded;
2083 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2084 NextMetadataNo++;
2085 };
2086 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2087 return Err;
2088 break;
2089 }
2090 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2091 if (Record.size() % 2 == 0)
2092 return error("Invalid record");
2093 unsigned ValueID = Record[0];
2094 if (ValueID >= ValueList.size())
2095 return error("Invalid record");
2096 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2097 if (Error Err = parseGlobalObjectAttachment(
2098 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2099 return Err;
2100 break;
2101 }
2102 case bitc::METADATA_KIND: {
2103 // Support older bitcode files that had METADATA_KIND records in a
2104 // block with METADATA_BLOCK_ID.
2105 if (Error Err = parseMetadataKindRecord(Record))
2106 return Err;
2107 break;
2108 }
2109 case bitc::METADATA_ARG_LIST: {
2110 SmallVector<ValueAsMetadata *, 4> Elts;
2111 Elts.reserve(Record.size());
2112 for (uint64_t Elt : Record) {
2113 Metadata *MD = getMD(Elt);
2114 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2115 return error(
2116 "Invalid record: DIArgList should not contain forward refs");
2117 if (!isa<ValueAsMetadata>(MD))
2118 return error("Invalid record");
2119 Elts.push_back(cast<ValueAsMetadata>(MD));
2120 }
2121
2122 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2123 NextMetadataNo++;
2124 break;
2125 }
2126 }
2127 return Error::success();
2128#undef GET_OR_DISTINCT
2129}
2130
2131Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2132 ArrayRef<uint64_t> Record, StringRef Blob,
2133 function_ref<void(StringRef)> CallBack) {
2134 // All the MDStrings in the block are emitted together in a single
2135 // record. The strings are concatenated and stored in a blob along with
2136 // their sizes.
2137 if (Record.size() != 2)
2138 return error("Invalid record: metadata strings layout");
2139
2140 unsigned NumStrings = Record[0];
2141 unsigned StringsOffset = Record[1];
2142 if (!NumStrings)
2143 return error("Invalid record: metadata strings with no strings");
2144 if (StringsOffset > Blob.size())
2145 return error("Invalid record: metadata strings corrupt offset");
2146
2147 StringRef Lengths = Blob.slice(0, StringsOffset);
2148 SimpleBitstreamCursor R(Lengths);
2149
2150 StringRef Strings = Blob.drop_front(StringsOffset);
2151 do {
2152 if (R.AtEndOfStream())
2153 return error("Invalid record: metadata strings bad length");
2154
2155 uint32_t Size;
2156 if (Error E = R.ReadVBR(6).moveInto(Size))
2157 return E;
2158 if (Strings.size() < Size)
2159 return error("Invalid record: metadata strings truncated chars");
2160
2161 CallBack(Strings.slice(0, Size));
2162 Strings = Strings.drop_front(Size);
2163 } while (--NumStrings);
2164
2165 return Error::success();
2166}
2167
2168Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2169 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2170 assert(Record.size() % 2 == 0)(static_cast <bool> (Record.size() % 2 == 0) ? void (0)
: __assert_fail ("Record.size() % 2 == 0", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 2170, __extension__ __PRETTY_FUNCTION__))
;
14
Assuming the condition is true
15
'?' condition is true
2171 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
16
Assuming 'I' is not equal to 'E'
17
Loop condition is true. Entering loop body
2172 auto K = MDKindMap.find(Record[I]);
2173 if (K == MDKindMap.end())
18
Taking false branch
2174 return error("Invalid ID");
2175 MDNode *MD =
2176 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
19
Calling 'MetadataLoaderImpl::getMetadataFwdRefOrLoad'
2177 if (!MD)
2178 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2179 GO.addMetadata(K->second, *MD);
2180 }
2181 return Error::success();
2182}
2183
2184/// Parse metadata attachments.
2185Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2186 Function &F, ArrayRef<Instruction *> InstructionList) {
2187 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2
Assuming the condition is false
3
Taking false branch
2188 return Err;
2189
2190 SmallVector<uint64_t, 64> Record;
2191 PlaceholderQueue Placeholders;
2192
2193 while (true) {
4
Loop condition is true. Entering loop body
2194 BitstreamEntry Entry;
2195 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
5
Taking false branch
2196 return E;
2197
2198 switch (Entry.Kind) {
6
Control jumps to 'case Record:' at line 2205
2199 case BitstreamEntry::SubBlock: // Handled for us already.
2200 case BitstreamEntry::Error:
2201 return error("Malformed block");
2202 case BitstreamEntry::EndBlock:
2203 resolveForwardRefsAndPlaceholders(Placeholders);
2204 return Error::success();
2205 case BitstreamEntry::Record:
2206 // The interesting case.
2207 break;
7
Execution continues on line 2211
2208 }
2209
2210 // Read a metadata attachment record.
2211 Record.clear();
2212 ++NumMDRecordLoaded;
2213 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2214 if (!MaybeRecord)
8
Taking false branch
2215 return MaybeRecord.takeError();
2216 switch (MaybeRecord.get()) {
9
Control jumps to 'case METADATA_ATTACHMENT:' at line 2219
2217 default: // Default behavior: ignore.
2218 break;
2219 case bitc::METADATA_ATTACHMENT: {
2220 unsigned RecordLength = Record.size();
2221 if (Record.empty())
10
Taking false branch
2222 return error("Invalid record");
2223 if (RecordLength % 2 == 0) {
11
Assuming the condition is true
12
Taking true branch
2224 // A function attachment.
2225 if (Error Err = parseGlobalObjectAttachment(F, Record))
13
Calling 'MetadataLoaderImpl::parseGlobalObjectAttachment'
2226 return Err;
2227 continue;
2228 }
2229
2230 // An instruction attachment.
2231 Instruction *Inst = InstructionList[Record[0]];
2232 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2233 unsigned Kind = Record[i];
2234 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2235 if (I == MDKindMap.end())
2236 return error("Invalid ID");
2237 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2238 continue;
2239
2240 auto Idx = Record[i + 1];
2241 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2242 !MetadataList.lookup(Idx)) {
2243 // Load the attachment if it is in the lazy-loadable range and hasn't
2244 // been loaded yet.
2245 lazyLoadOneMetadata(Idx, Placeholders);
2246 resolveForwardRefsAndPlaceholders(Placeholders);
2247 }
2248
2249 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2250 if (isa<LocalAsMetadata>(Node))
2251 // Drop the attachment. This used to be legal, but there's no
2252 // upgrade path.
2253 break;
2254 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2255 if (!MD)
2256 return error("Invalid metadata attachment");
2257
2258 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2259 MD = upgradeInstructionLoopAttachment(*MD);
2260
2261 if (I->second == LLVMContext::MD_tbaa) {
2262 assert(!MD->isTemporary() && "should load MDs before attachments")(static_cast <bool> (!MD->isTemporary() && "should load MDs before attachments"
) ? void (0) : __assert_fail ("!MD->isTemporary() && \"should load MDs before attachments\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 2262, __extension__
__PRETTY_FUNCTION__))
;
2263 MD = UpgradeTBAANode(*MD);
2264 }
2265 Inst->setMetadata(I->second, MD);
2266 }
2267 break;
2268 }
2269 }
2270 }
2271}
2272
2273/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2274Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2275 SmallVectorImpl<uint64_t> &Record) {
2276 if (Record.size() < 2)
2277 return error("Invalid record");
2278
2279 unsigned Kind = Record[0];
2280 SmallString<8> Name(Record.begin() + 1, Record.end());
2281
2282 unsigned NewKind = TheModule.getMDKindID(Name.str());
2283 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2284 return error("Conflicting METADATA_KIND records");
2285 return Error::success();
2286}
2287
2288/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2289Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2290 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2291 return Err;
2292
2293 SmallVector<uint64_t, 64> Record;
2294
2295 // Read all the records.
2296 while (true) {
2297 BitstreamEntry Entry;
2298 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2299 return E;
2300
2301 switch (Entry.Kind) {
2302 case BitstreamEntry::SubBlock: // Handled for us already.
2303 case BitstreamEntry::Error:
2304 return error("Malformed block");
2305 case BitstreamEntry::EndBlock:
2306 return Error::success();
2307 case BitstreamEntry::Record:
2308 // The interesting case.
2309 break;
2310 }
2311
2312 // Read a record.
2313 Record.clear();
2314 ++NumMDRecordLoaded;
2315 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2316 if (!MaybeCode)
2317 return MaybeCode.takeError();
2318 switch (MaybeCode.get()) {
2319 default: // Default behavior: ignore.
2320 break;
2321 case bitc::METADATA_KIND: {
2322 if (Error Err = parseMetadataKindRecord(Record))
2323 return Err;
2324 break;
2325 }
2326 }
2327 }
2328}
2329
2330MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2331 Pimpl = std::move(RHS.Pimpl);
2332 return *this;
2333}
2334MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2335 : Pimpl(std::move(RHS.Pimpl)) {}
2336
2337MetadataLoader::~MetadataLoader() = default;
2338MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2339 BitcodeReaderValueList &ValueList,
2340 bool IsImporting,
2341 std::function<Type *(unsigned)> getTypeByID)
2342 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2343 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
2344
2345Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2346 return Pimpl->parseMetadata(ModuleLevel);
2347}
2348
2349bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2350
2351/// Return the given metadata, creating a replaceable forward reference if
2352/// necessary.
2353Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
2354 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2355}
2356
2357DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2358 return Pimpl->lookupSubprogramForFunction(F);
2359}
2360
2361Error MetadataLoader::parseMetadataAttachment(
2362 Function &F, ArrayRef<Instruction *> InstructionList) {
2363 return Pimpl->parseMetadataAttachment(F, InstructionList);
1
Calling 'MetadataLoaderImpl::parseMetadataAttachment'
2364}
2365
2366Error MetadataLoader::parseMetadataKinds() {
2367 return Pimpl->parseMetadataKinds();
2368}
2369
2370void MetadataLoader::setStripTBAA(bool StripTBAA) {
2371 return Pimpl->setStripTBAA(StripTBAA);
2372}
2373
2374bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2375
2376unsigned MetadataLoader::size() const { return Pimpl->size(); }
2377void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2378
2379void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2380 return Pimpl->upgradeDebugIntrinsics(F);
2381}

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