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