blob: 3aadee457bfc714a27203e474e39ff798a472e82 [file] [log] [blame]
Mehdi Aminief27db82016-12-12 19:34:26 +00001//===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "MetadataLoader.h"
11#include "ValueList.h"
12
13#include "llvm/ADT/APFloat.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
Mehdi Amini19ef4fa2017-01-04 22:54:33 +000017#include "llvm/ADT/DenseSet.h"
Mehdi Aminief27db82016-12-12 19:34:26 +000018#include "llvm/ADT/None.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
Mehdi Amini19ef4fa2017-01-04 22:54:33 +000022#include "llvm/ADT/Statistic.h"
Mehdi Aminief27db82016-12-12 19:34:26 +000023#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Triple.h"
25#include "llvm/ADT/Twine.h"
26#include "llvm/Bitcode/BitcodeReader.h"
27#include "llvm/Bitcode/BitstreamReader.h"
28#include "llvm/Bitcode/LLVMBitCodes.h"
29#include "llvm/IR/Argument.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/AutoUpgrade.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/CallSite.h"
34#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/Comdat.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/DebugInfo.h"
39#include "llvm/IR/DebugInfoMetadata.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/DiagnosticInfo.h"
43#include "llvm/IR/DiagnosticPrinter.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GVMaterializer.h"
46#include "llvm/IR/GlobalAlias.h"
47#include "llvm/IR/GlobalIFunc.h"
48#include "llvm/IR/GlobalIndirectSymbol.h"
49#include "llvm/IR/GlobalObject.h"
50#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/GlobalVariable.h"
52#include "llvm/IR/InlineAsm.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
55#include "llvm/IR/Instructions.h"
Adrian Prantl6825fb62017-04-18 01:21:53 +000056#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000057#include "llvm/IR/Intrinsics.h"
Mehdi Aminief27db82016-12-12 19:34:26 +000058#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/ModuleSummaryIndex.h"
61#include "llvm/IR/OperandTraits.h"
62#include "llvm/IR/Operator.h"
63#include "llvm/IR/TrackingMDRef.h"
64#include "llvm/IR/Type.h"
65#include "llvm/IR/ValueHandle.h"
66#include "llvm/Support/AtomicOrdering.h"
67#include "llvm/Support/Casting.h"
68#include "llvm/Support/CommandLine.h"
69#include "llvm/Support/Compiler.h"
70#include "llvm/Support/Debug.h"
71#include "llvm/Support/Error.h"
72#include "llvm/Support/ErrorHandling.h"
73#include "llvm/Support/ManagedStatic.h"
74#include "llvm/Support/MemoryBuffer.h"
75#include "llvm/Support/raw_ostream.h"
76#include <algorithm>
77#include <cassert>
78#include <cstddef>
79#include <cstdint>
80#include <deque>
81#include <limits>
82#include <map>
83#include <memory>
84#include <string>
85#include <system_error>
86#include <tuple>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91
Mehdi Amini19ef4fa2017-01-04 22:54:33 +000092#define DEBUG_TYPE "bitcode-reader"
93
94STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
95STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
96STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
97
Teresa Johnsona61f5e32016-12-16 21:25:01 +000098/// Flag whether we need to import full type definitions for ThinLTO.
99/// Currently needed for Darwin and LLDB.
100static cl::opt<bool> ImportFullTypeDefinitions(
101 "import-full-type-definitions", cl::init(false), cl::Hidden,
102 cl::desc("Import full type definitions for ThinLTO."));
103
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000104static cl::opt<bool> DisableLazyLoading(
105 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
106 cl::desc("Force disable the lazy-loading on-demand of metadata when "
107 "loading bitcode for importing."));
108
Mehdi Aminief27db82016-12-12 19:34:26 +0000109namespace {
110
111static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
112
113class BitcodeReaderMetadataList {
Mehdi Aminief27db82016-12-12 19:34:26 +0000114 /// Array of metadata references.
115 ///
116 /// Don't use std::vector here. Some versions of libc++ copy (instead of
117 /// move) on resize, and TrackingMDRef is very expensive to copy.
118 SmallVector<TrackingMDRef, 1> MetadataPtrs;
119
Mehdi Amini690952d2016-12-25 04:22:54 +0000120 /// The set of indices in MetadataPtrs above of forward references that were
121 /// generated.
122 SmallDenseSet<unsigned, 1> ForwardReference;
123
124 /// The set of indices in MetadataPtrs above of Metadata that need to be
125 /// resolved.
126 SmallDenseSet<unsigned, 1> UnresolvedNodes;
127
Mehdi Aminief27db82016-12-12 19:34:26 +0000128 /// Structures for resolving old type refs.
129 struct {
130 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
131 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
132 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
133 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
134 } OldTypeRefs;
135
136 LLVMContext &Context;
137
138public:
Mehdi Amini70a9cd42016-12-23 02:20:07 +0000139 BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
Mehdi Aminief27db82016-12-12 19:34:26 +0000140
141 // vector compatibility methods
142 unsigned size() const { return MetadataPtrs.size(); }
143 void resize(unsigned N) { MetadataPtrs.resize(N); }
144 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
145 void clear() { MetadataPtrs.clear(); }
146 Metadata *back() const { return MetadataPtrs.back(); }
147 void pop_back() { MetadataPtrs.pop_back(); }
148 bool empty() const { return MetadataPtrs.empty(); }
149
150 Metadata *operator[](unsigned i) const {
151 assert(i < MetadataPtrs.size());
152 return MetadataPtrs[i];
153 }
154
155 Metadata *lookup(unsigned I) const {
156 if (I < MetadataPtrs.size())
157 return MetadataPtrs[I];
158 return nullptr;
159 }
160
161 void shrinkTo(unsigned N) {
162 assert(N <= size() && "Invalid shrinkTo request!");
Mehdi Amini690952d2016-12-25 04:22:54 +0000163 assert(ForwardReference.empty() && "Unexpected forward refs");
164 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
Mehdi Aminief27db82016-12-12 19:34:26 +0000165 MetadataPtrs.resize(N);
166 }
167
168 /// Return the given metadata, creating a replaceable forward reference if
169 /// necessary.
170 Metadata *getMetadataFwdRef(unsigned Idx);
171
172 /// Return the the given metadata only if it is fully resolved.
173 ///
174 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
175 /// would give \c false.
176 Metadata *getMetadataIfResolved(unsigned Idx);
177
178 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
179 void assignValue(Metadata *MD, unsigned Idx);
180 void tryToResolveCycles();
Mehdi Amini690952d2016-12-25 04:22:54 +0000181 bool hasFwdRefs() const { return !ForwardReference.empty(); }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000182 int getNextFwdRef() {
183 assert(hasFwdRefs());
184 return *ForwardReference.begin();
185 }
Mehdi Aminief27db82016-12-12 19:34:26 +0000186
187 /// Upgrade a type that had an MDString reference.
188 void addTypeRef(MDString &UUID, DICompositeType &CT);
189
190 /// Upgrade a type that had an MDString reference.
191 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
192
193 /// Upgrade a type ref array that may have MDString references.
194 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
195
196private:
197 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
198};
199
200void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Mehdi Amini690952d2016-12-25 04:22:54 +0000201 if (auto *MDN = dyn_cast<MDNode>(MD))
202 if (!MDN->isResolved())
203 UnresolvedNodes.insert(Idx);
204
Mehdi Aminief27db82016-12-12 19:34:26 +0000205 if (Idx == size()) {
206 push_back(MD);
207 return;
208 }
209
210 if (Idx >= size())
211 resize(Idx + 1);
212
213 TrackingMDRef &OldMD = MetadataPtrs[Idx];
214 if (!OldMD) {
215 OldMD.reset(MD);
216 return;
217 }
218
219 // If there was a forward reference to this value, replace it.
220 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
221 PrevMD->replaceAllUsesWith(MD);
Mehdi Amini690952d2016-12-25 04:22:54 +0000222 ForwardReference.erase(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +0000223}
224
225Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
226 if (Idx >= size())
227 resize(Idx + 1);
228
229 if (Metadata *MD = MetadataPtrs[Idx])
230 return MD;
231
232 // Track forward refs to be resolved later.
Mehdi Amini690952d2016-12-25 04:22:54 +0000233 ForwardReference.insert(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +0000234
235 // Create and return a placeholder, which will later be RAUW'd.
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000236 ++NumMDNodeTemporary;
Mehdi Aminief27db82016-12-12 19:34:26 +0000237 Metadata *MD = MDNode::getTemporary(Context, None).release();
238 MetadataPtrs[Idx].reset(MD);
239 return MD;
240}
241
242Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
243 Metadata *MD = lookup(Idx);
244 if (auto *N = dyn_cast_or_null<MDNode>(MD))
245 if (!N->isResolved())
246 return nullptr;
247 return MD;
248}
249
250MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
251 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
252}
253
254void BitcodeReaderMetadataList::tryToResolveCycles() {
Mehdi Amini690952d2016-12-25 04:22:54 +0000255 if (!ForwardReference.empty())
Mehdi Aminief27db82016-12-12 19:34:26 +0000256 // Still forward references... can't resolve cycles.
257 return;
258
Mehdi Aminief27db82016-12-12 19:34:26 +0000259 // Give up on finding a full definition for any forward decls that remain.
260 for (const auto &Ref : OldTypeRefs.FwdDecls)
261 OldTypeRefs.Final.insert(Ref);
262 OldTypeRefs.FwdDecls.clear();
263
264 // Upgrade from old type ref arrays. In strange cases, this could add to
265 // OldTypeRefs.Unknown.
Mehdi Amini690952d2016-12-25 04:22:54 +0000266 for (const auto &Array : OldTypeRefs.Arrays)
Mehdi Aminief27db82016-12-12 19:34:26 +0000267 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
Mehdi Aminief27db82016-12-12 19:34:26 +0000268 OldTypeRefs.Arrays.clear();
269
270 // Replace old string-based type refs with the resolved node, if possible.
271 // If we haven't seen the node, leave it to the verifier to complain about
272 // the invalid string reference.
273 for (const auto &Ref : OldTypeRefs.Unknown) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000274 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
275 Ref.second->replaceAllUsesWith(CT);
276 else
277 Ref.second->replaceAllUsesWith(Ref.first);
278 }
279 OldTypeRefs.Unknown.clear();
280
Mehdi Amini690952d2016-12-25 04:22:54 +0000281 if (UnresolvedNodes.empty())
Mehdi Aminief27db82016-12-12 19:34:26 +0000282 // Nothing to do.
283 return;
284
285 // Resolve any cycles.
Mehdi Amini690952d2016-12-25 04:22:54 +0000286 for (unsigned I : UnresolvedNodes) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000287 auto &MD = MetadataPtrs[I];
288 auto *N = dyn_cast_or_null<MDNode>(MD);
289 if (!N)
290 continue;
291
292 assert(!N->isTemporary() && "Unexpected forward reference");
293 N->resolveCycles();
294 }
295
Mehdi Amini690952d2016-12-25 04:22:54 +0000296 // Make sure we return early again until there's another unresolved ref.
297 UnresolvedNodes.clear();
Mehdi Aminief27db82016-12-12 19:34:26 +0000298}
299
300void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
301 DICompositeType &CT) {
302 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
303 if (CT.isForwardDecl())
304 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
305 else
306 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
307}
308
309Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
310 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
311 if (LLVM_LIKELY(!UUID))
312 return MaybeUUID;
313
314 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
315 return CT;
316
317 auto &Ref = OldTypeRefs.Unknown[UUID];
318 if (!Ref)
319 Ref = MDNode::getTemporary(Context, None);
320 return Ref.get();
321}
322
323Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
324 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
325 if (!Tuple || Tuple->isDistinct())
326 return MaybeTuple;
327
328 // Look through the array immediately if possible.
329 if (!Tuple->isTemporary())
330 return resolveTypeRefArray(Tuple);
331
332 // Create and return a placeholder to use for now. Eventually
333 // resolveTypeRefArrays() will be resolve this forward reference.
334 OldTypeRefs.Arrays.emplace_back(
335 std::piecewise_construct, std::forward_as_tuple(Tuple),
336 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
337 return OldTypeRefs.Arrays.back().second.get();
338}
339
340Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
341 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
342 if (!Tuple || Tuple->isDistinct())
343 return MaybeTuple;
344
345 // Look through the DITypeRefArray, upgrading each DITypeRef.
346 SmallVector<Metadata *, 32> Ops;
347 Ops.reserve(Tuple->getNumOperands());
348 for (Metadata *MD : Tuple->operands())
349 Ops.push_back(upgradeTypeRef(MD));
350
351 return MDTuple::get(Context, Ops);
352}
353
354namespace {
355
356class PlaceholderQueue {
357 // Placeholders would thrash around when moved, so store in a std::deque
358 // instead of some sort of vector.
359 std::deque<DistinctMDOperandPlaceholder> PHs;
360
361public:
Mehdi Amini27379892017-01-20 10:18:32 +0000362 ~PlaceholderQueue() {
363 assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
364 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000365 bool empty() { return PHs.empty(); }
Mehdi Aminief27db82016-12-12 19:34:26 +0000366 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
367 void flush(BitcodeReaderMetadataList &MetadataList);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000368
369 /// Return the list of temporaries nodes in the queue, these need to be
370 /// loaded before we can flush the queue.
371 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
372 DenseSet<unsigned> &Temporaries) {
373 for (auto &PH : PHs) {
374 auto ID = PH.getID();
375 auto *MD = MetadataList.lookup(ID);
376 if (!MD) {
377 Temporaries.insert(ID);
378 continue;
379 }
380 auto *N = dyn_cast_or_null<MDNode>(MD);
381 if (N && N->isTemporary())
382 Temporaries.insert(ID);
383 }
384 }
Mehdi Aminief27db82016-12-12 19:34:26 +0000385};
386
387} // end anonymous namespace
388
389DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
390 PHs.emplace_back(ID);
391 return PHs.back();
392}
393
394void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
395 while (!PHs.empty()) {
Mehdi Amini4f90ee02016-12-25 03:55:53 +0000396 auto *MD = MetadataList.lookup(PHs.front().getID());
397 assert(MD && "Flushing placeholder on unassigned MD");
Mehdi Amini5ae61702016-12-23 02:20:09 +0000398#ifndef NDEBUG
Mehdi Amini4f90ee02016-12-25 03:55:53 +0000399 if (auto *MDN = dyn_cast<MDNode>(MD))
Mehdi Amini5ae61702016-12-23 02:20:09 +0000400 assert(MDN->isResolved() &&
401 "Flushing Placeholder while cycles aren't resolved");
Mehdi Amini5ae61702016-12-23 02:20:09 +0000402#endif
403 PHs.front().replaceUseWith(MD);
Mehdi Aminief27db82016-12-12 19:34:26 +0000404 PHs.pop_front();
405 }
406}
407
408} // anonynous namespace
409
Florian Hahnffc498d2017-06-14 13:14:38 +0000410static Error error(const Twine &Message) {
411 return make_error<StringError>(
412 Message, make_error_code(BitcodeError::CorruptedBitcode));
413}
414
Mehdi Aminief27db82016-12-12 19:34:26 +0000415class MetadataLoader::MetadataLoaderImpl {
416 BitcodeReaderMetadataList MetadataList;
417 BitcodeReaderValueList &ValueList;
418 BitstreamCursor &Stream;
419 LLVMContext &Context;
420 Module &TheModule;
421 std::function<Type *(unsigned)> getTypeByID;
422
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000423 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
424 /// to keep around the right "context" (Abbrev list) to be able to jump in
425 /// the middle of the metadata block and load any record.
426 BitstreamCursor IndexCursor;
427
428 /// Index that keeps track of MDString values.
429 std::vector<StringRef> MDStringRef;
430
431 /// On-demand loading of a single MDString. Requires the index above to be
432 /// populated.
433 MDString *lazyLoadOneMDString(unsigned Idx);
434
435 /// Index that keeps track of where to find a metadata record in the stream.
436 std::vector<uint64_t> GlobalMetadataBitPosIndex;
437
438 /// Populate the index above to enable lazily loading of metadata, and load
439 /// the named metadata as well as the transitively referenced global
440 /// Metadata.
Mehdi Amini42ef1992017-01-07 18:31:38 +0000441 Expected<bool> lazyLoadModuleMetadataBlock();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000442
443 /// On-demand loading of a single metadata. Requires the index above to be
444 /// populated.
445 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
446
Mehdi Amini9f926f72016-12-23 03:59:18 +0000447 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
448 // point from SP to CU after a block is completly parsed.
449 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
450
Mehdi Aminief27db82016-12-12 19:34:26 +0000451 /// Functions that need to be matched with subprograms when upgrading old
452 /// metadata.
453 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
454
455 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
456 DenseMap<unsigned, unsigned> MDKindMap;
457
Mehdi Amini86623052016-12-16 19:16:29 +0000458 bool StripTBAA = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000459 bool HasSeenOldLoopTags = false;
Adrian Prantle37d3142017-02-07 17:35:41 +0000460 bool NeedUpgradeToDIGlobalVariableExpression = false;
Adrian Prantl6825fb62017-04-18 01:21:53 +0000461 bool NeedDeclareExpressionUpgrade = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000462
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000463 /// True if metadata is being parsed for a module being ThinLTO imported.
464 bool IsImporting = false;
465
Mehdi Amini9f926f72016-12-23 03:59:18 +0000466 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
467 PlaceholderQueue &Placeholders, StringRef Blob,
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000468 unsigned &NextMetadataNo);
Mehdi Aminief27db82016-12-12 19:34:26 +0000469 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000470 function_ref<void(StringRef)> CallBack);
Mehdi Aminief27db82016-12-12 19:34:26 +0000471 Error parseGlobalObjectAttachment(GlobalObject &GO,
472 ArrayRef<uint64_t> Record);
473 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
474
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000475 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
476
477 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
478 void upgradeCUSubprograms() {
479 for (auto CU_SP : CUSubprograms)
480 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
481 for (auto &Op : SPs->operands())
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000482 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
483 SP->replaceUnit(CU_SP.first);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000484 CUSubprograms.clear();
485 }
486
Adrian Prantle37d3142017-02-07 17:35:41 +0000487 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
488 void upgradeCUVariables() {
489 if (!NeedUpgradeToDIGlobalVariableExpression)
490 return;
491
492 // Upgrade list of variables attached to the CUs.
493 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
494 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
495 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
496 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
497 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
498 if (auto *GV =
499 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
Adrian Prantl05782212017-08-30 18:06:51 +0000500 auto *DGVE = DIGlobalVariableExpression::getDistinct(
501 Context, GV, DIExpression::get(Context, {}));
Adrian Prantle37d3142017-02-07 17:35:41 +0000502 GVs->replaceOperandWith(I, DGVE);
503 }
504 }
505
506 // Upgrade variables attached to globals.
507 for (auto &GV : TheModule.globals()) {
Davide Italiano56a08b42017-05-16 18:41:46 +0000508 SmallVector<MDNode *, 1> MDs;
Adrian Prantle37d3142017-02-07 17:35:41 +0000509 GV.getMetadata(LLVMContext::MD_dbg, MDs);
510 GV.eraseMetadata(LLVMContext::MD_dbg);
511 for (auto *MD : MDs)
512 if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
Adrian Prantl05782212017-08-30 18:06:51 +0000513 auto *DGVE = DIGlobalVariableExpression::getDistinct(
514 Context, DGV, DIExpression::get(Context, {}));
Adrian Prantle37d3142017-02-07 17:35:41 +0000515 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
516 } else
517 GV.addMetadata(LLVMContext::MD_dbg, *MD);
518 }
519 }
520
Adrian Prantl6825fb62017-04-18 01:21:53 +0000521 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
522 /// describes a function argument.
523 void upgradeDeclareExpressions(Function &F) {
524 if (!NeedDeclareExpressionUpgrade)
525 return;
526
527 for (auto &BB : F)
528 for (auto &I : BB)
529 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
530 if (auto *DIExpr = DDI->getExpression())
531 if (DIExpr->startsWithDeref() &&
532 dyn_cast_or_null<Argument>(DDI->getAddress())) {
533 SmallVector<uint64_t, 8> Ops;
534 Ops.append(std::next(DIExpr->elements_begin()),
535 DIExpr->elements_end());
536 auto *E = DIExpression::get(Context, Ops);
537 DDI->setOperand(2, MetadataAsValue::get(Context, E));
538 }
539 }
540
Florian Hahnffc498d2017-06-14 13:14:38 +0000541 /// Upgrade the expression from previous versions.
542 Error upgradeDIExpression(uint64_t FromVersion,
543 MutableArrayRef<uint64_t> &Expr,
544 SmallVectorImpl<uint64_t> &Buffer) {
545 auto N = Expr.size();
546 switch (FromVersion) {
547 default:
548 return error("Invalid record");
549 case 0:
550 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
551 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
552 LLVM_FALLTHROUGH;
553 case 1:
554 // Move DW_OP_deref to the end.
555 if (N && Expr[0] == dwarf::DW_OP_deref) {
556 auto End = Expr.end();
557 if (Expr.size() >= 3 &&
558 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
559 End = std::prev(End, 3);
560 std::move(std::next(Expr.begin()), End, Expr.begin());
561 *std::prev(End) = dwarf::DW_OP_deref;
562 }
563 NeedDeclareExpressionUpgrade = true;
564 LLVM_FALLTHROUGH;
565 case 2: {
566 // Change DW_OP_plus to DW_OP_plus_uconst.
567 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
568 auto SubExpr = ArrayRef<uint64_t>(Expr);
569 while (!SubExpr.empty()) {
570 // Skip past other operators with their operands
571 // for this version of the IR, obtained from
572 // from historic DIExpression::ExprOperand::getSize().
573 size_t HistoricSize;
574 switch (SubExpr.front()) {
575 default:
576 HistoricSize = 1;
577 break;
578 case dwarf::DW_OP_constu:
579 case dwarf::DW_OP_minus:
580 case dwarf::DW_OP_plus:
581 HistoricSize = 2;
582 break;
583 case dwarf::DW_OP_LLVM_fragment:
584 HistoricSize = 3;
585 break;
586 }
587
588 // If the expression is malformed, make sure we don't
589 // copy more elements than we should.
590 HistoricSize = std::min(SubExpr.size(), HistoricSize);
591 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize-1);
592
593 switch (SubExpr.front()) {
594 case dwarf::DW_OP_plus:
595 Buffer.push_back(dwarf::DW_OP_plus_uconst);
596 Buffer.append(Args.begin(), Args.end());
597 break;
598 case dwarf::DW_OP_minus:
599 Buffer.push_back(dwarf::DW_OP_constu);
600 Buffer.append(Args.begin(), Args.end());
601 Buffer.push_back(dwarf::DW_OP_minus);
602 break;
603 default:
604 Buffer.push_back(*SubExpr.begin());
605 Buffer.append(Args.begin(), Args.end());
606 break;
607 }
608
609 // Continue with remaining elements.
610 SubExpr = SubExpr.slice(HistoricSize);
611 }
612 Expr = MutableArrayRef<uint64_t>(Buffer);
613 LLVM_FALLTHROUGH;
614 }
615 case 3:
616 // Up-to-date!
617 break;
618 }
619
620 return Error::success();
621 }
622
Adrian Prantle37d3142017-02-07 17:35:41 +0000623 void upgradeDebugInfo() {
624 upgradeCUSubprograms();
625 upgradeCUVariables();
626 }
627
Mehdi Aminief27db82016-12-12 19:34:26 +0000628public:
629 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
630 BitcodeReaderValueList &ValueList,
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000631 std::function<Type *(unsigned)> getTypeByID,
632 bool IsImporting)
Mehdi Aminief27db82016-12-12 19:34:26 +0000633 : MetadataList(TheModule.getContext()), ValueList(ValueList),
634 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000635 getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
Mehdi Aminief27db82016-12-12 19:34:26 +0000636
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000637 Error parseMetadata(bool ModuleLevel);
Mehdi Aminief27db82016-12-12 19:34:26 +0000638
639 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000640
641 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
642 if (ID < MDStringRef.size())
643 return lazyLoadOneMDString(ID);
644 if (auto *MD = MetadataList.lookup(ID))
645 return MD;
646 // If lazy-loading is enabled, we try recursively to load the operand
647 // instead of creating a temporary.
648 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
649 PlaceholderQueue Placeholders;
650 lazyLoadOneMetadata(ID, Placeholders);
651 resolveForwardRefsAndPlaceholders(Placeholders);
652 return MetadataList.lookup(ID);
653 }
654 return MetadataList.getMetadataFwdRef(ID);
Mehdi Aminief27db82016-12-12 19:34:26 +0000655 }
656
657 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
658 return MetadataList.getMDNodeFwdRefOrNull(Idx);
659 }
660
661 DISubprogram *lookupSubprogramForFunction(Function *F) {
662 return FunctionsWithSPs.lookup(F);
663 }
664
665 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
666
667 Error parseMetadataAttachment(
668 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
669
670 Error parseMetadataKinds();
671
Mehdi Amini86623052016-12-16 19:16:29 +0000672 void setStripTBAA(bool Value) { StripTBAA = Value; }
673 bool isStrippingTBAA() { return StripTBAA; }
674
Mehdi Aminief27db82016-12-12 19:34:26 +0000675 unsigned size() const { return MetadataList.size(); }
676 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
Adrian Prantl6825fb62017-04-18 01:21:53 +0000677 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
Mehdi Aminief27db82016-12-12 19:34:26 +0000678};
679
Mehdi Amini42ef1992017-01-07 18:31:38 +0000680Expected<bool>
681MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000682 IndexCursor = Stream;
683 SmallVector<uint64_t, 64> Record;
684 // Get the abbrevs, and preload record positions to make them lazy-loadable.
685 while (true) {
686 BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
687 BitstreamCursor::AF_DontPopBlockAtEnd);
688 switch (Entry.Kind) {
689 case BitstreamEntry::SubBlock: // Handled for us already.
690 case BitstreamEntry::Error:
691 return error("Malformed block");
692 case BitstreamEntry::EndBlock: {
693 return true;
694 }
695 case BitstreamEntry::Record: {
696 // The interesting case.
697 ++NumMDRecordLoaded;
698 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
699 auto Code = IndexCursor.skipRecord(Entry.ID);
700 switch (Code) {
701 case bitc::METADATA_STRINGS: {
702 // Rewind and parse the strings.
703 IndexCursor.JumpToBit(CurrentPos);
704 StringRef Blob;
705 Record.clear();
706 IndexCursor.readRecord(Entry.ID, Record, &Blob);
707 unsigned NumStrings = Record[0];
708 MDStringRef.reserve(NumStrings);
709 auto IndexNextMDString = [&](StringRef Str) {
710 MDStringRef.push_back(Str);
711 };
712 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
713 return std::move(Err);
714 break;
715 }
716 case bitc::METADATA_INDEX_OFFSET: {
717 // This is the offset to the index, when we see this we skip all the
718 // records and load only an index to these.
719 IndexCursor.JumpToBit(CurrentPos);
720 Record.clear();
721 IndexCursor.readRecord(Entry.ID, Record);
722 if (Record.size() != 2)
723 return error("Invalid record");
724 auto Offset = Record[0] + (Record[1] << 32);
725 auto BeginPos = IndexCursor.GetCurrentBitNo();
726 IndexCursor.JumpToBit(BeginPos + Offset);
727 Entry = IndexCursor.advanceSkippingSubblocks(
728 BitstreamCursor::AF_DontPopBlockAtEnd);
729 assert(Entry.Kind == BitstreamEntry::Record &&
730 "Corrupted bitcode: Expected `Record` when trying to find the "
731 "Metadata index");
732 Record.clear();
733 auto Code = IndexCursor.readRecord(Entry.ID, Record);
734 (void)Code;
735 assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
736 "`METADATA_INDEX` when trying "
737 "to find the Metadata index");
738
739 // Delta unpack
740 auto CurrentValue = BeginPos;
741 GlobalMetadataBitPosIndex.reserve(Record.size());
742 for (auto &Elt : Record) {
743 CurrentValue += Elt;
744 GlobalMetadataBitPosIndex.push_back(CurrentValue);
745 }
746 break;
747 }
748 case bitc::METADATA_INDEX:
749 // We don't expect to get there, the Index is loaded when we encounter
750 // the offset.
751 return error("Corrupted Metadata block");
752 case bitc::METADATA_NAME: {
753 // Named metadata need to be materialized now and aren't deferred.
754 IndexCursor.JumpToBit(CurrentPos);
755 Record.clear();
756 unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
757 assert(Code == bitc::METADATA_NAME);
758
759 // Read name of the named metadata.
760 SmallString<8> Name(Record.begin(), Record.end());
761 Code = IndexCursor.ReadCode();
762
763 // Named Metadata comes in two parts, we expect the name to be followed
764 // by the node
765 Record.clear();
766 unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
767 assert(NextBitCode == bitc::METADATA_NAMED_NODE);
768 (void)NextBitCode;
769
770 // Read named metadata elements.
771 unsigned Size = Record.size();
772 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
773 for (unsigned i = 0; i != Size; ++i) {
774 // FIXME: We could use a placeholder here, however NamedMDNode are
775 // taking MDNode as operand and not using the Metadata infrastructure.
776 // It is acknowledged by 'TODO: Inherit from Metadata' in the
777 // NamedMDNode class definition.
778 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
779 assert(MD && "Invalid record");
780 NMD->addOperand(MD);
781 }
782 break;
783 }
784 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
785 // FIXME: we need to do this early because we don't materialize global
786 // value explicitly.
787 IndexCursor.JumpToBit(CurrentPos);
788 Record.clear();
789 IndexCursor.readRecord(Entry.ID, Record);
790 if (Record.size() % 2 == 0)
791 return error("Invalid record");
792 unsigned ValueID = Record[0];
793 if (ValueID >= ValueList.size())
794 return error("Invalid record");
795 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
796 if (Error Err = parseGlobalObjectAttachment(
797 *GO, ArrayRef<uint64_t>(Record).slice(1)))
798 return std::move(Err);
799 break;
800 }
801 case bitc::METADATA_KIND:
802 case bitc::METADATA_STRING_OLD:
803 case bitc::METADATA_OLD_FN_NODE:
804 case bitc::METADATA_OLD_NODE:
805 case bitc::METADATA_VALUE:
806 case bitc::METADATA_DISTINCT_NODE:
807 case bitc::METADATA_NODE:
808 case bitc::METADATA_LOCATION:
809 case bitc::METADATA_GENERIC_DEBUG:
810 case bitc::METADATA_SUBRANGE:
811 case bitc::METADATA_ENUMERATOR:
812 case bitc::METADATA_BASIC_TYPE:
813 case bitc::METADATA_DERIVED_TYPE:
814 case bitc::METADATA_COMPOSITE_TYPE:
815 case bitc::METADATA_SUBROUTINE_TYPE:
816 case bitc::METADATA_MODULE:
817 case bitc::METADATA_FILE:
818 case bitc::METADATA_COMPILE_UNIT:
819 case bitc::METADATA_SUBPROGRAM:
820 case bitc::METADATA_LEXICAL_BLOCK:
821 case bitc::METADATA_LEXICAL_BLOCK_FILE:
822 case bitc::METADATA_NAMESPACE:
823 case bitc::METADATA_MACRO:
824 case bitc::METADATA_MACRO_FILE:
825 case bitc::METADATA_TEMPLATE_TYPE:
826 case bitc::METADATA_TEMPLATE_VALUE:
827 case bitc::METADATA_GLOBAL_VAR:
828 case bitc::METADATA_LOCAL_VAR:
829 case bitc::METADATA_EXPRESSION:
830 case bitc::METADATA_OBJC_PROPERTY:
831 case bitc::METADATA_IMPORTED_ENTITY:
832 case bitc::METADATA_GLOBAL_VAR_EXPR:
833 // We don't expect to see any of these, if we see one, give up on
834 // lazy-loading and fallback.
835 MDStringRef.clear();
836 GlobalMetadataBitPosIndex.clear();
837 return false;
838 }
839 break;
840 }
841 }
842 }
843}
844
Mehdi Aminief27db82016-12-12 19:34:26 +0000845/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
846/// module level metadata.
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000847Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000848 if (!ModuleLevel && MetadataList.hasFwdRefs())
849 return error("Invalid metadata: fwd refs into function blocks");
850
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000851 // Record the entry position so that we can jump back here and efficiently
852 // skip the whole block in case we lazy-load.
853 auto EntryPos = Stream.GetCurrentBitNo();
854
Mehdi Aminief27db82016-12-12 19:34:26 +0000855 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
856 return error("Invalid record");
857
Mehdi Aminief27db82016-12-12 19:34:26 +0000858 SmallVector<uint64_t, 64> Record;
Mehdi Aminief27db82016-12-12 19:34:26 +0000859 PlaceholderQueue Placeholders;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000860
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000861 // We lazy-load module-level metadata: we build an index for each record, and
862 // then load individual record as needed, starting with the named metadata.
863 if (ModuleLevel && IsImporting && MetadataList.empty() &&
864 !DisableLazyLoading) {
Mehdi Amini42ef1992017-01-07 18:31:38 +0000865 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000866 if (!SuccessOrErr)
867 return SuccessOrErr.takeError();
868 if (SuccessOrErr.get()) {
869 // An index was successfully created and we will be able to load metadata
870 // on-demand.
871 MetadataList.resize(MDStringRef.size() +
872 GlobalMetadataBitPosIndex.size());
873
874 // Reading the named metadata created forward references and/or
875 // placeholders, that we flush here.
876 resolveForwardRefsAndPlaceholders(Placeholders);
Adrian Prantle37d3142017-02-07 17:35:41 +0000877 upgradeDebugInfo();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000878 // Return at the beginning of the block, since it is easy to skip it
879 // entirely from there.
880 Stream.ReadBlockEnd(); // Pop the abbrev block context.
881 Stream.JumpToBit(EntryPos);
882 if (Stream.SkipBlock())
883 return error("Invalid record");
884 return Error::success();
885 }
886 // Couldn't load an index, fallback to loading all the block "old-style".
887 }
888
889 unsigned NextMetadataNo = MetadataList.size();
890
Mehdi Amini9f926f72016-12-23 03:59:18 +0000891 // Read all the records.
892 while (true) {
893 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
894
895 switch (Entry.Kind) {
896 case BitstreamEntry::SubBlock: // Handled for us already.
897 case BitstreamEntry::Error:
898 return error("Malformed block");
899 case BitstreamEntry::EndBlock:
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000900 resolveForwardRefsAndPlaceholders(Placeholders);
Adrian Prantle37d3142017-02-07 17:35:41 +0000901 upgradeDebugInfo();
Mehdi Amini9f926f72016-12-23 03:59:18 +0000902 return Error::success();
903 case BitstreamEntry::Record:
904 // The interesting case.
905 break;
906 }
907
908 // Read a record.
909 Record.clear();
910 StringRef Blob;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000911 ++NumMDRecordLoaded;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000912 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000913 if (Error Err =
914 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
Mehdi Amini9f926f72016-12-23 03:59:18 +0000915 return Err;
916 }
917}
918
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000919MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
920 ++NumMDStringLoaded;
921 if (Metadata *MD = MetadataList.lookup(ID))
922 return cast<MDString>(MD);
923 auto MDS = MDString::get(Context, MDStringRef[ID]);
924 MetadataList.assignValue(MDS, ID);
925 return MDS;
926}
927
928void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
929 unsigned ID, PlaceholderQueue &Placeholders) {
930 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
931 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000932 // Lookup first if the metadata hasn't already been loaded.
933 if (auto *MD = MetadataList.lookup(ID)) {
934 auto *N = dyn_cast_or_null<MDNode>(MD);
Mehdi Amini67d2cc12017-01-18 18:36:21 +0000935 if (!N->isTemporary())
936 return;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000937 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000938 SmallVector<uint64_t, 64> Record;
939 StringRef Blob;
940 IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
941 auto Entry = IndexCursor.advanceSkippingSubblocks();
942 ++NumMDRecordLoaded;
943 unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
944 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
945 report_fatal_error("Can't lazyload MD");
946}
947
948/// Ensure that all forward-references and placeholders are resolved.
949/// Iteratively lazy-loading metadata on-demand if needed.
950void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
951 PlaceholderQueue &Placeholders) {
952 DenseSet<unsigned> Temporaries;
953 while (1) {
954 // Populate Temporaries with the placeholders that haven't been loaded yet.
955 Placeholders.getTemporaries(MetadataList, Temporaries);
956
957 // If we don't have any temporary, or FwdReference, we're done!
958 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
959 break;
960
961 // First, load all the temporaries. This can add new placeholders or
962 // forward references.
963 for (auto ID : Temporaries)
964 lazyLoadOneMetadata(ID, Placeholders);
965 Temporaries.clear();
966
967 // Second, load the forward-references. This can also add new placeholders
968 // or forward references.
969 while (MetadataList.hasFwdRefs())
970 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
971 }
972 // At this point we don't have any forward reference remaining, or temporary
973 // that haven't been loaded. We can safely drop RAUW support and mark cycles
974 // as resolved.
975 MetadataList.tryToResolveCycles();
976
977 // Finally, everything is in place, we can replace the placeholders operands
978 // with the final node they refer to.
979 Placeholders.flush(MetadataList);
980}
981
Mehdi Amini9f926f72016-12-23 03:59:18 +0000982Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
983 SmallVectorImpl<uint64_t> &Record, unsigned Code,
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000984 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
Mehdi Amini9f926f72016-12-23 03:59:18 +0000985
986 bool IsDistinct = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000987 auto getMD = [&](unsigned ID) -> Metadata * {
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000988 if (ID < MDStringRef.size())
989 return lazyLoadOneMDString(ID);
Mehdi Amini67d2cc12017-01-18 18:36:21 +0000990 if (!IsDistinct) {
991 if (auto *MD = MetadataList.lookup(ID))
992 return MD;
993 // If lazy-loading is enabled, we try recursively to load the operand
994 // instead of creating a temporary.
995 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
996 // Create a temporary for the node that is referencing the operand we
997 // will lazy-load. It is needed before recursing in case there are
998 // uniquing cycles.
999 MetadataList.getMetadataFwdRef(NextMetadataNo);
1000 lazyLoadOneMetadata(ID, Placeholders);
1001 return MetadataList.lookup(ID);
1002 }
1003 // Return a temporary.
Mehdi Aminief27db82016-12-12 19:34:26 +00001004 return MetadataList.getMetadataFwdRef(ID);
Mehdi Amini67d2cc12017-01-18 18:36:21 +00001005 }
Mehdi Aminief27db82016-12-12 19:34:26 +00001006 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1007 return MD;
1008 return &Placeholders.getPlaceholderOp(ID);
1009 };
1010 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1011 if (ID)
1012 return getMD(ID - 1);
1013 return nullptr;
1014 };
1015 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1016 if (ID)
1017 return MetadataList.getMetadataFwdRef(ID - 1);
1018 return nullptr;
1019 };
1020 auto getMDString = [&](unsigned ID) -> MDString * {
1021 // This requires that the ID is not really a forward reference. In
1022 // particular, the MDString must already have been resolved.
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001023 auto MDS = getMDOrNull(ID);
1024 return cast_or_null<MDString>(MDS);
Mehdi Aminief27db82016-12-12 19:34:26 +00001025 };
1026
1027 // Support for old type refs.
1028 auto getDITypeRefOrNull = [&](unsigned ID) {
1029 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1030 };
1031
1032#define GET_OR_DISTINCT(CLASS, ARGS) \
1033 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1034
Mehdi Amini9f926f72016-12-23 03:59:18 +00001035 switch (Code) {
1036 default: // Default behavior: ignore.
1037 break;
1038 case bitc::METADATA_NAME: {
1039 // Read name of the named metadata.
1040 SmallString<8> Name(Record.begin(), Record.end());
Mehdi Aminief27db82016-12-12 19:34:26 +00001041 Record.clear();
Mehdi Amini9f926f72016-12-23 03:59:18 +00001042 Code = Stream.ReadCode();
Mehdi Aminief27db82016-12-12 19:34:26 +00001043
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001044 ++NumMDRecordLoaded;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001045 unsigned NextBitCode = Stream.readRecord(Code, Record);
1046 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1047 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Mehdi Aminief27db82016-12-12 19:34:26 +00001048
Mehdi Amini9f926f72016-12-23 03:59:18 +00001049 // Read named metadata elements.
1050 unsigned Size = Record.size();
1051 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1052 for (unsigned i = 0; i != Size; ++i) {
1053 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1054 if (!MD)
1055 return error("Invalid record");
1056 NMD->addOperand(MD);
1057 }
1058 break;
1059 }
1060 case bitc::METADATA_OLD_FN_NODE: {
1061 // FIXME: Remove in 4.0.
1062 // This is a LocalAsMetadata record, the only type of function-local
1063 // metadata.
1064 if (Record.size() % 2 == 1)
1065 return error("Invalid record");
1066
1067 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1068 // to be legal, but there's no upgrade path.
1069 auto dropRecord = [&] {
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001070 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
1071 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001072 };
1073 if (Record.size() != 2) {
1074 dropRecord();
Mehdi Aminief27db82016-12-12 19:34:26 +00001075 break;
1076 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001077
1078 Type *Ty = getTypeByID(Record[0]);
1079 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1080 dropRecord();
1081 break;
1082 }
1083
1084 MetadataList.assignValue(
1085 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001086 NextMetadataNo);
1087 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001088 break;
1089 }
1090 case bitc::METADATA_OLD_NODE: {
1091 // FIXME: Remove in 4.0.
1092 if (Record.size() % 2 == 1)
1093 return error("Invalid record");
1094
1095 unsigned Size = Record.size();
1096 SmallVector<Metadata *, 8> Elts;
1097 for (unsigned i = 0; i != Size; i += 2) {
1098 Type *Ty = getTypeByID(Record[i]);
1099 if (!Ty)
Mehdi Aminief27db82016-12-12 19:34:26 +00001100 return error("Invalid record");
Mehdi Amini9f926f72016-12-23 03:59:18 +00001101 if (Ty->isMetadataTy())
1102 Elts.push_back(getMD(Record[i + 1]));
1103 else if (!Ty->isVoidTy()) {
1104 auto *MD =
1105 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1106 assert(isa<ConstantAsMetadata>(MD) &&
1107 "Expected non-function-local metadata");
1108 Elts.push_back(MD);
1109 } else
1110 Elts.push_back(nullptr);
1111 }
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001112 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1113 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001114 break;
1115 }
1116 case bitc::METADATA_VALUE: {
1117 if (Record.size() != 2)
1118 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001119
Mehdi Amini9f926f72016-12-23 03:59:18 +00001120 Type *Ty = getTypeByID(Record[0]);
1121 if (Ty->isMetadataTy() || Ty->isVoidTy())
1122 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001123
Mehdi Amini9f926f72016-12-23 03:59:18 +00001124 MetadataList.assignValue(
1125 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001126 NextMetadataNo);
1127 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001128 break;
1129 }
1130 case bitc::METADATA_DISTINCT_NODE:
1131 IsDistinct = true;
1132 LLVM_FALLTHROUGH;
1133 case bitc::METADATA_NODE: {
1134 SmallVector<Metadata *, 8> Elts;
1135 Elts.reserve(Record.size());
1136 for (unsigned ID : Record)
1137 Elts.push_back(getMDOrNull(ID));
1138 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1139 : MDNode::get(Context, Elts),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001140 NextMetadataNo);
1141 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001142 break;
1143 }
1144 case bitc::METADATA_LOCATION: {
1145 if (Record.size() != 5)
1146 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001147
Mehdi Amini9f926f72016-12-23 03:59:18 +00001148 IsDistinct = Record[0];
1149 unsigned Line = Record[1];
1150 unsigned Column = Record[2];
1151 Metadata *Scope = getMD(Record[3]);
1152 Metadata *InlinedAt = getMDOrNull(Record[4]);
1153 MetadataList.assignValue(
1154 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001155 NextMetadataNo);
1156 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001157 break;
1158 }
1159 case bitc::METADATA_GENERIC_DEBUG: {
1160 if (Record.size() < 4)
1161 return error("Invalid record");
1162
1163 IsDistinct = Record[0];
1164 unsigned Tag = Record[1];
1165 unsigned Version = Record[2];
1166
1167 if (Tag >= 1u << 16 || Version != 0)
1168 return error("Invalid record");
1169
1170 auto *Header = getMDString(Record[3]);
1171 SmallVector<Metadata *, 8> DwarfOps;
1172 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1173 DwarfOps.push_back(getMDOrNull(Record[I]));
1174 MetadataList.assignValue(
1175 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001176 NextMetadataNo);
1177 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001178 break;
1179 }
1180 case bitc::METADATA_SUBRANGE: {
1181 if (Record.size() != 3)
1182 return error("Invalid record");
1183
1184 IsDistinct = Record[0];
1185 MetadataList.assignValue(
1186 GET_OR_DISTINCT(DISubrange,
1187 (Context, Record[1], unrotateSign(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001188 NextMetadataNo);
1189 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001190 break;
1191 }
1192 case bitc::METADATA_ENUMERATOR: {
1193 if (Record.size() != 3)
1194 return error("Invalid record");
1195
1196 IsDistinct = Record[0];
1197 MetadataList.assignValue(
1198 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1199 getMDString(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001200 NextMetadataNo);
1201 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001202 break;
1203 }
1204 case bitc::METADATA_BASIC_TYPE: {
1205 if (Record.size() != 6)
1206 return error("Invalid record");
1207
1208 IsDistinct = Record[0];
1209 MetadataList.assignValue(
1210 GET_OR_DISTINCT(DIBasicType,
1211 (Context, Record[1], getMDString(Record[2]), Record[3],
1212 Record[4], Record[5])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001213 NextMetadataNo);
1214 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001215 break;
1216 }
1217 case bitc::METADATA_DERIVED_TYPE: {
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001218 if (Record.size() < 12 || Record.size() > 13)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001219 return error("Invalid record");
1220
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001221 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1222 // that there is no DWARF address space associated with DIDerivedType.
1223 Optional<unsigned> DWARFAddressSpace;
1224 if (Record.size() > 12 && Record[12])
1225 DWARFAddressSpace = Record[12] - 1;
1226
Mehdi Amini9f926f72016-12-23 03:59:18 +00001227 IsDistinct = Record[0];
1228 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1229 MetadataList.assignValue(
1230 GET_OR_DISTINCT(DIDerivedType,
1231 (Context, Record[1], getMDString(Record[2]),
1232 getMDOrNull(Record[3]), Record[4],
1233 getDITypeRefOrNull(Record[5]),
1234 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001235 Record[9], DWARFAddressSpace, Flags,
1236 getDITypeRefOrNull(Record[11]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001237 NextMetadataNo);
1238 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001239 break;
1240 }
1241 case bitc::METADATA_COMPOSITE_TYPE: {
1242 if (Record.size() != 16)
1243 return error("Invalid record");
1244
1245 // If we have a UUID and this is not a forward declaration, lookup the
1246 // mapping.
1247 IsDistinct = Record[0] & 0x1;
1248 bool IsNotUsedInTypeRef = Record[0] >= 2;
1249 unsigned Tag = Record[1];
1250 MDString *Name = getMDString(Record[2]);
1251 Metadata *File = getMDOrNull(Record[3]);
1252 unsigned Line = Record[4];
1253 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1254 Metadata *BaseType = nullptr;
1255 uint64_t SizeInBits = Record[7];
1256 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1257 return error("Alignment value is too large");
1258 uint32_t AlignInBits = Record[8];
1259 uint64_t OffsetInBits = 0;
1260 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1261 Metadata *Elements = nullptr;
1262 unsigned RuntimeLang = Record[12];
1263 Metadata *VTableHolder = nullptr;
1264 Metadata *TemplateParams = nullptr;
1265 auto *Identifier = getMDString(Record[15]);
1266 // If this module is being parsed so that it can be ThinLTO imported
1267 // into another module, composite types only need to be imported
1268 // as type declarations (unless full type definitions requested).
1269 // Create type declarations up front to save memory. Also, buildODRType
1270 // handles the case where this is type ODRed with a definition needed
1271 // by the importing module, in which case the existing definition is
1272 // used.
Teresa Johnson5a8dba52017-01-03 23:19:29 +00001273 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
Mehdi Amini9f926f72016-12-23 03:59:18 +00001274 (Tag == dwarf::DW_TAG_enumeration_type ||
1275 Tag == dwarf::DW_TAG_class_type ||
1276 Tag == dwarf::DW_TAG_structure_type ||
1277 Tag == dwarf::DW_TAG_union_type)) {
1278 Flags = Flags | DINode::FlagFwdDecl;
1279 } else {
1280 BaseType = getDITypeRefOrNull(Record[6]);
1281 OffsetInBits = Record[9];
1282 Elements = getMDOrNull(Record[11]);
1283 VTableHolder = getDITypeRefOrNull(Record[13]);
1284 TemplateParams = getMDOrNull(Record[14]);
1285 }
1286 DICompositeType *CT = nullptr;
1287 if (Identifier)
1288 CT = DICompositeType::buildODRType(
1289 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1290 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1291 VTableHolder, TemplateParams);
1292
1293 // Create a node if we didn't get a lazy ODR type.
1294 if (!CT)
1295 CT = GET_OR_DISTINCT(DICompositeType,
1296 (Context, Tag, Name, File, Line, Scope, BaseType,
1297 SizeInBits, AlignInBits, OffsetInBits, Flags,
1298 Elements, RuntimeLang, VTableHolder, TemplateParams,
1299 Identifier));
1300 if (!IsNotUsedInTypeRef && Identifier)
1301 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1302
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001303 MetadataList.assignValue(CT, NextMetadataNo);
1304 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001305 break;
1306 }
1307 case bitc::METADATA_SUBROUTINE_TYPE: {
1308 if (Record.size() < 3 || Record.size() > 4)
1309 return error("Invalid record");
1310 bool IsOldTypeRefArray = Record[0] < 2;
1311 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1312
1313 IsDistinct = Record[0] & 0x1;
1314 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1315 Metadata *Types = getMDOrNull(Record[2]);
1316 if (LLVM_UNLIKELY(IsOldTypeRefArray))
1317 Types = MetadataList.upgradeTypeRefArray(Types);
1318
1319 MetadataList.assignValue(
1320 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001321 NextMetadataNo);
1322 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001323 break;
1324 }
1325
1326 case bitc::METADATA_MODULE: {
1327 if (Record.size() != 6)
1328 return error("Invalid record");
1329
1330 IsDistinct = Record[0];
1331 MetadataList.assignValue(
1332 GET_OR_DISTINCT(DIModule,
1333 (Context, getMDOrNull(Record[1]),
1334 getMDString(Record[2]), getMDString(Record[3]),
1335 getMDString(Record[4]), getMDString(Record[5]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001336 NextMetadataNo);
1337 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001338 break;
1339 }
1340
1341 case bitc::METADATA_FILE: {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001342 if (Record.size() != 3 && Record.size() != 5)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001343 return error("Invalid record");
1344
1345 IsDistinct = Record[0];
1346 MetadataList.assignValue(
1347 GET_OR_DISTINCT(
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001348 DIFile,
1349 (Context, getMDString(Record[1]), getMDString(Record[2]),
1350 Record.size() == 3 ? DIFile::CSK_None
1351 : static_cast<DIFile::ChecksumKind>(Record[3]),
1352 Record.size() == 3 ? nullptr : getMDString(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001353 NextMetadataNo);
1354 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001355 break;
1356 }
1357 case bitc::METADATA_COMPILE_UNIT: {
Dehao Chen0944a8c2017-02-01 22:45:09 +00001358 if (Record.size() < 14 || Record.size() > 18)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001359 return error("Invalid record");
1360
1361 // Ignore Record[0], which indicates whether this compile unit is
1362 // distinct. It's always distinct.
1363 IsDistinct = true;
1364 auto *CU = DICompileUnit::getDistinct(
1365 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1366 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1367 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1368 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1369 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1370 Record.size() <= 14 ? 0 : Record[14],
Dehao Chen0944a8c2017-02-01 22:45:09 +00001371 Record.size() <= 16 ? true : Record[16],
1372 Record.size() <= 17 ? false : Record[17]);
Mehdi Amini9f926f72016-12-23 03:59:18 +00001373
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001374 MetadataList.assignValue(CU, NextMetadataNo);
1375 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001376
1377 // Move the Upgrade the list of subprograms.
1378 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1379 CUSubprograms.push_back({CU, SPs});
1380 break;
1381 }
1382 case bitc::METADATA_SUBPROGRAM: {
Adrian Prantl1d12b882017-04-26 22:56:44 +00001383 if (Record.size() < 18 || Record.size() > 21)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001384 return error("Invalid record");
1385
1386 IsDistinct =
1387 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1388 // Version 1 has a Function as Record[15].
1389 // Version 2 has removed Record[15].
1390 // Version 3 has the Unit as Record[15].
1391 // Version 4 added thisAdjustment.
1392 bool HasUnit = Record[0] >= 2;
1393 if (HasUnit && Record.size() < 19)
1394 return error("Invalid record");
1395 Metadata *CUorFn = getMDOrNull(Record[15]);
1396 unsigned Offset = Record.size() >= 19 ? 1 : 0;
1397 bool HasFn = Offset && !HasUnit;
1398 bool HasThisAdj = Record.size() >= 20;
Adrian Prantl1d12b882017-04-26 22:56:44 +00001399 bool HasThrownTypes = Record.size() >= 21;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001400 DISubprogram *SP = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00001401 DISubprogram,
1402 (Context,
1403 getDITypeRefOrNull(Record[1]), // scope
1404 getMDString(Record[2]), // name
1405 getMDString(Record[3]), // linkageName
1406 getMDOrNull(Record[4]), // file
1407 Record[5], // line
1408 getMDOrNull(Record[6]), // type
1409 Record[7], // isLocal
1410 Record[8], // isDefinition
1411 Record[9], // scopeLine
1412 getDITypeRefOrNull(Record[10]), // containingType
1413 Record[11], // virtuality
1414 Record[12], // virtualIndex
1415 HasThisAdj ? Record[19] : 0, // thisAdjustment
1416 static_cast<DINode::DIFlags>(Record[13]), // flags
1417 Record[14], // isOptimized
1418 HasUnit ? CUorFn : nullptr, // unit
1419 getMDOrNull(Record[15 + Offset]), // templateParams
1420 getMDOrNull(Record[16 + Offset]), // declaration
1421 getMDOrNull(Record[17 + Offset]), // variables
1422 HasThrownTypes ? getMDOrNull(Record[20]) : nullptr // thrownTypes
1423 ));
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001424 MetadataList.assignValue(SP, NextMetadataNo);
1425 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001426
1427 // Upgrade sp->function mapping to function->sp mapping.
1428 if (HasFn) {
1429 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1430 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1431 if (F->isMaterializable())
1432 // Defer until materialized; unmaterialized functions may not have
1433 // metadata.
1434 FunctionsWithSPs[F] = SP;
1435 else if (!F->empty())
1436 F->setSubprogram(SP);
1437 }
1438 }
1439 break;
1440 }
1441 case bitc::METADATA_LEXICAL_BLOCK: {
1442 if (Record.size() != 5)
1443 return error("Invalid record");
1444
1445 IsDistinct = Record[0];
1446 MetadataList.assignValue(
1447 GET_OR_DISTINCT(DILexicalBlock,
1448 (Context, getMDOrNull(Record[1]),
1449 getMDOrNull(Record[2]), Record[3], Record[4])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001450 NextMetadataNo);
1451 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001452 break;
1453 }
1454 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1455 if (Record.size() != 4)
1456 return error("Invalid record");
1457
1458 IsDistinct = Record[0];
1459 MetadataList.assignValue(
1460 GET_OR_DISTINCT(DILexicalBlockFile,
1461 (Context, getMDOrNull(Record[1]),
1462 getMDOrNull(Record[2]), Record[3])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001463 NextMetadataNo);
1464 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001465 break;
1466 }
1467 case bitc::METADATA_NAMESPACE: {
Adrian Prantlfed4f392017-04-28 22:25:46 +00001468 // Newer versions of DINamespace dropped file and line.
1469 MDString *Name;
1470 if (Record.size() == 3)
1471 Name = getMDString(Record[2]);
1472 else if (Record.size() == 5)
1473 Name = getMDString(Record[3]);
1474 else
Mehdi Amini9f926f72016-12-23 03:59:18 +00001475 return error("Invalid record");
1476
1477 IsDistinct = Record[0] & 1;
1478 bool ExportSymbols = Record[0] & 2;
1479 MetadataList.assignValue(
1480 GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00001481 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001482 NextMetadataNo);
1483 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001484 break;
1485 }
1486 case bitc::METADATA_MACRO: {
1487 if (Record.size() != 5)
1488 return error("Invalid record");
1489
1490 IsDistinct = Record[0];
1491 MetadataList.assignValue(
1492 GET_OR_DISTINCT(DIMacro,
1493 (Context, Record[1], Record[2], getMDString(Record[3]),
1494 getMDString(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001495 NextMetadataNo);
1496 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001497 break;
1498 }
1499 case bitc::METADATA_MACRO_FILE: {
1500 if (Record.size() != 5)
1501 return error("Invalid record");
1502
1503 IsDistinct = Record[0];
1504 MetadataList.assignValue(
1505 GET_OR_DISTINCT(DIMacroFile,
1506 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1507 getMDOrNull(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001508 NextMetadataNo);
1509 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001510 break;
1511 }
1512 case bitc::METADATA_TEMPLATE_TYPE: {
1513 if (Record.size() != 3)
1514 return error("Invalid record");
1515
1516 IsDistinct = Record[0];
1517 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1518 (Context, getMDString(Record[1]),
1519 getDITypeRefOrNull(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001520 NextMetadataNo);
1521 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001522 break;
1523 }
1524 case bitc::METADATA_TEMPLATE_VALUE: {
1525 if (Record.size() != 5)
1526 return error("Invalid record");
1527
1528 IsDistinct = Record[0];
1529 MetadataList.assignValue(
1530 GET_OR_DISTINCT(DITemplateValueParameter,
1531 (Context, Record[1], getMDString(Record[2]),
1532 getDITypeRefOrNull(Record[3]),
1533 getMDOrNull(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001534 NextMetadataNo);
1535 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001536 break;
1537 }
1538 case bitc::METADATA_GLOBAL_VAR: {
1539 if (Record.size() < 11 || Record.size() > 12)
1540 return error("Invalid record");
1541
1542 IsDistinct = Record[0] & 1;
1543 unsigned Version = Record[0] >> 1;
1544
1545 if (Version == 1) {
Mehdi Aminief27db82016-12-12 19:34:26 +00001546 MetadataList.assignValue(
Mehdi Amini9f926f72016-12-23 03:59:18 +00001547 GET_OR_DISTINCT(DIGlobalVariable,
Mehdi Aminief27db82016-12-12 19:34:26 +00001548 (Context, getMDOrNull(Record[1]),
1549 getMDString(Record[2]), getMDString(Record[3]),
Mehdi Amini9f926f72016-12-23 03:59:18 +00001550 getMDOrNull(Record[4]), Record[5],
1551 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1552 getMDOrNull(Record[10]), Record[11])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001553 NextMetadataNo);
1554 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001555 } else if (Version == 0) {
1556 // Upgrade old metadata, which stored a global variable reference or a
1557 // ConstantInt here.
Adrian Prantla5bf2d72017-02-08 17:44:43 +00001558 NeedUpgradeToDIGlobalVariableExpression = true;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001559 Metadata *Expr = getMDOrNull(Record[9]);
Mehdi Aminief27db82016-12-12 19:34:26 +00001560 uint32_t AlignInBits = 0;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001561 if (Record.size() > 11) {
1562 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
Mehdi Aminief27db82016-12-12 19:34:26 +00001563 return error("Alignment value is too large");
Mehdi Amini9f926f72016-12-23 03:59:18 +00001564 AlignInBits = Record[11];
Mehdi Aminief27db82016-12-12 19:34:26 +00001565 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001566 GlobalVariable *Attach = nullptr;
1567 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1568 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1569 Attach = GV;
1570 Expr = nullptr;
1571 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1572 Expr = DIExpression::get(Context,
1573 {dwarf::DW_OP_constu, CI->getZExtValue(),
1574 dwarf::DW_OP_stack_value});
1575 } else {
1576 Expr = nullptr;
1577 }
1578 }
1579 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1580 DIGlobalVariable,
1581 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1582 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1583 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1584 getMDOrNull(Record[10]), AlignInBits));
1585
Adrian Prantle37d3142017-02-07 17:35:41 +00001586 DIGlobalVariableExpression *DGVE = nullptr;
1587 if (Attach || Expr)
Adrian Prantl05782212017-08-30 18:06:51 +00001588 DGVE = DIGlobalVariableExpression::getDistinct(
1589 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
Mehdi Amini9f926f72016-12-23 03:59:18 +00001590 if (Attach)
1591 Attach->addDebugInfo(DGVE);
Adrian Prantle37d3142017-02-07 17:35:41 +00001592
1593 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1594 MetadataList.assignValue(MDNode, NextMetadataNo);
1595 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001596 } else
1597 return error("Invalid record");
1598
1599 break;
1600 }
1601 case bitc::METADATA_LOCAL_VAR: {
1602 // 10th field is for the obseleted 'inlinedAt:' field.
1603 if (Record.size() < 8 || Record.size() > 10)
1604 return error("Invalid record");
1605
1606 IsDistinct = Record[0] & 1;
1607 bool HasAlignment = Record[0] & 2;
1608 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1609 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
Simon Pilgrim68168d12017-03-30 12:59:53 +00001610 // this is newer version of record which doesn't have artificial tag.
Mehdi Amini9f926f72016-12-23 03:59:18 +00001611 bool HasTag = !HasAlignment && Record.size() > 8;
1612 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1613 uint32_t AlignInBits = 0;
1614 if (HasAlignment) {
1615 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1616 return error("Alignment value is too large");
1617 AlignInBits = Record[8 + HasTag];
Mehdi Aminief27db82016-12-12 19:34:26 +00001618 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001619 MetadataList.assignValue(
1620 GET_OR_DISTINCT(DILocalVariable,
1621 (Context, getMDOrNull(Record[1 + HasTag]),
1622 getMDString(Record[2 + HasTag]),
1623 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1624 getDITypeRefOrNull(Record[5 + HasTag]),
1625 Record[6 + HasTag], Flags, AlignInBits)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001626 NextMetadataNo);
1627 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001628 break;
1629 }
1630 case bitc::METADATA_EXPRESSION: {
1631 if (Record.size() < 1)
1632 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001633
Mehdi Amini9f926f72016-12-23 03:59:18 +00001634 IsDistinct = Record[0] & 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001635 uint64_t Version = Record[0] >> 1;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001636 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001637
1638 SmallVector<uint64_t, 6> Buffer;
1639 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
1640 return Err;
Mehdi Aminief27db82016-12-12 19:34:26 +00001641
Mehdi Amini9f926f72016-12-23 03:59:18 +00001642 MetadataList.assignValue(
Florian Hahnffc498d2017-06-14 13:14:38 +00001643 GET_OR_DISTINCT(DIExpression, (Context, Elts)), NextMetadataNo);
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001644 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001645 break;
1646 }
1647 case bitc::METADATA_GLOBAL_VAR_EXPR: {
1648 if (Record.size() != 3)
1649 return error("Invalid record");
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001650
Mehdi Amini9f926f72016-12-23 03:59:18 +00001651 IsDistinct = Record[0];
Adrian Prantl05782212017-08-30 18:06:51 +00001652 Metadata *Expr = getMDOrNull(Record[2]);
1653 if (!Expr)
1654 Expr = DIExpression::get(Context, {});
1655 MetadataList.assignValue(
1656 GET_OR_DISTINCT(DIGlobalVariableExpression,
1657 (Context, getMDOrNull(Record[1]), Expr)),
1658 NextMetadataNo);
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001659 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001660 break;
1661 }
1662 case bitc::METADATA_OBJC_PROPERTY: {
1663 if (Record.size() != 8)
1664 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001665
Mehdi Amini9f926f72016-12-23 03:59:18 +00001666 IsDistinct = Record[0];
1667 MetadataList.assignValue(
1668 GET_OR_DISTINCT(DIObjCProperty,
1669 (Context, getMDString(Record[1]),
1670 getMDOrNull(Record[2]), Record[3],
1671 getMDString(Record[4]), getMDString(Record[5]),
1672 Record[6], getDITypeRefOrNull(Record[7]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001673 NextMetadataNo);
1674 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001675 break;
1676 }
1677 case bitc::METADATA_IMPORTED_ENTITY: {
Adrian Prantld63bfd22017-07-19 00:09:54 +00001678 if (Record.size() != 6 && Record.size() != 7)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001679 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001680
Mehdi Amini9f926f72016-12-23 03:59:18 +00001681 IsDistinct = Record[0];
Adrian Prantld63bfd22017-07-19 00:09:54 +00001682 bool HasFile = (Record.size() == 7);
Mehdi Amini9f926f72016-12-23 03:59:18 +00001683 MetadataList.assignValue(
1684 GET_OR_DISTINCT(DIImportedEntity,
1685 (Context, Record[1], getMDOrNull(Record[2]),
Adrian Prantld63bfd22017-07-19 00:09:54 +00001686 getDITypeRefOrNull(Record[3]),
1687 HasFile ? getMDOrNull(Record[6]) : nullptr,
1688 HasFile ? Record[4] : 0, getMDString(Record[5]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001689 NextMetadataNo);
1690 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001691 break;
1692 }
1693 case bitc::METADATA_STRING_OLD: {
1694 std::string String(Record.begin(), Record.end());
Mehdi Aminief27db82016-12-12 19:34:26 +00001695
Mehdi Amini9f926f72016-12-23 03:59:18 +00001696 // Test for upgrading !llvm.loop.
1697 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001698 ++NumMDStringLoaded;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001699 Metadata *MD = MDString::get(Context, String);
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001700 MetadataList.assignValue(MD, NextMetadataNo);
1701 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001702 break;
1703 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001704 case bitc::METADATA_STRINGS: {
1705 auto CreateNextMDString = [&](StringRef Str) {
1706 ++NumMDStringLoaded;
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001707 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
1708 NextMetadataNo++;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001709 };
1710 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
Mehdi Amini9f926f72016-12-23 03:59:18 +00001711 return Err;
1712 break;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001713 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001714 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1715 if (Record.size() % 2 == 0)
1716 return error("Invalid record");
1717 unsigned ValueID = Record[0];
1718 if (ValueID >= ValueList.size())
1719 return error("Invalid record");
1720 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1721 if (Error Err = parseGlobalObjectAttachment(
1722 *GO, ArrayRef<uint64_t>(Record).slice(1)))
Mehdi Aminief27db82016-12-12 19:34:26 +00001723 return Err;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001724 break;
1725 }
1726 case bitc::METADATA_KIND: {
1727 // Support older bitcode files that had METADATA_KIND records in a
1728 // block with METADATA_BLOCK_ID.
1729 if (Error Err = parseMetadataKindRecord(Record))
1730 return Err;
1731 break;
1732 }
Mehdi Aminief27db82016-12-12 19:34:26 +00001733 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001734 return Error::success();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001735#undef GET_OR_DISTINCT
Mehdi Aminief27db82016-12-12 19:34:26 +00001736}
1737
1738Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001739 ArrayRef<uint64_t> Record, StringRef Blob,
Benjamin Kramer061f4a52017-01-13 14:39:03 +00001740 function_ref<void(StringRef)> CallBack) {
Mehdi Aminief27db82016-12-12 19:34:26 +00001741 // All the MDStrings in the block are emitted together in a single
1742 // record. The strings are concatenated and stored in a blob along with
1743 // their sizes.
1744 if (Record.size() != 2)
1745 return error("Invalid record: metadata strings layout");
1746
1747 unsigned NumStrings = Record[0];
1748 unsigned StringsOffset = Record[1];
1749 if (!NumStrings)
1750 return error("Invalid record: metadata strings with no strings");
1751 if (StringsOffset > Blob.size())
1752 return error("Invalid record: metadata strings corrupt offset");
1753
1754 StringRef Lengths = Blob.slice(0, StringsOffset);
1755 SimpleBitstreamCursor R(Lengths);
1756
1757 StringRef Strings = Blob.drop_front(StringsOffset);
1758 do {
1759 if (R.AtEndOfStream())
1760 return error("Invalid record: metadata strings bad length");
1761
1762 unsigned Size = R.ReadVBR(6);
1763 if (Strings.size() < Size)
1764 return error("Invalid record: metadata strings truncated chars");
1765
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001766 CallBack(Strings.slice(0, Size));
Mehdi Aminief27db82016-12-12 19:34:26 +00001767 Strings = Strings.drop_front(Size);
1768 } while (--NumStrings);
1769
1770 return Error::success();
1771}
1772
1773Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1774 GlobalObject &GO, ArrayRef<uint64_t> Record) {
1775 assert(Record.size() % 2 == 0);
1776 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1777 auto K = MDKindMap.find(Record[I]);
1778 if (K == MDKindMap.end())
1779 return error("Invalid ID");
1780 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1781 if (!MD)
1782 return error("Invalid metadata attachment");
1783 GO.addMetadata(K->second, *MD);
1784 }
1785 return Error::success();
1786}
1787
1788/// Parse metadata attachments.
1789Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1790 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1791 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1792 return error("Invalid record");
1793
1794 SmallVector<uint64_t, 64> Record;
Mehdi Amini7b0d1452017-01-08 00:44:45 +00001795 PlaceholderQueue Placeholders;
Mehdi Aminief27db82016-12-12 19:34:26 +00001796
1797 while (true) {
1798 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1799
1800 switch (Entry.Kind) {
1801 case BitstreamEntry::SubBlock: // Handled for us already.
1802 case BitstreamEntry::Error:
1803 return error("Malformed block");
1804 case BitstreamEntry::EndBlock:
Mehdi Amini7b0d1452017-01-08 00:44:45 +00001805 resolveForwardRefsAndPlaceholders(Placeholders);
Mehdi Aminief27db82016-12-12 19:34:26 +00001806 return Error::success();
1807 case BitstreamEntry::Record:
1808 // The interesting case.
1809 break;
1810 }
1811
1812 // Read a metadata attachment record.
1813 Record.clear();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001814 ++NumMDRecordLoaded;
Mehdi Aminief27db82016-12-12 19:34:26 +00001815 switch (Stream.readRecord(Entry.ID, Record)) {
1816 default: // Default behavior: ignore.
1817 break;
1818 case bitc::METADATA_ATTACHMENT: {
1819 unsigned RecordLength = Record.size();
1820 if (Record.empty())
1821 return error("Invalid record");
1822 if (RecordLength % 2 == 0) {
1823 // A function attachment.
1824 if (Error Err = parseGlobalObjectAttachment(F, Record))
1825 return Err;
1826 continue;
1827 }
1828
1829 // An instruction attachment.
1830 Instruction *Inst = InstructionList[Record[0]];
1831 for (unsigned i = 1; i != RecordLength; i = i + 2) {
1832 unsigned Kind = Record[i];
1833 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1834 if (I == MDKindMap.end())
1835 return error("Invalid ID");
Mehdi Amini86623052016-12-16 19:16:29 +00001836 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1837 continue;
1838
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001839 auto Idx = Record[i + 1];
1840 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
Mehdi Aminid5549f32017-01-07 20:24:23 +00001841 !MetadataList.lookup(Idx)) {
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001842 // Load the attachment if it is in the lazy-loadable range and hasn't
1843 // been loaded yet.
1844 lazyLoadOneMetadata(Idx, Placeholders);
Mehdi Aminid5549f32017-01-07 20:24:23 +00001845 resolveForwardRefsAndPlaceholders(Placeholders);
1846 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001847
1848 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +00001849 if (isa<LocalAsMetadata>(Node))
1850 // Drop the attachment. This used to be legal, but there's no
1851 // upgrade path.
1852 break;
1853 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1854 if (!MD)
1855 return error("Invalid metadata attachment");
1856
1857 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1858 MD = upgradeInstructionLoopAttachment(*MD);
1859
1860 if (I->second == LLVMContext::MD_tbaa) {
1861 assert(!MD->isTemporary() && "should load MDs before attachments");
1862 MD = UpgradeTBAANode(*MD);
1863 }
1864 Inst->setMetadata(I->second, MD);
1865 }
1866 break;
1867 }
1868 }
1869 }
1870}
1871
1872/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1873Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1874 SmallVectorImpl<uint64_t> &Record) {
1875 if (Record.size() < 2)
1876 return error("Invalid record");
1877
1878 unsigned Kind = Record[0];
1879 SmallString<8> Name(Record.begin() + 1, Record.end());
1880
1881 unsigned NewKind = TheModule.getMDKindID(Name.str());
1882 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1883 return error("Conflicting METADATA_KIND records");
1884 return Error::success();
1885}
1886
1887/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1888Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1889 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1890 return error("Invalid record");
1891
1892 SmallVector<uint64_t, 64> Record;
1893
1894 // Read all the records.
1895 while (true) {
1896 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1897
1898 switch (Entry.Kind) {
1899 case BitstreamEntry::SubBlock: // Handled for us already.
1900 case BitstreamEntry::Error:
1901 return error("Malformed block");
1902 case BitstreamEntry::EndBlock:
1903 return Error::success();
1904 case BitstreamEntry::Record:
1905 // The interesting case.
1906 break;
1907 }
1908
1909 // Read a record.
1910 Record.clear();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001911 ++NumMDRecordLoaded;
Mehdi Aminief27db82016-12-12 19:34:26 +00001912 unsigned Code = Stream.readRecord(Entry.ID, Record);
1913 switch (Code) {
1914 default: // Default behavior: ignore.
1915 break;
1916 case bitc::METADATA_KIND: {
1917 if (Error Err = parseMetadataKindRecord(Record))
1918 return Err;
1919 break;
1920 }
1921 }
1922 }
1923}
1924
1925MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1926 Pimpl = std::move(RHS.Pimpl);
1927 return *this;
1928}
1929MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001930 : Pimpl(std::move(RHS.Pimpl)) {}
Mehdi Aminief27db82016-12-12 19:34:26 +00001931
1932MetadataLoader::~MetadataLoader() = default;
1933MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1934 BitcodeReaderValueList &ValueList,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00001935 bool IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00001936 std::function<Type *(unsigned)> getTypeByID)
Benjamin Kramer061f4a52017-01-13 14:39:03 +00001937 : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1938 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
Mehdi Aminief27db82016-12-12 19:34:26 +00001939
1940Error MetadataLoader::parseMetadata(bool ModuleLevel) {
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001941 return Pimpl->parseMetadata(ModuleLevel);
Mehdi Aminief27db82016-12-12 19:34:26 +00001942}
1943
1944bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1945
1946/// Return the given metadata, creating a replaceable forward reference if
1947/// necessary.
Mehdi Amini3bb4d012017-01-20 20:29:16 +00001948Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1949 return Pimpl->getMetadataFwdRefOrLoad(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +00001950}
1951
1952MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1953 return Pimpl->getMDNodeFwdRefOrNull(Idx);
1954}
1955
1956DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1957 return Pimpl->lookupSubprogramForFunction(F);
1958}
1959
1960Error MetadataLoader::parseMetadataAttachment(
1961 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1962 return Pimpl->parseMetadataAttachment(F, InstructionList);
1963}
1964
1965Error MetadataLoader::parseMetadataKinds() {
1966 return Pimpl->parseMetadataKinds();
1967}
1968
Mehdi Amini86623052016-12-16 19:16:29 +00001969void MetadataLoader::setStripTBAA(bool StripTBAA) {
1970 return Pimpl->setStripTBAA(StripTBAA);
1971}
1972
1973bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1974
Mehdi Aminief27db82016-12-12 19:34:26 +00001975unsigned MetadataLoader::size() const { return Pimpl->size(); }
1976void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
Adrian Prantl6825fb62017-04-18 01:21:53 +00001977
1978void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
1979 return Pimpl->upgradeDebugIntrinsics(F);
1980}