1b915e9e0SDimitry Andric //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2b915e9e0SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b915e9e0SDimitry Andric //
7b915e9e0SDimitry Andric //===----------------------------------------------------------------------===//
8b915e9e0SDimitry Andric
9b915e9e0SDimitry Andric #include "MetadataLoader.h"
10b915e9e0SDimitry Andric #include "ValueList.h"
11b915e9e0SDimitry Andric
12b915e9e0SDimitry Andric #include "llvm/ADT/APInt.h"
13b915e9e0SDimitry Andric #include "llvm/ADT/ArrayRef.h"
14145449b1SDimitry Andric #include "llvm/ADT/BitmaskEnum.h"
15b915e9e0SDimitry Andric #include "llvm/ADT/DenseMap.h"
167e7b6700SDimitry Andric #include "llvm/ADT/DenseSet.h"
17145449b1SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h"
187fa27ce4SDimitry Andric #include "llvm/ADT/SetVector.h"
19b915e9e0SDimitry Andric #include "llvm/ADT/SmallString.h"
20145449b1SDimitry Andric #include "llvm/ADT/SmallVector.h"
217e7b6700SDimitry Andric #include "llvm/ADT/Statistic.h"
22b915e9e0SDimitry Andric #include "llvm/ADT/StringRef.h"
23b915e9e0SDimitry Andric #include "llvm/ADT/Twine.h"
24145449b1SDimitry Andric #include "llvm/ADT/ilist_iterator.h"
25145449b1SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
26b915e9e0SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
27b915e9e0SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
28c0981da4SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
29b915e9e0SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
30b915e9e0SDimitry Andric #include "llvm/IR/BasicBlock.h"
31b915e9e0SDimitry Andric #include "llvm/IR/Constants.h"
32b915e9e0SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
33b915e9e0SDimitry Andric #include "llvm/IR/Function.h"
34b915e9e0SDimitry Andric #include "llvm/IR/GlobalObject.h"
35b915e9e0SDimitry Andric #include "llvm/IR/GlobalVariable.h"
36b915e9e0SDimitry Andric #include "llvm/IR/Instruction.h"
37d99dafe2SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
38b915e9e0SDimitry Andric #include "llvm/IR/LLVMContext.h"
39145449b1SDimitry Andric #include "llvm/IR/Metadata.h"
40b915e9e0SDimitry Andric #include "llvm/IR/Module.h"
41b915e9e0SDimitry Andric #include "llvm/IR/TrackingMDRef.h"
42b915e9e0SDimitry Andric #include "llvm/IR/Type.h"
43b915e9e0SDimitry Andric #include "llvm/Support/Casting.h"
44b915e9e0SDimitry Andric #include "llvm/Support/CommandLine.h"
45b915e9e0SDimitry Andric #include "llvm/Support/Compiler.h"
46b915e9e0SDimitry Andric #include "llvm/Support/ErrorHandling.h"
47145449b1SDimitry Andric #include "llvm/Support/type_traits.h"
48145449b1SDimitry Andric
49b915e9e0SDimitry Andric #include <algorithm>
50b915e9e0SDimitry Andric #include <cassert>
51b915e9e0SDimitry Andric #include <cstddef>
52b915e9e0SDimitry Andric #include <cstdint>
53b915e9e0SDimitry Andric #include <deque>
54145449b1SDimitry Andric #include <iterator>
55b915e9e0SDimitry Andric #include <limits>
567fa27ce4SDimitry Andric #include <map>
57e3b55780SDimitry Andric #include <optional>
58b915e9e0SDimitry Andric #include <string>
59b915e9e0SDimitry Andric #include <tuple>
60145449b1SDimitry Andric #include <type_traits>
61b915e9e0SDimitry Andric #include <utility>
62b915e9e0SDimitry Andric #include <vector>
63145449b1SDimitry Andric namespace llvm {
64145449b1SDimitry Andric class Argument;
65145449b1SDimitry Andric }
66b915e9e0SDimitry Andric
67b915e9e0SDimitry Andric using namespace llvm;
68b915e9e0SDimitry Andric
697e7b6700SDimitry Andric #define DEBUG_TYPE "bitcode-reader"
707e7b6700SDimitry Andric
717e7b6700SDimitry Andric STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
727e7b6700SDimitry Andric STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
737e7b6700SDimitry Andric STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
747e7b6700SDimitry Andric
75b915e9e0SDimitry Andric /// Flag whether we need to import full type definitions for ThinLTO.
76b915e9e0SDimitry Andric /// Currently needed for Darwin and LLDB.
77b915e9e0SDimitry Andric static cl::opt<bool> ImportFullTypeDefinitions(
78b915e9e0SDimitry Andric "import-full-type-definitions", cl::init(false), cl::Hidden,
79b915e9e0SDimitry Andric cl::desc("Import full type definitions for ThinLTO."));
80b915e9e0SDimitry Andric
817e7b6700SDimitry Andric static cl::opt<bool> DisableLazyLoading(
827e7b6700SDimitry Andric "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
837e7b6700SDimitry Andric cl::desc("Force disable the lazy-loading on-demand of metadata when "
847e7b6700SDimitry Andric "loading bitcode for importing."));
857e7b6700SDimitry Andric
86b915e9e0SDimitry Andric namespace {
87b915e9e0SDimitry Andric
unrotateSign(uint64_t U)88e6d15924SDimitry Andric static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
89b915e9e0SDimitry Andric
90b915e9e0SDimitry Andric class BitcodeReaderMetadataList {
91b915e9e0SDimitry Andric /// Array of metadata references.
92b915e9e0SDimitry Andric ///
93b915e9e0SDimitry Andric /// Don't use std::vector here. Some versions of libc++ copy (instead of
94b915e9e0SDimitry Andric /// move) on resize, and TrackingMDRef is very expensive to copy.
95b915e9e0SDimitry Andric SmallVector<TrackingMDRef, 1> MetadataPtrs;
96b915e9e0SDimitry Andric
97b915e9e0SDimitry Andric /// The set of indices in MetadataPtrs above of forward references that were
98b915e9e0SDimitry Andric /// generated.
99b915e9e0SDimitry Andric SmallDenseSet<unsigned, 1> ForwardReference;
100b915e9e0SDimitry Andric
101b915e9e0SDimitry Andric /// The set of indices in MetadataPtrs above of Metadata that need to be
102b915e9e0SDimitry Andric /// resolved.
103b915e9e0SDimitry Andric SmallDenseSet<unsigned, 1> UnresolvedNodes;
104b915e9e0SDimitry Andric
105b915e9e0SDimitry Andric /// Structures for resolving old type refs.
106b915e9e0SDimitry Andric struct {
107b915e9e0SDimitry Andric SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
108b915e9e0SDimitry Andric SmallDenseMap<MDString *, DICompositeType *, 1> Final;
109b915e9e0SDimitry Andric SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
110b915e9e0SDimitry Andric SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
111b915e9e0SDimitry Andric } OldTypeRefs;
112b915e9e0SDimitry Andric
113b915e9e0SDimitry Andric LLVMContext &Context;
114b915e9e0SDimitry Andric
115e6d15924SDimitry Andric /// Maximum number of valid references. Forward references exceeding the
116e6d15924SDimitry Andric /// maximum must be invalid.
117e6d15924SDimitry Andric unsigned RefsUpperBound;
118e6d15924SDimitry Andric
119b915e9e0SDimitry Andric public:
BitcodeReaderMetadataList(LLVMContext & C,size_t RefsUpperBound)120e6d15924SDimitry Andric BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
121e6d15924SDimitry Andric : Context(C),
122e6d15924SDimitry Andric RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
123e6d15924SDimitry Andric RefsUpperBound)) {}
124b915e9e0SDimitry Andric
125b915e9e0SDimitry Andric // vector compatibility methods
size() const126b915e9e0SDimitry Andric unsigned size() const { return MetadataPtrs.size(); }
resize(unsigned N)127b915e9e0SDimitry Andric void resize(unsigned N) { MetadataPtrs.resize(N); }
push_back(Metadata * MD)128b915e9e0SDimitry Andric void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
clear()129b915e9e0SDimitry Andric void clear() { MetadataPtrs.clear(); }
back() const130b915e9e0SDimitry Andric Metadata *back() const { return MetadataPtrs.back(); }
pop_back()131b915e9e0SDimitry Andric void pop_back() { MetadataPtrs.pop_back(); }
empty() const132b915e9e0SDimitry Andric bool empty() const { return MetadataPtrs.empty(); }
133b915e9e0SDimitry Andric
operator [](unsigned i) const134b915e9e0SDimitry Andric Metadata *operator[](unsigned i) const {
135b915e9e0SDimitry Andric assert(i < MetadataPtrs.size());
136b915e9e0SDimitry Andric return MetadataPtrs[i];
137b915e9e0SDimitry Andric }
138b915e9e0SDimitry Andric
lookup(unsigned I) const139b915e9e0SDimitry Andric Metadata *lookup(unsigned I) const {
140b915e9e0SDimitry Andric if (I < MetadataPtrs.size())
141b915e9e0SDimitry Andric return MetadataPtrs[I];
142b915e9e0SDimitry Andric return nullptr;
143b915e9e0SDimitry Andric }
144b915e9e0SDimitry Andric
shrinkTo(unsigned N)145b915e9e0SDimitry Andric void shrinkTo(unsigned N) {
146b915e9e0SDimitry Andric assert(N <= size() && "Invalid shrinkTo request!");
147b915e9e0SDimitry Andric assert(ForwardReference.empty() && "Unexpected forward refs");
148b915e9e0SDimitry Andric assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
149b915e9e0SDimitry Andric MetadataPtrs.resize(N);
150b915e9e0SDimitry Andric }
151b915e9e0SDimitry Andric
152b915e9e0SDimitry Andric /// Return the given metadata, creating a replaceable forward reference if
153b915e9e0SDimitry Andric /// necessary.
154b915e9e0SDimitry Andric Metadata *getMetadataFwdRef(unsigned Idx);
155b915e9e0SDimitry Andric
156eb11fae6SDimitry Andric /// Return the given metadata only if it is fully resolved.
157b915e9e0SDimitry Andric ///
158b915e9e0SDimitry Andric /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
159b915e9e0SDimitry Andric /// would give \c false.
160b915e9e0SDimitry Andric Metadata *getMetadataIfResolved(unsigned Idx);
161b915e9e0SDimitry Andric
162b915e9e0SDimitry Andric MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
163b915e9e0SDimitry Andric void assignValue(Metadata *MD, unsigned Idx);
164b915e9e0SDimitry Andric void tryToResolveCycles();
hasFwdRefs() const165b915e9e0SDimitry Andric bool hasFwdRefs() const { return !ForwardReference.empty(); }
getNextFwdRef()1667e7b6700SDimitry Andric int getNextFwdRef() {
1677e7b6700SDimitry Andric assert(hasFwdRefs());
1687e7b6700SDimitry Andric return *ForwardReference.begin();
1697e7b6700SDimitry Andric }
170b915e9e0SDimitry Andric
171b915e9e0SDimitry Andric /// Upgrade a type that had an MDString reference.
172b915e9e0SDimitry Andric void addTypeRef(MDString &UUID, DICompositeType &CT);
173b915e9e0SDimitry Andric
174b915e9e0SDimitry Andric /// Upgrade a type that had an MDString reference.
175b915e9e0SDimitry Andric Metadata *upgradeTypeRef(Metadata *MaybeUUID);
176b915e9e0SDimitry Andric
177b915e9e0SDimitry Andric /// Upgrade a type ref array that may have MDString references.
178b915e9e0SDimitry Andric Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
179b915e9e0SDimitry Andric
180b915e9e0SDimitry Andric private:
181b915e9e0SDimitry Andric Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
182b915e9e0SDimitry Andric };
183b915e9e0SDimitry Andric
assignValue(Metadata * MD,unsigned Idx)184b915e9e0SDimitry Andric void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
185b915e9e0SDimitry Andric if (auto *MDN = dyn_cast<MDNode>(MD))
186b915e9e0SDimitry Andric if (!MDN->isResolved())
187b915e9e0SDimitry Andric UnresolvedNodes.insert(Idx);
188b915e9e0SDimitry Andric
189b915e9e0SDimitry Andric if (Idx == size()) {
190b915e9e0SDimitry Andric push_back(MD);
191b915e9e0SDimitry Andric return;
192b915e9e0SDimitry Andric }
193b915e9e0SDimitry Andric
194b915e9e0SDimitry Andric if (Idx >= size())
195b915e9e0SDimitry Andric resize(Idx + 1);
196b915e9e0SDimitry Andric
197b915e9e0SDimitry Andric TrackingMDRef &OldMD = MetadataPtrs[Idx];
198b915e9e0SDimitry Andric if (!OldMD) {
199b915e9e0SDimitry Andric OldMD.reset(MD);
200b915e9e0SDimitry Andric return;
201b915e9e0SDimitry Andric }
202b915e9e0SDimitry Andric
203b915e9e0SDimitry Andric // If there was a forward reference to this value, replace it.
204b915e9e0SDimitry Andric TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
205b915e9e0SDimitry Andric PrevMD->replaceAllUsesWith(MD);
206b915e9e0SDimitry Andric ForwardReference.erase(Idx);
207b915e9e0SDimitry Andric }
208b915e9e0SDimitry Andric
getMetadataFwdRef(unsigned Idx)209b915e9e0SDimitry Andric Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
210e6d15924SDimitry Andric // Bail out for a clearly invalid value.
211e6d15924SDimitry Andric if (Idx >= RefsUpperBound)
212e6d15924SDimitry Andric return nullptr;
213e6d15924SDimitry Andric
214b915e9e0SDimitry Andric if (Idx >= size())
215b915e9e0SDimitry Andric resize(Idx + 1);
216b915e9e0SDimitry Andric
217b915e9e0SDimitry Andric if (Metadata *MD = MetadataPtrs[Idx])
218b915e9e0SDimitry Andric return MD;
219b915e9e0SDimitry Andric
220b915e9e0SDimitry Andric // Track forward refs to be resolved later.
221b915e9e0SDimitry Andric ForwardReference.insert(Idx);
222b915e9e0SDimitry Andric
223b915e9e0SDimitry Andric // Create and return a placeholder, which will later be RAUW'd.
2247e7b6700SDimitry Andric ++NumMDNodeTemporary;
225e3b55780SDimitry Andric Metadata *MD = MDNode::getTemporary(Context, std::nullopt).release();
226b915e9e0SDimitry Andric MetadataPtrs[Idx].reset(MD);
227b915e9e0SDimitry Andric return MD;
228b915e9e0SDimitry Andric }
229b915e9e0SDimitry Andric
getMetadataIfResolved(unsigned Idx)230b915e9e0SDimitry Andric Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
231b915e9e0SDimitry Andric Metadata *MD = lookup(Idx);
232b915e9e0SDimitry Andric if (auto *N = dyn_cast_or_null<MDNode>(MD))
233b915e9e0SDimitry Andric if (!N->isResolved())
234b915e9e0SDimitry Andric return nullptr;
235b915e9e0SDimitry Andric return MD;
236b915e9e0SDimitry Andric }
237b915e9e0SDimitry Andric
getMDNodeFwdRefOrNull(unsigned Idx)238b915e9e0SDimitry Andric MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
239b915e9e0SDimitry Andric return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
240b915e9e0SDimitry Andric }
241b915e9e0SDimitry Andric
tryToResolveCycles()242b915e9e0SDimitry Andric void BitcodeReaderMetadataList::tryToResolveCycles() {
243b915e9e0SDimitry Andric if (!ForwardReference.empty())
244b915e9e0SDimitry Andric // Still forward references... can't resolve cycles.
245b915e9e0SDimitry Andric return;
246b915e9e0SDimitry Andric
247b915e9e0SDimitry Andric // Give up on finding a full definition for any forward decls that remain.
248b915e9e0SDimitry Andric for (const auto &Ref : OldTypeRefs.FwdDecls)
249b915e9e0SDimitry Andric OldTypeRefs.Final.insert(Ref);
250b915e9e0SDimitry Andric OldTypeRefs.FwdDecls.clear();
251b915e9e0SDimitry Andric
252b915e9e0SDimitry Andric // Upgrade from old type ref arrays. In strange cases, this could add to
253b915e9e0SDimitry Andric // OldTypeRefs.Unknown.
254b915e9e0SDimitry Andric for (const auto &Array : OldTypeRefs.Arrays)
255b915e9e0SDimitry Andric Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
256b915e9e0SDimitry Andric OldTypeRefs.Arrays.clear();
257b915e9e0SDimitry Andric
258b915e9e0SDimitry Andric // Replace old string-based type refs with the resolved node, if possible.
259b915e9e0SDimitry Andric // If we haven't seen the node, leave it to the verifier to complain about
260b915e9e0SDimitry Andric // the invalid string reference.
261b915e9e0SDimitry Andric for (const auto &Ref : OldTypeRefs.Unknown) {
262b915e9e0SDimitry Andric if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
263b915e9e0SDimitry Andric Ref.second->replaceAllUsesWith(CT);
264b915e9e0SDimitry Andric else
265b915e9e0SDimitry Andric Ref.second->replaceAllUsesWith(Ref.first);
266b915e9e0SDimitry Andric }
267b915e9e0SDimitry Andric OldTypeRefs.Unknown.clear();
268b915e9e0SDimitry Andric
269b915e9e0SDimitry Andric if (UnresolvedNodes.empty())
270b915e9e0SDimitry Andric // Nothing to do.
271b915e9e0SDimitry Andric return;
272b915e9e0SDimitry Andric
273b915e9e0SDimitry Andric // Resolve any cycles.
274b915e9e0SDimitry Andric for (unsigned I : UnresolvedNodes) {
275b915e9e0SDimitry Andric auto &MD = MetadataPtrs[I];
276b915e9e0SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD);
277b915e9e0SDimitry Andric if (!N)
278b915e9e0SDimitry Andric continue;
279b915e9e0SDimitry Andric
280b915e9e0SDimitry Andric assert(!N->isTemporary() && "Unexpected forward reference");
281b915e9e0SDimitry Andric N->resolveCycles();
282b915e9e0SDimitry Andric }
283b915e9e0SDimitry Andric
284b915e9e0SDimitry Andric // Make sure we return early again until there's another unresolved ref.
285b915e9e0SDimitry Andric UnresolvedNodes.clear();
286b915e9e0SDimitry Andric }
287b915e9e0SDimitry Andric
addTypeRef(MDString & UUID,DICompositeType & CT)288b915e9e0SDimitry Andric void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
289b915e9e0SDimitry Andric DICompositeType &CT) {
290b915e9e0SDimitry Andric assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
291b915e9e0SDimitry Andric if (CT.isForwardDecl())
292b915e9e0SDimitry Andric OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
293b915e9e0SDimitry Andric else
294b915e9e0SDimitry Andric OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
295b915e9e0SDimitry Andric }
296b915e9e0SDimitry Andric
upgradeTypeRef(Metadata * MaybeUUID)297b915e9e0SDimitry Andric Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
298b915e9e0SDimitry Andric auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
299b915e9e0SDimitry Andric if (LLVM_LIKELY(!UUID))
300b915e9e0SDimitry Andric return MaybeUUID;
301b915e9e0SDimitry Andric
302b915e9e0SDimitry Andric if (auto *CT = OldTypeRefs.Final.lookup(UUID))
303b915e9e0SDimitry Andric return CT;
304b915e9e0SDimitry Andric
305b915e9e0SDimitry Andric auto &Ref = OldTypeRefs.Unknown[UUID];
306b915e9e0SDimitry Andric if (!Ref)
307e3b55780SDimitry Andric Ref = MDNode::getTemporary(Context, std::nullopt);
308b915e9e0SDimitry Andric return Ref.get();
309b915e9e0SDimitry Andric }
310b915e9e0SDimitry Andric
upgradeTypeRefArray(Metadata * MaybeTuple)311b915e9e0SDimitry Andric Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
312b915e9e0SDimitry Andric auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
313b915e9e0SDimitry Andric if (!Tuple || Tuple->isDistinct())
314b915e9e0SDimitry Andric return MaybeTuple;
315b915e9e0SDimitry Andric
316b915e9e0SDimitry Andric // Look through the array immediately if possible.
317b915e9e0SDimitry Andric if (!Tuple->isTemporary())
318b915e9e0SDimitry Andric return resolveTypeRefArray(Tuple);
319b915e9e0SDimitry Andric
320b915e9e0SDimitry Andric // Create and return a placeholder to use for now. Eventually
321b915e9e0SDimitry Andric // resolveTypeRefArrays() will be resolve this forward reference.
322b915e9e0SDimitry Andric OldTypeRefs.Arrays.emplace_back(
323b915e9e0SDimitry Andric std::piecewise_construct, std::forward_as_tuple(Tuple),
324e3b55780SDimitry Andric std::forward_as_tuple(MDTuple::getTemporary(Context, std::nullopt)));
325b915e9e0SDimitry Andric return OldTypeRefs.Arrays.back().second.get();
326b915e9e0SDimitry Andric }
327b915e9e0SDimitry Andric
resolveTypeRefArray(Metadata * MaybeTuple)328b915e9e0SDimitry Andric Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
329b915e9e0SDimitry Andric auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
330b915e9e0SDimitry Andric if (!Tuple || Tuple->isDistinct())
331b915e9e0SDimitry Andric return MaybeTuple;
332b915e9e0SDimitry Andric
333e6d15924SDimitry Andric // Look through the DITypeRefArray, upgrading each DIType *.
334b915e9e0SDimitry Andric SmallVector<Metadata *, 32> Ops;
335b915e9e0SDimitry Andric Ops.reserve(Tuple->getNumOperands());
336b915e9e0SDimitry Andric for (Metadata *MD : Tuple->operands())
337b915e9e0SDimitry Andric Ops.push_back(upgradeTypeRef(MD));
338b915e9e0SDimitry Andric
339b915e9e0SDimitry Andric return MDTuple::get(Context, Ops);
340b915e9e0SDimitry Andric }
341b915e9e0SDimitry Andric
342b915e9e0SDimitry Andric namespace {
343b915e9e0SDimitry Andric
344b915e9e0SDimitry Andric class PlaceholderQueue {
345b915e9e0SDimitry Andric // Placeholders would thrash around when moved, so store in a std::deque
346b915e9e0SDimitry Andric // instead of some sort of vector.
347b915e9e0SDimitry Andric std::deque<DistinctMDOperandPlaceholder> PHs;
348b915e9e0SDimitry Andric
349b915e9e0SDimitry Andric public:
~PlaceholderQueue()35071d5a254SDimitry Andric ~PlaceholderQueue() {
351c0981da4SDimitry Andric assert(empty() &&
352c0981da4SDimitry Andric "PlaceholderQueue hasn't been flushed before being destroyed");
35371d5a254SDimitry Andric }
empty() const354b60736ecSDimitry Andric bool empty() const { return PHs.empty(); }
355b915e9e0SDimitry Andric DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
356b915e9e0SDimitry Andric void flush(BitcodeReaderMetadataList &MetadataList);
3577e7b6700SDimitry Andric
3587e7b6700SDimitry Andric /// Return the list of temporaries nodes in the queue, these need to be
3597e7b6700SDimitry Andric /// loaded before we can flush the queue.
getTemporaries(BitcodeReaderMetadataList & MetadataList,DenseSet<unsigned> & Temporaries)3607e7b6700SDimitry Andric void getTemporaries(BitcodeReaderMetadataList &MetadataList,
3617e7b6700SDimitry Andric DenseSet<unsigned> &Temporaries) {
3627e7b6700SDimitry Andric for (auto &PH : PHs) {
3637e7b6700SDimitry Andric auto ID = PH.getID();
3647e7b6700SDimitry Andric auto *MD = MetadataList.lookup(ID);
3657e7b6700SDimitry Andric if (!MD) {
3667e7b6700SDimitry Andric Temporaries.insert(ID);
3677e7b6700SDimitry Andric continue;
3687e7b6700SDimitry Andric }
3697e7b6700SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD);
3707e7b6700SDimitry Andric if (N && N->isTemporary())
3717e7b6700SDimitry Andric Temporaries.insert(ID);
3727e7b6700SDimitry Andric }
3737e7b6700SDimitry Andric }
374b915e9e0SDimitry Andric };
375b915e9e0SDimitry Andric
376b915e9e0SDimitry Andric } // end anonymous namespace
377b915e9e0SDimitry Andric
getPlaceholderOp(unsigned ID)378b915e9e0SDimitry Andric DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
379b915e9e0SDimitry Andric PHs.emplace_back(ID);
380b915e9e0SDimitry Andric return PHs.back();
381b915e9e0SDimitry Andric }
382b915e9e0SDimitry Andric
flush(BitcodeReaderMetadataList & MetadataList)383b915e9e0SDimitry Andric void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
384b915e9e0SDimitry Andric while (!PHs.empty()) {
385b915e9e0SDimitry Andric auto *MD = MetadataList.lookup(PHs.front().getID());
386b915e9e0SDimitry Andric assert(MD && "Flushing placeholder on unassigned MD");
387b915e9e0SDimitry Andric #ifndef NDEBUG
388b915e9e0SDimitry Andric if (auto *MDN = dyn_cast<MDNode>(MD))
389b915e9e0SDimitry Andric assert(MDN->isResolved() &&
390b915e9e0SDimitry Andric "Flushing Placeholder while cycles aren't resolved");
391b915e9e0SDimitry Andric #endif
392b915e9e0SDimitry Andric PHs.front().replaceUseWith(MD);
393b915e9e0SDimitry Andric PHs.pop_front();
394b915e9e0SDimitry Andric }
395b915e9e0SDimitry Andric }
396b915e9e0SDimitry Andric
397706b4fc4SDimitry Andric } // anonymous namespace
398b915e9e0SDimitry Andric
error(const Twine & Message)3997c7aba6eSDimitry Andric static Error error(const Twine &Message) {
4007c7aba6eSDimitry Andric return make_error<StringError>(
4017c7aba6eSDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode));
4027c7aba6eSDimitry Andric }
4037c7aba6eSDimitry Andric
404b915e9e0SDimitry Andric class MetadataLoader::MetadataLoaderImpl {
405b915e9e0SDimitry Andric BitcodeReaderMetadataList MetadataList;
406b915e9e0SDimitry Andric BitcodeReaderValueList &ValueList;
407b915e9e0SDimitry Andric BitstreamCursor &Stream;
408b915e9e0SDimitry Andric LLVMContext &Context;
409b915e9e0SDimitry Andric Module &TheModule;
410e3b55780SDimitry Andric MetadataLoaderCallbacks Callbacks;
411b915e9e0SDimitry Andric
4127e7b6700SDimitry Andric /// Cursor associated with the lazy-loading of Metadata. This is the easy way
4137e7b6700SDimitry Andric /// to keep around the right "context" (Abbrev list) to be able to jump in
4147e7b6700SDimitry Andric /// the middle of the metadata block and load any record.
4157e7b6700SDimitry Andric BitstreamCursor IndexCursor;
4167e7b6700SDimitry Andric
4177e7b6700SDimitry Andric /// Index that keeps track of MDString values.
4187e7b6700SDimitry Andric std::vector<StringRef> MDStringRef;
4197e7b6700SDimitry Andric
4207e7b6700SDimitry Andric /// On-demand loading of a single MDString. Requires the index above to be
4217e7b6700SDimitry Andric /// populated.
4227e7b6700SDimitry Andric MDString *lazyLoadOneMDString(unsigned Idx);
4237e7b6700SDimitry Andric
4247e7b6700SDimitry Andric /// Index that keeps track of where to find a metadata record in the stream.
4257e7b6700SDimitry Andric std::vector<uint64_t> GlobalMetadataBitPosIndex;
4267e7b6700SDimitry Andric
427b60736ecSDimitry Andric /// Cursor position of the start of the global decl attachments, to enable
428b60736ecSDimitry Andric /// loading using the index built for lazy loading, instead of forward
429b60736ecSDimitry Andric /// references.
430b60736ecSDimitry Andric uint64_t GlobalDeclAttachmentPos = 0;
431b60736ecSDimitry Andric
432b60736ecSDimitry Andric #ifndef NDEBUG
433f65dcba8SDimitry Andric /// Baisic correctness check that we end up parsing all of the global decl
434f65dcba8SDimitry Andric /// attachments.
435b60736ecSDimitry Andric unsigned NumGlobalDeclAttachSkipped = 0;
436b60736ecSDimitry Andric unsigned NumGlobalDeclAttachParsed = 0;
437b60736ecSDimitry Andric #endif
438b60736ecSDimitry Andric
439b60736ecSDimitry Andric /// Load the global decl attachments, using the index built for lazy loading.
440b60736ecSDimitry Andric Expected<bool> loadGlobalDeclAttachments();
441b60736ecSDimitry Andric
4427e7b6700SDimitry Andric /// Populate the index above to enable lazily loading of metadata, and load
4437e7b6700SDimitry Andric /// the named metadata as well as the transitively referenced global
4447e7b6700SDimitry Andric /// Metadata.
445909545a8SDimitry Andric Expected<bool> lazyLoadModuleMetadataBlock();
4467e7b6700SDimitry Andric
4477e7b6700SDimitry Andric /// On-demand loading of a single metadata. Requires the index above to be
4487e7b6700SDimitry Andric /// populated.
4497e7b6700SDimitry Andric void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
4507e7b6700SDimitry Andric
451b915e9e0SDimitry Andric // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
452b915e9e0SDimitry Andric // point from SP to CU after a block is completly parsed.
453b915e9e0SDimitry Andric std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
454b915e9e0SDimitry Andric
455b915e9e0SDimitry Andric /// Functions that need to be matched with subprograms when upgrading old
456b915e9e0SDimitry Andric /// metadata.
457b915e9e0SDimitry Andric SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
458b915e9e0SDimitry Andric
459b915e9e0SDimitry Andric // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
460b915e9e0SDimitry Andric DenseMap<unsigned, unsigned> MDKindMap;
461b915e9e0SDimitry Andric
462b915e9e0SDimitry Andric bool StripTBAA = false;
463b915e9e0SDimitry Andric bool HasSeenOldLoopTags = false;
4643897d3b8SDimitry Andric bool NeedUpgradeToDIGlobalVariableExpression = false;
465d99dafe2SDimitry Andric bool NeedDeclareExpressionUpgrade = false;
466b915e9e0SDimitry Andric
4677fa27ce4SDimitry Andric /// Map DILocalScope to the enclosing DISubprogram, if any.
4687fa27ce4SDimitry Andric DenseMap<DILocalScope *, DISubprogram *> ParentSubprogram;
4697fa27ce4SDimitry Andric
470b915e9e0SDimitry Andric /// True if metadata is being parsed for a module being ThinLTO imported.
471b915e9e0SDimitry Andric bool IsImporting = false;
472b915e9e0SDimitry Andric
473b915e9e0SDimitry Andric Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
474b915e9e0SDimitry Andric PlaceholderQueue &Placeholders, StringRef Blob,
475b915e9e0SDimitry Andric unsigned &NextMetadataNo);
4767e7b6700SDimitry Andric Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
47771d5a254SDimitry Andric function_ref<void(StringRef)> CallBack);
478b915e9e0SDimitry Andric Error parseGlobalObjectAttachment(GlobalObject &GO,
479b915e9e0SDimitry Andric ArrayRef<uint64_t> Record);
480b915e9e0SDimitry Andric Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
481b915e9e0SDimitry Andric
4827e7b6700SDimitry Andric void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
4837e7b6700SDimitry Andric
4847e7b6700SDimitry Andric /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
upgradeCUSubprograms()4857e7b6700SDimitry Andric void upgradeCUSubprograms() {
4867e7b6700SDimitry Andric for (auto CU_SP : CUSubprograms)
4877e7b6700SDimitry Andric if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
4887e7b6700SDimitry Andric for (auto &Op : SPs->operands())
489a303c417SDimitry Andric if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
490a303c417SDimitry Andric SP->replaceUnit(CU_SP.first);
4917e7b6700SDimitry Andric CUSubprograms.clear();
4927e7b6700SDimitry Andric }
4937e7b6700SDimitry Andric
4943897d3b8SDimitry Andric /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
upgradeCUVariables()4953897d3b8SDimitry Andric void upgradeCUVariables() {
4963897d3b8SDimitry Andric if (!NeedUpgradeToDIGlobalVariableExpression)
4973897d3b8SDimitry Andric return;
4983897d3b8SDimitry Andric
4993897d3b8SDimitry Andric // Upgrade list of variables attached to the CUs.
5003897d3b8SDimitry Andric if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
5013897d3b8SDimitry Andric for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
5023897d3b8SDimitry Andric auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
5033897d3b8SDimitry Andric if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
5043897d3b8SDimitry Andric for (unsigned I = 0; I < GVs->getNumOperands(); I++)
5053897d3b8SDimitry Andric if (auto *GV =
5063897d3b8SDimitry Andric dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
507044eb2f6SDimitry Andric auto *DGVE = DIGlobalVariableExpression::getDistinct(
508044eb2f6SDimitry Andric Context, GV, DIExpression::get(Context, {}));
5093897d3b8SDimitry Andric GVs->replaceOperandWith(I, DGVE);
5103897d3b8SDimitry Andric }
5113897d3b8SDimitry Andric }
5123897d3b8SDimitry Andric
5133897d3b8SDimitry Andric // Upgrade variables attached to globals.
5143897d3b8SDimitry Andric for (auto &GV : TheModule.globals()) {
5156b3f41edSDimitry Andric SmallVector<MDNode *, 1> MDs;
5163897d3b8SDimitry Andric GV.getMetadata(LLVMContext::MD_dbg, MDs);
5173897d3b8SDimitry Andric GV.eraseMetadata(LLVMContext::MD_dbg);
5183897d3b8SDimitry Andric for (auto *MD : MDs)
5191d5ae102SDimitry Andric if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
520044eb2f6SDimitry Andric auto *DGVE = DIGlobalVariableExpression::getDistinct(
521044eb2f6SDimitry Andric Context, DGV, DIExpression::get(Context, {}));
5223897d3b8SDimitry Andric GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
5233897d3b8SDimitry Andric } else
5243897d3b8SDimitry Andric GV.addMetadata(LLVMContext::MD_dbg, *MD);
5253897d3b8SDimitry Andric }
5263897d3b8SDimitry Andric }
5273897d3b8SDimitry Andric
findEnclosingSubprogram(DILocalScope * S)5287fa27ce4SDimitry Andric DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
5297fa27ce4SDimitry Andric if (!S)
5307fa27ce4SDimitry Andric return nullptr;
5317fa27ce4SDimitry Andric if (auto *SP = ParentSubprogram[S]) {
5327fa27ce4SDimitry Andric return SP;
5337fa27ce4SDimitry Andric }
5347fa27ce4SDimitry Andric
5357fa27ce4SDimitry Andric DILocalScope *InitialScope = S;
5367fa27ce4SDimitry Andric DenseSet<DILocalScope *> Visited;
5377fa27ce4SDimitry Andric while (S && !isa<DISubprogram>(S)) {
5387fa27ce4SDimitry Andric S = dyn_cast_or_null<DILocalScope>(S->getScope());
5397fa27ce4SDimitry Andric if (Visited.contains(S))
5407fa27ce4SDimitry Andric break;
5417fa27ce4SDimitry Andric Visited.insert(S);
5427fa27ce4SDimitry Andric }
5437fa27ce4SDimitry Andric ParentSubprogram[InitialScope] = llvm::dyn_cast_or_null<DISubprogram>(S);
5447fa27ce4SDimitry Andric
5457fa27ce4SDimitry Andric return ParentSubprogram[InitialScope];
5467fa27ce4SDimitry Andric }
5477fa27ce4SDimitry Andric
5487fa27ce4SDimitry Andric /// Move local imports from DICompileUnit's 'imports' field to
5497fa27ce4SDimitry Andric /// DISubprogram's retainedNodes.
upgradeCULocals()5507fa27ce4SDimitry Andric void upgradeCULocals() {
5517fa27ce4SDimitry Andric if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu")) {
552ac9a064cSDimitry Andric for (MDNode *N : CUNodes->operands()) {
553ac9a064cSDimitry Andric auto *CU = dyn_cast<DICompileUnit>(N);
5547fa27ce4SDimitry Andric if (!CU)
5557fa27ce4SDimitry Andric continue;
5567fa27ce4SDimitry Andric
557b1c73532SDimitry Andric if (CU->getRawImportedEntities()) {
5587fa27ce4SDimitry Andric // Collect a set of imported entities to be moved.
5597fa27ce4SDimitry Andric SetVector<Metadata *> EntitiesToRemove;
5607fa27ce4SDimitry Andric for (Metadata *Op : CU->getImportedEntities()->operands()) {
5617fa27ce4SDimitry Andric auto *IE = cast<DIImportedEntity>(Op);
562b1c73532SDimitry Andric if (dyn_cast_or_null<DILocalScope>(IE->getScope())) {
5637fa27ce4SDimitry Andric EntitiesToRemove.insert(IE);
5647fa27ce4SDimitry Andric }
5657fa27ce4SDimitry Andric }
5667fa27ce4SDimitry Andric
5677fa27ce4SDimitry Andric if (!EntitiesToRemove.empty()) {
5687fa27ce4SDimitry Andric // Make a new list of CU's 'imports'.
5697fa27ce4SDimitry Andric SmallVector<Metadata *> NewImports;
5707fa27ce4SDimitry Andric for (Metadata *Op : CU->getImportedEntities()->operands()) {
5717fa27ce4SDimitry Andric if (!EntitiesToRemove.contains(cast<DIImportedEntity>(Op))) {
5727fa27ce4SDimitry Andric NewImports.push_back(Op);
5737fa27ce4SDimitry Andric }
5747fa27ce4SDimitry Andric }
5757fa27ce4SDimitry Andric
5767fa27ce4SDimitry Andric // Find DISubprogram corresponding to each entity.
5777fa27ce4SDimitry Andric std::map<DISubprogram *, SmallVector<Metadata *>> SPToEntities;
5787fa27ce4SDimitry Andric for (auto *I : EntitiesToRemove) {
5797fa27ce4SDimitry Andric auto *Entity = cast<DIImportedEntity>(I);
5807fa27ce4SDimitry Andric if (auto *SP = findEnclosingSubprogram(
5817fa27ce4SDimitry Andric cast<DILocalScope>(Entity->getScope()))) {
5827fa27ce4SDimitry Andric SPToEntities[SP].push_back(Entity);
5837fa27ce4SDimitry Andric }
5847fa27ce4SDimitry Andric }
5857fa27ce4SDimitry Andric
5867fa27ce4SDimitry Andric // Update DISubprograms' retainedNodes.
5877fa27ce4SDimitry Andric for (auto I = SPToEntities.begin(); I != SPToEntities.end(); ++I) {
5887fa27ce4SDimitry Andric auto *SP = I->first;
5897fa27ce4SDimitry Andric auto RetainedNodes = SP->getRetainedNodes();
5907fa27ce4SDimitry Andric SmallVector<Metadata *> MDs(RetainedNodes.begin(),
5917fa27ce4SDimitry Andric RetainedNodes.end());
5927fa27ce4SDimitry Andric MDs.append(I->second);
5937fa27ce4SDimitry Andric SP->replaceRetainedNodes(MDNode::get(Context, MDs));
5947fa27ce4SDimitry Andric }
5957fa27ce4SDimitry Andric
5967fa27ce4SDimitry Andric // Remove entities with local scope from CU.
5977fa27ce4SDimitry Andric CU->replaceImportedEntities(MDTuple::get(Context, NewImports));
5987fa27ce4SDimitry Andric }
5997fa27ce4SDimitry Andric }
6007fa27ce4SDimitry Andric }
6017fa27ce4SDimitry Andric }
6027fa27ce4SDimitry Andric
6037fa27ce4SDimitry Andric ParentSubprogram.clear();
6047fa27ce4SDimitry Andric }
6057fa27ce4SDimitry Andric
606d99dafe2SDimitry Andric /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
607d99dafe2SDimitry Andric /// describes a function argument.
upgradeDeclareExpressions(Function & F)608d99dafe2SDimitry Andric void upgradeDeclareExpressions(Function &F) {
609d99dafe2SDimitry Andric if (!NeedDeclareExpressionUpgrade)
610d99dafe2SDimitry Andric return;
611d99dafe2SDimitry Andric
612ac9a064cSDimitry Andric auto UpdateDeclareIfNeeded = [&](auto *Declare) {
613ac9a064cSDimitry Andric auto *DIExpr = Declare->getExpression();
614ac9a064cSDimitry Andric if (!DIExpr || !DIExpr->startsWithDeref() ||
615ac9a064cSDimitry Andric !isa_and_nonnull<Argument>(Declare->getAddress()))
616ac9a064cSDimitry Andric return;
617d99dafe2SDimitry Andric SmallVector<uint64_t, 8> Ops;
618ac9a064cSDimitry Andric Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
619ac9a064cSDimitry Andric Declare->setExpression(DIExpression::get(Context, Ops));
620ac9a064cSDimitry Andric };
621ac9a064cSDimitry Andric
622ac9a064cSDimitry Andric for (auto &BB : F)
623ac9a064cSDimitry Andric for (auto &I : BB) {
624ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
625ac9a064cSDimitry Andric if (DVR.isDbgDeclare())
626ac9a064cSDimitry Andric UpdateDeclareIfNeeded(&DVR);
627ac9a064cSDimitry Andric }
628ac9a064cSDimitry Andric if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
629ac9a064cSDimitry Andric UpdateDeclareIfNeeded(DDI);
630d99dafe2SDimitry Andric }
631d99dafe2SDimitry Andric }
632d99dafe2SDimitry Andric
6337c7aba6eSDimitry Andric /// Upgrade the expression from previous versions.
upgradeDIExpression(uint64_t FromVersion,MutableArrayRef<uint64_t> & Expr,SmallVectorImpl<uint64_t> & Buffer)6347c7aba6eSDimitry Andric Error upgradeDIExpression(uint64_t FromVersion,
6357c7aba6eSDimitry Andric MutableArrayRef<uint64_t> &Expr,
6367c7aba6eSDimitry Andric SmallVectorImpl<uint64_t> &Buffer) {
6377c7aba6eSDimitry Andric auto N = Expr.size();
6387c7aba6eSDimitry Andric switch (FromVersion) {
6397c7aba6eSDimitry Andric default:
6407c7aba6eSDimitry Andric return error("Invalid record");
6417c7aba6eSDimitry Andric case 0:
6427c7aba6eSDimitry Andric if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
6437c7aba6eSDimitry Andric Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
644e3b55780SDimitry Andric [[fallthrough]];
6457c7aba6eSDimitry Andric case 1:
6467c7aba6eSDimitry Andric // Move DW_OP_deref to the end.
6477c7aba6eSDimitry Andric if (N && Expr[0] == dwarf::DW_OP_deref) {
6487c7aba6eSDimitry Andric auto End = Expr.end();
6497c7aba6eSDimitry Andric if (Expr.size() >= 3 &&
6507c7aba6eSDimitry Andric *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
6517c7aba6eSDimitry Andric End = std::prev(End, 3);
6527c7aba6eSDimitry Andric std::move(std::next(Expr.begin()), End, Expr.begin());
6537c7aba6eSDimitry Andric *std::prev(End) = dwarf::DW_OP_deref;
6547c7aba6eSDimitry Andric }
6557c7aba6eSDimitry Andric NeedDeclareExpressionUpgrade = true;
656e3b55780SDimitry Andric [[fallthrough]];
6577c7aba6eSDimitry Andric case 2: {
6587c7aba6eSDimitry Andric // Change DW_OP_plus to DW_OP_plus_uconst.
6597c7aba6eSDimitry Andric // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
6607c7aba6eSDimitry Andric auto SubExpr = ArrayRef<uint64_t>(Expr);
6617c7aba6eSDimitry Andric while (!SubExpr.empty()) {
6627c7aba6eSDimitry Andric // Skip past other operators with their operands
6637c7aba6eSDimitry Andric // for this version of the IR, obtained from
6647c7aba6eSDimitry Andric // from historic DIExpression::ExprOperand::getSize().
6657c7aba6eSDimitry Andric size_t HistoricSize;
6667c7aba6eSDimitry Andric switch (SubExpr.front()) {
6677c7aba6eSDimitry Andric default:
6687c7aba6eSDimitry Andric HistoricSize = 1;
6697c7aba6eSDimitry Andric break;
6707c7aba6eSDimitry Andric case dwarf::DW_OP_constu:
6717c7aba6eSDimitry Andric case dwarf::DW_OP_minus:
6727c7aba6eSDimitry Andric case dwarf::DW_OP_plus:
6737c7aba6eSDimitry Andric HistoricSize = 2;
6747c7aba6eSDimitry Andric break;
6757c7aba6eSDimitry Andric case dwarf::DW_OP_LLVM_fragment:
6767c7aba6eSDimitry Andric HistoricSize = 3;
6777c7aba6eSDimitry Andric break;
6787c7aba6eSDimitry Andric }
6797c7aba6eSDimitry Andric
6807c7aba6eSDimitry Andric // If the expression is malformed, make sure we don't
6817c7aba6eSDimitry Andric // copy more elements than we should.
6827c7aba6eSDimitry Andric HistoricSize = std::min(SubExpr.size(), HistoricSize);
6837c7aba6eSDimitry Andric ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
6847c7aba6eSDimitry Andric
6857c7aba6eSDimitry Andric switch (SubExpr.front()) {
6867c7aba6eSDimitry Andric case dwarf::DW_OP_plus:
6877c7aba6eSDimitry Andric Buffer.push_back(dwarf::DW_OP_plus_uconst);
6887c7aba6eSDimitry Andric Buffer.append(Args.begin(), Args.end());
6897c7aba6eSDimitry Andric break;
6907c7aba6eSDimitry Andric case dwarf::DW_OP_minus:
6917c7aba6eSDimitry Andric Buffer.push_back(dwarf::DW_OP_constu);
6927c7aba6eSDimitry Andric Buffer.append(Args.begin(), Args.end());
6937c7aba6eSDimitry Andric Buffer.push_back(dwarf::DW_OP_minus);
6947c7aba6eSDimitry Andric break;
6957c7aba6eSDimitry Andric default:
6967c7aba6eSDimitry Andric Buffer.push_back(*SubExpr.begin());
6977c7aba6eSDimitry Andric Buffer.append(Args.begin(), Args.end());
6987c7aba6eSDimitry Andric break;
6997c7aba6eSDimitry Andric }
7007c7aba6eSDimitry Andric
7017c7aba6eSDimitry Andric // Continue with remaining elements.
7027c7aba6eSDimitry Andric SubExpr = SubExpr.slice(HistoricSize);
7037c7aba6eSDimitry Andric }
7047c7aba6eSDimitry Andric Expr = MutableArrayRef<uint64_t>(Buffer);
705e3b55780SDimitry Andric [[fallthrough]];
7067c7aba6eSDimitry Andric }
7077c7aba6eSDimitry Andric case 3:
7087c7aba6eSDimitry Andric // Up-to-date!
7097c7aba6eSDimitry Andric break;
7107c7aba6eSDimitry Andric }
7117c7aba6eSDimitry Andric
7127c7aba6eSDimitry Andric return Error::success();
7137c7aba6eSDimitry Andric }
7147c7aba6eSDimitry Andric
upgradeDebugInfo(bool ModuleLevel)715b1c73532SDimitry Andric void upgradeDebugInfo(bool ModuleLevel) {
7163897d3b8SDimitry Andric upgradeCUSubprograms();
7173897d3b8SDimitry Andric upgradeCUVariables();
718b1c73532SDimitry Andric if (ModuleLevel)
7197fa27ce4SDimitry Andric upgradeCULocals();
7203897d3b8SDimitry Andric }
7213897d3b8SDimitry Andric
722e3b55780SDimitry Andric void callMDTypeCallback(Metadata **Val, unsigned TypeID);
723e3b55780SDimitry Andric
724b915e9e0SDimitry Andric public:
MetadataLoaderImpl(BitstreamCursor & Stream,Module & TheModule,BitcodeReaderValueList & ValueList,MetadataLoaderCallbacks Callbacks,bool IsImporting)725b915e9e0SDimitry Andric MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
726b915e9e0SDimitry Andric BitcodeReaderValueList &ValueList,
727e3b55780SDimitry Andric MetadataLoaderCallbacks Callbacks, bool IsImporting)
728e6d15924SDimitry Andric : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
729e6d15924SDimitry Andric ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
730e3b55780SDimitry Andric TheModule(TheModule), Callbacks(std::move(Callbacks)),
731e6d15924SDimitry Andric IsImporting(IsImporting) {}
732b915e9e0SDimitry Andric
733b915e9e0SDimitry Andric Error parseMetadata(bool ModuleLevel);
734b915e9e0SDimitry Andric
hasFwdRefs() const735b915e9e0SDimitry Andric bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
73602a33680SDimitry Andric
getMetadataFwdRefOrLoad(unsigned ID)73702a33680SDimitry Andric Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
73802a33680SDimitry Andric if (ID < MDStringRef.size())
73902a33680SDimitry Andric return lazyLoadOneMDString(ID);
74002a33680SDimitry Andric if (auto *MD = MetadataList.lookup(ID))
74102a33680SDimitry Andric return MD;
74202a33680SDimitry Andric // If lazy-loading is enabled, we try recursively to load the operand
74302a33680SDimitry Andric // instead of creating a temporary.
74402a33680SDimitry Andric if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
74502a33680SDimitry Andric PlaceholderQueue Placeholders;
74602a33680SDimitry Andric lazyLoadOneMetadata(ID, Placeholders);
74702a33680SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
74802a33680SDimitry Andric return MetadataList.lookup(ID);
74902a33680SDimitry Andric }
75002a33680SDimitry Andric return MetadataList.getMetadataFwdRef(ID);
751b915e9e0SDimitry Andric }
752b915e9e0SDimitry Andric
lookupSubprogramForFunction(Function * F)753b915e9e0SDimitry Andric DISubprogram *lookupSubprogramForFunction(Function *F) {
754b915e9e0SDimitry Andric return FunctionsWithSPs.lookup(F);
755b915e9e0SDimitry Andric }
756b915e9e0SDimitry Andric
hasSeenOldLoopTags() const757b60736ecSDimitry Andric bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
758b915e9e0SDimitry Andric
759145449b1SDimitry Andric Error parseMetadataAttachment(Function &F,
760145449b1SDimitry Andric ArrayRef<Instruction *> InstructionList);
761b915e9e0SDimitry Andric
762b915e9e0SDimitry Andric Error parseMetadataKinds();
763b915e9e0SDimitry Andric
setStripTBAA(bool Value)764b915e9e0SDimitry Andric void setStripTBAA(bool Value) { StripTBAA = Value; }
isStrippingTBAA() const765b60736ecSDimitry Andric bool isStrippingTBAA() const { return StripTBAA; }
766b915e9e0SDimitry Andric
size() const767b915e9e0SDimitry Andric unsigned size() const { return MetadataList.size(); }
shrinkTo(unsigned N)768b915e9e0SDimitry Andric void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
upgradeDebugIntrinsics(Function & F)769d99dafe2SDimitry Andric void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
770b915e9e0SDimitry Andric };
771b915e9e0SDimitry Andric
772909545a8SDimitry Andric Expected<bool>
lazyLoadModuleMetadataBlock()773909545a8SDimitry Andric MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
7747e7b6700SDimitry Andric IndexCursor = Stream;
7757e7b6700SDimitry Andric SmallVector<uint64_t, 64> Record;
776b60736ecSDimitry Andric GlobalDeclAttachmentPos = 0;
7777e7b6700SDimitry Andric // Get the abbrevs, and preload record positions to make them lazy-loadable.
7787e7b6700SDimitry Andric while (true) {
779b60736ecSDimitry Andric uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
780c0981da4SDimitry Andric BitstreamEntry Entry;
781c0981da4SDimitry Andric if (Error E =
782c0981da4SDimitry Andric IndexCursor
783c0981da4SDimitry Andric .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
784c0981da4SDimitry Andric .moveInto(Entry))
785c0981da4SDimitry Andric return std::move(E);
786e6d15924SDimitry Andric
7877e7b6700SDimitry Andric switch (Entry.Kind) {
7887e7b6700SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
7897e7b6700SDimitry Andric case BitstreamEntry::Error:
7907e7b6700SDimitry Andric return error("Malformed block");
7917e7b6700SDimitry Andric case BitstreamEntry::EndBlock: {
7927e7b6700SDimitry Andric return true;
7937e7b6700SDimitry Andric }
7947e7b6700SDimitry Andric case BitstreamEntry::Record: {
7957e7b6700SDimitry Andric // The interesting case.
7967e7b6700SDimitry Andric ++NumMDRecordLoaded;
7977e7b6700SDimitry Andric uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
798c0981da4SDimitry Andric unsigned Code;
799c0981da4SDimitry Andric if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
800c0981da4SDimitry Andric return std::move(E);
8017e7b6700SDimitry Andric switch (Code) {
8027e7b6700SDimitry Andric case bitc::METADATA_STRINGS: {
8037e7b6700SDimitry Andric // Rewind and parse the strings.
804e6d15924SDimitry Andric if (Error Err = IndexCursor.JumpToBit(CurrentPos))
805e6d15924SDimitry Andric return std::move(Err);
8067e7b6700SDimitry Andric StringRef Blob;
8077e7b6700SDimitry Andric Record.clear();
808e6d15924SDimitry Andric if (Expected<unsigned> MaybeRecord =
809e6d15924SDimitry Andric IndexCursor.readRecord(Entry.ID, Record, &Blob))
810e6d15924SDimitry Andric ;
811e6d15924SDimitry Andric else
812e6d15924SDimitry Andric return MaybeRecord.takeError();
8137e7b6700SDimitry Andric unsigned NumStrings = Record[0];
8147e7b6700SDimitry Andric MDStringRef.reserve(NumStrings);
8157e7b6700SDimitry Andric auto IndexNextMDString = [&](StringRef Str) {
8167e7b6700SDimitry Andric MDStringRef.push_back(Str);
8177e7b6700SDimitry Andric };
8187e7b6700SDimitry Andric if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
8197e7b6700SDimitry Andric return std::move(Err);
8207e7b6700SDimitry Andric break;
8217e7b6700SDimitry Andric }
8227e7b6700SDimitry Andric case bitc::METADATA_INDEX_OFFSET: {
8237e7b6700SDimitry Andric // This is the offset to the index, when we see this we skip all the
8247e7b6700SDimitry Andric // records and load only an index to these.
825e6d15924SDimitry Andric if (Error Err = IndexCursor.JumpToBit(CurrentPos))
826e6d15924SDimitry Andric return std::move(Err);
8277e7b6700SDimitry Andric Record.clear();
828e6d15924SDimitry Andric if (Expected<unsigned> MaybeRecord =
829e6d15924SDimitry Andric IndexCursor.readRecord(Entry.ID, Record))
830e6d15924SDimitry Andric ;
831e6d15924SDimitry Andric else
832e6d15924SDimitry Andric return MaybeRecord.takeError();
8337e7b6700SDimitry Andric if (Record.size() != 2)
8347e7b6700SDimitry Andric return error("Invalid record");
8357e7b6700SDimitry Andric auto Offset = Record[0] + (Record[1] << 32);
8367e7b6700SDimitry Andric auto BeginPos = IndexCursor.GetCurrentBitNo();
837e6d15924SDimitry Andric if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
838e6d15924SDimitry Andric return std::move(Err);
839e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry =
840e6d15924SDimitry Andric IndexCursor.advanceSkippingSubblocks(
8417e7b6700SDimitry Andric BitstreamCursor::AF_DontPopBlockAtEnd);
842e6d15924SDimitry Andric if (!MaybeEntry)
843e6d15924SDimitry Andric return MaybeEntry.takeError();
844e6d15924SDimitry Andric Entry = MaybeEntry.get();
8457e7b6700SDimitry Andric assert(Entry.Kind == BitstreamEntry::Record &&
8467e7b6700SDimitry Andric "Corrupted bitcode: Expected `Record` when trying to find the "
8477e7b6700SDimitry Andric "Metadata index");
8487e7b6700SDimitry Andric Record.clear();
849e6d15924SDimitry Andric if (Expected<unsigned> MaybeCode =
850e6d15924SDimitry Andric IndexCursor.readRecord(Entry.ID, Record))
851e6d15924SDimitry Andric assert(MaybeCode.get() == bitc::METADATA_INDEX &&
852e6d15924SDimitry Andric "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
853e6d15924SDimitry Andric "find the Metadata index");
854e6d15924SDimitry Andric else
855e6d15924SDimitry Andric return MaybeCode.takeError();
8567e7b6700SDimitry Andric // Delta unpack
8577e7b6700SDimitry Andric auto CurrentValue = BeginPos;
8587e7b6700SDimitry Andric GlobalMetadataBitPosIndex.reserve(Record.size());
8597e7b6700SDimitry Andric for (auto &Elt : Record) {
8607e7b6700SDimitry Andric CurrentValue += Elt;
8617e7b6700SDimitry Andric GlobalMetadataBitPosIndex.push_back(CurrentValue);
8627e7b6700SDimitry Andric }
8637e7b6700SDimitry Andric break;
8647e7b6700SDimitry Andric }
8657e7b6700SDimitry Andric case bitc::METADATA_INDEX:
8667e7b6700SDimitry Andric // We don't expect to get there, the Index is loaded when we encounter
8677e7b6700SDimitry Andric // the offset.
8687e7b6700SDimitry Andric return error("Corrupted Metadata block");
8697e7b6700SDimitry Andric case bitc::METADATA_NAME: {
8707e7b6700SDimitry Andric // Named metadata need to be materialized now and aren't deferred.
871e6d15924SDimitry Andric if (Error Err = IndexCursor.JumpToBit(CurrentPos))
872e6d15924SDimitry Andric return std::move(Err);
8737e7b6700SDimitry Andric Record.clear();
874e6d15924SDimitry Andric
875e6d15924SDimitry Andric unsigned Code;
876e6d15924SDimitry Andric if (Expected<unsigned> MaybeCode =
877e6d15924SDimitry Andric IndexCursor.readRecord(Entry.ID, Record)) {
878e6d15924SDimitry Andric Code = MaybeCode.get();
8797e7b6700SDimitry Andric assert(Code == bitc::METADATA_NAME);
880e6d15924SDimitry Andric } else
881e6d15924SDimitry Andric return MaybeCode.takeError();
8827e7b6700SDimitry Andric
8837e7b6700SDimitry Andric // Read name of the named metadata.
8847e7b6700SDimitry Andric SmallString<8> Name(Record.begin(), Record.end());
885e6d15924SDimitry Andric if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
886e6d15924SDimitry Andric Code = MaybeCode.get();
887e6d15924SDimitry Andric else
888e6d15924SDimitry Andric return MaybeCode.takeError();
8897e7b6700SDimitry Andric
8907e7b6700SDimitry Andric // Named Metadata comes in two parts, we expect the name to be followed
8917e7b6700SDimitry Andric // by the node
8927e7b6700SDimitry Andric Record.clear();
893e6d15924SDimitry Andric if (Expected<unsigned> MaybeNextBitCode =
894e6d15924SDimitry Andric IndexCursor.readRecord(Code, Record))
895e6d15924SDimitry Andric assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
896e6d15924SDimitry Andric else
897e6d15924SDimitry Andric return MaybeNextBitCode.takeError();
8987e7b6700SDimitry Andric
8997e7b6700SDimitry Andric // Read named metadata elements.
9007e7b6700SDimitry Andric unsigned Size = Record.size();
9017e7b6700SDimitry Andric NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
9027e7b6700SDimitry Andric for (unsigned i = 0; i != Size; ++i) {
9037e7b6700SDimitry Andric // FIXME: We could use a placeholder here, however NamedMDNode are
9047e7b6700SDimitry Andric // taking MDNode as operand and not using the Metadata infrastructure.
9057e7b6700SDimitry Andric // It is acknowledged by 'TODO: Inherit from Metadata' in the
9067e7b6700SDimitry Andric // NamedMDNode class definition.
9077e7b6700SDimitry Andric MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
908d8e91e46SDimitry Andric assert(MD && "Invalid metadata: expect fwd ref to MDNode");
9097e7b6700SDimitry Andric NMD->addOperand(MD);
9107e7b6700SDimitry Andric }
9117e7b6700SDimitry Andric break;
9127e7b6700SDimitry Andric }
9137e7b6700SDimitry Andric case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
914b60736ecSDimitry Andric if (!GlobalDeclAttachmentPos)
915b60736ecSDimitry Andric GlobalDeclAttachmentPos = SavedPos;
916b60736ecSDimitry Andric #ifndef NDEBUG
917b60736ecSDimitry Andric NumGlobalDeclAttachSkipped++;
918b60736ecSDimitry Andric #endif
9197e7b6700SDimitry Andric break;
9207e7b6700SDimitry Andric }
9217e7b6700SDimitry Andric case bitc::METADATA_KIND:
9227e7b6700SDimitry Andric case bitc::METADATA_STRING_OLD:
9237e7b6700SDimitry Andric case bitc::METADATA_OLD_FN_NODE:
9247e7b6700SDimitry Andric case bitc::METADATA_OLD_NODE:
9257e7b6700SDimitry Andric case bitc::METADATA_VALUE:
9267e7b6700SDimitry Andric case bitc::METADATA_DISTINCT_NODE:
9277e7b6700SDimitry Andric case bitc::METADATA_NODE:
9287e7b6700SDimitry Andric case bitc::METADATA_LOCATION:
9297e7b6700SDimitry Andric case bitc::METADATA_GENERIC_DEBUG:
9307e7b6700SDimitry Andric case bitc::METADATA_SUBRANGE:
9317e7b6700SDimitry Andric case bitc::METADATA_ENUMERATOR:
9327e7b6700SDimitry Andric case bitc::METADATA_BASIC_TYPE:
933b60736ecSDimitry Andric case bitc::METADATA_STRING_TYPE:
9347e7b6700SDimitry Andric case bitc::METADATA_DERIVED_TYPE:
9357e7b6700SDimitry Andric case bitc::METADATA_COMPOSITE_TYPE:
9367e7b6700SDimitry Andric case bitc::METADATA_SUBROUTINE_TYPE:
9377e7b6700SDimitry Andric case bitc::METADATA_MODULE:
9387e7b6700SDimitry Andric case bitc::METADATA_FILE:
9397e7b6700SDimitry Andric case bitc::METADATA_COMPILE_UNIT:
9407e7b6700SDimitry Andric case bitc::METADATA_SUBPROGRAM:
9417e7b6700SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK:
9427e7b6700SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK_FILE:
9437e7b6700SDimitry Andric case bitc::METADATA_NAMESPACE:
944e6d15924SDimitry Andric case bitc::METADATA_COMMON_BLOCK:
9457e7b6700SDimitry Andric case bitc::METADATA_MACRO:
9467e7b6700SDimitry Andric case bitc::METADATA_MACRO_FILE:
9477e7b6700SDimitry Andric case bitc::METADATA_TEMPLATE_TYPE:
9487e7b6700SDimitry Andric case bitc::METADATA_TEMPLATE_VALUE:
9497e7b6700SDimitry Andric case bitc::METADATA_GLOBAL_VAR:
9507e7b6700SDimitry Andric case bitc::METADATA_LOCAL_VAR:
951e3b55780SDimitry Andric case bitc::METADATA_ASSIGN_ID:
952eb11fae6SDimitry Andric case bitc::METADATA_LABEL:
9537e7b6700SDimitry Andric case bitc::METADATA_EXPRESSION:
9547e7b6700SDimitry Andric case bitc::METADATA_OBJC_PROPERTY:
9557e7b6700SDimitry Andric case bitc::METADATA_IMPORTED_ENTITY:
9567e7b6700SDimitry Andric case bitc::METADATA_GLOBAL_VAR_EXPR:
957b60736ecSDimitry Andric case bitc::METADATA_GENERIC_SUBRANGE:
9587e7b6700SDimitry Andric // We don't expect to see any of these, if we see one, give up on
9597e7b6700SDimitry Andric // lazy-loading and fallback.
9607e7b6700SDimitry Andric MDStringRef.clear();
9617e7b6700SDimitry Andric GlobalMetadataBitPosIndex.clear();
9627e7b6700SDimitry Andric return false;
9637e7b6700SDimitry Andric }
9647e7b6700SDimitry Andric break;
9657e7b6700SDimitry Andric }
9667e7b6700SDimitry Andric }
9677e7b6700SDimitry Andric }
9687e7b6700SDimitry Andric }
9697e7b6700SDimitry Andric
970b60736ecSDimitry Andric // Load the global decl attachments after building the lazy loading index.
971b60736ecSDimitry Andric // We don't load them "lazily" - all global decl attachments must be
972b60736ecSDimitry Andric // parsed since they aren't materialized on demand. However, by delaying
973b60736ecSDimitry Andric // their parsing until after the index is created, we can use the index
974b60736ecSDimitry Andric // instead of creating temporaries.
loadGlobalDeclAttachments()975b60736ecSDimitry Andric Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
976b60736ecSDimitry Andric // Nothing to do if we didn't find any of these metadata records.
977b60736ecSDimitry Andric if (!GlobalDeclAttachmentPos)
978b60736ecSDimitry Andric return true;
979b60736ecSDimitry Andric // Use a temporary cursor so that we don't mess up the main Stream cursor or
980b60736ecSDimitry Andric // the lazy loading IndexCursor (which holds the necessary abbrev ids).
981b60736ecSDimitry Andric BitstreamCursor TempCursor = Stream;
982b60736ecSDimitry Andric SmallVector<uint64_t, 64> Record;
983b60736ecSDimitry Andric // Jump to the position before the first global decl attachment, so we can
984b60736ecSDimitry Andric // scan for the first BitstreamEntry record.
985b60736ecSDimitry Andric if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
986b60736ecSDimitry Andric return std::move(Err);
987b60736ecSDimitry Andric while (true) {
988c0981da4SDimitry Andric BitstreamEntry Entry;
989c0981da4SDimitry Andric if (Error E =
990c0981da4SDimitry Andric TempCursor
991c0981da4SDimitry Andric .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
992c0981da4SDimitry Andric .moveInto(Entry))
993c0981da4SDimitry Andric return std::move(E);
994b60736ecSDimitry Andric
995b60736ecSDimitry Andric switch (Entry.Kind) {
996b60736ecSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
997b60736ecSDimitry Andric case BitstreamEntry::Error:
998b60736ecSDimitry Andric return error("Malformed block");
999b60736ecSDimitry Andric case BitstreamEntry::EndBlock:
1000f65dcba8SDimitry Andric // Check that we parsed them all.
1001b60736ecSDimitry Andric assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1002b60736ecSDimitry Andric return true;
1003b60736ecSDimitry Andric case BitstreamEntry::Record:
1004b60736ecSDimitry Andric break;
1005b60736ecSDimitry Andric }
1006b60736ecSDimitry Andric uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
1007b60736ecSDimitry Andric Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1008b60736ecSDimitry Andric if (!MaybeCode)
1009b60736ecSDimitry Andric return MaybeCode.takeError();
1010b60736ecSDimitry Andric if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
1011b60736ecSDimitry Andric // Anything other than a global decl attachment signals the end of
1012f65dcba8SDimitry Andric // these records. Check that we parsed them all.
1013b60736ecSDimitry Andric assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1014b60736ecSDimitry Andric return true;
1015b60736ecSDimitry Andric }
1016b60736ecSDimitry Andric #ifndef NDEBUG
1017b60736ecSDimitry Andric NumGlobalDeclAttachParsed++;
1018b60736ecSDimitry Andric #endif
1019b60736ecSDimitry Andric // FIXME: we need to do this early because we don't materialize global
1020b60736ecSDimitry Andric // value explicitly.
1021b60736ecSDimitry Andric if (Error Err = TempCursor.JumpToBit(CurrentPos))
1022b60736ecSDimitry Andric return std::move(Err);
1023b60736ecSDimitry Andric Record.clear();
1024b60736ecSDimitry Andric if (Expected<unsigned> MaybeRecord =
1025b60736ecSDimitry Andric TempCursor.readRecord(Entry.ID, Record))
1026b60736ecSDimitry Andric ;
1027b60736ecSDimitry Andric else
1028b60736ecSDimitry Andric return MaybeRecord.takeError();
1029b60736ecSDimitry Andric if (Record.size() % 2 == 0)
1030b60736ecSDimitry Andric return error("Invalid record");
1031b60736ecSDimitry Andric unsigned ValueID = Record[0];
1032b60736ecSDimitry Andric if (ValueID >= ValueList.size())
1033b60736ecSDimitry Andric return error("Invalid record");
1034b60736ecSDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
1035b60736ecSDimitry Andric // Need to save and restore the current position since
1036b60736ecSDimitry Andric // parseGlobalObjectAttachment will resolve all forward references which
1037b60736ecSDimitry Andric // would require parsing from locations stored in the index.
1038b60736ecSDimitry Andric CurrentPos = TempCursor.GetCurrentBitNo();
1039b60736ecSDimitry Andric if (Error Err = parseGlobalObjectAttachment(
1040b60736ecSDimitry Andric *GO, ArrayRef<uint64_t>(Record).slice(1)))
1041b60736ecSDimitry Andric return std::move(Err);
1042b60736ecSDimitry Andric if (Error Err = TempCursor.JumpToBit(CurrentPos))
1043b60736ecSDimitry Andric return std::move(Err);
1044b60736ecSDimitry Andric }
1045b60736ecSDimitry Andric }
1046b60736ecSDimitry Andric }
1047b60736ecSDimitry Andric
callMDTypeCallback(Metadata ** Val,unsigned TypeID)1048e3b55780SDimitry Andric void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1049e3b55780SDimitry Andric unsigned TypeID) {
1050e3b55780SDimitry Andric if (Callbacks.MDType) {
1051e3b55780SDimitry Andric (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1052e3b55780SDimitry Andric Callbacks.GetContainedTypeID);
1053e3b55780SDimitry Andric }
1054e3b55780SDimitry Andric }
1055e3b55780SDimitry Andric
1056b915e9e0SDimitry Andric /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1057b915e9e0SDimitry Andric /// module level metadata.
parseMetadata(bool ModuleLevel)1058b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
1059b915e9e0SDimitry Andric if (!ModuleLevel && MetadataList.hasFwdRefs())
1060b915e9e0SDimitry Andric return error("Invalid metadata: fwd refs into function blocks");
1061b915e9e0SDimitry Andric
10627e7b6700SDimitry Andric // Record the entry position so that we can jump back here and efficiently
10637e7b6700SDimitry Andric // skip the whole block in case we lazy-load.
10647e7b6700SDimitry Andric auto EntryPos = Stream.GetCurrentBitNo();
10657e7b6700SDimitry Andric
1066e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1067e6d15924SDimitry Andric return Err;
1068b915e9e0SDimitry Andric
1069b915e9e0SDimitry Andric SmallVector<uint64_t, 64> Record;
1070b915e9e0SDimitry Andric PlaceholderQueue Placeholders;
1071b915e9e0SDimitry Andric
10727e7b6700SDimitry Andric // We lazy-load module-level metadata: we build an index for each record, and
10737e7b6700SDimitry Andric // then load individual record as needed, starting with the named metadata.
10747e7b6700SDimitry Andric if (ModuleLevel && IsImporting && MetadataList.empty() &&
10757e7b6700SDimitry Andric !DisableLazyLoading) {
1076909545a8SDimitry Andric auto SuccessOrErr = lazyLoadModuleMetadataBlock();
10777e7b6700SDimitry Andric if (!SuccessOrErr)
10787e7b6700SDimitry Andric return SuccessOrErr.takeError();
10797e7b6700SDimitry Andric if (SuccessOrErr.get()) {
10807e7b6700SDimitry Andric // An index was successfully created and we will be able to load metadata
10817e7b6700SDimitry Andric // on-demand.
10827e7b6700SDimitry Andric MetadataList.resize(MDStringRef.size() +
10837e7b6700SDimitry Andric GlobalMetadataBitPosIndex.size());
10847e7b6700SDimitry Andric
1085b60736ecSDimitry Andric // Now that we have built the index, load the global decl attachments
1086b60736ecSDimitry Andric // that were deferred during that process. This avoids creating
1087b60736ecSDimitry Andric // temporaries.
1088b60736ecSDimitry Andric SuccessOrErr = loadGlobalDeclAttachments();
1089b60736ecSDimitry Andric if (!SuccessOrErr)
1090b60736ecSDimitry Andric return SuccessOrErr.takeError();
1091b60736ecSDimitry Andric assert(SuccessOrErr.get());
1092b60736ecSDimitry Andric
10937e7b6700SDimitry Andric // Reading the named metadata created forward references and/or
10947e7b6700SDimitry Andric // placeholders, that we flush here.
10957e7b6700SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
1096b1c73532SDimitry Andric upgradeDebugInfo(ModuleLevel);
10977e7b6700SDimitry Andric // Return at the beginning of the block, since it is easy to skip it
10987e7b6700SDimitry Andric // entirely from there.
10997e7b6700SDimitry Andric Stream.ReadBlockEnd(); // Pop the abbrev block context.
1100e6d15924SDimitry Andric if (Error Err = IndexCursor.JumpToBit(EntryPos))
1101e6d15924SDimitry Andric return Err;
1102e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock()) {
1103e6d15924SDimitry Andric // FIXME this drops the error on the floor, which
1104e6d15924SDimitry Andric // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1105e6d15924SDimitry Andric consumeError(std::move(Err));
1106e6d15924SDimitry Andric return Error::success();
1107e6d15924SDimitry Andric }
11087e7b6700SDimitry Andric return Error::success();
11097e7b6700SDimitry Andric }
11107e7b6700SDimitry Andric // Couldn't load an index, fallback to loading all the block "old-style".
11117e7b6700SDimitry Andric }
11127e7b6700SDimitry Andric
11137e7b6700SDimitry Andric unsigned NextMetadataNo = MetadataList.size();
11147e7b6700SDimitry Andric
1115b915e9e0SDimitry Andric // Read all the records.
1116b915e9e0SDimitry Andric while (true) {
1117c0981da4SDimitry Andric BitstreamEntry Entry;
1118c0981da4SDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1119c0981da4SDimitry Andric return E;
1120b915e9e0SDimitry Andric
1121b915e9e0SDimitry Andric switch (Entry.Kind) {
1122b915e9e0SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
1123b915e9e0SDimitry Andric case BitstreamEntry::Error:
1124b915e9e0SDimitry Andric return error("Malformed block");
1125b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
11267e7b6700SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
1127b1c73532SDimitry Andric upgradeDebugInfo(ModuleLevel);
1128b915e9e0SDimitry Andric return Error::success();
1129b915e9e0SDimitry Andric case BitstreamEntry::Record:
1130b915e9e0SDimitry Andric // The interesting case.
1131b915e9e0SDimitry Andric break;
1132b915e9e0SDimitry Andric }
1133b915e9e0SDimitry Andric
1134b915e9e0SDimitry Andric // Read a record.
1135b915e9e0SDimitry Andric Record.clear();
1136b915e9e0SDimitry Andric StringRef Blob;
11377e7b6700SDimitry Andric ++NumMDRecordLoaded;
1138e6d15924SDimitry Andric if (Expected<unsigned> MaybeCode =
1139e6d15924SDimitry Andric Stream.readRecord(Entry.ID, Record, &Blob)) {
1140e6d15924SDimitry Andric if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1141e6d15924SDimitry Andric Blob, NextMetadataNo))
1142b915e9e0SDimitry Andric return Err;
1143e6d15924SDimitry Andric } else
1144e6d15924SDimitry Andric return MaybeCode.takeError();
1145b915e9e0SDimitry Andric }
1146b915e9e0SDimitry Andric }
1147b915e9e0SDimitry Andric
lazyLoadOneMDString(unsigned ID)11487e7b6700SDimitry Andric MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
11497e7b6700SDimitry Andric ++NumMDStringLoaded;
11507e7b6700SDimitry Andric if (Metadata *MD = MetadataList.lookup(ID))
11517e7b6700SDimitry Andric return cast<MDString>(MD);
11527e7b6700SDimitry Andric auto MDS = MDString::get(Context, MDStringRef[ID]);
11537e7b6700SDimitry Andric MetadataList.assignValue(MDS, ID);
11547e7b6700SDimitry Andric return MDS;
11557e7b6700SDimitry Andric }
11567e7b6700SDimitry Andric
lazyLoadOneMetadata(unsigned ID,PlaceholderQueue & Placeholders)11577e7b6700SDimitry Andric void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
11587e7b6700SDimitry Andric unsigned ID, PlaceholderQueue &Placeholders) {
11597e7b6700SDimitry Andric assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
11607e7b6700SDimitry Andric assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
11617e7b6700SDimitry Andric // Lookup first if the metadata hasn't already been loaded.
11627e7b6700SDimitry Andric if (auto *MD = MetadataList.lookup(ID)) {
11631d5ae102SDimitry Andric auto *N = cast<MDNode>(MD);
11647c71d32aSDimitry Andric if (!N->isTemporary())
11657c71d32aSDimitry Andric return;
11667e7b6700SDimitry Andric }
11677e7b6700SDimitry Andric SmallVector<uint64_t, 64> Record;
11687e7b6700SDimitry Andric StringRef Blob;
1169e6d15924SDimitry Andric if (Error Err = IndexCursor.JumpToBit(
1170e6d15924SDimitry Andric GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1171e6d15924SDimitry Andric report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1172c0981da4SDimitry Andric Twine(toString(std::move(Err))));
1173c0981da4SDimitry Andric BitstreamEntry Entry;
1174c0981da4SDimitry Andric if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1175e6d15924SDimitry Andric // FIXME this drops the error on the floor.
1176e6d15924SDimitry Andric report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1177c0981da4SDimitry Andric Twine(toString(std::move(E))));
11787e7b6700SDimitry Andric ++NumMDRecordLoaded;
1179e6d15924SDimitry Andric if (Expected<unsigned> MaybeCode =
1180e6d15924SDimitry Andric IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1181e6d15924SDimitry Andric if (Error Err =
1182e6d15924SDimitry Andric parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1183e6d15924SDimitry Andric report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1184c0981da4SDimitry Andric Twine(toString(std::move(Err))));
1185e6d15924SDimitry Andric } else
1186c0981da4SDimitry Andric report_fatal_error("Can't lazyload MD: " +
1187c0981da4SDimitry Andric Twine(toString(MaybeCode.takeError())));
11887e7b6700SDimitry Andric }
11897e7b6700SDimitry Andric
11907e7b6700SDimitry Andric /// Ensure that all forward-references and placeholders are resolved.
11917e7b6700SDimitry Andric /// Iteratively lazy-loading metadata on-demand if needed.
resolveForwardRefsAndPlaceholders(PlaceholderQueue & Placeholders)11927e7b6700SDimitry Andric void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
11937e7b6700SDimitry Andric PlaceholderQueue &Placeholders) {
11947e7b6700SDimitry Andric DenseSet<unsigned> Temporaries;
11956f8fc217SDimitry Andric while (true) {
11967e7b6700SDimitry Andric // Populate Temporaries with the placeholders that haven't been loaded yet.
11977e7b6700SDimitry Andric Placeholders.getTemporaries(MetadataList, Temporaries);
11987e7b6700SDimitry Andric
11997e7b6700SDimitry Andric // If we don't have any temporary, or FwdReference, we're done!
12007e7b6700SDimitry Andric if (Temporaries.empty() && !MetadataList.hasFwdRefs())
12017e7b6700SDimitry Andric break;
12027e7b6700SDimitry Andric
12037e7b6700SDimitry Andric // First, load all the temporaries. This can add new placeholders or
12047e7b6700SDimitry Andric // forward references.
12057e7b6700SDimitry Andric for (auto ID : Temporaries)
12067e7b6700SDimitry Andric lazyLoadOneMetadata(ID, Placeholders);
12077e7b6700SDimitry Andric Temporaries.clear();
12087e7b6700SDimitry Andric
12097e7b6700SDimitry Andric // Second, load the forward-references. This can also add new placeholders
12107e7b6700SDimitry Andric // or forward references.
12117e7b6700SDimitry Andric while (MetadataList.hasFwdRefs())
12127e7b6700SDimitry Andric lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
12137e7b6700SDimitry Andric }
12147e7b6700SDimitry Andric // At this point we don't have any forward reference remaining, or temporary
12157e7b6700SDimitry Andric // that haven't been loaded. We can safely drop RAUW support and mark cycles
12167e7b6700SDimitry Andric // as resolved.
12177e7b6700SDimitry Andric MetadataList.tryToResolveCycles();
12187e7b6700SDimitry Andric
12197e7b6700SDimitry Andric // Finally, everything is in place, we can replace the placeholders operands
12207e7b6700SDimitry Andric // with the final node they refer to.
12217e7b6700SDimitry Andric Placeholders.flush(MetadataList);
12227e7b6700SDimitry Andric }
12237e7b6700SDimitry Andric
getValueFwdRef(BitcodeReaderValueList & ValueList,unsigned Idx,Type * Ty,unsigned TyID)1224b1c73532SDimitry Andric static Value *getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx,
1225b1c73532SDimitry Andric Type *Ty, unsigned TyID) {
1226b1c73532SDimitry Andric Value *V = ValueList.getValueFwdRef(Idx, Ty, TyID,
1227b1c73532SDimitry Andric /*ConstExprInsertBB*/ nullptr);
1228b1c73532SDimitry Andric if (V)
1229b1c73532SDimitry Andric return V;
1230b1c73532SDimitry Andric
1231b1c73532SDimitry Andric // This is a reference to a no longer supported constant expression.
1232b1c73532SDimitry Andric // Pretend that the constant was deleted, which will replace metadata
1233b1c73532SDimitry Andric // references with undef.
1234b1c73532SDimitry Andric // TODO: This is a rather indirect check. It would be more elegant to use
1235b1c73532SDimitry Andric // a separate ErrorInfo for constant materialization failure and thread
1236b1c73532SDimitry Andric // the error reporting through getValueFwdRef().
1237b1c73532SDimitry Andric if (Idx < ValueList.size() && ValueList[Idx] &&
1238b1c73532SDimitry Andric ValueList[Idx]->getType() == Ty)
1239b1c73532SDimitry Andric return UndefValue::get(Ty);
1240b1c73532SDimitry Andric
1241b1c73532SDimitry Andric return nullptr;
1242b1c73532SDimitry Andric }
1243b1c73532SDimitry Andric
parseOneMetadata(SmallVectorImpl<uint64_t> & Record,unsigned Code,PlaceholderQueue & Placeholders,StringRef Blob,unsigned & NextMetadataNo)1244b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1245b915e9e0SDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Code,
12467e7b6700SDimitry Andric PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1247b915e9e0SDimitry Andric
1248b915e9e0SDimitry Andric bool IsDistinct = false;
1249b915e9e0SDimitry Andric auto getMD = [&](unsigned ID) -> Metadata * {
12507e7b6700SDimitry Andric if (ID < MDStringRef.size())
12517e7b6700SDimitry Andric return lazyLoadOneMDString(ID);
12527c71d32aSDimitry Andric if (!IsDistinct) {
12537c71d32aSDimitry Andric if (auto *MD = MetadataList.lookup(ID))
12547c71d32aSDimitry Andric return MD;
12557c71d32aSDimitry Andric // If lazy-loading is enabled, we try recursively to load the operand
12567c71d32aSDimitry Andric // instead of creating a temporary.
12577c71d32aSDimitry Andric if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
12587c71d32aSDimitry Andric // Create a temporary for the node that is referencing the operand we
12597c71d32aSDimitry Andric // will lazy-load. It is needed before recursing in case there are
12607c71d32aSDimitry Andric // uniquing cycles.
12617c71d32aSDimitry Andric MetadataList.getMetadataFwdRef(NextMetadataNo);
12627c71d32aSDimitry Andric lazyLoadOneMetadata(ID, Placeholders);
12637c71d32aSDimitry Andric return MetadataList.lookup(ID);
12647c71d32aSDimitry Andric }
12657c71d32aSDimitry Andric // Return a temporary.
1266b915e9e0SDimitry Andric return MetadataList.getMetadataFwdRef(ID);
12677c71d32aSDimitry Andric }
1268b915e9e0SDimitry Andric if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1269b915e9e0SDimitry Andric return MD;
1270b915e9e0SDimitry Andric return &Placeholders.getPlaceholderOp(ID);
1271b915e9e0SDimitry Andric };
1272b915e9e0SDimitry Andric auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1273b915e9e0SDimitry Andric if (ID)
1274b915e9e0SDimitry Andric return getMD(ID - 1);
1275b915e9e0SDimitry Andric return nullptr;
1276b915e9e0SDimitry Andric };
1277b915e9e0SDimitry Andric auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1278b915e9e0SDimitry Andric if (ID)
1279b915e9e0SDimitry Andric return MetadataList.getMetadataFwdRef(ID - 1);
1280b915e9e0SDimitry Andric return nullptr;
1281b915e9e0SDimitry Andric };
1282b915e9e0SDimitry Andric auto getMDString = [&](unsigned ID) -> MDString * {
1283b915e9e0SDimitry Andric // This requires that the ID is not really a forward reference. In
1284b915e9e0SDimitry Andric // particular, the MDString must already have been resolved.
12857e7b6700SDimitry Andric auto MDS = getMDOrNull(ID);
12867e7b6700SDimitry Andric return cast_or_null<MDString>(MDS);
1287b915e9e0SDimitry Andric };
1288b915e9e0SDimitry Andric
1289b915e9e0SDimitry Andric // Support for old type refs.
1290b915e9e0SDimitry Andric auto getDITypeRefOrNull = [&](unsigned ID) {
1291b915e9e0SDimitry Andric return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1292b915e9e0SDimitry Andric };
1293b915e9e0SDimitry Andric
1294b915e9e0SDimitry Andric #define GET_OR_DISTINCT(CLASS, ARGS) \
1295b915e9e0SDimitry Andric (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1296b915e9e0SDimitry Andric
1297b915e9e0SDimitry Andric switch (Code) {
1298b915e9e0SDimitry Andric default: // Default behavior: ignore.
1299b915e9e0SDimitry Andric break;
1300b915e9e0SDimitry Andric case bitc::METADATA_NAME: {
1301b915e9e0SDimitry Andric // Read name of the named metadata.
1302b915e9e0SDimitry Andric SmallString<8> Name(Record.begin(), Record.end());
1303b915e9e0SDimitry Andric Record.clear();
1304c0981da4SDimitry Andric if (Error E = Stream.ReadCode().moveInto(Code))
1305c0981da4SDimitry Andric return E;
1306b915e9e0SDimitry Andric
13077e7b6700SDimitry Andric ++NumMDRecordLoaded;
1308e6d15924SDimitry Andric if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1309e6d15924SDimitry Andric if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1310b915e9e0SDimitry Andric return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1311e6d15924SDimitry Andric } else
1312e6d15924SDimitry Andric return MaybeNextBitCode.takeError();
1313b915e9e0SDimitry Andric
1314b915e9e0SDimitry Andric // Read named metadata elements.
1315b915e9e0SDimitry Andric unsigned Size = Record.size();
1316b915e9e0SDimitry Andric NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1317b915e9e0SDimitry Andric for (unsigned i = 0; i != Size; ++i) {
1318b915e9e0SDimitry Andric MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1319b915e9e0SDimitry Andric if (!MD)
1320d8e91e46SDimitry Andric return error("Invalid named metadata: expect fwd ref to MDNode");
1321b915e9e0SDimitry Andric NMD->addOperand(MD);
1322b915e9e0SDimitry Andric }
1323b915e9e0SDimitry Andric break;
1324b915e9e0SDimitry Andric }
1325b915e9e0SDimitry Andric case bitc::METADATA_OLD_FN_NODE: {
1326cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
1327b915e9e0SDimitry Andric // This is a LocalAsMetadata record, the only type of function-local
1328b915e9e0SDimitry Andric // metadata.
1329b915e9e0SDimitry Andric if (Record.size() % 2 == 1)
1330b915e9e0SDimitry Andric return error("Invalid record");
1331b915e9e0SDimitry Andric
1332b915e9e0SDimitry Andric // If this isn't a LocalAsMetadata record, we're dropping it. This used
1333b915e9e0SDimitry Andric // to be legal, but there's no upgrade path.
1334b915e9e0SDimitry Andric auto dropRecord = [&] {
1335e3b55780SDimitry Andric MetadataList.assignValue(MDNode::get(Context, std::nullopt),
1336e3b55780SDimitry Andric NextMetadataNo);
1337aac4ca60SDimitry Andric NextMetadataNo++;
1338b915e9e0SDimitry Andric };
1339b915e9e0SDimitry Andric if (Record.size() != 2) {
1340b915e9e0SDimitry Andric dropRecord();
1341b915e9e0SDimitry Andric break;
1342b915e9e0SDimitry Andric }
1343b915e9e0SDimitry Andric
1344145449b1SDimitry Andric unsigned TyID = Record[0];
1345e3b55780SDimitry Andric Type *Ty = Callbacks.GetTypeByID(TyID);
1346b1c73532SDimitry Andric if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
1347b915e9e0SDimitry Andric dropRecord();
1348b915e9e0SDimitry Andric break;
1349b915e9e0SDimitry Andric }
1350b915e9e0SDimitry Andric
13514b4fe385SDimitry Andric Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
13524b4fe385SDimitry Andric /*ConstExprInsertBB*/ nullptr);
13534b4fe385SDimitry Andric if (!V)
13544b4fe385SDimitry Andric return error("Invalid value reference from old fn metadata");
13554b4fe385SDimitry Andric
13564b4fe385SDimitry Andric MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
1357aac4ca60SDimitry Andric NextMetadataNo++;
1358b915e9e0SDimitry Andric break;
1359b915e9e0SDimitry Andric }
1360b915e9e0SDimitry Andric case bitc::METADATA_OLD_NODE: {
1361cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
1362b915e9e0SDimitry Andric if (Record.size() % 2 == 1)
1363b915e9e0SDimitry Andric return error("Invalid record");
1364b915e9e0SDimitry Andric
1365b915e9e0SDimitry Andric unsigned Size = Record.size();
1366b915e9e0SDimitry Andric SmallVector<Metadata *, 8> Elts;
1367b915e9e0SDimitry Andric for (unsigned i = 0; i != Size; i += 2) {
1368145449b1SDimitry Andric unsigned TyID = Record[i];
1369e3b55780SDimitry Andric Type *Ty = Callbacks.GetTypeByID(TyID);
1370b915e9e0SDimitry Andric if (!Ty)
1371b915e9e0SDimitry Andric return error("Invalid record");
1372b915e9e0SDimitry Andric if (Ty->isMetadataTy())
1373b915e9e0SDimitry Andric Elts.push_back(getMD(Record[i + 1]));
1374b915e9e0SDimitry Andric else if (!Ty->isVoidTy()) {
1375b1c73532SDimitry Andric Value *V = getValueFwdRef(ValueList, Record[i + 1], Ty, TyID);
13764b4fe385SDimitry Andric if (!V)
13774b4fe385SDimitry Andric return error("Invalid value reference from old metadata");
1378e3b55780SDimitry Andric Metadata *MD = ValueAsMetadata::get(V);
1379b915e9e0SDimitry Andric assert(isa<ConstantAsMetadata>(MD) &&
1380b915e9e0SDimitry Andric "Expected non-function-local metadata");
1381e3b55780SDimitry Andric callMDTypeCallback(&MD, TyID);
1382b915e9e0SDimitry Andric Elts.push_back(MD);
1383b915e9e0SDimitry Andric } else
1384b915e9e0SDimitry Andric Elts.push_back(nullptr);
1385b915e9e0SDimitry Andric }
1386aac4ca60SDimitry Andric MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1387aac4ca60SDimitry Andric NextMetadataNo++;
1388b915e9e0SDimitry Andric break;
1389b915e9e0SDimitry Andric }
1390b915e9e0SDimitry Andric case bitc::METADATA_VALUE: {
1391b915e9e0SDimitry Andric if (Record.size() != 2)
1392b915e9e0SDimitry Andric return error("Invalid record");
1393b915e9e0SDimitry Andric
1394145449b1SDimitry Andric unsigned TyID = Record[0];
1395e3b55780SDimitry Andric Type *Ty = Callbacks.GetTypeByID(TyID);
1396b1c73532SDimitry Andric if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
1397b915e9e0SDimitry Andric return error("Invalid record");
1398b915e9e0SDimitry Andric
1399b1c73532SDimitry Andric Value *V = getValueFwdRef(ValueList, Record[1], Ty, TyID);
14004b4fe385SDimitry Andric if (!V)
14014b4fe385SDimitry Andric return error("Invalid value reference from metadata");
14024b4fe385SDimitry Andric
1403e3b55780SDimitry Andric Metadata *MD = ValueAsMetadata::get(V);
1404e3b55780SDimitry Andric callMDTypeCallback(&MD, TyID);
1405e3b55780SDimitry Andric MetadataList.assignValue(MD, NextMetadataNo);
1406aac4ca60SDimitry Andric NextMetadataNo++;
1407b915e9e0SDimitry Andric break;
1408b915e9e0SDimitry Andric }
1409b915e9e0SDimitry Andric case bitc::METADATA_DISTINCT_NODE:
1410b915e9e0SDimitry Andric IsDistinct = true;
1411e3b55780SDimitry Andric [[fallthrough]];
1412b915e9e0SDimitry Andric case bitc::METADATA_NODE: {
1413b915e9e0SDimitry Andric SmallVector<Metadata *, 8> Elts;
1414b915e9e0SDimitry Andric Elts.reserve(Record.size());
1415b915e9e0SDimitry Andric for (unsigned ID : Record)
1416b915e9e0SDimitry Andric Elts.push_back(getMDOrNull(ID));
1417b915e9e0SDimitry Andric MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1418b915e9e0SDimitry Andric : MDNode::get(Context, Elts),
1419aac4ca60SDimitry Andric NextMetadataNo);
1420aac4ca60SDimitry Andric NextMetadataNo++;
1421b915e9e0SDimitry Andric break;
1422b915e9e0SDimitry Andric }
1423b915e9e0SDimitry Andric case bitc::METADATA_LOCATION: {
1424d8e91e46SDimitry Andric if (Record.size() != 5 && Record.size() != 6)
1425b915e9e0SDimitry Andric return error("Invalid record");
1426b915e9e0SDimitry Andric
1427b915e9e0SDimitry Andric IsDistinct = Record[0];
1428b915e9e0SDimitry Andric unsigned Line = Record[1];
1429b915e9e0SDimitry Andric unsigned Column = Record[2];
1430b915e9e0SDimitry Andric Metadata *Scope = getMD(Record[3]);
1431b915e9e0SDimitry Andric Metadata *InlinedAt = getMDOrNull(Record[4]);
1432d8e91e46SDimitry Andric bool ImplicitCode = Record.size() == 6 && Record[5];
1433b915e9e0SDimitry Andric MetadataList.assignValue(
1434d8e91e46SDimitry Andric GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1435d8e91e46SDimitry Andric ImplicitCode)),
1436aac4ca60SDimitry Andric NextMetadataNo);
1437aac4ca60SDimitry Andric NextMetadataNo++;
1438b915e9e0SDimitry Andric break;
1439b915e9e0SDimitry Andric }
1440b915e9e0SDimitry Andric case bitc::METADATA_GENERIC_DEBUG: {
1441b915e9e0SDimitry Andric if (Record.size() < 4)
1442b915e9e0SDimitry Andric return error("Invalid record");
1443b915e9e0SDimitry Andric
1444b915e9e0SDimitry Andric IsDistinct = Record[0];
1445b915e9e0SDimitry Andric unsigned Tag = Record[1];
1446b915e9e0SDimitry Andric unsigned Version = Record[2];
1447b915e9e0SDimitry Andric
1448b915e9e0SDimitry Andric if (Tag >= 1u << 16 || Version != 0)
1449b915e9e0SDimitry Andric return error("Invalid record");
1450b915e9e0SDimitry Andric
1451b915e9e0SDimitry Andric auto *Header = getMDString(Record[3]);
1452b915e9e0SDimitry Andric SmallVector<Metadata *, 8> DwarfOps;
1453b915e9e0SDimitry Andric for (unsigned I = 4, E = Record.size(); I != E; ++I)
1454b915e9e0SDimitry Andric DwarfOps.push_back(getMDOrNull(Record[I]));
1455b915e9e0SDimitry Andric MetadataList.assignValue(
1456b915e9e0SDimitry Andric GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1457aac4ca60SDimitry Andric NextMetadataNo);
1458aac4ca60SDimitry Andric NextMetadataNo++;
1459b915e9e0SDimitry Andric break;
1460b915e9e0SDimitry Andric }
1461b915e9e0SDimitry Andric case bitc::METADATA_SUBRANGE: {
1462eb11fae6SDimitry Andric Metadata *Val = nullptr;
1463eb11fae6SDimitry Andric // Operand 'count' is interpreted as:
1464eb11fae6SDimitry Andric // - Signed integer (version 0)
1465eb11fae6SDimitry Andric // - Metadata node (version 1)
1466cfca06d7SDimitry Andric // Operand 'lowerBound' is interpreted as:
1467cfca06d7SDimitry Andric // - Signed integer (version 0 and 1)
1468cfca06d7SDimitry Andric // - Metadata node (version 2)
1469cfca06d7SDimitry Andric // Operands 'upperBound' and 'stride' are interpreted as:
1470cfca06d7SDimitry Andric // - Metadata node (version 2)
1471eb11fae6SDimitry Andric switch (Record[0] >> 1) {
1472eb11fae6SDimitry Andric case 0:
1473eb11fae6SDimitry Andric Val = GET_OR_DISTINCT(DISubrange,
1474cfca06d7SDimitry Andric (Context, Record[1], unrotateSign(Record[2])));
1475eb11fae6SDimitry Andric break;
1476eb11fae6SDimitry Andric case 1:
1477eb11fae6SDimitry Andric Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1478cfca06d7SDimitry Andric unrotateSign(Record[2])));
1479cfca06d7SDimitry Andric break;
1480cfca06d7SDimitry Andric case 2:
1481cfca06d7SDimitry Andric Val = GET_OR_DISTINCT(
1482cfca06d7SDimitry Andric DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1483cfca06d7SDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1484eb11fae6SDimitry Andric break;
1485eb11fae6SDimitry Andric default:
1486eb11fae6SDimitry Andric return error("Invalid record: Unsupported version of DISubrange");
1487eb11fae6SDimitry Andric }
1488b915e9e0SDimitry Andric
1489eb11fae6SDimitry Andric MetadataList.assignValue(Val, NextMetadataNo);
1490eb11fae6SDimitry Andric IsDistinct = Record[0] & 1;
1491aac4ca60SDimitry Andric NextMetadataNo++;
1492b915e9e0SDimitry Andric break;
1493b915e9e0SDimitry Andric }
1494b60736ecSDimitry Andric case bitc::METADATA_GENERIC_SUBRANGE: {
1495b60736ecSDimitry Andric Metadata *Val = nullptr;
1496b60736ecSDimitry Andric Val = GET_OR_DISTINCT(DIGenericSubrange,
1497b60736ecSDimitry Andric (Context, getMDOrNull(Record[1]),
1498b60736ecSDimitry Andric getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1499b60736ecSDimitry Andric getMDOrNull(Record[4])));
1500b60736ecSDimitry Andric
1501b60736ecSDimitry Andric MetadataList.assignValue(Val, NextMetadataNo);
1502b60736ecSDimitry Andric IsDistinct = Record[0] & 1;
1503b60736ecSDimitry Andric NextMetadataNo++;
1504b60736ecSDimitry Andric break;
1505b60736ecSDimitry Andric }
1506b915e9e0SDimitry Andric case bitc::METADATA_ENUMERATOR: {
1507cfca06d7SDimitry Andric if (Record.size() < 3)
1508b915e9e0SDimitry Andric return error("Invalid record");
1509b915e9e0SDimitry Andric
1510eb11fae6SDimitry Andric IsDistinct = Record[0] & 1;
1511eb11fae6SDimitry Andric bool IsUnsigned = Record[0] & 2;
1512cfca06d7SDimitry Andric bool IsBigInt = Record[0] & 4;
1513cfca06d7SDimitry Andric APInt Value;
1514cfca06d7SDimitry Andric
1515cfca06d7SDimitry Andric if (IsBigInt) {
1516cfca06d7SDimitry Andric const uint64_t BitWidth = Record[1];
1517cfca06d7SDimitry Andric const size_t NumWords = Record.size() - 3;
1518e3b55780SDimitry Andric Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
1519cfca06d7SDimitry Andric } else
1520cfca06d7SDimitry Andric Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1521cfca06d7SDimitry Andric
1522b915e9e0SDimitry Andric MetadataList.assignValue(
1523cfca06d7SDimitry Andric GET_OR_DISTINCT(DIEnumerator,
1524cfca06d7SDimitry Andric (Context, Value, IsUnsigned, getMDString(Record[2]))),
1525aac4ca60SDimitry Andric NextMetadataNo);
1526aac4ca60SDimitry Andric NextMetadataNo++;
1527b915e9e0SDimitry Andric break;
1528b915e9e0SDimitry Andric }
1529b915e9e0SDimitry Andric case bitc::METADATA_BASIC_TYPE: {
1530d8e91e46SDimitry Andric if (Record.size() < 6 || Record.size() > 7)
1531b915e9e0SDimitry Andric return error("Invalid record");
1532b915e9e0SDimitry Andric
1533b915e9e0SDimitry Andric IsDistinct = Record[0];
1534c0981da4SDimitry Andric DINode::DIFlags Flags = (Record.size() > 6)
1535c0981da4SDimitry Andric ? static_cast<DINode::DIFlags>(Record[6])
1536c0981da4SDimitry Andric : DINode::FlagZero;
1537d8e91e46SDimitry Andric
1538b915e9e0SDimitry Andric MetadataList.assignValue(
1539b915e9e0SDimitry Andric GET_OR_DISTINCT(DIBasicType,
1540b915e9e0SDimitry Andric (Context, Record[1], getMDString(Record[2]), Record[3],
1541d8e91e46SDimitry Andric Record[4], Record[5], Flags)),
1542aac4ca60SDimitry Andric NextMetadataNo);
1543aac4ca60SDimitry Andric NextMetadataNo++;
1544b915e9e0SDimitry Andric break;
1545b915e9e0SDimitry Andric }
1546b60736ecSDimitry Andric case bitc::METADATA_STRING_TYPE: {
15476f8fc217SDimitry Andric if (Record.size() > 9 || Record.size() < 8)
1548b60736ecSDimitry Andric return error("Invalid record");
1549b60736ecSDimitry Andric
1550b60736ecSDimitry Andric IsDistinct = Record[0];
15516f8fc217SDimitry Andric bool SizeIs8 = Record.size() == 8;
15526f8fc217SDimitry Andric // StringLocationExp (i.e. Record[5]) is added at a later time
15536f8fc217SDimitry Andric // than the other fields. The code here enables backward compatibility.
15546f8fc217SDimitry Andric Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
15556f8fc217SDimitry Andric unsigned Offset = SizeIs8 ? 5 : 6;
1556b60736ecSDimitry Andric MetadataList.assignValue(
1557b60736ecSDimitry Andric GET_OR_DISTINCT(DIStringType,
1558b60736ecSDimitry Andric (Context, Record[1], getMDString(Record[2]),
1559b60736ecSDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4]),
15606f8fc217SDimitry Andric StringLocationExp, Record[Offset], Record[Offset + 1],
15616f8fc217SDimitry Andric Record[Offset + 2])),
1562b60736ecSDimitry Andric NextMetadataNo);
1563b60736ecSDimitry Andric NextMetadataNo++;
1564b60736ecSDimitry Andric break;
1565b60736ecSDimitry Andric }
1566b915e9e0SDimitry Andric case bitc::METADATA_DERIVED_TYPE: {
1567ac9a064cSDimitry Andric if (Record.size() < 12 || Record.size() > 15)
1568b915e9e0SDimitry Andric return error("Invalid record");
1569b915e9e0SDimitry Andric
157071d5a254SDimitry Andric // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
157171d5a254SDimitry Andric // that there is no DWARF address space associated with DIDerivedType.
1572e3b55780SDimitry Andric std::optional<unsigned> DWARFAddressSpace;
157371d5a254SDimitry Andric if (Record.size() > 12 && Record[12])
157471d5a254SDimitry Andric DWARFAddressSpace = Record[12] - 1;
157571d5a254SDimitry Andric
1576c0981da4SDimitry Andric Metadata *Annotations = nullptr;
1577ac9a064cSDimitry Andric std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1578ac9a064cSDimitry Andric
1579ac9a064cSDimitry Andric // Only look for annotations/ptrauth if both are allocated.
1580ac9a064cSDimitry Andric // If not, we can't tell which was intended to be embedded, as both ptrauth
1581ac9a064cSDimitry Andric // and annotations have been expected at Record[13] at various times.
1582ac9a064cSDimitry Andric if (Record.size() > 14) {
1583ac9a064cSDimitry Andric if (Record[13])
1584c0981da4SDimitry Andric Annotations = getMDOrNull(Record[13]);
1585ac9a064cSDimitry Andric if (Record[14])
1586ac9a064cSDimitry Andric PtrAuthData.emplace(Record[14]);
1587ac9a064cSDimitry Andric }
1588c0981da4SDimitry Andric
1589b915e9e0SDimitry Andric IsDistinct = Record[0];
1590b915e9e0SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1591b915e9e0SDimitry Andric MetadataList.assignValue(
1592b915e9e0SDimitry Andric GET_OR_DISTINCT(DIDerivedType,
1593b915e9e0SDimitry Andric (Context, Record[1], getMDString(Record[2]),
1594b915e9e0SDimitry Andric getMDOrNull(Record[3]), Record[4],
1595b915e9e0SDimitry Andric getDITypeRefOrNull(Record[5]),
1596b915e9e0SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1597ac9a064cSDimitry Andric Record[9], DWARFAddressSpace, PtrAuthData, Flags,
1598c0981da4SDimitry Andric getDITypeRefOrNull(Record[11]), Annotations)),
1599aac4ca60SDimitry Andric NextMetadataNo);
1600aac4ca60SDimitry Andric NextMetadataNo++;
1601b915e9e0SDimitry Andric break;
1602b915e9e0SDimitry Andric }
1603b915e9e0SDimitry Andric case bitc::METADATA_COMPOSITE_TYPE: {
1604c0981da4SDimitry Andric if (Record.size() < 16 || Record.size() > 22)
1605b915e9e0SDimitry Andric return error("Invalid record");
1606b915e9e0SDimitry Andric
1607b915e9e0SDimitry Andric // If we have a UUID and this is not a forward declaration, lookup the
1608b915e9e0SDimitry Andric // mapping.
1609b915e9e0SDimitry Andric IsDistinct = Record[0] & 0x1;
1610b915e9e0SDimitry Andric bool IsNotUsedInTypeRef = Record[0] >= 2;
1611b915e9e0SDimitry Andric unsigned Tag = Record[1];
1612b915e9e0SDimitry Andric MDString *Name = getMDString(Record[2]);
1613b915e9e0SDimitry Andric Metadata *File = getMDOrNull(Record[3]);
1614b915e9e0SDimitry Andric unsigned Line = Record[4];
1615b915e9e0SDimitry Andric Metadata *Scope = getDITypeRefOrNull(Record[5]);
1616b915e9e0SDimitry Andric Metadata *BaseType = nullptr;
1617b915e9e0SDimitry Andric uint64_t SizeInBits = Record[7];
1618b915e9e0SDimitry Andric if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1619b915e9e0SDimitry Andric return error("Alignment value is too large");
1620b915e9e0SDimitry Andric uint32_t AlignInBits = Record[8];
1621b915e9e0SDimitry Andric uint64_t OffsetInBits = 0;
1622b915e9e0SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1623b915e9e0SDimitry Andric Metadata *Elements = nullptr;
1624b915e9e0SDimitry Andric unsigned RuntimeLang = Record[12];
1625b915e9e0SDimitry Andric Metadata *VTableHolder = nullptr;
1626b915e9e0SDimitry Andric Metadata *TemplateParams = nullptr;
1627eb11fae6SDimitry Andric Metadata *Discriminator = nullptr;
1628cfca06d7SDimitry Andric Metadata *DataLocation = nullptr;
1629b60736ecSDimitry Andric Metadata *Associated = nullptr;
1630b60736ecSDimitry Andric Metadata *Allocated = nullptr;
1631b60736ecSDimitry Andric Metadata *Rank = nullptr;
1632c0981da4SDimitry Andric Metadata *Annotations = nullptr;
1633b915e9e0SDimitry Andric auto *Identifier = getMDString(Record[15]);
1634b915e9e0SDimitry Andric // If this module is being parsed so that it can be ThinLTO imported
16354df029ccSDimitry Andric // into another module, composite types only need to be imported as
16364df029ccSDimitry Andric // type declarations (unless full type definitions are requested).
16374df029ccSDimitry Andric // Create type declarations up front to save memory. This is only
16384df029ccSDimitry Andric // done for types which have an Identifier, and are therefore
16394df029ccSDimitry Andric // subject to the ODR.
16404df029ccSDimitry Andric //
16414df029ccSDimitry Andric // buildODRType handles the case where this is type ODRed with a
16424df029ccSDimitry Andric // definition needed by the importing module, in which case the
16434df029ccSDimitry Andric // existing definition is used.
16444df029ccSDimitry Andric //
16454df029ccSDimitry Andric // We always import full definitions for anonymous composite types,
16464df029ccSDimitry Andric // as without a name, debuggers cannot easily resolve a declaration
16474df029ccSDimitry Andric // to its definition.
16484df029ccSDimitry Andric if (IsImporting && !ImportFullTypeDefinitions && Identifier && Name &&
1649b915e9e0SDimitry Andric (Tag == dwarf::DW_TAG_enumeration_type ||
1650b915e9e0SDimitry Andric Tag == dwarf::DW_TAG_class_type ||
1651b915e9e0SDimitry Andric Tag == dwarf::DW_TAG_structure_type ||
1652b915e9e0SDimitry Andric Tag == dwarf::DW_TAG_union_type)) {
1653b915e9e0SDimitry Andric Flags = Flags | DINode::FlagFwdDecl;
1654145449b1SDimitry Andric // This is a hack around preserving template parameters for simplified
1655145449b1SDimitry Andric // template names - it should probably be replaced with a
1656145449b1SDimitry Andric // DICompositeType flag specifying whether template parameters are
1657145449b1SDimitry Andric // required on declarations of this type.
1658145449b1SDimitry Andric StringRef NameStr = Name->getString();
1659312c0ed1SDimitry Andric if (!NameStr.contains('<') || NameStr.starts_with("_STN|"))
1660145449b1SDimitry Andric TemplateParams = getMDOrNull(Record[14]);
1661b915e9e0SDimitry Andric } else {
1662b915e9e0SDimitry Andric BaseType = getDITypeRefOrNull(Record[6]);
1663b915e9e0SDimitry Andric OffsetInBits = Record[9];
1664b915e9e0SDimitry Andric Elements = getMDOrNull(Record[11]);
1665b915e9e0SDimitry Andric VTableHolder = getDITypeRefOrNull(Record[13]);
1666b915e9e0SDimitry Andric TemplateParams = getMDOrNull(Record[14]);
1667eb11fae6SDimitry Andric if (Record.size() > 16)
1668eb11fae6SDimitry Andric Discriminator = getMDOrNull(Record[16]);
1669cfca06d7SDimitry Andric if (Record.size() > 17)
1670cfca06d7SDimitry Andric DataLocation = getMDOrNull(Record[17]);
1671b60736ecSDimitry Andric if (Record.size() > 19) {
1672b60736ecSDimitry Andric Associated = getMDOrNull(Record[18]);
1673b60736ecSDimitry Andric Allocated = getMDOrNull(Record[19]);
1674b60736ecSDimitry Andric }
1675b60736ecSDimitry Andric if (Record.size() > 20) {
1676b60736ecSDimitry Andric Rank = getMDOrNull(Record[20]);
1677b60736ecSDimitry Andric }
1678c0981da4SDimitry Andric if (Record.size() > 21) {
1679c0981da4SDimitry Andric Annotations = getMDOrNull(Record[21]);
1680c0981da4SDimitry Andric }
1681b915e9e0SDimitry Andric }
1682b915e9e0SDimitry Andric DICompositeType *CT = nullptr;
1683b915e9e0SDimitry Andric if (Identifier)
1684b915e9e0SDimitry Andric CT = DICompositeType::buildODRType(
1685b915e9e0SDimitry Andric Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1686b915e9e0SDimitry Andric SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1687b60736ecSDimitry Andric VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1688c0981da4SDimitry Andric Allocated, Rank, Annotations);
1689b915e9e0SDimitry Andric
1690b915e9e0SDimitry Andric // Create a node if we didn't get a lazy ODR type.
1691b915e9e0SDimitry Andric if (!CT)
1692b915e9e0SDimitry Andric CT = GET_OR_DISTINCT(DICompositeType,
1693b915e9e0SDimitry Andric (Context, Tag, Name, File, Line, Scope, BaseType,
1694b915e9e0SDimitry Andric SizeInBits, AlignInBits, OffsetInBits, Flags,
1695b915e9e0SDimitry Andric Elements, RuntimeLang, VTableHolder, TemplateParams,
1696b60736ecSDimitry Andric Identifier, Discriminator, DataLocation, Associated,
1697c0981da4SDimitry Andric Allocated, Rank, Annotations));
1698b915e9e0SDimitry Andric if (!IsNotUsedInTypeRef && Identifier)
1699b915e9e0SDimitry Andric MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1700b915e9e0SDimitry Andric
1701aac4ca60SDimitry Andric MetadataList.assignValue(CT, NextMetadataNo);
1702aac4ca60SDimitry Andric NextMetadataNo++;
1703b915e9e0SDimitry Andric break;
1704b915e9e0SDimitry Andric }
1705b915e9e0SDimitry Andric case bitc::METADATA_SUBROUTINE_TYPE: {
1706b915e9e0SDimitry Andric if (Record.size() < 3 || Record.size() > 4)
1707b915e9e0SDimitry Andric return error("Invalid record");
1708b915e9e0SDimitry Andric bool IsOldTypeRefArray = Record[0] < 2;
1709b915e9e0SDimitry Andric unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1710b915e9e0SDimitry Andric
1711b915e9e0SDimitry Andric IsDistinct = Record[0] & 0x1;
1712b915e9e0SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1713b915e9e0SDimitry Andric Metadata *Types = getMDOrNull(Record[2]);
1714b915e9e0SDimitry Andric if (LLVM_UNLIKELY(IsOldTypeRefArray))
1715b915e9e0SDimitry Andric Types = MetadataList.upgradeTypeRefArray(Types);
1716b915e9e0SDimitry Andric
1717b915e9e0SDimitry Andric MetadataList.assignValue(
1718b915e9e0SDimitry Andric GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1719aac4ca60SDimitry Andric NextMetadataNo);
1720aac4ca60SDimitry Andric NextMetadataNo++;
1721b915e9e0SDimitry Andric break;
1722b915e9e0SDimitry Andric }
1723b915e9e0SDimitry Andric
1724b915e9e0SDimitry Andric case bitc::METADATA_MODULE: {
1725b60736ecSDimitry Andric if (Record.size() < 5 || Record.size() > 9)
1726b915e9e0SDimitry Andric return error("Invalid record");
1727b915e9e0SDimitry Andric
1728b60736ecSDimitry Andric unsigned Offset = Record.size() >= 8 ? 2 : 1;
1729b915e9e0SDimitry Andric IsDistinct = Record[0];
1730b915e9e0SDimitry Andric MetadataList.assignValue(
1731cfca06d7SDimitry Andric GET_OR_DISTINCT(
1732cfca06d7SDimitry Andric DIModule,
1733b60736ecSDimitry Andric (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1734cfca06d7SDimitry Andric getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1735cfca06d7SDimitry Andric getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1736cfca06d7SDimitry Andric getMDString(Record[4 + Offset]),
1737b60736ecSDimitry Andric Record.size() <= 7 ? 0 : Record[7],
1738b60736ecSDimitry Andric Record.size() <= 8 ? false : Record[8])),
1739aac4ca60SDimitry Andric NextMetadataNo);
1740aac4ca60SDimitry Andric NextMetadataNo++;
1741b915e9e0SDimitry Andric break;
1742b915e9e0SDimitry Andric }
1743b915e9e0SDimitry Andric
1744b915e9e0SDimitry Andric case bitc::METADATA_FILE: {
1745eb11fae6SDimitry Andric if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1746b915e9e0SDimitry Andric return error("Invalid record");
1747b915e9e0SDimitry Andric
1748b915e9e0SDimitry Andric IsDistinct = Record[0];
1749e3b55780SDimitry Andric std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1750eb11fae6SDimitry Andric // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1751eb11fae6SDimitry Andric // is not present. This matches up with the old internal representation,
1752eb11fae6SDimitry Andric // and the old encoding for CSK_None in the ChecksumKind. The new
1753eb11fae6SDimitry Andric // representation reserves the value 0 in the ChecksumKind to continue to
1754eb11fae6SDimitry Andric // encode None in a backwards-compatible way.
1755eb11fae6SDimitry Andric if (Record.size() > 4 && Record[3] && Record[4])
1756eb11fae6SDimitry Andric Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1757eb11fae6SDimitry Andric getMDString(Record[4]));
1758b915e9e0SDimitry Andric MetadataList.assignValue(
1759e3b55780SDimitry Andric GET_OR_DISTINCT(DIFile,
1760e3b55780SDimitry Andric (Context, getMDString(Record[1]),
1761e3b55780SDimitry Andric getMDString(Record[2]), Checksum,
1762e3b55780SDimitry Andric Record.size() > 5 ? getMDString(Record[5]) : nullptr)),
1763aac4ca60SDimitry Andric NextMetadataNo);
1764aac4ca60SDimitry Andric NextMetadataNo++;
1765b915e9e0SDimitry Andric break;
1766b915e9e0SDimitry Andric }
1767b915e9e0SDimitry Andric case bitc::METADATA_COMPILE_UNIT: {
1768cfca06d7SDimitry Andric if (Record.size() < 14 || Record.size() > 22)
1769b915e9e0SDimitry Andric return error("Invalid record");
1770b915e9e0SDimitry Andric
1771b915e9e0SDimitry Andric // Ignore Record[0], which indicates whether this compile unit is
1772b915e9e0SDimitry Andric // distinct. It's always distinct.
1773b915e9e0SDimitry Andric IsDistinct = true;
1774b915e9e0SDimitry Andric auto *CU = DICompileUnit::getDistinct(
1775b915e9e0SDimitry Andric Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1776b915e9e0SDimitry Andric Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1777b915e9e0SDimitry Andric Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1778b915e9e0SDimitry Andric getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1779b915e9e0SDimitry Andric Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1780b915e9e0SDimitry Andric Record.size() <= 14 ? 0 : Record[14],
178171d5a254SDimitry Andric Record.size() <= 16 ? true : Record[16],
1782044eb2f6SDimitry Andric Record.size() <= 17 ? false : Record[17],
1783d8e91e46SDimitry Andric Record.size() <= 18 ? 0 : Record[18],
17846f8fc217SDimitry Andric Record.size() <= 19 ? false : Record[19],
1785cfca06d7SDimitry Andric Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1786cfca06d7SDimitry Andric Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1787b915e9e0SDimitry Andric
1788aac4ca60SDimitry Andric MetadataList.assignValue(CU, NextMetadataNo);
1789aac4ca60SDimitry Andric NextMetadataNo++;
1790b915e9e0SDimitry Andric
1791b915e9e0SDimitry Andric // Move the Upgrade the list of subprograms.
1792b915e9e0SDimitry Andric if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1793b915e9e0SDimitry Andric CUSubprograms.push_back({CU, SPs});
1794b915e9e0SDimitry Andric break;
1795b915e9e0SDimitry Andric }
1796b915e9e0SDimitry Andric case bitc::METADATA_SUBPROGRAM: {
1797a303c417SDimitry Andric if (Record.size() < 18 || Record.size() > 21)
1798b915e9e0SDimitry Andric return error("Invalid record");
1799b915e9e0SDimitry Andric
1800d8e91e46SDimitry Andric bool HasSPFlags = Record[0] & 4;
1801e6d15924SDimitry Andric
1802e6d15924SDimitry Andric DINode::DIFlags Flags;
1803e6d15924SDimitry Andric DISubprogram::DISPFlags SPFlags;
1804e6d15924SDimitry Andric if (!HasSPFlags)
1805e6d15924SDimitry Andric Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1806e6d15924SDimitry Andric else {
1807e6d15924SDimitry Andric Flags = static_cast<DINode::DIFlags>(Record[11]);
1808e6d15924SDimitry Andric SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1809e6d15924SDimitry Andric }
1810e6d15924SDimitry Andric
1811e6d15924SDimitry Andric // Support for old metadata when
1812e6d15924SDimitry Andric // subprogram specific flags are placed in DIFlags.
1813e6d15924SDimitry Andric const unsigned DIFlagMainSubprogram = 1 << 21;
1814e6d15924SDimitry Andric bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
1815e6d15924SDimitry Andric if (HasOldMainSubprogramFlag)
1816e6d15924SDimitry Andric // Remove old DIFlagMainSubprogram from DIFlags.
1817e6d15924SDimitry Andric // Note: This assumes that any future use of bit 21 defaults to it
1818e6d15924SDimitry Andric // being 0.
1819e6d15924SDimitry Andric Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1820e6d15924SDimitry Andric
1821e6d15924SDimitry Andric if (HasOldMainSubprogramFlag && HasSPFlags)
1822e6d15924SDimitry Andric SPFlags |= DISubprogram::SPFlagMainSubprogram;
1823e6d15924SDimitry Andric else if (!HasSPFlags)
1824e6d15924SDimitry Andric SPFlags = DISubprogram::toSPFlags(
1825d8e91e46SDimitry Andric /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
1826e6d15924SDimitry Andric /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
18276f8fc217SDimitry Andric /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
1828d8e91e46SDimitry Andric
1829d8e91e46SDimitry Andric // All definitions should be distinct.
1830d8e91e46SDimitry Andric IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1831b915e9e0SDimitry Andric // Version 1 has a Function as Record[15].
1832b915e9e0SDimitry Andric // Version 2 has removed Record[15].
1833b915e9e0SDimitry Andric // Version 3 has the Unit as Record[15].
1834b915e9e0SDimitry Andric // Version 4 added thisAdjustment.
1835d8e91e46SDimitry Andric // Version 5 repacked flags into DISPFlags, changing many element numbers.
1836d8e91e46SDimitry Andric bool HasUnit = Record[0] & 2;
1837d8e91e46SDimitry Andric if (!HasSPFlags && HasUnit && Record.size() < 19)
1838b915e9e0SDimitry Andric return error("Invalid record");
1839d8e91e46SDimitry Andric if (HasSPFlags && !HasUnit)
1840d8e91e46SDimitry Andric return error("Invalid record");
1841d8e91e46SDimitry Andric // Accommodate older formats.
1842d8e91e46SDimitry Andric bool HasFn = false;
1843d8e91e46SDimitry Andric bool HasThisAdj = true;
1844d8e91e46SDimitry Andric bool HasThrownTypes = true;
1845c0981da4SDimitry Andric bool HasAnnotations = false;
1846145449b1SDimitry Andric bool HasTargetFuncName = false;
1847d8e91e46SDimitry Andric unsigned OffsetA = 0;
1848d8e91e46SDimitry Andric unsigned OffsetB = 0;
1849d8e91e46SDimitry Andric if (!HasSPFlags) {
1850d8e91e46SDimitry Andric OffsetA = 2;
1851d8e91e46SDimitry Andric OffsetB = 2;
1852d8e91e46SDimitry Andric if (Record.size() >= 19) {
1853d8e91e46SDimitry Andric HasFn = !HasUnit;
1854d8e91e46SDimitry Andric OffsetB++;
1855d8e91e46SDimitry Andric }
1856d8e91e46SDimitry Andric HasThisAdj = Record.size() >= 20;
1857d8e91e46SDimitry Andric HasThrownTypes = Record.size() >= 21;
1858c0981da4SDimitry Andric } else {
1859c0981da4SDimitry Andric HasAnnotations = Record.size() >= 19;
1860145449b1SDimitry Andric HasTargetFuncName = Record.size() >= 20;
1861d8e91e46SDimitry Andric }
1862d8e91e46SDimitry Andric Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1863b915e9e0SDimitry Andric DISubprogram *SP = GET_OR_DISTINCT(
1864a303c417SDimitry Andric DISubprogram,
1865a303c417SDimitry Andric (Context,
1866b915e9e0SDimitry Andric getDITypeRefOrNull(Record[1]), // scope
1867b915e9e0SDimitry Andric getMDString(Record[2]), // name
1868b915e9e0SDimitry Andric getMDString(Record[3]), // linkageName
1869b915e9e0SDimitry Andric getMDOrNull(Record[4]), // file
1870b915e9e0SDimitry Andric Record[5], // line
1871b915e9e0SDimitry Andric getMDOrNull(Record[6]), // type
1872d8e91e46SDimitry Andric Record[7 + OffsetA], // scopeLine
1873d8e91e46SDimitry Andric getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
1874d8e91e46SDimitry Andric Record[10 + OffsetA], // virtualIndex
1875d8e91e46SDimitry Andric HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
1876e6d15924SDimitry Andric Flags, // flags
1877d8e91e46SDimitry Andric SPFlags, // SPFlags
1878b915e9e0SDimitry Andric HasUnit ? CUorFn : nullptr, // unit
1879d8e91e46SDimitry Andric getMDOrNull(Record[13 + OffsetB]), // templateParams
1880d8e91e46SDimitry Andric getMDOrNull(Record[14 + OffsetB]), // declaration
1881d8e91e46SDimitry Andric getMDOrNull(Record[15 + OffsetB]), // retainedNodes
1882d8e91e46SDimitry Andric HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1883c0981da4SDimitry Andric : nullptr, // thrownTypes
1884c0981da4SDimitry Andric HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1885145449b1SDimitry Andric : nullptr, // annotations
1886145449b1SDimitry Andric HasTargetFuncName ? getMDString(Record[19 + OffsetB])
1887145449b1SDimitry Andric : nullptr // targetFuncName
1888b915e9e0SDimitry Andric ));
1889aac4ca60SDimitry Andric MetadataList.assignValue(SP, NextMetadataNo);
1890aac4ca60SDimitry Andric NextMetadataNo++;
1891b915e9e0SDimitry Andric
1892b915e9e0SDimitry Andric // Upgrade sp->function mapping to function->sp mapping.
1893b915e9e0SDimitry Andric if (HasFn) {
1894b915e9e0SDimitry Andric if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1895b915e9e0SDimitry Andric if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1896b915e9e0SDimitry Andric if (F->isMaterializable())
1897b915e9e0SDimitry Andric // Defer until materialized; unmaterialized functions may not have
1898b915e9e0SDimitry Andric // metadata.
1899b915e9e0SDimitry Andric FunctionsWithSPs[F] = SP;
1900b915e9e0SDimitry Andric else if (!F->empty())
1901b915e9e0SDimitry Andric F->setSubprogram(SP);
1902b915e9e0SDimitry Andric }
1903b915e9e0SDimitry Andric }
1904b915e9e0SDimitry Andric break;
1905b915e9e0SDimitry Andric }
1906b915e9e0SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK: {
1907b915e9e0SDimitry Andric if (Record.size() != 5)
1908b915e9e0SDimitry Andric return error("Invalid record");
1909b915e9e0SDimitry Andric
1910b915e9e0SDimitry Andric IsDistinct = Record[0];
1911b915e9e0SDimitry Andric MetadataList.assignValue(
1912b915e9e0SDimitry Andric GET_OR_DISTINCT(DILexicalBlock,
1913b915e9e0SDimitry Andric (Context, getMDOrNull(Record[1]),
1914b915e9e0SDimitry Andric getMDOrNull(Record[2]), Record[3], Record[4])),
1915aac4ca60SDimitry Andric NextMetadataNo);
1916aac4ca60SDimitry Andric NextMetadataNo++;
1917b915e9e0SDimitry Andric break;
1918b915e9e0SDimitry Andric }
1919b915e9e0SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1920b915e9e0SDimitry Andric if (Record.size() != 4)
1921b915e9e0SDimitry Andric return error("Invalid record");
1922b915e9e0SDimitry Andric
1923b915e9e0SDimitry Andric IsDistinct = Record[0];
1924b915e9e0SDimitry Andric MetadataList.assignValue(
1925b915e9e0SDimitry Andric GET_OR_DISTINCT(DILexicalBlockFile,
1926b915e9e0SDimitry Andric (Context, getMDOrNull(Record[1]),
1927b915e9e0SDimitry Andric getMDOrNull(Record[2]), Record[3])),
1928aac4ca60SDimitry Andric NextMetadataNo);
1929aac4ca60SDimitry Andric NextMetadataNo++;
1930b915e9e0SDimitry Andric break;
1931b915e9e0SDimitry Andric }
1932e6d15924SDimitry Andric case bitc::METADATA_COMMON_BLOCK: {
1933e6d15924SDimitry Andric IsDistinct = Record[0] & 1;
1934e6d15924SDimitry Andric MetadataList.assignValue(
1935e6d15924SDimitry Andric GET_OR_DISTINCT(DICommonBlock,
1936e6d15924SDimitry Andric (Context, getMDOrNull(Record[1]),
1937e6d15924SDimitry Andric getMDOrNull(Record[2]), getMDString(Record[3]),
1938e6d15924SDimitry Andric getMDOrNull(Record[4]), Record[5])),
1939e6d15924SDimitry Andric NextMetadataNo);
1940e6d15924SDimitry Andric NextMetadataNo++;
1941e6d15924SDimitry Andric break;
1942e6d15924SDimitry Andric }
1943b915e9e0SDimitry Andric case bitc::METADATA_NAMESPACE: {
1944a303c417SDimitry Andric // Newer versions of DINamespace dropped file and line.
1945a303c417SDimitry Andric MDString *Name;
1946a303c417SDimitry Andric if (Record.size() == 3)
1947a303c417SDimitry Andric Name = getMDString(Record[2]);
1948a303c417SDimitry Andric else if (Record.size() == 5)
1949a303c417SDimitry Andric Name = getMDString(Record[3]);
1950a303c417SDimitry Andric else
1951b915e9e0SDimitry Andric return error("Invalid record");
1952b915e9e0SDimitry Andric
1953b915e9e0SDimitry Andric IsDistinct = Record[0] & 1;
1954b915e9e0SDimitry Andric bool ExportSymbols = Record[0] & 2;
1955b915e9e0SDimitry Andric MetadataList.assignValue(
1956b915e9e0SDimitry Andric GET_OR_DISTINCT(DINamespace,
1957a303c417SDimitry Andric (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1958aac4ca60SDimitry Andric NextMetadataNo);
1959aac4ca60SDimitry Andric NextMetadataNo++;
1960b915e9e0SDimitry Andric break;
1961b915e9e0SDimitry Andric }
1962b915e9e0SDimitry Andric case bitc::METADATA_MACRO: {
1963b915e9e0SDimitry Andric if (Record.size() != 5)
1964b915e9e0SDimitry Andric return error("Invalid record");
1965b915e9e0SDimitry Andric
1966b915e9e0SDimitry Andric IsDistinct = Record[0];
1967b915e9e0SDimitry Andric MetadataList.assignValue(
1968b915e9e0SDimitry Andric GET_OR_DISTINCT(DIMacro,
1969b915e9e0SDimitry Andric (Context, Record[1], Record[2], getMDString(Record[3]),
1970b915e9e0SDimitry Andric getMDString(Record[4]))),
1971aac4ca60SDimitry Andric NextMetadataNo);
1972aac4ca60SDimitry Andric NextMetadataNo++;
1973b915e9e0SDimitry Andric break;
1974b915e9e0SDimitry Andric }
1975b915e9e0SDimitry Andric case bitc::METADATA_MACRO_FILE: {
1976b915e9e0SDimitry Andric if (Record.size() != 5)
1977b915e9e0SDimitry Andric return error("Invalid record");
1978b915e9e0SDimitry Andric
1979b915e9e0SDimitry Andric IsDistinct = Record[0];
1980b915e9e0SDimitry Andric MetadataList.assignValue(
1981b915e9e0SDimitry Andric GET_OR_DISTINCT(DIMacroFile,
1982b915e9e0SDimitry Andric (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1983b915e9e0SDimitry Andric getMDOrNull(Record[4]))),
1984aac4ca60SDimitry Andric NextMetadataNo);
1985aac4ca60SDimitry Andric NextMetadataNo++;
1986b915e9e0SDimitry Andric break;
1987b915e9e0SDimitry Andric }
1988b915e9e0SDimitry Andric case bitc::METADATA_TEMPLATE_TYPE: {
1989cfca06d7SDimitry Andric if (Record.size() < 3 || Record.size() > 4)
1990b915e9e0SDimitry Andric return error("Invalid record");
1991b915e9e0SDimitry Andric
1992b915e9e0SDimitry Andric IsDistinct = Record[0];
1993cfca06d7SDimitry Andric MetadataList.assignValue(
1994cfca06d7SDimitry Andric GET_OR_DISTINCT(DITemplateTypeParameter,
1995b915e9e0SDimitry Andric (Context, getMDString(Record[1]),
1996cfca06d7SDimitry Andric getDITypeRefOrNull(Record[2]),
1997cfca06d7SDimitry Andric (Record.size() == 4) ? getMDOrNull(Record[3])
1998cfca06d7SDimitry Andric : getMDOrNull(false))),
1999aac4ca60SDimitry Andric NextMetadataNo);
2000aac4ca60SDimitry Andric NextMetadataNo++;
2001b915e9e0SDimitry Andric break;
2002b915e9e0SDimitry Andric }
2003b915e9e0SDimitry Andric case bitc::METADATA_TEMPLATE_VALUE: {
2004cfca06d7SDimitry Andric if (Record.size() < 5 || Record.size() > 6)
2005b915e9e0SDimitry Andric return error("Invalid record");
2006b915e9e0SDimitry Andric
2007b915e9e0SDimitry Andric IsDistinct = Record[0];
2008cfca06d7SDimitry Andric
2009b915e9e0SDimitry Andric MetadataList.assignValue(
2010cfca06d7SDimitry Andric GET_OR_DISTINCT(
2011cfca06d7SDimitry Andric DITemplateValueParameter,
2012b915e9e0SDimitry Andric (Context, Record[1], getMDString(Record[2]),
2013b915e9e0SDimitry Andric getDITypeRefOrNull(Record[3]),
2014cfca06d7SDimitry Andric (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
2015cfca06d7SDimitry Andric (Record.size() == 6) ? getMDOrNull(Record[5])
2016cfca06d7SDimitry Andric : getMDOrNull(Record[4]))),
2017aac4ca60SDimitry Andric NextMetadataNo);
2018aac4ca60SDimitry Andric NextMetadataNo++;
2019b915e9e0SDimitry Andric break;
2020b915e9e0SDimitry Andric }
2021b915e9e0SDimitry Andric case bitc::METADATA_GLOBAL_VAR: {
2022d8e91e46SDimitry Andric if (Record.size() < 11 || Record.size() > 13)
2023b915e9e0SDimitry Andric return error("Invalid record");
2024b915e9e0SDimitry Andric
2025b915e9e0SDimitry Andric IsDistinct = Record[0] & 1;
2026b915e9e0SDimitry Andric unsigned Version = Record[0] >> 1;
2027b915e9e0SDimitry Andric
2028d8e91e46SDimitry Andric if (Version == 2) {
2029c0981da4SDimitry Andric Metadata *Annotations = nullptr;
2030c0981da4SDimitry Andric if (Record.size() > 12)
2031c0981da4SDimitry Andric Annotations = getMDOrNull(Record[12]);
2032c0981da4SDimitry Andric
2033d8e91e46SDimitry Andric MetadataList.assignValue(
2034c0981da4SDimitry Andric GET_OR_DISTINCT(DIGlobalVariable,
2035c0981da4SDimitry Andric (Context, getMDOrNull(Record[1]),
2036c0981da4SDimitry Andric getMDString(Record[2]), getMDString(Record[3]),
2037c0981da4SDimitry Andric getMDOrNull(Record[4]), Record[5],
2038d8e91e46SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2039c0981da4SDimitry Andric getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2040c0981da4SDimitry Andric Record[11], Annotations)),
2041d8e91e46SDimitry Andric NextMetadataNo);
2042d8e91e46SDimitry Andric
2043d8e91e46SDimitry Andric NextMetadataNo++;
2044d8e91e46SDimitry Andric } else if (Version == 1) {
2045d8e91e46SDimitry Andric // No upgrade necessary. A null field will be introduced to indicate
2046d8e91e46SDimitry Andric // that no parameter information is available.
2047b915e9e0SDimitry Andric MetadataList.assignValue(
2048c0981da4SDimitry Andric GET_OR_DISTINCT(
2049c0981da4SDimitry Andric DIGlobalVariable,
2050c0981da4SDimitry Andric (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2051c0981da4SDimitry Andric getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2052b915e9e0SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2053c0981da4SDimitry Andric getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
2054aac4ca60SDimitry Andric NextMetadataNo);
2055d8e91e46SDimitry Andric
2056aac4ca60SDimitry Andric NextMetadataNo++;
2057b915e9e0SDimitry Andric } else if (Version == 0) {
2058b915e9e0SDimitry Andric // Upgrade old metadata, which stored a global variable reference or a
2059b915e9e0SDimitry Andric // ConstantInt here.
206071d5a254SDimitry Andric NeedUpgradeToDIGlobalVariableExpression = true;
2061b915e9e0SDimitry Andric Metadata *Expr = getMDOrNull(Record[9]);
2062b915e9e0SDimitry Andric uint32_t AlignInBits = 0;
2063b915e9e0SDimitry Andric if (Record.size() > 11) {
2064b915e9e0SDimitry Andric if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2065b915e9e0SDimitry Andric return error("Alignment value is too large");
2066b915e9e0SDimitry Andric AlignInBits = Record[11];
2067b915e9e0SDimitry Andric }
2068b915e9e0SDimitry Andric GlobalVariable *Attach = nullptr;
2069b915e9e0SDimitry Andric if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2070b915e9e0SDimitry Andric if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2071b915e9e0SDimitry Andric Attach = GV;
2072b915e9e0SDimitry Andric Expr = nullptr;
2073b915e9e0SDimitry Andric } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2074b915e9e0SDimitry Andric Expr = DIExpression::get(Context,
2075b915e9e0SDimitry Andric {dwarf::DW_OP_constu, CI->getZExtValue(),
2076b915e9e0SDimitry Andric dwarf::DW_OP_stack_value});
2077b915e9e0SDimitry Andric } else {
2078b915e9e0SDimitry Andric Expr = nullptr;
2079b915e9e0SDimitry Andric }
2080b915e9e0SDimitry Andric }
2081b915e9e0SDimitry Andric DIGlobalVariable *DGV = GET_OR_DISTINCT(
2082b915e9e0SDimitry Andric DIGlobalVariable,
2083b915e9e0SDimitry Andric (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2084b915e9e0SDimitry Andric getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2085b915e9e0SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2086c0981da4SDimitry Andric getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
2087b915e9e0SDimitry Andric
20883897d3b8SDimitry Andric DIGlobalVariableExpression *DGVE = nullptr;
20893897d3b8SDimitry Andric if (Attach || Expr)
2090044eb2f6SDimitry Andric DGVE = DIGlobalVariableExpression::getDistinct(
2091044eb2f6SDimitry Andric Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
2092b915e9e0SDimitry Andric if (Attach)
2093b915e9e0SDimitry Andric Attach->addDebugInfo(DGVE);
20943897d3b8SDimitry Andric
20953897d3b8SDimitry Andric auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
20963897d3b8SDimitry Andric MetadataList.assignValue(MDNode, NextMetadataNo);
20973897d3b8SDimitry Andric NextMetadataNo++;
2098b915e9e0SDimitry Andric } else
2099b915e9e0SDimitry Andric return error("Invalid record");
2100b915e9e0SDimitry Andric
2101b915e9e0SDimitry Andric break;
2102b915e9e0SDimitry Andric }
2103e3b55780SDimitry Andric case bitc::METADATA_ASSIGN_ID: {
2104e3b55780SDimitry Andric if (Record.size() != 1)
2105e3b55780SDimitry Andric return error("Invalid DIAssignID record.");
2106e3b55780SDimitry Andric
2107e3b55780SDimitry Andric IsDistinct = Record[0] & 1;
2108e3b55780SDimitry Andric if (!IsDistinct)
2109e3b55780SDimitry Andric return error("Invalid DIAssignID record. Must be distinct");
2110e3b55780SDimitry Andric
2111e3b55780SDimitry Andric MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2112e3b55780SDimitry Andric NextMetadataNo++;
2113e3b55780SDimitry Andric break;
2114e3b55780SDimitry Andric }
2115b915e9e0SDimitry Andric case bitc::METADATA_LOCAL_VAR: {
2116b915e9e0SDimitry Andric // 10th field is for the obseleted 'inlinedAt:' field.
2117b915e9e0SDimitry Andric if (Record.size() < 8 || Record.size() > 10)
2118b915e9e0SDimitry Andric return error("Invalid record");
2119b915e9e0SDimitry Andric
2120b915e9e0SDimitry Andric IsDistinct = Record[0] & 1;
2121b915e9e0SDimitry Andric bool HasAlignment = Record[0] & 2;
2122b915e9e0SDimitry Andric // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2123b915e9e0SDimitry Andric // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
212471d5a254SDimitry Andric // this is newer version of record which doesn't have artificial tag.
2125b915e9e0SDimitry Andric bool HasTag = !HasAlignment && Record.size() > 8;
2126b915e9e0SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
2127b915e9e0SDimitry Andric uint32_t AlignInBits = 0;
2128c0981da4SDimitry Andric Metadata *Annotations = nullptr;
2129b915e9e0SDimitry Andric if (HasAlignment) {
2130c0981da4SDimitry Andric if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2131b915e9e0SDimitry Andric return error("Alignment value is too large");
2132c0981da4SDimitry Andric AlignInBits = Record[8];
2133c0981da4SDimitry Andric if (Record.size() > 9)
2134c0981da4SDimitry Andric Annotations = getMDOrNull(Record[9]);
2135b915e9e0SDimitry Andric }
2136c0981da4SDimitry Andric
2137b915e9e0SDimitry Andric MetadataList.assignValue(
2138b915e9e0SDimitry Andric GET_OR_DISTINCT(DILocalVariable,
2139b915e9e0SDimitry Andric (Context, getMDOrNull(Record[1 + HasTag]),
2140b915e9e0SDimitry Andric getMDString(Record[2 + HasTag]),
2141b915e9e0SDimitry Andric getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2142b915e9e0SDimitry Andric getDITypeRefOrNull(Record[5 + HasTag]),
2143c0981da4SDimitry Andric Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2144aac4ca60SDimitry Andric NextMetadataNo);
2145aac4ca60SDimitry Andric NextMetadataNo++;
2146b915e9e0SDimitry Andric break;
2147b915e9e0SDimitry Andric }
2148eb11fae6SDimitry Andric case bitc::METADATA_LABEL: {
2149eb11fae6SDimitry Andric if (Record.size() != 5)
2150eb11fae6SDimitry Andric return error("Invalid record");
2151eb11fae6SDimitry Andric
2152eb11fae6SDimitry Andric IsDistinct = Record[0] & 1;
2153eb11fae6SDimitry Andric MetadataList.assignValue(
2154c0981da4SDimitry Andric GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
2155eb11fae6SDimitry Andric getMDString(Record[2]),
2156eb11fae6SDimitry Andric getMDOrNull(Record[3]), Record[4])),
2157eb11fae6SDimitry Andric NextMetadataNo);
2158eb11fae6SDimitry Andric NextMetadataNo++;
2159eb11fae6SDimitry Andric break;
2160eb11fae6SDimitry Andric }
2161b915e9e0SDimitry Andric case bitc::METADATA_EXPRESSION: {
2162b915e9e0SDimitry Andric if (Record.size() < 1)
2163b915e9e0SDimitry Andric return error("Invalid record");
2164b915e9e0SDimitry Andric
2165b915e9e0SDimitry Andric IsDistinct = Record[0] & 1;
2166d99dafe2SDimitry Andric uint64_t Version = Record[0] >> 1;
2167b915e9e0SDimitry Andric auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
21687c7aba6eSDimitry Andric
21697c7aba6eSDimitry Andric SmallVector<uint64_t, 6> Buffer;
21707c7aba6eSDimitry Andric if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
21717c7aba6eSDimitry Andric return Err;
2172b915e9e0SDimitry Andric
2173c0981da4SDimitry Andric MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2174c0981da4SDimitry Andric NextMetadataNo);
2175aac4ca60SDimitry Andric NextMetadataNo++;
2176b915e9e0SDimitry Andric break;
2177b915e9e0SDimitry Andric }
2178b915e9e0SDimitry Andric case bitc::METADATA_GLOBAL_VAR_EXPR: {
2179b915e9e0SDimitry Andric if (Record.size() != 3)
2180b915e9e0SDimitry Andric return error("Invalid record");
2181b915e9e0SDimitry Andric
2182b915e9e0SDimitry Andric IsDistinct = Record[0];
2183044eb2f6SDimitry Andric Metadata *Expr = getMDOrNull(Record[2]);
2184044eb2f6SDimitry Andric if (!Expr)
2185044eb2f6SDimitry Andric Expr = DIExpression::get(Context, {});
2186044eb2f6SDimitry Andric MetadataList.assignValue(
2187044eb2f6SDimitry Andric GET_OR_DISTINCT(DIGlobalVariableExpression,
2188044eb2f6SDimitry Andric (Context, getMDOrNull(Record[1]), Expr)),
2189aac4ca60SDimitry Andric NextMetadataNo);
2190aac4ca60SDimitry Andric NextMetadataNo++;
2191b915e9e0SDimitry Andric break;
2192b915e9e0SDimitry Andric }
2193b915e9e0SDimitry Andric case bitc::METADATA_OBJC_PROPERTY: {
2194b915e9e0SDimitry Andric if (Record.size() != 8)
2195b915e9e0SDimitry Andric return error("Invalid record");
2196b915e9e0SDimitry Andric
2197b915e9e0SDimitry Andric IsDistinct = Record[0];
2198b915e9e0SDimitry Andric MetadataList.assignValue(
2199b915e9e0SDimitry Andric GET_OR_DISTINCT(DIObjCProperty,
2200b915e9e0SDimitry Andric (Context, getMDString(Record[1]),
2201b915e9e0SDimitry Andric getMDOrNull(Record[2]), Record[3],
2202b915e9e0SDimitry Andric getMDString(Record[4]), getMDString(Record[5]),
2203b915e9e0SDimitry Andric Record[6], getDITypeRefOrNull(Record[7]))),
2204aac4ca60SDimitry Andric NextMetadataNo);
2205aac4ca60SDimitry Andric NextMetadataNo++;
2206b915e9e0SDimitry Andric break;
2207b915e9e0SDimitry Andric }
2208b915e9e0SDimitry Andric case bitc::METADATA_IMPORTED_ENTITY: {
2209145449b1SDimitry Andric if (Record.size() < 6 || Record.size() > 8)
2210145449b1SDimitry Andric return error("Invalid DIImportedEntity record");
2211b915e9e0SDimitry Andric
2212b915e9e0SDimitry Andric IsDistinct = Record[0];
2213c0981da4SDimitry Andric bool HasFile = (Record.size() >= 7);
2214c0981da4SDimitry Andric bool HasElements = (Record.size() >= 8);
2215b915e9e0SDimitry Andric MetadataList.assignValue(
2216b915e9e0SDimitry Andric GET_OR_DISTINCT(DIImportedEntity,
2217b915e9e0SDimitry Andric (Context, Record[1], getMDOrNull(Record[2]),
221893c91e39SDimitry Andric getDITypeRefOrNull(Record[3]),
221993c91e39SDimitry Andric HasFile ? getMDOrNull(Record[6]) : nullptr,
2220c0981da4SDimitry Andric HasFile ? Record[4] : 0, getMDString(Record[5]),
2221c0981da4SDimitry Andric HasElements ? getMDOrNull(Record[7]) : nullptr)),
2222aac4ca60SDimitry Andric NextMetadataNo);
2223aac4ca60SDimitry Andric NextMetadataNo++;
2224b915e9e0SDimitry Andric break;
2225b915e9e0SDimitry Andric }
2226b915e9e0SDimitry Andric case bitc::METADATA_STRING_OLD: {
2227b915e9e0SDimitry Andric std::string String(Record.begin(), Record.end());
2228b915e9e0SDimitry Andric
2229b915e9e0SDimitry Andric // Test for upgrading !llvm.loop.
2230b915e9e0SDimitry Andric HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
22317e7b6700SDimitry Andric ++NumMDStringLoaded;
2232b915e9e0SDimitry Andric Metadata *MD = MDString::get(Context, String);
2233aac4ca60SDimitry Andric MetadataList.assignValue(MD, NextMetadataNo);
2234aac4ca60SDimitry Andric NextMetadataNo++;
2235b915e9e0SDimitry Andric break;
2236b915e9e0SDimitry Andric }
22377e7b6700SDimitry Andric case bitc::METADATA_STRINGS: {
22387e7b6700SDimitry Andric auto CreateNextMDString = [&](StringRef Str) {
22397e7b6700SDimitry Andric ++NumMDStringLoaded;
2240aac4ca60SDimitry Andric MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2241aac4ca60SDimitry Andric NextMetadataNo++;
22427e7b6700SDimitry Andric };
22437e7b6700SDimitry Andric if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2244b915e9e0SDimitry Andric return Err;
2245b915e9e0SDimitry Andric break;
22467e7b6700SDimitry Andric }
2247b915e9e0SDimitry Andric case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2248b915e9e0SDimitry Andric if (Record.size() % 2 == 0)
2249b915e9e0SDimitry Andric return error("Invalid record");
2250b915e9e0SDimitry Andric unsigned ValueID = Record[0];
2251b915e9e0SDimitry Andric if (ValueID >= ValueList.size())
2252b915e9e0SDimitry Andric return error("Invalid record");
2253b915e9e0SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2254b915e9e0SDimitry Andric if (Error Err = parseGlobalObjectAttachment(
2255b915e9e0SDimitry Andric *GO, ArrayRef<uint64_t>(Record).slice(1)))
2256b915e9e0SDimitry Andric return Err;
2257b915e9e0SDimitry Andric break;
2258b915e9e0SDimitry Andric }
2259b915e9e0SDimitry Andric case bitc::METADATA_KIND: {
2260b915e9e0SDimitry Andric // Support older bitcode files that had METADATA_KIND records in a
2261b915e9e0SDimitry Andric // block with METADATA_BLOCK_ID.
2262b915e9e0SDimitry Andric if (Error Err = parseMetadataKindRecord(Record))
2263b915e9e0SDimitry Andric return Err;
2264b915e9e0SDimitry Andric break;
2265b915e9e0SDimitry Andric }
2266344a3780SDimitry Andric case bitc::METADATA_ARG_LIST: {
2267344a3780SDimitry Andric SmallVector<ValueAsMetadata *, 4> Elts;
2268344a3780SDimitry Andric Elts.reserve(Record.size());
2269344a3780SDimitry Andric for (uint64_t Elt : Record) {
2270344a3780SDimitry Andric Metadata *MD = getMD(Elt);
2271344a3780SDimitry Andric if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2272344a3780SDimitry Andric return error(
2273344a3780SDimitry Andric "Invalid record: DIArgList should not contain forward refs");
2274344a3780SDimitry Andric if (!isa<ValueAsMetadata>(MD))
2275344a3780SDimitry Andric return error("Invalid record");
2276344a3780SDimitry Andric Elts.push_back(cast<ValueAsMetadata>(MD));
2277344a3780SDimitry Andric }
2278344a3780SDimitry Andric
2279344a3780SDimitry Andric MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2280344a3780SDimitry Andric NextMetadataNo++;
2281344a3780SDimitry Andric break;
2282344a3780SDimitry Andric }
2283b915e9e0SDimitry Andric }
2284b915e9e0SDimitry Andric return Error::success();
22857e7b6700SDimitry Andric #undef GET_OR_DISTINCT
2286b915e9e0SDimitry Andric }
2287b915e9e0SDimitry Andric
parseMetadataStrings(ArrayRef<uint64_t> Record,StringRef Blob,function_ref<void (StringRef)> CallBack)2288b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
22897e7b6700SDimitry Andric ArrayRef<uint64_t> Record, StringRef Blob,
229071d5a254SDimitry Andric function_ref<void(StringRef)> CallBack) {
2291b915e9e0SDimitry Andric // All the MDStrings in the block are emitted together in a single
2292b915e9e0SDimitry Andric // record. The strings are concatenated and stored in a blob along with
2293b915e9e0SDimitry Andric // their sizes.
2294b915e9e0SDimitry Andric if (Record.size() != 2)
2295b915e9e0SDimitry Andric return error("Invalid record: metadata strings layout");
2296b915e9e0SDimitry Andric
2297b915e9e0SDimitry Andric unsigned NumStrings = Record[0];
2298b915e9e0SDimitry Andric unsigned StringsOffset = Record[1];
2299b915e9e0SDimitry Andric if (!NumStrings)
2300b915e9e0SDimitry Andric return error("Invalid record: metadata strings with no strings");
2301b915e9e0SDimitry Andric if (StringsOffset > Blob.size())
2302b915e9e0SDimitry Andric return error("Invalid record: metadata strings corrupt offset");
2303b915e9e0SDimitry Andric
2304b915e9e0SDimitry Andric StringRef Lengths = Blob.slice(0, StringsOffset);
2305b915e9e0SDimitry Andric SimpleBitstreamCursor R(Lengths);
2306b915e9e0SDimitry Andric
2307b915e9e0SDimitry Andric StringRef Strings = Blob.drop_front(StringsOffset);
2308b915e9e0SDimitry Andric do {
2309b915e9e0SDimitry Andric if (R.AtEndOfStream())
2310b915e9e0SDimitry Andric return error("Invalid record: metadata strings bad length");
2311b915e9e0SDimitry Andric
2312c0981da4SDimitry Andric uint32_t Size;
2313c0981da4SDimitry Andric if (Error E = R.ReadVBR(6).moveInto(Size))
2314c0981da4SDimitry Andric return E;
2315b915e9e0SDimitry Andric if (Strings.size() < Size)
2316b915e9e0SDimitry Andric return error("Invalid record: metadata strings truncated chars");
2317b915e9e0SDimitry Andric
23187e7b6700SDimitry Andric CallBack(Strings.slice(0, Size));
2319b915e9e0SDimitry Andric Strings = Strings.drop_front(Size);
2320b915e9e0SDimitry Andric } while (--NumStrings);
2321b915e9e0SDimitry Andric
2322b915e9e0SDimitry Andric return Error::success();
2323b915e9e0SDimitry Andric }
2324b915e9e0SDimitry Andric
parseGlobalObjectAttachment(GlobalObject & GO,ArrayRef<uint64_t> Record)2325b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2326b915e9e0SDimitry Andric GlobalObject &GO, ArrayRef<uint64_t> Record) {
2327b915e9e0SDimitry Andric assert(Record.size() % 2 == 0);
2328b915e9e0SDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2329b915e9e0SDimitry Andric auto K = MDKindMap.find(Record[I]);
2330b915e9e0SDimitry Andric if (K == MDKindMap.end())
2331b915e9e0SDimitry Andric return error("Invalid ID");
2332b60736ecSDimitry Andric MDNode *MD =
2333b60736ecSDimitry Andric dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2334b915e9e0SDimitry Andric if (!MD)
2335d8e91e46SDimitry Andric return error("Invalid metadata attachment: expect fwd ref to MDNode");
2336b915e9e0SDimitry Andric GO.addMetadata(K->second, *MD);
2337b915e9e0SDimitry Andric }
2338b915e9e0SDimitry Andric return Error::success();
2339b915e9e0SDimitry Andric }
2340b915e9e0SDimitry Andric
2341b915e9e0SDimitry Andric /// Parse metadata attachments.
parseMetadataAttachment(Function & F,ArrayRef<Instruction * > InstructionList)2342b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2343145449b1SDimitry Andric Function &F, ArrayRef<Instruction *> InstructionList) {
2344e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2345e6d15924SDimitry Andric return Err;
2346b915e9e0SDimitry Andric
2347b915e9e0SDimitry Andric SmallVector<uint64_t, 64> Record;
23487e7b6700SDimitry Andric PlaceholderQueue Placeholders;
23497e7b6700SDimitry Andric
2350b915e9e0SDimitry Andric while (true) {
2351c0981da4SDimitry Andric BitstreamEntry Entry;
2352c0981da4SDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2353c0981da4SDimitry Andric return E;
2354b915e9e0SDimitry Andric
2355b915e9e0SDimitry Andric switch (Entry.Kind) {
2356b915e9e0SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
2357b915e9e0SDimitry Andric case BitstreamEntry::Error:
2358b915e9e0SDimitry Andric return error("Malformed block");
2359b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
23607e7b6700SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
2361b915e9e0SDimitry Andric return Error::success();
2362b915e9e0SDimitry Andric case BitstreamEntry::Record:
2363b915e9e0SDimitry Andric // The interesting case.
2364b915e9e0SDimitry Andric break;
2365b915e9e0SDimitry Andric }
2366b915e9e0SDimitry Andric
2367b915e9e0SDimitry Andric // Read a metadata attachment record.
2368b915e9e0SDimitry Andric Record.clear();
23697e7b6700SDimitry Andric ++NumMDRecordLoaded;
2370e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2371e6d15924SDimitry Andric if (!MaybeRecord)
2372e6d15924SDimitry Andric return MaybeRecord.takeError();
2373e6d15924SDimitry Andric switch (MaybeRecord.get()) {
2374b915e9e0SDimitry Andric default: // Default behavior: ignore.
2375b915e9e0SDimitry Andric break;
2376b915e9e0SDimitry Andric case bitc::METADATA_ATTACHMENT: {
2377b915e9e0SDimitry Andric unsigned RecordLength = Record.size();
2378b915e9e0SDimitry Andric if (Record.empty())
2379b915e9e0SDimitry Andric return error("Invalid record");
2380b915e9e0SDimitry Andric if (RecordLength % 2 == 0) {
2381b915e9e0SDimitry Andric // A function attachment.
2382b915e9e0SDimitry Andric if (Error Err = parseGlobalObjectAttachment(F, Record))
2383b915e9e0SDimitry Andric return Err;
2384b915e9e0SDimitry Andric continue;
2385b915e9e0SDimitry Andric }
2386b915e9e0SDimitry Andric
2387b915e9e0SDimitry Andric // An instruction attachment.
2388b915e9e0SDimitry Andric Instruction *Inst = InstructionList[Record[0]];
2389b915e9e0SDimitry Andric for (unsigned i = 1; i != RecordLength; i = i + 2) {
2390b915e9e0SDimitry Andric unsigned Kind = Record[i];
2391b915e9e0SDimitry Andric DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2392b915e9e0SDimitry Andric if (I == MDKindMap.end())
2393b915e9e0SDimitry Andric return error("Invalid ID");
2394b915e9e0SDimitry Andric if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2395b915e9e0SDimitry Andric continue;
2396b915e9e0SDimitry Andric
23977e7b6700SDimitry Andric auto Idx = Record[i + 1];
23987e7b6700SDimitry Andric if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2399909545a8SDimitry Andric !MetadataList.lookup(Idx)) {
24007e7b6700SDimitry Andric // Load the attachment if it is in the lazy-loadable range and hasn't
24017e7b6700SDimitry Andric // been loaded yet.
24027e7b6700SDimitry Andric lazyLoadOneMetadata(Idx, Placeholders);
2403909545a8SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
2404909545a8SDimitry Andric }
24057e7b6700SDimitry Andric
24067e7b6700SDimitry Andric Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2407b915e9e0SDimitry Andric if (isa<LocalAsMetadata>(Node))
2408b915e9e0SDimitry Andric // Drop the attachment. This used to be legal, but there's no
2409b915e9e0SDimitry Andric // upgrade path.
2410b915e9e0SDimitry Andric break;
2411b915e9e0SDimitry Andric MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2412b915e9e0SDimitry Andric if (!MD)
2413b915e9e0SDimitry Andric return error("Invalid metadata attachment");
2414b915e9e0SDimitry Andric
2415b915e9e0SDimitry Andric if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2416b915e9e0SDimitry Andric MD = upgradeInstructionLoopAttachment(*MD);
2417b915e9e0SDimitry Andric
2418b915e9e0SDimitry Andric if (I->second == LLVMContext::MD_tbaa) {
2419b915e9e0SDimitry Andric assert(!MD->isTemporary() && "should load MDs before attachments");
2420b915e9e0SDimitry Andric MD = UpgradeTBAANode(*MD);
2421b915e9e0SDimitry Andric }
2422b915e9e0SDimitry Andric Inst->setMetadata(I->second, MD);
2423b915e9e0SDimitry Andric }
2424b915e9e0SDimitry Andric break;
2425b915e9e0SDimitry Andric }
2426b915e9e0SDimitry Andric }
2427b915e9e0SDimitry Andric }
2428b915e9e0SDimitry Andric }
2429b915e9e0SDimitry Andric
2430b915e9e0SDimitry Andric /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
parseMetadataKindRecord(SmallVectorImpl<uint64_t> & Record)2431b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2432b915e9e0SDimitry Andric SmallVectorImpl<uint64_t> &Record) {
2433b915e9e0SDimitry Andric if (Record.size() < 2)
2434b915e9e0SDimitry Andric return error("Invalid record");
2435b915e9e0SDimitry Andric
2436b915e9e0SDimitry Andric unsigned Kind = Record[0];
2437b915e9e0SDimitry Andric SmallString<8> Name(Record.begin() + 1, Record.end());
2438b915e9e0SDimitry Andric
2439b915e9e0SDimitry Andric unsigned NewKind = TheModule.getMDKindID(Name.str());
2440b915e9e0SDimitry Andric if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2441b915e9e0SDimitry Andric return error("Conflicting METADATA_KIND records");
2442b915e9e0SDimitry Andric return Error::success();
2443b915e9e0SDimitry Andric }
2444b915e9e0SDimitry Andric
2445b915e9e0SDimitry Andric /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
parseMetadataKinds()2446b915e9e0SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2447e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2448e6d15924SDimitry Andric return Err;
2449b915e9e0SDimitry Andric
2450b915e9e0SDimitry Andric SmallVector<uint64_t, 64> Record;
2451b915e9e0SDimitry Andric
2452b915e9e0SDimitry Andric // Read all the records.
2453b915e9e0SDimitry Andric while (true) {
2454c0981da4SDimitry Andric BitstreamEntry Entry;
2455c0981da4SDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2456c0981da4SDimitry Andric return E;
2457b915e9e0SDimitry Andric
2458b915e9e0SDimitry Andric switch (Entry.Kind) {
2459b915e9e0SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
2460b915e9e0SDimitry Andric case BitstreamEntry::Error:
2461b915e9e0SDimitry Andric return error("Malformed block");
2462b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
2463b915e9e0SDimitry Andric return Error::success();
2464b915e9e0SDimitry Andric case BitstreamEntry::Record:
2465b915e9e0SDimitry Andric // The interesting case.
2466b915e9e0SDimitry Andric break;
2467b915e9e0SDimitry Andric }
2468b915e9e0SDimitry Andric
2469b915e9e0SDimitry Andric // Read a record.
2470b915e9e0SDimitry Andric Record.clear();
24717e7b6700SDimitry Andric ++NumMDRecordLoaded;
2472e6d15924SDimitry Andric Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2473e6d15924SDimitry Andric if (!MaybeCode)
2474e6d15924SDimitry Andric return MaybeCode.takeError();
2475e6d15924SDimitry Andric switch (MaybeCode.get()) {
2476b915e9e0SDimitry Andric default: // Default behavior: ignore.
2477b915e9e0SDimitry Andric break;
2478b915e9e0SDimitry Andric case bitc::METADATA_KIND: {
2479b915e9e0SDimitry Andric if (Error Err = parseMetadataKindRecord(Record))
2480b915e9e0SDimitry Andric return Err;
2481b915e9e0SDimitry Andric break;
2482b915e9e0SDimitry Andric }
2483b915e9e0SDimitry Andric }
2484b915e9e0SDimitry Andric }
2485b915e9e0SDimitry Andric }
2486b915e9e0SDimitry Andric
operator =(MetadataLoader && RHS)2487b915e9e0SDimitry Andric MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2488b915e9e0SDimitry Andric Pimpl = std::move(RHS.Pimpl);
2489b915e9e0SDimitry Andric return *this;
2490b915e9e0SDimitry Andric }
MetadataLoader(MetadataLoader && RHS)2491b915e9e0SDimitry Andric MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2492b915e9e0SDimitry Andric : Pimpl(std::move(RHS.Pimpl)) {}
2493b915e9e0SDimitry Andric
2494b915e9e0SDimitry Andric MetadataLoader::~MetadataLoader() = default;
MetadataLoader(BitstreamCursor & Stream,Module & TheModule,BitcodeReaderValueList & ValueList,bool IsImporting,MetadataLoaderCallbacks Callbacks)2495b915e9e0SDimitry Andric MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2496b915e9e0SDimitry Andric BitcodeReaderValueList &ValueList,
2497b915e9e0SDimitry Andric bool IsImporting,
2498e3b55780SDimitry Andric MetadataLoaderCallbacks Callbacks)
24991d5ae102SDimitry Andric : Pimpl(std::make_unique<MetadataLoaderImpl>(
2500e3b55780SDimitry Andric Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
2501b915e9e0SDimitry Andric
parseMetadata(bool ModuleLevel)2502b915e9e0SDimitry Andric Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2503b915e9e0SDimitry Andric return Pimpl->parseMetadata(ModuleLevel);
2504b915e9e0SDimitry Andric }
2505b915e9e0SDimitry Andric
hasFwdRefs() const2506b915e9e0SDimitry Andric bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2507b915e9e0SDimitry Andric
2508b915e9e0SDimitry Andric /// Return the given metadata, creating a replaceable forward reference if
2509b915e9e0SDimitry Andric /// necessary.
getMetadataFwdRefOrLoad(unsigned Idx)251002a33680SDimitry Andric Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
251102a33680SDimitry Andric return Pimpl->getMetadataFwdRefOrLoad(Idx);
2512b915e9e0SDimitry Andric }
2513b915e9e0SDimitry Andric
lookupSubprogramForFunction(Function * F)2514b915e9e0SDimitry Andric DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2515b915e9e0SDimitry Andric return Pimpl->lookupSubprogramForFunction(F);
2516b915e9e0SDimitry Andric }
2517b915e9e0SDimitry Andric
parseMetadataAttachment(Function & F,ArrayRef<Instruction * > InstructionList)2518b915e9e0SDimitry Andric Error MetadataLoader::parseMetadataAttachment(
2519145449b1SDimitry Andric Function &F, ArrayRef<Instruction *> InstructionList) {
2520b915e9e0SDimitry Andric return Pimpl->parseMetadataAttachment(F, InstructionList);
2521b915e9e0SDimitry Andric }
2522b915e9e0SDimitry Andric
parseMetadataKinds()2523b915e9e0SDimitry Andric Error MetadataLoader::parseMetadataKinds() {
2524b915e9e0SDimitry Andric return Pimpl->parseMetadataKinds();
2525b915e9e0SDimitry Andric }
2526b915e9e0SDimitry Andric
setStripTBAA(bool StripTBAA)2527b915e9e0SDimitry Andric void MetadataLoader::setStripTBAA(bool StripTBAA) {
2528b915e9e0SDimitry Andric return Pimpl->setStripTBAA(StripTBAA);
2529b915e9e0SDimitry Andric }
2530b915e9e0SDimitry Andric
isStrippingTBAA()2531b915e9e0SDimitry Andric bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2532b915e9e0SDimitry Andric
size() const2533b915e9e0SDimitry Andric unsigned MetadataLoader::size() const { return Pimpl->size(); }
shrinkTo(unsigned N)2534b915e9e0SDimitry Andric void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2535d99dafe2SDimitry Andric
upgradeDebugIntrinsics(Function & F)2536d99dafe2SDimitry Andric void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2537d99dafe2SDimitry Andric return Pimpl->upgradeDebugIntrinsics(F);
2538d99dafe2SDimitry Andric }
2539