blob: 41985e2590caad046c315f12e1a7607f257f4dec [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"
56#include "llvm/IR/Intrinsics.h"
57#include "llvm/IR/LLVMContext.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/ModuleSummaryIndex.h"
60#include "llvm/IR/OperandTraits.h"
61#include "llvm/IR/Operator.h"
62#include "llvm/IR/TrackingMDRef.h"
63#include "llvm/IR/Type.h"
64#include "llvm/IR/ValueHandle.h"
65#include "llvm/Support/AtomicOrdering.h"
66#include "llvm/Support/Casting.h"
67#include "llvm/Support/CommandLine.h"
68#include "llvm/Support/Compiler.h"
69#include "llvm/Support/Debug.h"
70#include "llvm/Support/Error.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/ManagedStatic.h"
73#include "llvm/Support/MemoryBuffer.h"
74#include "llvm/Support/raw_ostream.h"
75#include <algorithm>
76#include <cassert>
77#include <cstddef>
78#include <cstdint>
79#include <deque>
80#include <limits>
81#include <map>
82#include <memory>
83#include <string>
84#include <system_error>
85#include <tuple>
86#include <utility>
87#include <vector>
88
89using namespace llvm;
90
Mehdi Amini19ef4fa2017-01-04 22:54:33 +000091#define DEBUG_TYPE "bitcode-reader"
92
93STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
94STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
95STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
96
Teresa Johnsona61f5e32016-12-16 21:25:01 +000097/// Flag whether we need to import full type definitions for ThinLTO.
98/// Currently needed for Darwin and LLDB.
99static cl::opt<bool> ImportFullTypeDefinitions(
100 "import-full-type-definitions", cl::init(false), cl::Hidden,
101 cl::desc("Import full type definitions for ThinLTO."));
102
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000103static cl::opt<bool> DisableLazyLoading(
104 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
105 cl::desc("Force disable the lazy-loading on-demand of metadata when "
106 "loading bitcode for importing."));
107
Mehdi Aminief27db82016-12-12 19:34:26 +0000108namespace {
109
110static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
111
112class BitcodeReaderMetadataList {
Mehdi Aminief27db82016-12-12 19:34:26 +0000113 /// Array of metadata references.
114 ///
115 /// Don't use std::vector here. Some versions of libc++ copy (instead of
116 /// move) on resize, and TrackingMDRef is very expensive to copy.
117 SmallVector<TrackingMDRef, 1> MetadataPtrs;
118
Mehdi Amini690952d2016-12-25 04:22:54 +0000119 /// The set of indices in MetadataPtrs above of forward references that were
120 /// generated.
121 SmallDenseSet<unsigned, 1> ForwardReference;
122
123 /// The set of indices in MetadataPtrs above of Metadata that need to be
124 /// resolved.
125 SmallDenseSet<unsigned, 1> UnresolvedNodes;
126
Mehdi Aminief27db82016-12-12 19:34:26 +0000127 /// Structures for resolving old type refs.
128 struct {
129 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
130 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
131 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
132 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
133 } OldTypeRefs;
134
135 LLVMContext &Context;
136
137public:
Mehdi Amini70a9cd42016-12-23 02:20:07 +0000138 BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
Mehdi Aminief27db82016-12-12 19:34:26 +0000139
140 // vector compatibility methods
141 unsigned size() const { return MetadataPtrs.size(); }
142 void resize(unsigned N) { MetadataPtrs.resize(N); }
143 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
144 void clear() { MetadataPtrs.clear(); }
145 Metadata *back() const { return MetadataPtrs.back(); }
146 void pop_back() { MetadataPtrs.pop_back(); }
147 bool empty() const { return MetadataPtrs.empty(); }
148
149 Metadata *operator[](unsigned i) const {
150 assert(i < MetadataPtrs.size());
151 return MetadataPtrs[i];
152 }
153
154 Metadata *lookup(unsigned I) const {
155 if (I < MetadataPtrs.size())
156 return MetadataPtrs[I];
157 return nullptr;
158 }
159
160 void shrinkTo(unsigned N) {
161 assert(N <= size() && "Invalid shrinkTo request!");
Mehdi Amini690952d2016-12-25 04:22:54 +0000162 assert(ForwardReference.empty() && "Unexpected forward refs");
163 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
Mehdi Aminief27db82016-12-12 19:34:26 +0000164 MetadataPtrs.resize(N);
165 }
166
167 /// Return the given metadata, creating a replaceable forward reference if
168 /// necessary.
169 Metadata *getMetadataFwdRef(unsigned Idx);
170
171 /// Return the the given metadata only if it is fully resolved.
172 ///
173 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
174 /// would give \c false.
175 Metadata *getMetadataIfResolved(unsigned Idx);
176
177 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
178 void assignValue(Metadata *MD, unsigned Idx);
179 void tryToResolveCycles();
Mehdi Amini690952d2016-12-25 04:22:54 +0000180 bool hasFwdRefs() const { return !ForwardReference.empty(); }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000181 int getNextFwdRef() {
182 assert(hasFwdRefs());
183 return *ForwardReference.begin();
184 }
Mehdi Aminief27db82016-12-12 19:34:26 +0000185
186 /// Upgrade a type that had an MDString reference.
187 void addTypeRef(MDString &UUID, DICompositeType &CT);
188
189 /// Upgrade a type that had an MDString reference.
190 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
191
192 /// Upgrade a type ref array that may have MDString references.
193 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
194
195private:
196 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
197};
198
199void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Mehdi Amini690952d2016-12-25 04:22:54 +0000200 if (auto *MDN = dyn_cast<MDNode>(MD))
201 if (!MDN->isResolved())
202 UnresolvedNodes.insert(Idx);
203
Mehdi Aminief27db82016-12-12 19:34:26 +0000204 if (Idx == size()) {
205 push_back(MD);
206 return;
207 }
208
209 if (Idx >= size())
210 resize(Idx + 1);
211
212 TrackingMDRef &OldMD = MetadataPtrs[Idx];
213 if (!OldMD) {
214 OldMD.reset(MD);
215 return;
216 }
217
218 // If there was a forward reference to this value, replace it.
219 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
220 PrevMD->replaceAllUsesWith(MD);
Mehdi Amini690952d2016-12-25 04:22:54 +0000221 ForwardReference.erase(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +0000222}
223
224Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
225 if (Idx >= size())
226 resize(Idx + 1);
227
228 if (Metadata *MD = MetadataPtrs[Idx])
229 return MD;
230
231 // Track forward refs to be resolved later.
Mehdi Amini690952d2016-12-25 04:22:54 +0000232 ForwardReference.insert(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +0000233
234 // Create and return a placeholder, which will later be RAUW'd.
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000235 ++NumMDNodeTemporary;
Mehdi Aminief27db82016-12-12 19:34:26 +0000236 Metadata *MD = MDNode::getTemporary(Context, None).release();
237 MetadataPtrs[Idx].reset(MD);
238 return MD;
239}
240
241Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
242 Metadata *MD = lookup(Idx);
243 if (auto *N = dyn_cast_or_null<MDNode>(MD))
244 if (!N->isResolved())
245 return nullptr;
246 return MD;
247}
248
249MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
250 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
251}
252
253void BitcodeReaderMetadataList::tryToResolveCycles() {
Mehdi Amini690952d2016-12-25 04:22:54 +0000254 if (!ForwardReference.empty())
Mehdi Aminief27db82016-12-12 19:34:26 +0000255 // Still forward references... can't resolve cycles.
256 return;
257
Mehdi Aminief27db82016-12-12 19:34:26 +0000258 // Give up on finding a full definition for any forward decls that remain.
259 for (const auto &Ref : OldTypeRefs.FwdDecls)
260 OldTypeRefs.Final.insert(Ref);
261 OldTypeRefs.FwdDecls.clear();
262
263 // Upgrade from old type ref arrays. In strange cases, this could add to
264 // OldTypeRefs.Unknown.
Mehdi Amini690952d2016-12-25 04:22:54 +0000265 for (const auto &Array : OldTypeRefs.Arrays)
Mehdi Aminief27db82016-12-12 19:34:26 +0000266 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
Mehdi Aminief27db82016-12-12 19:34:26 +0000267 OldTypeRefs.Arrays.clear();
268
269 // Replace old string-based type refs with the resolved node, if possible.
270 // If we haven't seen the node, leave it to the verifier to complain about
271 // the invalid string reference.
272 for (const auto &Ref : OldTypeRefs.Unknown) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000273 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
274 Ref.second->replaceAllUsesWith(CT);
275 else
276 Ref.second->replaceAllUsesWith(Ref.first);
277 }
278 OldTypeRefs.Unknown.clear();
279
Mehdi Amini690952d2016-12-25 04:22:54 +0000280 if (UnresolvedNodes.empty())
Mehdi Aminief27db82016-12-12 19:34:26 +0000281 // Nothing to do.
282 return;
283
284 // Resolve any cycles.
Mehdi Amini690952d2016-12-25 04:22:54 +0000285 for (unsigned I : UnresolvedNodes) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000286 auto &MD = MetadataPtrs[I];
287 auto *N = dyn_cast_or_null<MDNode>(MD);
288 if (!N)
289 continue;
290
291 assert(!N->isTemporary() && "Unexpected forward reference");
292 N->resolveCycles();
293 }
294
Mehdi Amini690952d2016-12-25 04:22:54 +0000295 // Make sure we return early again until there's another unresolved ref.
296 UnresolvedNodes.clear();
Mehdi Aminief27db82016-12-12 19:34:26 +0000297}
298
299void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
300 DICompositeType &CT) {
301 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
302 if (CT.isForwardDecl())
303 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
304 else
305 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
306}
307
308Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
309 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
310 if (LLVM_LIKELY(!UUID))
311 return MaybeUUID;
312
313 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
314 return CT;
315
316 auto &Ref = OldTypeRefs.Unknown[UUID];
317 if (!Ref)
318 Ref = MDNode::getTemporary(Context, None);
319 return Ref.get();
320}
321
322Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
323 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
324 if (!Tuple || Tuple->isDistinct())
325 return MaybeTuple;
326
327 // Look through the array immediately if possible.
328 if (!Tuple->isTemporary())
329 return resolveTypeRefArray(Tuple);
330
331 // Create and return a placeholder to use for now. Eventually
332 // resolveTypeRefArrays() will be resolve this forward reference.
333 OldTypeRefs.Arrays.emplace_back(
334 std::piecewise_construct, std::forward_as_tuple(Tuple),
335 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
336 return OldTypeRefs.Arrays.back().second.get();
337}
338
339Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
340 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
341 if (!Tuple || Tuple->isDistinct())
342 return MaybeTuple;
343
344 // Look through the DITypeRefArray, upgrading each DITypeRef.
345 SmallVector<Metadata *, 32> Ops;
346 Ops.reserve(Tuple->getNumOperands());
347 for (Metadata *MD : Tuple->operands())
348 Ops.push_back(upgradeTypeRef(MD));
349
350 return MDTuple::get(Context, Ops);
351}
352
353namespace {
354
355class PlaceholderQueue {
356 // Placeholders would thrash around when moved, so store in a std::deque
357 // instead of some sort of vector.
358 std::deque<DistinctMDOperandPlaceholder> PHs;
359
360public:
Mehdi Amini27379892017-01-20 10:18:32 +0000361 ~PlaceholderQueue() {
362 assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
363 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000364 bool empty() { return PHs.empty(); }
Mehdi Aminief27db82016-12-12 19:34:26 +0000365 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
366 void flush(BitcodeReaderMetadataList &MetadataList);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000367
368 /// Return the list of temporaries nodes in the queue, these need to be
369 /// loaded before we can flush the queue.
370 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
371 DenseSet<unsigned> &Temporaries) {
372 for (auto &PH : PHs) {
373 auto ID = PH.getID();
374 auto *MD = MetadataList.lookup(ID);
375 if (!MD) {
376 Temporaries.insert(ID);
377 continue;
378 }
379 auto *N = dyn_cast_or_null<MDNode>(MD);
380 if (N && N->isTemporary())
381 Temporaries.insert(ID);
382 }
383 }
Mehdi Aminief27db82016-12-12 19:34:26 +0000384};
385
386} // end anonymous namespace
387
388DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
389 PHs.emplace_back(ID);
390 return PHs.back();
391}
392
393void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
394 while (!PHs.empty()) {
Mehdi Amini4f90ee02016-12-25 03:55:53 +0000395 auto *MD = MetadataList.lookup(PHs.front().getID());
396 assert(MD && "Flushing placeholder on unassigned MD");
Mehdi Amini5ae61702016-12-23 02:20:09 +0000397#ifndef NDEBUG
Mehdi Amini4f90ee02016-12-25 03:55:53 +0000398 if (auto *MDN = dyn_cast<MDNode>(MD))
Mehdi Amini5ae61702016-12-23 02:20:09 +0000399 assert(MDN->isResolved() &&
400 "Flushing Placeholder while cycles aren't resolved");
Mehdi Amini5ae61702016-12-23 02:20:09 +0000401#endif
402 PHs.front().replaceUseWith(MD);
Mehdi Aminief27db82016-12-12 19:34:26 +0000403 PHs.pop_front();
404 }
405}
406
407} // anonynous namespace
408
409class MetadataLoader::MetadataLoaderImpl {
410 BitcodeReaderMetadataList MetadataList;
411 BitcodeReaderValueList &ValueList;
412 BitstreamCursor &Stream;
413 LLVMContext &Context;
414 Module &TheModule;
415 std::function<Type *(unsigned)> getTypeByID;
416
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000417 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
418 /// to keep around the right "context" (Abbrev list) to be able to jump in
419 /// the middle of the metadata block and load any record.
420 BitstreamCursor IndexCursor;
421
422 /// Index that keeps track of MDString values.
423 std::vector<StringRef> MDStringRef;
424
425 /// On-demand loading of a single MDString. Requires the index above to be
426 /// populated.
427 MDString *lazyLoadOneMDString(unsigned Idx);
428
429 /// Index that keeps track of where to find a metadata record in the stream.
430 std::vector<uint64_t> GlobalMetadataBitPosIndex;
431
432 /// Populate the index above to enable lazily loading of metadata, and load
433 /// the named metadata as well as the transitively referenced global
434 /// Metadata.
Mehdi Amini42ef1992017-01-07 18:31:38 +0000435 Expected<bool> lazyLoadModuleMetadataBlock();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000436
437 /// On-demand loading of a single metadata. Requires the index above to be
438 /// populated.
439 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
440
Mehdi Amini9f926f72016-12-23 03:59:18 +0000441 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
442 // point from SP to CU after a block is completly parsed.
443 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
444
Mehdi Aminief27db82016-12-12 19:34:26 +0000445 /// Functions that need to be matched with subprograms when upgrading old
446 /// metadata.
447 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
448
449 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
450 DenseMap<unsigned, unsigned> MDKindMap;
451
Mehdi Amini86623052016-12-16 19:16:29 +0000452 bool StripTBAA = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000453 bool HasSeenOldLoopTags = false;
Adrian Prantle37d3142017-02-07 17:35:41 +0000454 bool NeedUpgradeToDIGlobalVariableExpression = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000455
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000456 /// True if metadata is being parsed for a module being ThinLTO imported.
457 bool IsImporting = false;
458
Mehdi Amini9f926f72016-12-23 03:59:18 +0000459 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
460 PlaceholderQueue &Placeholders, StringRef Blob,
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000461 unsigned &NextMetadataNo);
Mehdi Aminief27db82016-12-12 19:34:26 +0000462 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000463 function_ref<void(StringRef)> CallBack);
Mehdi Aminief27db82016-12-12 19:34:26 +0000464 Error parseGlobalObjectAttachment(GlobalObject &GO,
465 ArrayRef<uint64_t> Record);
466 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
467
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000468 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
469
470 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
471 void upgradeCUSubprograms() {
472 for (auto CU_SP : CUSubprograms)
473 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
474 for (auto &Op : SPs->operands())
475 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
476 SP->replaceOperandWith(7, CU_SP.first);
477 CUSubprograms.clear();
478 }
479
Adrian Prantle37d3142017-02-07 17:35:41 +0000480 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
481 void upgradeCUVariables() {
482 if (!NeedUpgradeToDIGlobalVariableExpression)
483 return;
484
485 // Upgrade list of variables attached to the CUs.
486 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
487 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
488 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
489 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
490 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
491 if (auto *GV =
492 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
493 auto *DGVE =
494 DIGlobalVariableExpression::getDistinct(Context, GV, nullptr);
495 GVs->replaceOperandWith(I, DGVE);
496 }
497 }
498
499 // Upgrade variables attached to globals.
500 for (auto &GV : TheModule.globals()) {
501 SmallVector<MDNode *, 1> MDs, NewMDs;
502 GV.getMetadata(LLVMContext::MD_dbg, MDs);
503 GV.eraseMetadata(LLVMContext::MD_dbg);
504 for (auto *MD : MDs)
505 if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
506 auto *DGVE =
507 DIGlobalVariableExpression::getDistinct(Context, DGV, nullptr);
508 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
509 } else
510 GV.addMetadata(LLVMContext::MD_dbg, *MD);
511 }
512 }
513
514 void upgradeDebugInfo() {
515 upgradeCUSubprograms();
516 upgradeCUVariables();
517 }
518
Mehdi Aminief27db82016-12-12 19:34:26 +0000519public:
520 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
521 BitcodeReaderValueList &ValueList,
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000522 std::function<Type *(unsigned)> getTypeByID,
523 bool IsImporting)
Mehdi Aminief27db82016-12-12 19:34:26 +0000524 : MetadataList(TheModule.getContext()), ValueList(ValueList),
525 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000526 getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
Mehdi Aminief27db82016-12-12 19:34:26 +0000527
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000528 Error parseMetadata(bool ModuleLevel);
Mehdi Aminief27db82016-12-12 19:34:26 +0000529
530 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000531
532 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
533 if (ID < MDStringRef.size())
534 return lazyLoadOneMDString(ID);
535 if (auto *MD = MetadataList.lookup(ID))
536 return MD;
537 // If lazy-loading is enabled, we try recursively to load the operand
538 // instead of creating a temporary.
539 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
540 PlaceholderQueue Placeholders;
541 lazyLoadOneMetadata(ID, Placeholders);
542 resolveForwardRefsAndPlaceholders(Placeholders);
543 return MetadataList.lookup(ID);
544 }
545 return MetadataList.getMetadataFwdRef(ID);
Mehdi Aminief27db82016-12-12 19:34:26 +0000546 }
547
548 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
549 return MetadataList.getMDNodeFwdRefOrNull(Idx);
550 }
551
552 DISubprogram *lookupSubprogramForFunction(Function *F) {
553 return FunctionsWithSPs.lookup(F);
554 }
555
556 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
557
558 Error parseMetadataAttachment(
559 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
560
561 Error parseMetadataKinds();
562
Mehdi Amini86623052016-12-16 19:16:29 +0000563 void setStripTBAA(bool Value) { StripTBAA = Value; }
564 bool isStrippingTBAA() { return StripTBAA; }
565
Mehdi Aminief27db82016-12-12 19:34:26 +0000566 unsigned size() const { return MetadataList.size(); }
567 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
568};
569
570Error error(const Twine &Message) {
571 return make_error<StringError>(
572 Message, make_error_code(BitcodeError::CorruptedBitcode));
573}
574
Mehdi Amini42ef1992017-01-07 18:31:38 +0000575Expected<bool>
576MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000577 IndexCursor = Stream;
578 SmallVector<uint64_t, 64> Record;
579 // Get the abbrevs, and preload record positions to make them lazy-loadable.
580 while (true) {
581 BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
582 BitstreamCursor::AF_DontPopBlockAtEnd);
583 switch (Entry.Kind) {
584 case BitstreamEntry::SubBlock: // Handled for us already.
585 case BitstreamEntry::Error:
586 return error("Malformed block");
587 case BitstreamEntry::EndBlock: {
588 return true;
589 }
590 case BitstreamEntry::Record: {
591 // The interesting case.
592 ++NumMDRecordLoaded;
593 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
594 auto Code = IndexCursor.skipRecord(Entry.ID);
595 switch (Code) {
596 case bitc::METADATA_STRINGS: {
597 // Rewind and parse the strings.
598 IndexCursor.JumpToBit(CurrentPos);
599 StringRef Blob;
600 Record.clear();
601 IndexCursor.readRecord(Entry.ID, Record, &Blob);
602 unsigned NumStrings = Record[0];
603 MDStringRef.reserve(NumStrings);
604 auto IndexNextMDString = [&](StringRef Str) {
605 MDStringRef.push_back(Str);
606 };
607 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
608 return std::move(Err);
609 break;
610 }
611 case bitc::METADATA_INDEX_OFFSET: {
612 // This is the offset to the index, when we see this we skip all the
613 // records and load only an index to these.
614 IndexCursor.JumpToBit(CurrentPos);
615 Record.clear();
616 IndexCursor.readRecord(Entry.ID, Record);
617 if (Record.size() != 2)
618 return error("Invalid record");
619 auto Offset = Record[0] + (Record[1] << 32);
620 auto BeginPos = IndexCursor.GetCurrentBitNo();
621 IndexCursor.JumpToBit(BeginPos + Offset);
622 Entry = IndexCursor.advanceSkippingSubblocks(
623 BitstreamCursor::AF_DontPopBlockAtEnd);
624 assert(Entry.Kind == BitstreamEntry::Record &&
625 "Corrupted bitcode: Expected `Record` when trying to find the "
626 "Metadata index");
627 Record.clear();
628 auto Code = IndexCursor.readRecord(Entry.ID, Record);
629 (void)Code;
630 assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
631 "`METADATA_INDEX` when trying "
632 "to find the Metadata index");
633
634 // Delta unpack
635 auto CurrentValue = BeginPos;
636 GlobalMetadataBitPosIndex.reserve(Record.size());
637 for (auto &Elt : Record) {
638 CurrentValue += Elt;
639 GlobalMetadataBitPosIndex.push_back(CurrentValue);
640 }
641 break;
642 }
643 case bitc::METADATA_INDEX:
644 // We don't expect to get there, the Index is loaded when we encounter
645 // the offset.
646 return error("Corrupted Metadata block");
647 case bitc::METADATA_NAME: {
648 // Named metadata need to be materialized now and aren't deferred.
649 IndexCursor.JumpToBit(CurrentPos);
650 Record.clear();
651 unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
652 assert(Code == bitc::METADATA_NAME);
653
654 // Read name of the named metadata.
655 SmallString<8> Name(Record.begin(), Record.end());
656 Code = IndexCursor.ReadCode();
657
658 // Named Metadata comes in two parts, we expect the name to be followed
659 // by the node
660 Record.clear();
661 unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
662 assert(NextBitCode == bitc::METADATA_NAMED_NODE);
663 (void)NextBitCode;
664
665 // Read named metadata elements.
666 unsigned Size = Record.size();
667 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
668 for (unsigned i = 0; i != Size; ++i) {
669 // FIXME: We could use a placeholder here, however NamedMDNode are
670 // taking MDNode as operand and not using the Metadata infrastructure.
671 // It is acknowledged by 'TODO: Inherit from Metadata' in the
672 // NamedMDNode class definition.
673 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
674 assert(MD && "Invalid record");
675 NMD->addOperand(MD);
676 }
677 break;
678 }
679 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
680 // FIXME: we need to do this early because we don't materialize global
681 // value explicitly.
682 IndexCursor.JumpToBit(CurrentPos);
683 Record.clear();
684 IndexCursor.readRecord(Entry.ID, Record);
685 if (Record.size() % 2 == 0)
686 return error("Invalid record");
687 unsigned ValueID = Record[0];
688 if (ValueID >= ValueList.size())
689 return error("Invalid record");
690 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
691 if (Error Err = parseGlobalObjectAttachment(
692 *GO, ArrayRef<uint64_t>(Record).slice(1)))
693 return std::move(Err);
694 break;
695 }
696 case bitc::METADATA_KIND:
697 case bitc::METADATA_STRING_OLD:
698 case bitc::METADATA_OLD_FN_NODE:
699 case bitc::METADATA_OLD_NODE:
700 case bitc::METADATA_VALUE:
701 case bitc::METADATA_DISTINCT_NODE:
702 case bitc::METADATA_NODE:
703 case bitc::METADATA_LOCATION:
704 case bitc::METADATA_GENERIC_DEBUG:
705 case bitc::METADATA_SUBRANGE:
706 case bitc::METADATA_ENUMERATOR:
707 case bitc::METADATA_BASIC_TYPE:
708 case bitc::METADATA_DERIVED_TYPE:
709 case bitc::METADATA_COMPOSITE_TYPE:
710 case bitc::METADATA_SUBROUTINE_TYPE:
711 case bitc::METADATA_MODULE:
712 case bitc::METADATA_FILE:
713 case bitc::METADATA_COMPILE_UNIT:
714 case bitc::METADATA_SUBPROGRAM:
715 case bitc::METADATA_LEXICAL_BLOCK:
716 case bitc::METADATA_LEXICAL_BLOCK_FILE:
717 case bitc::METADATA_NAMESPACE:
718 case bitc::METADATA_MACRO:
719 case bitc::METADATA_MACRO_FILE:
720 case bitc::METADATA_TEMPLATE_TYPE:
721 case bitc::METADATA_TEMPLATE_VALUE:
722 case bitc::METADATA_GLOBAL_VAR:
723 case bitc::METADATA_LOCAL_VAR:
724 case bitc::METADATA_EXPRESSION:
725 case bitc::METADATA_OBJC_PROPERTY:
726 case bitc::METADATA_IMPORTED_ENTITY:
727 case bitc::METADATA_GLOBAL_VAR_EXPR:
728 // We don't expect to see any of these, if we see one, give up on
729 // lazy-loading and fallback.
730 MDStringRef.clear();
731 GlobalMetadataBitPosIndex.clear();
732 return false;
733 }
734 break;
735 }
736 }
737 }
738}
739
Mehdi Aminief27db82016-12-12 19:34:26 +0000740/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
741/// module level metadata.
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000742Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000743 if (!ModuleLevel && MetadataList.hasFwdRefs())
744 return error("Invalid metadata: fwd refs into function blocks");
745
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000746 // Record the entry position so that we can jump back here and efficiently
747 // skip the whole block in case we lazy-load.
748 auto EntryPos = Stream.GetCurrentBitNo();
749
Mehdi Aminief27db82016-12-12 19:34:26 +0000750 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
751 return error("Invalid record");
752
Mehdi Aminief27db82016-12-12 19:34:26 +0000753 SmallVector<uint64_t, 64> Record;
Mehdi Aminief27db82016-12-12 19:34:26 +0000754 PlaceholderQueue Placeholders;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000755
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000756 // We lazy-load module-level metadata: we build an index for each record, and
757 // then load individual record as needed, starting with the named metadata.
758 if (ModuleLevel && IsImporting && MetadataList.empty() &&
759 !DisableLazyLoading) {
Mehdi Amini42ef1992017-01-07 18:31:38 +0000760 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000761 if (!SuccessOrErr)
762 return SuccessOrErr.takeError();
763 if (SuccessOrErr.get()) {
764 // An index was successfully created and we will be able to load metadata
765 // on-demand.
766 MetadataList.resize(MDStringRef.size() +
767 GlobalMetadataBitPosIndex.size());
768
769 // Reading the named metadata created forward references and/or
770 // placeholders, that we flush here.
771 resolveForwardRefsAndPlaceholders(Placeholders);
Adrian Prantle37d3142017-02-07 17:35:41 +0000772 upgradeDebugInfo();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000773 // Return at the beginning of the block, since it is easy to skip it
774 // entirely from there.
775 Stream.ReadBlockEnd(); // Pop the abbrev block context.
776 Stream.JumpToBit(EntryPos);
777 if (Stream.SkipBlock())
778 return error("Invalid record");
779 return Error::success();
780 }
781 // Couldn't load an index, fallback to loading all the block "old-style".
782 }
783
784 unsigned NextMetadataNo = MetadataList.size();
785
Mehdi Amini9f926f72016-12-23 03:59:18 +0000786 // Read all the records.
787 while (true) {
788 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
789
790 switch (Entry.Kind) {
791 case BitstreamEntry::SubBlock: // Handled for us already.
792 case BitstreamEntry::Error:
793 return error("Malformed block");
794 case BitstreamEntry::EndBlock:
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000795 resolveForwardRefsAndPlaceholders(Placeholders);
Adrian Prantle37d3142017-02-07 17:35:41 +0000796 upgradeDebugInfo();
Mehdi Amini9f926f72016-12-23 03:59:18 +0000797 return Error::success();
798 case BitstreamEntry::Record:
799 // The interesting case.
800 break;
801 }
802
803 // Read a record.
804 Record.clear();
805 StringRef Blob;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000806 ++NumMDRecordLoaded;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000807 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000808 if (Error Err =
809 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
Mehdi Amini9f926f72016-12-23 03:59:18 +0000810 return Err;
811 }
812}
813
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000814MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
815 ++NumMDStringLoaded;
816 if (Metadata *MD = MetadataList.lookup(ID))
817 return cast<MDString>(MD);
818 auto MDS = MDString::get(Context, MDStringRef[ID]);
819 MetadataList.assignValue(MDS, ID);
820 return MDS;
821}
822
823void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
824 unsigned ID, PlaceholderQueue &Placeholders) {
825 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
826 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000827 // Lookup first if the metadata hasn't already been loaded.
828 if (auto *MD = MetadataList.lookup(ID)) {
829 auto *N = dyn_cast_or_null<MDNode>(MD);
Mehdi Amini67d2cc12017-01-18 18:36:21 +0000830 if (!N->isTemporary())
831 return;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000832 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000833 SmallVector<uint64_t, 64> Record;
834 StringRef Blob;
835 IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
836 auto Entry = IndexCursor.advanceSkippingSubblocks();
837 ++NumMDRecordLoaded;
838 unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
839 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
840 report_fatal_error("Can't lazyload MD");
841}
842
843/// Ensure that all forward-references and placeholders are resolved.
844/// Iteratively lazy-loading metadata on-demand if needed.
845void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
846 PlaceholderQueue &Placeholders) {
847 DenseSet<unsigned> Temporaries;
848 while (1) {
849 // Populate Temporaries with the placeholders that haven't been loaded yet.
850 Placeholders.getTemporaries(MetadataList, Temporaries);
851
852 // If we don't have any temporary, or FwdReference, we're done!
853 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
854 break;
855
856 // First, load all the temporaries. This can add new placeholders or
857 // forward references.
858 for (auto ID : Temporaries)
859 lazyLoadOneMetadata(ID, Placeholders);
860 Temporaries.clear();
861
862 // Second, load the forward-references. This can also add new placeholders
863 // or forward references.
864 while (MetadataList.hasFwdRefs())
865 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
866 }
867 // At this point we don't have any forward reference remaining, or temporary
868 // that haven't been loaded. We can safely drop RAUW support and mark cycles
869 // as resolved.
870 MetadataList.tryToResolveCycles();
871
872 // Finally, everything is in place, we can replace the placeholders operands
873 // with the final node they refer to.
874 Placeholders.flush(MetadataList);
875}
876
Mehdi Amini9f926f72016-12-23 03:59:18 +0000877Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
878 SmallVectorImpl<uint64_t> &Record, unsigned Code,
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000879 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
Mehdi Amini9f926f72016-12-23 03:59:18 +0000880
881 bool IsDistinct = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000882 auto getMD = [&](unsigned ID) -> Metadata * {
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000883 if (ID < MDStringRef.size())
884 return lazyLoadOneMDString(ID);
Mehdi Amini67d2cc12017-01-18 18:36:21 +0000885 if (!IsDistinct) {
886 if (auto *MD = MetadataList.lookup(ID))
887 return MD;
888 // If lazy-loading is enabled, we try recursively to load the operand
889 // instead of creating a temporary.
890 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
891 // Create a temporary for the node that is referencing the operand we
892 // will lazy-load. It is needed before recursing in case there are
893 // uniquing cycles.
894 MetadataList.getMetadataFwdRef(NextMetadataNo);
895 lazyLoadOneMetadata(ID, Placeholders);
896 return MetadataList.lookup(ID);
897 }
898 // Return a temporary.
Mehdi Aminief27db82016-12-12 19:34:26 +0000899 return MetadataList.getMetadataFwdRef(ID);
Mehdi Amini67d2cc12017-01-18 18:36:21 +0000900 }
Mehdi Aminief27db82016-12-12 19:34:26 +0000901 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
902 return MD;
903 return &Placeholders.getPlaceholderOp(ID);
904 };
905 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
906 if (ID)
907 return getMD(ID - 1);
908 return nullptr;
909 };
910 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
911 if (ID)
912 return MetadataList.getMetadataFwdRef(ID - 1);
913 return nullptr;
914 };
915 auto getMDString = [&](unsigned ID) -> MDString * {
916 // This requires that the ID is not really a forward reference. In
917 // particular, the MDString must already have been resolved.
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000918 auto MDS = getMDOrNull(ID);
919 return cast_or_null<MDString>(MDS);
Mehdi Aminief27db82016-12-12 19:34:26 +0000920 };
921
922 // Support for old type refs.
923 auto getDITypeRefOrNull = [&](unsigned ID) {
924 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
925 };
926
927#define GET_OR_DISTINCT(CLASS, ARGS) \
928 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
929
Mehdi Amini9f926f72016-12-23 03:59:18 +0000930 switch (Code) {
931 default: // Default behavior: ignore.
932 break;
933 case bitc::METADATA_NAME: {
934 // Read name of the named metadata.
935 SmallString<8> Name(Record.begin(), Record.end());
Mehdi Aminief27db82016-12-12 19:34:26 +0000936 Record.clear();
Mehdi Amini9f926f72016-12-23 03:59:18 +0000937 Code = Stream.ReadCode();
Mehdi Aminief27db82016-12-12 19:34:26 +0000938
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000939 ++NumMDRecordLoaded;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000940 unsigned NextBitCode = Stream.readRecord(Code, Record);
941 if (NextBitCode != bitc::METADATA_NAMED_NODE)
942 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Mehdi Aminief27db82016-12-12 19:34:26 +0000943
Mehdi Amini9f926f72016-12-23 03:59:18 +0000944 // Read named metadata elements.
945 unsigned Size = Record.size();
946 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
947 for (unsigned i = 0; i != Size; ++i) {
948 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
949 if (!MD)
950 return error("Invalid record");
951 NMD->addOperand(MD);
952 }
953 break;
954 }
955 case bitc::METADATA_OLD_FN_NODE: {
956 // FIXME: Remove in 4.0.
957 // This is a LocalAsMetadata record, the only type of function-local
958 // metadata.
959 if (Record.size() % 2 == 1)
960 return error("Invalid record");
961
962 // If this isn't a LocalAsMetadata record, we're dropping it. This used
963 // to be legal, but there's no upgrade path.
964 auto dropRecord = [&] {
Ivan Krasinc05c9db2017-01-27 15:54:49 +0000965 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
966 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000967 };
968 if (Record.size() != 2) {
969 dropRecord();
Mehdi Aminief27db82016-12-12 19:34:26 +0000970 break;
971 }
Mehdi Amini9f926f72016-12-23 03:59:18 +0000972
973 Type *Ty = getTypeByID(Record[0]);
974 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
975 dropRecord();
976 break;
977 }
978
979 MetadataList.assignValue(
980 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +0000981 NextMetadataNo);
982 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000983 break;
984 }
985 case bitc::METADATA_OLD_NODE: {
986 // FIXME: Remove in 4.0.
987 if (Record.size() % 2 == 1)
988 return error("Invalid record");
989
990 unsigned Size = Record.size();
991 SmallVector<Metadata *, 8> Elts;
992 for (unsigned i = 0; i != Size; i += 2) {
993 Type *Ty = getTypeByID(Record[i]);
994 if (!Ty)
Mehdi Aminief27db82016-12-12 19:34:26 +0000995 return error("Invalid record");
Mehdi Amini9f926f72016-12-23 03:59:18 +0000996 if (Ty->isMetadataTy())
997 Elts.push_back(getMD(Record[i + 1]));
998 else if (!Ty->isVoidTy()) {
999 auto *MD =
1000 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1001 assert(isa<ConstantAsMetadata>(MD) &&
1002 "Expected non-function-local metadata");
1003 Elts.push_back(MD);
1004 } else
1005 Elts.push_back(nullptr);
1006 }
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001007 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1008 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001009 break;
1010 }
1011 case bitc::METADATA_VALUE: {
1012 if (Record.size() != 2)
1013 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001014
Mehdi Amini9f926f72016-12-23 03:59:18 +00001015 Type *Ty = getTypeByID(Record[0]);
1016 if (Ty->isMetadataTy() || Ty->isVoidTy())
1017 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001018
Mehdi Amini9f926f72016-12-23 03:59:18 +00001019 MetadataList.assignValue(
1020 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001021 NextMetadataNo);
1022 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001023 break;
1024 }
1025 case bitc::METADATA_DISTINCT_NODE:
1026 IsDistinct = true;
1027 LLVM_FALLTHROUGH;
1028 case bitc::METADATA_NODE: {
1029 SmallVector<Metadata *, 8> Elts;
1030 Elts.reserve(Record.size());
1031 for (unsigned ID : Record)
1032 Elts.push_back(getMDOrNull(ID));
1033 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1034 : MDNode::get(Context, Elts),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001035 NextMetadataNo);
1036 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001037 break;
1038 }
1039 case bitc::METADATA_LOCATION: {
1040 if (Record.size() != 5)
1041 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001042
Mehdi Amini9f926f72016-12-23 03:59:18 +00001043 IsDistinct = Record[0];
1044 unsigned Line = Record[1];
1045 unsigned Column = Record[2];
1046 Metadata *Scope = getMD(Record[3]);
1047 Metadata *InlinedAt = getMDOrNull(Record[4]);
1048 MetadataList.assignValue(
1049 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001050 NextMetadataNo);
1051 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001052 break;
1053 }
1054 case bitc::METADATA_GENERIC_DEBUG: {
1055 if (Record.size() < 4)
1056 return error("Invalid record");
1057
1058 IsDistinct = Record[0];
1059 unsigned Tag = Record[1];
1060 unsigned Version = Record[2];
1061
1062 if (Tag >= 1u << 16 || Version != 0)
1063 return error("Invalid record");
1064
1065 auto *Header = getMDString(Record[3]);
1066 SmallVector<Metadata *, 8> DwarfOps;
1067 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1068 DwarfOps.push_back(getMDOrNull(Record[I]));
1069 MetadataList.assignValue(
1070 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001071 NextMetadataNo);
1072 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001073 break;
1074 }
1075 case bitc::METADATA_SUBRANGE: {
1076 if (Record.size() != 3)
1077 return error("Invalid record");
1078
1079 IsDistinct = Record[0];
1080 MetadataList.assignValue(
1081 GET_OR_DISTINCT(DISubrange,
1082 (Context, Record[1], unrotateSign(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001083 NextMetadataNo);
1084 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001085 break;
1086 }
1087 case bitc::METADATA_ENUMERATOR: {
1088 if (Record.size() != 3)
1089 return error("Invalid record");
1090
1091 IsDistinct = Record[0];
1092 MetadataList.assignValue(
1093 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1094 getMDString(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001095 NextMetadataNo);
1096 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001097 break;
1098 }
1099 case bitc::METADATA_BASIC_TYPE: {
1100 if (Record.size() != 6)
1101 return error("Invalid record");
1102
1103 IsDistinct = Record[0];
1104 MetadataList.assignValue(
1105 GET_OR_DISTINCT(DIBasicType,
1106 (Context, Record[1], getMDString(Record[2]), Record[3],
1107 Record[4], Record[5])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001108 NextMetadataNo);
1109 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001110 break;
1111 }
1112 case bitc::METADATA_DERIVED_TYPE: {
1113 if (Record.size() != 12)
1114 return error("Invalid record");
1115
1116 IsDistinct = Record[0];
1117 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1118 MetadataList.assignValue(
1119 GET_OR_DISTINCT(DIDerivedType,
1120 (Context, Record[1], getMDString(Record[2]),
1121 getMDOrNull(Record[3]), Record[4],
1122 getDITypeRefOrNull(Record[5]),
1123 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1124 Record[9], Flags, getDITypeRefOrNull(Record[11]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001125 NextMetadataNo);
1126 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001127 break;
1128 }
1129 case bitc::METADATA_COMPOSITE_TYPE: {
1130 if (Record.size() != 16)
1131 return error("Invalid record");
1132
1133 // If we have a UUID and this is not a forward declaration, lookup the
1134 // mapping.
1135 IsDistinct = Record[0] & 0x1;
1136 bool IsNotUsedInTypeRef = Record[0] >= 2;
1137 unsigned Tag = Record[1];
1138 MDString *Name = getMDString(Record[2]);
1139 Metadata *File = getMDOrNull(Record[3]);
1140 unsigned Line = Record[4];
1141 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1142 Metadata *BaseType = nullptr;
1143 uint64_t SizeInBits = Record[7];
1144 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1145 return error("Alignment value is too large");
1146 uint32_t AlignInBits = Record[8];
1147 uint64_t OffsetInBits = 0;
1148 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1149 Metadata *Elements = nullptr;
1150 unsigned RuntimeLang = Record[12];
1151 Metadata *VTableHolder = nullptr;
1152 Metadata *TemplateParams = nullptr;
1153 auto *Identifier = getMDString(Record[15]);
1154 // If this module is being parsed so that it can be ThinLTO imported
1155 // into another module, composite types only need to be imported
1156 // as type declarations (unless full type definitions requested).
1157 // Create type declarations up front to save memory. Also, buildODRType
1158 // handles the case where this is type ODRed with a definition needed
1159 // by the importing module, in which case the existing definition is
1160 // used.
Teresa Johnson5a8dba52017-01-03 23:19:29 +00001161 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
Mehdi Amini9f926f72016-12-23 03:59:18 +00001162 (Tag == dwarf::DW_TAG_enumeration_type ||
1163 Tag == dwarf::DW_TAG_class_type ||
1164 Tag == dwarf::DW_TAG_structure_type ||
1165 Tag == dwarf::DW_TAG_union_type)) {
1166 Flags = Flags | DINode::FlagFwdDecl;
1167 } else {
1168 BaseType = getDITypeRefOrNull(Record[6]);
1169 OffsetInBits = Record[9];
1170 Elements = getMDOrNull(Record[11]);
1171 VTableHolder = getDITypeRefOrNull(Record[13]);
1172 TemplateParams = getMDOrNull(Record[14]);
1173 }
1174 DICompositeType *CT = nullptr;
1175 if (Identifier)
1176 CT = DICompositeType::buildODRType(
1177 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1178 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1179 VTableHolder, TemplateParams);
1180
1181 // Create a node if we didn't get a lazy ODR type.
1182 if (!CT)
1183 CT = GET_OR_DISTINCT(DICompositeType,
1184 (Context, Tag, Name, File, Line, Scope, BaseType,
1185 SizeInBits, AlignInBits, OffsetInBits, Flags,
1186 Elements, RuntimeLang, VTableHolder, TemplateParams,
1187 Identifier));
1188 if (!IsNotUsedInTypeRef && Identifier)
1189 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1190
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001191 MetadataList.assignValue(CT, NextMetadataNo);
1192 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001193 break;
1194 }
1195 case bitc::METADATA_SUBROUTINE_TYPE: {
1196 if (Record.size() < 3 || Record.size() > 4)
1197 return error("Invalid record");
1198 bool IsOldTypeRefArray = Record[0] < 2;
1199 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1200
1201 IsDistinct = Record[0] & 0x1;
1202 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1203 Metadata *Types = getMDOrNull(Record[2]);
1204 if (LLVM_UNLIKELY(IsOldTypeRefArray))
1205 Types = MetadataList.upgradeTypeRefArray(Types);
1206
1207 MetadataList.assignValue(
1208 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001209 NextMetadataNo);
1210 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001211 break;
1212 }
1213
1214 case bitc::METADATA_MODULE: {
1215 if (Record.size() != 6)
1216 return error("Invalid record");
1217
1218 IsDistinct = Record[0];
1219 MetadataList.assignValue(
1220 GET_OR_DISTINCT(DIModule,
1221 (Context, getMDOrNull(Record[1]),
1222 getMDString(Record[2]), getMDString(Record[3]),
1223 getMDString(Record[4]), getMDString(Record[5]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001224 NextMetadataNo);
1225 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001226 break;
1227 }
1228
1229 case bitc::METADATA_FILE: {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001230 if (Record.size() != 3 && Record.size() != 5)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001231 return error("Invalid record");
1232
1233 IsDistinct = Record[0];
1234 MetadataList.assignValue(
1235 GET_OR_DISTINCT(
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001236 DIFile,
1237 (Context, getMDString(Record[1]), getMDString(Record[2]),
1238 Record.size() == 3 ? DIFile::CSK_None
1239 : static_cast<DIFile::ChecksumKind>(Record[3]),
1240 Record.size() == 3 ? nullptr : getMDString(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001241 NextMetadataNo);
1242 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001243 break;
1244 }
1245 case bitc::METADATA_COMPILE_UNIT: {
Dehao Chen0944a8c2017-02-01 22:45:09 +00001246 if (Record.size() < 14 || Record.size() > 18)
Mehdi Amini9f926f72016-12-23 03:59:18 +00001247 return error("Invalid record");
1248
1249 // Ignore Record[0], which indicates whether this compile unit is
1250 // distinct. It's always distinct.
1251 IsDistinct = true;
1252 auto *CU = DICompileUnit::getDistinct(
1253 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1254 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1255 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1256 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1257 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1258 Record.size() <= 14 ? 0 : Record[14],
Dehao Chen0944a8c2017-02-01 22:45:09 +00001259 Record.size() <= 16 ? true : Record[16],
1260 Record.size() <= 17 ? false : Record[17]);
Mehdi Amini9f926f72016-12-23 03:59:18 +00001261
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001262 MetadataList.assignValue(CU, NextMetadataNo);
1263 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001264
1265 // Move the Upgrade the list of subprograms.
1266 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1267 CUSubprograms.push_back({CU, SPs});
1268 break;
1269 }
1270 case bitc::METADATA_SUBPROGRAM: {
1271 if (Record.size() < 18 || Record.size() > 20)
1272 return error("Invalid record");
1273
1274 IsDistinct =
1275 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1276 // Version 1 has a Function as Record[15].
1277 // Version 2 has removed Record[15].
1278 // Version 3 has the Unit as Record[15].
1279 // Version 4 added thisAdjustment.
1280 bool HasUnit = Record[0] >= 2;
1281 if (HasUnit && Record.size() < 19)
1282 return error("Invalid record");
1283 Metadata *CUorFn = getMDOrNull(Record[15]);
1284 unsigned Offset = Record.size() >= 19 ? 1 : 0;
1285 bool HasFn = Offset && !HasUnit;
1286 bool HasThisAdj = Record.size() >= 20;
1287 DISubprogram *SP = GET_OR_DISTINCT(
1288 DISubprogram, (Context,
1289 getDITypeRefOrNull(Record[1]), // scope
1290 getMDString(Record[2]), // name
1291 getMDString(Record[3]), // linkageName
1292 getMDOrNull(Record[4]), // file
1293 Record[5], // line
1294 getMDOrNull(Record[6]), // type
1295 Record[7], // isLocal
1296 Record[8], // isDefinition
1297 Record[9], // scopeLine
1298 getDITypeRefOrNull(Record[10]), // containingType
1299 Record[11], // virtuality
1300 Record[12], // virtualIndex
1301 HasThisAdj ? Record[19] : 0, // thisAdjustment
1302 static_cast<DINode::DIFlags>(Record[13] // flags
1303 ),
1304 Record[14], // isOptimized
1305 HasUnit ? CUorFn : nullptr, // unit
1306 getMDOrNull(Record[15 + Offset]), // templateParams
1307 getMDOrNull(Record[16 + Offset]), // declaration
1308 getMDOrNull(Record[17 + Offset]) // variables
1309 ));
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001310 MetadataList.assignValue(SP, NextMetadataNo);
1311 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001312
1313 // Upgrade sp->function mapping to function->sp mapping.
1314 if (HasFn) {
1315 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1316 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1317 if (F->isMaterializable())
1318 // Defer until materialized; unmaterialized functions may not have
1319 // metadata.
1320 FunctionsWithSPs[F] = SP;
1321 else if (!F->empty())
1322 F->setSubprogram(SP);
1323 }
1324 }
1325 break;
1326 }
1327 case bitc::METADATA_LEXICAL_BLOCK: {
1328 if (Record.size() != 5)
1329 return error("Invalid record");
1330
1331 IsDistinct = Record[0];
1332 MetadataList.assignValue(
1333 GET_OR_DISTINCT(DILexicalBlock,
1334 (Context, getMDOrNull(Record[1]),
1335 getMDOrNull(Record[2]), Record[3], Record[4])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001336 NextMetadataNo);
1337 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001338 break;
1339 }
1340 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1341 if (Record.size() != 4)
1342 return error("Invalid record");
1343
1344 IsDistinct = Record[0];
1345 MetadataList.assignValue(
1346 GET_OR_DISTINCT(DILexicalBlockFile,
1347 (Context, getMDOrNull(Record[1]),
1348 getMDOrNull(Record[2]), Record[3])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001349 NextMetadataNo);
1350 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001351 break;
1352 }
1353 case bitc::METADATA_NAMESPACE: {
1354 if (Record.size() != 5)
1355 return error("Invalid record");
1356
1357 IsDistinct = Record[0] & 1;
1358 bool ExportSymbols = Record[0] & 2;
1359 MetadataList.assignValue(
1360 GET_OR_DISTINCT(DINamespace,
1361 (Context, getMDOrNull(Record[1]),
1362 getMDOrNull(Record[2]), getMDString(Record[3]),
1363 Record[4], ExportSymbols)),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001364 NextMetadataNo);
1365 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001366 break;
1367 }
1368 case bitc::METADATA_MACRO: {
1369 if (Record.size() != 5)
1370 return error("Invalid record");
1371
1372 IsDistinct = Record[0];
1373 MetadataList.assignValue(
1374 GET_OR_DISTINCT(DIMacro,
1375 (Context, Record[1], Record[2], getMDString(Record[3]),
1376 getMDString(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001377 NextMetadataNo);
1378 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001379 break;
1380 }
1381 case bitc::METADATA_MACRO_FILE: {
1382 if (Record.size() != 5)
1383 return error("Invalid record");
1384
1385 IsDistinct = Record[0];
1386 MetadataList.assignValue(
1387 GET_OR_DISTINCT(DIMacroFile,
1388 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1389 getMDOrNull(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001390 NextMetadataNo);
1391 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001392 break;
1393 }
1394 case bitc::METADATA_TEMPLATE_TYPE: {
1395 if (Record.size() != 3)
1396 return error("Invalid record");
1397
1398 IsDistinct = Record[0];
1399 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1400 (Context, getMDString(Record[1]),
1401 getDITypeRefOrNull(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001402 NextMetadataNo);
1403 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001404 break;
1405 }
1406 case bitc::METADATA_TEMPLATE_VALUE: {
1407 if (Record.size() != 5)
1408 return error("Invalid record");
1409
1410 IsDistinct = Record[0];
1411 MetadataList.assignValue(
1412 GET_OR_DISTINCT(DITemplateValueParameter,
1413 (Context, Record[1], getMDString(Record[2]),
1414 getDITypeRefOrNull(Record[3]),
1415 getMDOrNull(Record[4]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001416 NextMetadataNo);
1417 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001418 break;
1419 }
1420 case bitc::METADATA_GLOBAL_VAR: {
1421 if (Record.size() < 11 || Record.size() > 12)
1422 return error("Invalid record");
1423
1424 IsDistinct = Record[0] & 1;
1425 unsigned Version = Record[0] >> 1;
1426
1427 if (Version == 1) {
Mehdi Aminief27db82016-12-12 19:34:26 +00001428 MetadataList.assignValue(
Mehdi Amini9f926f72016-12-23 03:59:18 +00001429 GET_OR_DISTINCT(DIGlobalVariable,
Mehdi Aminief27db82016-12-12 19:34:26 +00001430 (Context, getMDOrNull(Record[1]),
1431 getMDString(Record[2]), getMDString(Record[3]),
Mehdi Amini9f926f72016-12-23 03:59:18 +00001432 getMDOrNull(Record[4]), Record[5],
1433 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1434 getMDOrNull(Record[10]), Record[11])),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001435 NextMetadataNo);
1436 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001437 } else if (Version == 0) {
1438 // Upgrade old metadata, which stored a global variable reference or a
1439 // ConstantInt here.
1440 Metadata *Expr = getMDOrNull(Record[9]);
Mehdi Aminief27db82016-12-12 19:34:26 +00001441 uint32_t AlignInBits = 0;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001442 if (Record.size() > 11) {
1443 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
Mehdi Aminief27db82016-12-12 19:34:26 +00001444 return error("Alignment value is too large");
Mehdi Amini9f926f72016-12-23 03:59:18 +00001445 AlignInBits = Record[11];
Mehdi Aminief27db82016-12-12 19:34:26 +00001446 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001447 GlobalVariable *Attach = nullptr;
1448 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1449 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1450 Attach = GV;
1451 Expr = nullptr;
1452 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1453 Expr = DIExpression::get(Context,
1454 {dwarf::DW_OP_constu, CI->getZExtValue(),
1455 dwarf::DW_OP_stack_value});
1456 } else {
1457 Expr = nullptr;
1458 }
1459 }
1460 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1461 DIGlobalVariable,
1462 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1463 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1464 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1465 getMDOrNull(Record[10]), AlignInBits));
1466
Adrian Prantle37d3142017-02-07 17:35:41 +00001467 DIGlobalVariableExpression *DGVE = nullptr;
1468 if (Attach || Expr)
1469 DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1470 else
1471 NeedUpgradeToDIGlobalVariableExpression = true;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001472 if (Attach)
1473 Attach->addDebugInfo(DGVE);
Adrian Prantle37d3142017-02-07 17:35:41 +00001474
1475 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1476 MetadataList.assignValue(MDNode, NextMetadataNo);
1477 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001478 } else
1479 return error("Invalid record");
1480
1481 break;
1482 }
1483 case bitc::METADATA_LOCAL_VAR: {
1484 // 10th field is for the obseleted 'inlinedAt:' field.
1485 if (Record.size() < 8 || Record.size() > 10)
1486 return error("Invalid record");
1487
1488 IsDistinct = Record[0] & 1;
1489 bool HasAlignment = Record[0] & 2;
1490 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1491 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1492 // this is newer version of record which doesn't have artifical tag.
1493 bool HasTag = !HasAlignment && Record.size() > 8;
1494 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1495 uint32_t AlignInBits = 0;
1496 if (HasAlignment) {
1497 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1498 return error("Alignment value is too large");
1499 AlignInBits = Record[8 + HasTag];
Mehdi Aminief27db82016-12-12 19:34:26 +00001500 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001501 MetadataList.assignValue(
1502 GET_OR_DISTINCT(DILocalVariable,
1503 (Context, getMDOrNull(Record[1 + HasTag]),
1504 getMDString(Record[2 + HasTag]),
1505 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1506 getDITypeRefOrNull(Record[5 + HasTag]),
1507 Record[6 + HasTag], Flags, AlignInBits)),
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_EXPRESSION: {
1513 if (Record.size() < 1)
1514 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001515
Mehdi Amini9f926f72016-12-23 03:59:18 +00001516 IsDistinct = Record[0] & 1;
1517 bool HasOpFragment = Record[0] & 2;
1518 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1519 if (!HasOpFragment)
1520 if (unsigned N = Elts.size())
1521 if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1522 Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
Mehdi Aminief27db82016-12-12 19:34:26 +00001523
Mehdi Amini9f926f72016-12-23 03:59:18 +00001524 MetadataList.assignValue(
1525 GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001526 NextMetadataNo);
1527 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001528 break;
1529 }
1530 case bitc::METADATA_GLOBAL_VAR_EXPR: {
1531 if (Record.size() != 3)
1532 return error("Invalid record");
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001533
Mehdi Amini9f926f72016-12-23 03:59:18 +00001534 IsDistinct = Record[0];
1535 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1536 (Context, getMDOrNull(Record[1]),
1537 getMDOrNull(Record[2]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001538 NextMetadataNo);
1539 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001540 break;
1541 }
1542 case bitc::METADATA_OBJC_PROPERTY: {
1543 if (Record.size() != 8)
1544 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001545
Mehdi Amini9f926f72016-12-23 03:59:18 +00001546 IsDistinct = Record[0];
1547 MetadataList.assignValue(
1548 GET_OR_DISTINCT(DIObjCProperty,
1549 (Context, getMDString(Record[1]),
1550 getMDOrNull(Record[2]), Record[3],
1551 getMDString(Record[4]), getMDString(Record[5]),
1552 Record[6], getDITypeRefOrNull(Record[7]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001553 NextMetadataNo);
1554 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001555 break;
1556 }
1557 case bitc::METADATA_IMPORTED_ENTITY: {
1558 if (Record.size() != 6)
1559 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001560
Mehdi Amini9f926f72016-12-23 03:59:18 +00001561 IsDistinct = Record[0];
1562 MetadataList.assignValue(
1563 GET_OR_DISTINCT(DIImportedEntity,
1564 (Context, Record[1], getMDOrNull(Record[2]),
1565 getDITypeRefOrNull(Record[3]), Record[4],
1566 getMDString(Record[5]))),
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001567 NextMetadataNo);
1568 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001569 break;
1570 }
1571 case bitc::METADATA_STRING_OLD: {
1572 std::string String(Record.begin(), Record.end());
Mehdi Aminief27db82016-12-12 19:34:26 +00001573
Mehdi Amini9f926f72016-12-23 03:59:18 +00001574 // Test for upgrading !llvm.loop.
1575 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001576 ++NumMDStringLoaded;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001577 Metadata *MD = MDString::get(Context, String);
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001578 MetadataList.assignValue(MD, NextMetadataNo);
1579 NextMetadataNo++;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001580 break;
1581 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001582 case bitc::METADATA_STRINGS: {
1583 auto CreateNextMDString = [&](StringRef Str) {
1584 ++NumMDStringLoaded;
Ivan Krasinc05c9db2017-01-27 15:54:49 +00001585 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
1586 NextMetadataNo++;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001587 };
1588 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
Mehdi Amini9f926f72016-12-23 03:59:18 +00001589 return Err;
1590 break;
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001591 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001592 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1593 if (Record.size() % 2 == 0)
1594 return error("Invalid record");
1595 unsigned ValueID = Record[0];
1596 if (ValueID >= ValueList.size())
1597 return error("Invalid record");
1598 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1599 if (Error Err = parseGlobalObjectAttachment(
1600 *GO, ArrayRef<uint64_t>(Record).slice(1)))
Mehdi Aminief27db82016-12-12 19:34:26 +00001601 return Err;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001602 break;
1603 }
1604 case bitc::METADATA_KIND: {
1605 // Support older bitcode files that had METADATA_KIND records in a
1606 // block with METADATA_BLOCK_ID.
1607 if (Error Err = parseMetadataKindRecord(Record))
1608 return Err;
1609 break;
1610 }
Mehdi Aminief27db82016-12-12 19:34:26 +00001611 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001612 return Error::success();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001613#undef GET_OR_DISTINCT
Mehdi Aminief27db82016-12-12 19:34:26 +00001614}
1615
1616Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001617 ArrayRef<uint64_t> Record, StringRef Blob,
Benjamin Kramer061f4a52017-01-13 14:39:03 +00001618 function_ref<void(StringRef)> CallBack) {
Mehdi Aminief27db82016-12-12 19:34:26 +00001619 // All the MDStrings in the block are emitted together in a single
1620 // record. The strings are concatenated and stored in a blob along with
1621 // their sizes.
1622 if (Record.size() != 2)
1623 return error("Invalid record: metadata strings layout");
1624
1625 unsigned NumStrings = Record[0];
1626 unsigned StringsOffset = Record[1];
1627 if (!NumStrings)
1628 return error("Invalid record: metadata strings with no strings");
1629 if (StringsOffset > Blob.size())
1630 return error("Invalid record: metadata strings corrupt offset");
1631
1632 StringRef Lengths = Blob.slice(0, StringsOffset);
1633 SimpleBitstreamCursor R(Lengths);
1634
1635 StringRef Strings = Blob.drop_front(StringsOffset);
1636 do {
1637 if (R.AtEndOfStream())
1638 return error("Invalid record: metadata strings bad length");
1639
1640 unsigned Size = R.ReadVBR(6);
1641 if (Strings.size() < Size)
1642 return error("Invalid record: metadata strings truncated chars");
1643
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001644 CallBack(Strings.slice(0, Size));
Mehdi Aminief27db82016-12-12 19:34:26 +00001645 Strings = Strings.drop_front(Size);
1646 } while (--NumStrings);
1647
1648 return Error::success();
1649}
1650
1651Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1652 GlobalObject &GO, ArrayRef<uint64_t> Record) {
1653 assert(Record.size() % 2 == 0);
1654 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1655 auto K = MDKindMap.find(Record[I]);
1656 if (K == MDKindMap.end())
1657 return error("Invalid ID");
1658 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1659 if (!MD)
1660 return error("Invalid metadata attachment");
1661 GO.addMetadata(K->second, *MD);
1662 }
1663 return Error::success();
1664}
1665
1666/// Parse metadata attachments.
1667Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1668 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1669 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1670 return error("Invalid record");
1671
1672 SmallVector<uint64_t, 64> Record;
Mehdi Amini7b0d1452017-01-08 00:44:45 +00001673 PlaceholderQueue Placeholders;
Mehdi Aminief27db82016-12-12 19:34:26 +00001674
1675 while (true) {
1676 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1677
1678 switch (Entry.Kind) {
1679 case BitstreamEntry::SubBlock: // Handled for us already.
1680 case BitstreamEntry::Error:
1681 return error("Malformed block");
1682 case BitstreamEntry::EndBlock:
Mehdi Amini7b0d1452017-01-08 00:44:45 +00001683 resolveForwardRefsAndPlaceholders(Placeholders);
Mehdi Aminief27db82016-12-12 19:34:26 +00001684 return Error::success();
1685 case BitstreamEntry::Record:
1686 // The interesting case.
1687 break;
1688 }
1689
1690 // Read a metadata attachment record.
1691 Record.clear();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001692 ++NumMDRecordLoaded;
Mehdi Aminief27db82016-12-12 19:34:26 +00001693 switch (Stream.readRecord(Entry.ID, Record)) {
1694 default: // Default behavior: ignore.
1695 break;
1696 case bitc::METADATA_ATTACHMENT: {
1697 unsigned RecordLength = Record.size();
1698 if (Record.empty())
1699 return error("Invalid record");
1700 if (RecordLength % 2 == 0) {
1701 // A function attachment.
1702 if (Error Err = parseGlobalObjectAttachment(F, Record))
1703 return Err;
1704 continue;
1705 }
1706
1707 // An instruction attachment.
1708 Instruction *Inst = InstructionList[Record[0]];
1709 for (unsigned i = 1; i != RecordLength; i = i + 2) {
1710 unsigned Kind = Record[i];
1711 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1712 if (I == MDKindMap.end())
1713 return error("Invalid ID");
Mehdi Amini86623052016-12-16 19:16:29 +00001714 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1715 continue;
1716
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001717 auto Idx = Record[i + 1];
1718 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
Mehdi Aminid5549f32017-01-07 20:24:23 +00001719 !MetadataList.lookup(Idx)) {
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001720 // Load the attachment if it is in the lazy-loadable range and hasn't
1721 // been loaded yet.
1722 lazyLoadOneMetadata(Idx, Placeholders);
Mehdi Aminid5549f32017-01-07 20:24:23 +00001723 resolveForwardRefsAndPlaceholders(Placeholders);
1724 }
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001725
1726 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +00001727 if (isa<LocalAsMetadata>(Node))
1728 // Drop the attachment. This used to be legal, but there's no
1729 // upgrade path.
1730 break;
1731 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1732 if (!MD)
1733 return error("Invalid metadata attachment");
1734
1735 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1736 MD = upgradeInstructionLoopAttachment(*MD);
1737
1738 if (I->second == LLVMContext::MD_tbaa) {
1739 assert(!MD->isTemporary() && "should load MDs before attachments");
1740 MD = UpgradeTBAANode(*MD);
1741 }
1742 Inst->setMetadata(I->second, MD);
1743 }
1744 break;
1745 }
1746 }
1747 }
1748}
1749
1750/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1751Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1752 SmallVectorImpl<uint64_t> &Record) {
1753 if (Record.size() < 2)
1754 return error("Invalid record");
1755
1756 unsigned Kind = Record[0];
1757 SmallString<8> Name(Record.begin() + 1, Record.end());
1758
1759 unsigned NewKind = TheModule.getMDKindID(Name.str());
1760 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1761 return error("Conflicting METADATA_KIND records");
1762 return Error::success();
1763}
1764
1765/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1766Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1767 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1768 return error("Invalid record");
1769
1770 SmallVector<uint64_t, 64> Record;
1771
1772 // Read all the records.
1773 while (true) {
1774 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1775
1776 switch (Entry.Kind) {
1777 case BitstreamEntry::SubBlock: // Handled for us already.
1778 case BitstreamEntry::Error:
1779 return error("Malformed block");
1780 case BitstreamEntry::EndBlock:
1781 return Error::success();
1782 case BitstreamEntry::Record:
1783 // The interesting case.
1784 break;
1785 }
1786
1787 // Read a record.
1788 Record.clear();
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001789 ++NumMDRecordLoaded;
Mehdi Aminief27db82016-12-12 19:34:26 +00001790 unsigned Code = Stream.readRecord(Entry.ID, Record);
1791 switch (Code) {
1792 default: // Default behavior: ignore.
1793 break;
1794 case bitc::METADATA_KIND: {
1795 if (Error Err = parseMetadataKindRecord(Record))
1796 return Err;
1797 break;
1798 }
1799 }
1800 }
1801}
1802
1803MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1804 Pimpl = std::move(RHS.Pimpl);
1805 return *this;
1806}
1807MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001808 : Pimpl(std::move(RHS.Pimpl)) {}
Mehdi Aminief27db82016-12-12 19:34:26 +00001809
1810MetadataLoader::~MetadataLoader() = default;
1811MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1812 BitcodeReaderValueList &ValueList,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00001813 bool IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00001814 std::function<Type *(unsigned)> getTypeByID)
Benjamin Kramer061f4a52017-01-13 14:39:03 +00001815 : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1816 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
Mehdi Aminief27db82016-12-12 19:34:26 +00001817
1818Error MetadataLoader::parseMetadata(bool ModuleLevel) {
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001819 return Pimpl->parseMetadata(ModuleLevel);
Mehdi Aminief27db82016-12-12 19:34:26 +00001820}
1821
1822bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1823
1824/// Return the given metadata, creating a replaceable forward reference if
1825/// necessary.
Mehdi Amini3bb4d012017-01-20 20:29:16 +00001826Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1827 return Pimpl->getMetadataFwdRefOrLoad(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +00001828}
1829
1830MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1831 return Pimpl->getMDNodeFwdRefOrNull(Idx);
1832}
1833
1834DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1835 return Pimpl->lookupSubprogramForFunction(F);
1836}
1837
1838Error MetadataLoader::parseMetadataAttachment(
1839 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1840 return Pimpl->parseMetadataAttachment(F, InstructionList);
1841}
1842
1843Error MetadataLoader::parseMetadataKinds() {
1844 return Pimpl->parseMetadataKinds();
1845}
1846
Mehdi Amini86623052016-12-16 19:16:29 +00001847void MetadataLoader::setStripTBAA(bool StripTBAA) {
1848 return Pimpl->setStripTBAA(StripTBAA);
1849}
1850
1851bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1852
Mehdi Aminief27db82016-12-12 19:34:26 +00001853unsigned MetadataLoader::size() const { return Pimpl->size(); }
1854void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }