blob: 5da421a79b7b5a719e5aee2b477c9542c36097f7 [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"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/Bitcode/BitcodeReader.h"
25#include "llvm/Bitcode/BitstreamReader.h"
26#include "llvm/Bitcode/LLVMBitCodes.h"
27#include "llvm/IR/Argument.h"
28#include "llvm/IR/Attributes.h"
29#include "llvm/IR/AutoUpgrade.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CallSite.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/Comdat.h"
34#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DebugInfoMetadata.h"
38#include "llvm/IR/DebugLoc.h"
39#include "llvm/IR/DerivedTypes.h"
40#include "llvm/IR/DiagnosticInfo.h"
41#include "llvm/IR/DiagnosticPrinter.h"
42#include "llvm/IR/Function.h"
43#include "llvm/IR/GVMaterializer.h"
44#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalIFunc.h"
46#include "llvm/IR/GlobalIndirectSymbol.h"
47#include "llvm/IR/GlobalObject.h"
48#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/GlobalVariable.h"
50#include "llvm/IR/InlineAsm.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
54#include "llvm/IR/Intrinsics.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/ModuleSummaryIndex.h"
58#include "llvm/IR/OperandTraits.h"
59#include "llvm/IR/Operator.h"
60#include "llvm/IR/TrackingMDRef.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/ValueHandle.h"
63#include "llvm/Support/AtomicOrdering.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/ErrorHandling.h"
70#include "llvm/Support/ManagedStatic.h"
71#include "llvm/Support/MemoryBuffer.h"
72#include "llvm/Support/raw_ostream.h"
73#include <algorithm>
74#include <cassert>
75#include <cstddef>
76#include <cstdint>
77#include <deque>
78#include <limits>
79#include <map>
80#include <memory>
81#include <string>
82#include <system_error>
83#include <tuple>
84#include <utility>
85#include <vector>
86
87using namespace llvm;
88
Teresa Johnsona61f5e32016-12-16 21:25:01 +000089/// Flag whether we need to import full type definitions for ThinLTO.
90/// Currently needed for Darwin and LLDB.
91static cl::opt<bool> ImportFullTypeDefinitions(
92 "import-full-type-definitions", cl::init(false), cl::Hidden,
93 cl::desc("Import full type definitions for ThinLTO."));
94
Mehdi Aminief27db82016-12-12 19:34:26 +000095namespace {
96
97static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
98
99class BitcodeReaderMetadataList {
Mehdi Aminief27db82016-12-12 19:34:26 +0000100 /// Array of metadata references.
101 ///
102 /// Don't use std::vector here. Some versions of libc++ copy (instead of
103 /// move) on resize, and TrackingMDRef is very expensive to copy.
104 SmallVector<TrackingMDRef, 1> MetadataPtrs;
105
Mehdi Amini690952d2016-12-25 04:22:54 +0000106 /// The set of indices in MetadataPtrs above of forward references that were
107 /// generated.
108 SmallDenseSet<unsigned, 1> ForwardReference;
109
110 /// The set of indices in MetadataPtrs above of Metadata that need to be
111 /// resolved.
112 SmallDenseSet<unsigned, 1> UnresolvedNodes;
113
Mehdi Aminief27db82016-12-12 19:34:26 +0000114 /// Structures for resolving old type refs.
115 struct {
116 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
117 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
118 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
119 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
120 } OldTypeRefs;
121
122 LLVMContext &Context;
123
124public:
Mehdi Amini70a9cd42016-12-23 02:20:07 +0000125 BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
Mehdi Aminief27db82016-12-12 19:34:26 +0000126
127 // vector compatibility methods
128 unsigned size() const { return MetadataPtrs.size(); }
129 void resize(unsigned N) { MetadataPtrs.resize(N); }
130 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
131 void clear() { MetadataPtrs.clear(); }
132 Metadata *back() const { return MetadataPtrs.back(); }
133 void pop_back() { MetadataPtrs.pop_back(); }
134 bool empty() const { return MetadataPtrs.empty(); }
135
136 Metadata *operator[](unsigned i) const {
137 assert(i < MetadataPtrs.size());
138 return MetadataPtrs[i];
139 }
140
141 Metadata *lookup(unsigned I) const {
142 if (I < MetadataPtrs.size())
143 return MetadataPtrs[I];
144 return nullptr;
145 }
146
147 void shrinkTo(unsigned N) {
148 assert(N <= size() && "Invalid shrinkTo request!");
Mehdi Amini690952d2016-12-25 04:22:54 +0000149 assert(ForwardReference.empty() && "Unexpected forward refs");
150 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
Mehdi Aminief27db82016-12-12 19:34:26 +0000151 MetadataPtrs.resize(N);
152 }
153
154 /// Return the given metadata, creating a replaceable forward reference if
155 /// necessary.
156 Metadata *getMetadataFwdRef(unsigned Idx);
157
158 /// Return the the given metadata only if it is fully resolved.
159 ///
160 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
161 /// would give \c false.
162 Metadata *getMetadataIfResolved(unsigned Idx);
163
164 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
165 void assignValue(Metadata *MD, unsigned Idx);
166 void tryToResolveCycles();
Mehdi Amini690952d2016-12-25 04:22:54 +0000167 bool hasFwdRefs() const { return !ForwardReference.empty(); }
Mehdi Aminief27db82016-12-12 19:34:26 +0000168
169 /// Upgrade a type that had an MDString reference.
170 void addTypeRef(MDString &UUID, DICompositeType &CT);
171
172 /// Upgrade a type that had an MDString reference.
173 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
174
175 /// Upgrade a type ref array that may have MDString references.
176 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
177
178private:
179 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
180};
181
182void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Mehdi Amini690952d2016-12-25 04:22:54 +0000183 if (auto *MDN = dyn_cast<MDNode>(MD))
184 if (!MDN->isResolved())
185 UnresolvedNodes.insert(Idx);
186
Mehdi Aminief27db82016-12-12 19:34:26 +0000187 if (Idx == size()) {
188 push_back(MD);
189 return;
190 }
191
192 if (Idx >= size())
193 resize(Idx + 1);
194
195 TrackingMDRef &OldMD = MetadataPtrs[Idx];
196 if (!OldMD) {
197 OldMD.reset(MD);
198 return;
199 }
200
201 // If there was a forward reference to this value, replace it.
202 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
203 PrevMD->replaceAllUsesWith(MD);
Mehdi Amini690952d2016-12-25 04:22:54 +0000204 ForwardReference.erase(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +0000205}
206
207Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
208 if (Idx >= size())
209 resize(Idx + 1);
210
211 if (Metadata *MD = MetadataPtrs[Idx])
212 return MD;
213
214 // Track forward refs to be resolved later.
Mehdi Amini690952d2016-12-25 04:22:54 +0000215 ForwardReference.insert(Idx);
Mehdi Aminief27db82016-12-12 19:34:26 +0000216
217 // Create and return a placeholder, which will later be RAUW'd.
218 Metadata *MD = MDNode::getTemporary(Context, None).release();
219 MetadataPtrs[Idx].reset(MD);
220 return MD;
221}
222
223Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
224 Metadata *MD = lookup(Idx);
225 if (auto *N = dyn_cast_or_null<MDNode>(MD))
226 if (!N->isResolved())
227 return nullptr;
228 return MD;
229}
230
231MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
232 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
233}
234
235void BitcodeReaderMetadataList::tryToResolveCycles() {
Mehdi Amini690952d2016-12-25 04:22:54 +0000236 if (!ForwardReference.empty())
Mehdi Aminief27db82016-12-12 19:34:26 +0000237 // Still forward references... can't resolve cycles.
238 return;
239
Mehdi Aminief27db82016-12-12 19:34:26 +0000240 // Give up on finding a full definition for any forward decls that remain.
241 for (const auto &Ref : OldTypeRefs.FwdDecls)
242 OldTypeRefs.Final.insert(Ref);
243 OldTypeRefs.FwdDecls.clear();
244
245 // Upgrade from old type ref arrays. In strange cases, this could add to
246 // OldTypeRefs.Unknown.
Mehdi Amini690952d2016-12-25 04:22:54 +0000247 for (const auto &Array : OldTypeRefs.Arrays)
Mehdi Aminief27db82016-12-12 19:34:26 +0000248 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
Mehdi Aminief27db82016-12-12 19:34:26 +0000249 OldTypeRefs.Arrays.clear();
250
251 // Replace old string-based type refs with the resolved node, if possible.
252 // If we haven't seen the node, leave it to the verifier to complain about
253 // the invalid string reference.
254 for (const auto &Ref : OldTypeRefs.Unknown) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000255 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
256 Ref.second->replaceAllUsesWith(CT);
257 else
258 Ref.second->replaceAllUsesWith(Ref.first);
259 }
260 OldTypeRefs.Unknown.clear();
261
Mehdi Amini690952d2016-12-25 04:22:54 +0000262 if (UnresolvedNodes.empty())
Mehdi Aminief27db82016-12-12 19:34:26 +0000263 // Nothing to do.
264 return;
265
266 // Resolve any cycles.
Mehdi Amini690952d2016-12-25 04:22:54 +0000267 for (unsigned I : UnresolvedNodes) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000268 auto &MD = MetadataPtrs[I];
269 auto *N = dyn_cast_or_null<MDNode>(MD);
270 if (!N)
271 continue;
272
273 assert(!N->isTemporary() && "Unexpected forward reference");
274 N->resolveCycles();
275 }
276
Mehdi Amini690952d2016-12-25 04:22:54 +0000277 // Make sure we return early again until there's another unresolved ref.
278 UnresolvedNodes.clear();
Mehdi Aminief27db82016-12-12 19:34:26 +0000279}
280
281void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
282 DICompositeType &CT) {
283 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
284 if (CT.isForwardDecl())
285 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
286 else
287 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
288}
289
290Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
291 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
292 if (LLVM_LIKELY(!UUID))
293 return MaybeUUID;
294
295 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
296 return CT;
297
298 auto &Ref = OldTypeRefs.Unknown[UUID];
299 if (!Ref)
300 Ref = MDNode::getTemporary(Context, None);
301 return Ref.get();
302}
303
304Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
305 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
306 if (!Tuple || Tuple->isDistinct())
307 return MaybeTuple;
308
309 // Look through the array immediately if possible.
310 if (!Tuple->isTemporary())
311 return resolveTypeRefArray(Tuple);
312
313 // Create and return a placeholder to use for now. Eventually
314 // resolveTypeRefArrays() will be resolve this forward reference.
315 OldTypeRefs.Arrays.emplace_back(
316 std::piecewise_construct, std::forward_as_tuple(Tuple),
317 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
318 return OldTypeRefs.Arrays.back().second.get();
319}
320
321Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
322 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
323 if (!Tuple || Tuple->isDistinct())
324 return MaybeTuple;
325
326 // Look through the DITypeRefArray, upgrading each DITypeRef.
327 SmallVector<Metadata *, 32> Ops;
328 Ops.reserve(Tuple->getNumOperands());
329 for (Metadata *MD : Tuple->operands())
330 Ops.push_back(upgradeTypeRef(MD));
331
332 return MDTuple::get(Context, Ops);
333}
334
335namespace {
336
337class PlaceholderQueue {
338 // Placeholders would thrash around when moved, so store in a std::deque
339 // instead of some sort of vector.
340 std::deque<DistinctMDOperandPlaceholder> PHs;
341
342public:
343 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
344 void flush(BitcodeReaderMetadataList &MetadataList);
345};
346
347} // end anonymous namespace
348
349DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
350 PHs.emplace_back(ID);
351 return PHs.back();
352}
353
354void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
355 while (!PHs.empty()) {
Mehdi Amini4f90ee02016-12-25 03:55:53 +0000356 auto *MD = MetadataList.lookup(PHs.front().getID());
357 assert(MD && "Flushing placeholder on unassigned MD");
Mehdi Amini5ae61702016-12-23 02:20:09 +0000358#ifndef NDEBUG
Mehdi Amini4f90ee02016-12-25 03:55:53 +0000359 if (auto *MDN = dyn_cast<MDNode>(MD))
Mehdi Amini5ae61702016-12-23 02:20:09 +0000360 assert(MDN->isResolved() &&
361 "Flushing Placeholder while cycles aren't resolved");
Mehdi Amini5ae61702016-12-23 02:20:09 +0000362#endif
363 PHs.front().replaceUseWith(MD);
Mehdi Aminief27db82016-12-12 19:34:26 +0000364 PHs.pop_front();
365 }
366}
367
368} // anonynous namespace
369
370class MetadataLoader::MetadataLoaderImpl {
371 BitcodeReaderMetadataList MetadataList;
372 BitcodeReaderValueList &ValueList;
373 BitstreamCursor &Stream;
374 LLVMContext &Context;
375 Module &TheModule;
376 std::function<Type *(unsigned)> getTypeByID;
377
Mehdi Amini9f926f72016-12-23 03:59:18 +0000378 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
379 // point from SP to CU after a block is completly parsed.
380 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
381
Mehdi Aminief27db82016-12-12 19:34:26 +0000382 /// Functions that need to be matched with subprograms when upgrading old
383 /// metadata.
384 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
385
386 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
387 DenseMap<unsigned, unsigned> MDKindMap;
388
Mehdi Amini86623052016-12-16 19:16:29 +0000389 bool StripTBAA = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000390 bool HasSeenOldLoopTags = false;
391
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000392 /// True if metadata is being parsed for a module being ThinLTO imported.
393 bool IsImporting = false;
394
Mehdi Amini9f926f72016-12-23 03:59:18 +0000395 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
396 PlaceholderQueue &Placeholders, StringRef Blob,
397 bool ModuleLevel, unsigned &NextMetadataNo);
Mehdi Aminief27db82016-12-12 19:34:26 +0000398 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
399 unsigned &NextMetadataNo);
400 Error parseGlobalObjectAttachment(GlobalObject &GO,
401 ArrayRef<uint64_t> Record);
402 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
403
404public:
405 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
406 BitcodeReaderValueList &ValueList,
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000407 std::function<Type *(unsigned)> getTypeByID,
408 bool IsImporting)
Mehdi Aminief27db82016-12-12 19:34:26 +0000409 : MetadataList(TheModule.getContext()), ValueList(ValueList),
410 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000411 getTypeByID(getTypeByID), IsImporting(IsImporting) {}
Mehdi Aminief27db82016-12-12 19:34:26 +0000412
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000413 Error parseMetadata(bool ModuleLevel);
Mehdi Aminief27db82016-12-12 19:34:26 +0000414
415 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
416 Metadata *getMetadataFwdRef(unsigned Idx) {
417 return MetadataList.getMetadataFwdRef(Idx);
418 }
419
420 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
421 return MetadataList.getMDNodeFwdRefOrNull(Idx);
422 }
423
424 DISubprogram *lookupSubprogramForFunction(Function *F) {
425 return FunctionsWithSPs.lookup(F);
426 }
427
428 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
429
430 Error parseMetadataAttachment(
431 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
432
433 Error parseMetadataKinds();
434
Mehdi Amini86623052016-12-16 19:16:29 +0000435 void setStripTBAA(bool Value) { StripTBAA = Value; }
436 bool isStrippingTBAA() { return StripTBAA; }
437
Mehdi Aminief27db82016-12-12 19:34:26 +0000438 unsigned size() const { return MetadataList.size(); }
439 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
440};
441
442Error error(const Twine &Message) {
443 return make_error<StringError>(
444 Message, make_error_code(BitcodeError::CorruptedBitcode));
445}
446
447/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
448/// module level metadata.
Mehdi Aminiec68dd42016-12-23 02:20:02 +0000449Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
Mehdi Aminief27db82016-12-12 19:34:26 +0000450 if (!ModuleLevel && MetadataList.hasFwdRefs())
451 return error("Invalid metadata: fwd refs into function blocks");
452
453 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
454 return error("Invalid record");
455
456 unsigned NextMetadataNo = MetadataList.size();
Mehdi Aminief27db82016-12-12 19:34:26 +0000457 SmallVector<uint64_t, 64> Record;
458
459 PlaceholderQueue Placeholders;
Mehdi Amini9f926f72016-12-23 03:59:18 +0000460
461 // Read all the records.
462 while (true) {
463 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
464
465 switch (Entry.Kind) {
466 case BitstreamEntry::SubBlock: // Handled for us already.
467 case BitstreamEntry::Error:
468 return error("Malformed block");
469 case BitstreamEntry::EndBlock:
470 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
471 for (auto CU_SP : CUSubprograms)
472 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
473 for (auto &Op : SPs->operands())
474 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
475 SP->replaceOperandWith(7, CU_SP.first);
476 CUSubprograms.clear();
477
478 MetadataList.tryToResolveCycles();
479 Placeholders.flush(MetadataList);
480 return Error::success();
481 case BitstreamEntry::Record:
482 // The interesting case.
483 break;
484 }
485
486 // Read a record.
487 Record.clear();
488 StringRef Blob;
489 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
490 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob,
491 ModuleLevel, NextMetadataNo))
492 return Err;
493 }
494}
495
496Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
497 SmallVectorImpl<uint64_t> &Record, unsigned Code,
498 PlaceholderQueue &Placeholders, StringRef Blob, bool ModuleLevel,
499 unsigned &NextMetadataNo) {
500
501 bool IsDistinct = false;
Mehdi Aminief27db82016-12-12 19:34:26 +0000502 auto getMD = [&](unsigned ID) -> Metadata * {
503 if (!IsDistinct)
504 return MetadataList.getMetadataFwdRef(ID);
505 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
506 return MD;
507 return &Placeholders.getPlaceholderOp(ID);
508 };
509 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
510 if (ID)
511 return getMD(ID - 1);
512 return nullptr;
513 };
514 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
515 if (ID)
516 return MetadataList.getMetadataFwdRef(ID - 1);
517 return nullptr;
518 };
519 auto getMDString = [&](unsigned ID) -> MDString * {
520 // This requires that the ID is not really a forward reference. In
521 // particular, the MDString must already have been resolved.
522 return cast_or_null<MDString>(getMDOrNull(ID));
523 };
524
525 // Support for old type refs.
526 auto getDITypeRefOrNull = [&](unsigned ID) {
527 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
528 };
529
530#define GET_OR_DISTINCT(CLASS, ARGS) \
531 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
532
Mehdi Amini9f926f72016-12-23 03:59:18 +0000533 switch (Code) {
534 default: // Default behavior: ignore.
535 break;
536 case bitc::METADATA_NAME: {
537 // Read name of the named metadata.
538 SmallString<8> Name(Record.begin(), Record.end());
Mehdi Aminief27db82016-12-12 19:34:26 +0000539 Record.clear();
Mehdi Amini9f926f72016-12-23 03:59:18 +0000540 Code = Stream.ReadCode();
Mehdi Aminief27db82016-12-12 19:34:26 +0000541
Mehdi Amini9f926f72016-12-23 03:59:18 +0000542 unsigned NextBitCode = Stream.readRecord(Code, Record);
543 if (NextBitCode != bitc::METADATA_NAMED_NODE)
544 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Mehdi Aminief27db82016-12-12 19:34:26 +0000545
Mehdi Amini9f926f72016-12-23 03:59:18 +0000546 // Read named metadata elements.
547 unsigned Size = Record.size();
548 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
549 for (unsigned i = 0; i != Size; ++i) {
550 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
551 if (!MD)
552 return error("Invalid record");
553 NMD->addOperand(MD);
554 }
555 break;
556 }
557 case bitc::METADATA_OLD_FN_NODE: {
558 // FIXME: Remove in 4.0.
559 // This is a LocalAsMetadata record, the only type of function-local
560 // metadata.
561 if (Record.size() % 2 == 1)
562 return error("Invalid record");
563
564 // If this isn't a LocalAsMetadata record, we're dropping it. This used
565 // to be legal, but there's no upgrade path.
566 auto dropRecord = [&] {
567 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
568 };
569 if (Record.size() != 2) {
570 dropRecord();
Mehdi Aminief27db82016-12-12 19:34:26 +0000571 break;
572 }
Mehdi Amini9f926f72016-12-23 03:59:18 +0000573
574 Type *Ty = getTypeByID(Record[0]);
575 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
576 dropRecord();
577 break;
578 }
579
580 MetadataList.assignValue(
581 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
582 NextMetadataNo++);
583 break;
584 }
585 case bitc::METADATA_OLD_NODE: {
586 // FIXME: Remove in 4.0.
587 if (Record.size() % 2 == 1)
588 return error("Invalid record");
589
590 unsigned Size = Record.size();
591 SmallVector<Metadata *, 8> Elts;
592 for (unsigned i = 0; i != Size; i += 2) {
593 Type *Ty = getTypeByID(Record[i]);
594 if (!Ty)
Mehdi Aminief27db82016-12-12 19:34:26 +0000595 return error("Invalid record");
Mehdi Amini9f926f72016-12-23 03:59:18 +0000596 if (Ty->isMetadataTy())
597 Elts.push_back(getMD(Record[i + 1]));
598 else if (!Ty->isVoidTy()) {
599 auto *MD =
600 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
601 assert(isa<ConstantAsMetadata>(MD) &&
602 "Expected non-function-local metadata");
603 Elts.push_back(MD);
604 } else
605 Elts.push_back(nullptr);
606 }
607 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
608 break;
609 }
610 case bitc::METADATA_VALUE: {
611 if (Record.size() != 2)
612 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +0000613
Mehdi Amini9f926f72016-12-23 03:59:18 +0000614 Type *Ty = getTypeByID(Record[0]);
615 if (Ty->isMetadataTy() || Ty->isVoidTy())
616 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +0000617
Mehdi Amini9f926f72016-12-23 03:59:18 +0000618 MetadataList.assignValue(
619 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
620 NextMetadataNo++);
621 break;
622 }
623 case bitc::METADATA_DISTINCT_NODE:
624 IsDistinct = true;
625 LLVM_FALLTHROUGH;
626 case bitc::METADATA_NODE: {
627 SmallVector<Metadata *, 8> Elts;
628 Elts.reserve(Record.size());
629 for (unsigned ID : Record)
630 Elts.push_back(getMDOrNull(ID));
631 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
632 : MDNode::get(Context, Elts),
633 NextMetadataNo++);
634 break;
635 }
636 case bitc::METADATA_LOCATION: {
637 if (Record.size() != 5)
638 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +0000639
Mehdi Amini9f926f72016-12-23 03:59:18 +0000640 IsDistinct = Record[0];
641 unsigned Line = Record[1];
642 unsigned Column = Record[2];
643 Metadata *Scope = getMD(Record[3]);
644 Metadata *InlinedAt = getMDOrNull(Record[4]);
645 MetadataList.assignValue(
646 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
647 NextMetadataNo++);
648 break;
649 }
650 case bitc::METADATA_GENERIC_DEBUG: {
651 if (Record.size() < 4)
652 return error("Invalid record");
653
654 IsDistinct = Record[0];
655 unsigned Tag = Record[1];
656 unsigned Version = Record[2];
657
658 if (Tag >= 1u << 16 || Version != 0)
659 return error("Invalid record");
660
661 auto *Header = getMDString(Record[3]);
662 SmallVector<Metadata *, 8> DwarfOps;
663 for (unsigned I = 4, E = Record.size(); I != E; ++I)
664 DwarfOps.push_back(getMDOrNull(Record[I]));
665 MetadataList.assignValue(
666 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
667 NextMetadataNo++);
668 break;
669 }
670 case bitc::METADATA_SUBRANGE: {
671 if (Record.size() != 3)
672 return error("Invalid record");
673
674 IsDistinct = Record[0];
675 MetadataList.assignValue(
676 GET_OR_DISTINCT(DISubrange,
677 (Context, Record[1], unrotateSign(Record[2]))),
678 NextMetadataNo++);
679 break;
680 }
681 case bitc::METADATA_ENUMERATOR: {
682 if (Record.size() != 3)
683 return error("Invalid record");
684
685 IsDistinct = Record[0];
686 MetadataList.assignValue(
687 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
688 getMDString(Record[2]))),
689 NextMetadataNo++);
690 break;
691 }
692 case bitc::METADATA_BASIC_TYPE: {
693 if (Record.size() != 6)
694 return error("Invalid record");
695
696 IsDistinct = Record[0];
697 MetadataList.assignValue(
698 GET_OR_DISTINCT(DIBasicType,
699 (Context, Record[1], getMDString(Record[2]), Record[3],
700 Record[4], Record[5])),
701 NextMetadataNo++);
702 break;
703 }
704 case bitc::METADATA_DERIVED_TYPE: {
705 if (Record.size() != 12)
706 return error("Invalid record");
707
708 IsDistinct = Record[0];
709 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
710 MetadataList.assignValue(
711 GET_OR_DISTINCT(DIDerivedType,
712 (Context, Record[1], getMDString(Record[2]),
713 getMDOrNull(Record[3]), Record[4],
714 getDITypeRefOrNull(Record[5]),
715 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
716 Record[9], Flags, getDITypeRefOrNull(Record[11]))),
717 NextMetadataNo++);
718 break;
719 }
720 case bitc::METADATA_COMPOSITE_TYPE: {
721 if (Record.size() != 16)
722 return error("Invalid record");
723
724 // If we have a UUID and this is not a forward declaration, lookup the
725 // mapping.
726 IsDistinct = Record[0] & 0x1;
727 bool IsNotUsedInTypeRef = Record[0] >= 2;
728 unsigned Tag = Record[1];
729 MDString *Name = getMDString(Record[2]);
730 Metadata *File = getMDOrNull(Record[3]);
731 unsigned Line = Record[4];
732 Metadata *Scope = getDITypeRefOrNull(Record[5]);
733 Metadata *BaseType = nullptr;
734 uint64_t SizeInBits = Record[7];
735 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
736 return error("Alignment value is too large");
737 uint32_t AlignInBits = Record[8];
738 uint64_t OffsetInBits = 0;
739 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
740 Metadata *Elements = nullptr;
741 unsigned RuntimeLang = Record[12];
742 Metadata *VTableHolder = nullptr;
743 Metadata *TemplateParams = nullptr;
744 auto *Identifier = getMDString(Record[15]);
745 // If this module is being parsed so that it can be ThinLTO imported
746 // into another module, composite types only need to be imported
747 // as type declarations (unless full type definitions requested).
748 // Create type declarations up front to save memory. Also, buildODRType
749 // handles the case where this is type ODRed with a definition needed
750 // by the importing module, in which case the existing definition is
751 // used.
Teresa Johnson5a8dba52017-01-03 23:19:29 +0000752 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
Mehdi Amini9f926f72016-12-23 03:59:18 +0000753 (Tag == dwarf::DW_TAG_enumeration_type ||
754 Tag == dwarf::DW_TAG_class_type ||
755 Tag == dwarf::DW_TAG_structure_type ||
756 Tag == dwarf::DW_TAG_union_type)) {
757 Flags = Flags | DINode::FlagFwdDecl;
758 } else {
759 BaseType = getDITypeRefOrNull(Record[6]);
760 OffsetInBits = Record[9];
761 Elements = getMDOrNull(Record[11]);
762 VTableHolder = getDITypeRefOrNull(Record[13]);
763 TemplateParams = getMDOrNull(Record[14]);
764 }
765 DICompositeType *CT = nullptr;
766 if (Identifier)
767 CT = DICompositeType::buildODRType(
768 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
769 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
770 VTableHolder, TemplateParams);
771
772 // Create a node if we didn't get a lazy ODR type.
773 if (!CT)
774 CT = GET_OR_DISTINCT(DICompositeType,
775 (Context, Tag, Name, File, Line, Scope, BaseType,
776 SizeInBits, AlignInBits, OffsetInBits, Flags,
777 Elements, RuntimeLang, VTableHolder, TemplateParams,
778 Identifier));
779 if (!IsNotUsedInTypeRef && Identifier)
780 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
781
782 MetadataList.assignValue(CT, NextMetadataNo++);
783 break;
784 }
785 case bitc::METADATA_SUBROUTINE_TYPE: {
786 if (Record.size() < 3 || Record.size() > 4)
787 return error("Invalid record");
788 bool IsOldTypeRefArray = Record[0] < 2;
789 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
790
791 IsDistinct = Record[0] & 0x1;
792 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
793 Metadata *Types = getMDOrNull(Record[2]);
794 if (LLVM_UNLIKELY(IsOldTypeRefArray))
795 Types = MetadataList.upgradeTypeRefArray(Types);
796
797 MetadataList.assignValue(
798 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
799 NextMetadataNo++);
800 break;
801 }
802
803 case bitc::METADATA_MODULE: {
804 if (Record.size() != 6)
805 return error("Invalid record");
806
807 IsDistinct = Record[0];
808 MetadataList.assignValue(
809 GET_OR_DISTINCT(DIModule,
810 (Context, getMDOrNull(Record[1]),
811 getMDString(Record[2]), getMDString(Record[3]),
812 getMDString(Record[4]), getMDString(Record[5]))),
813 NextMetadataNo++);
814 break;
815 }
816
817 case bitc::METADATA_FILE: {
Amjad Aboud7faeecc2016-12-25 10:12:09 +0000818 if (Record.size() != 3 && Record.size() != 5)
Mehdi Amini9f926f72016-12-23 03:59:18 +0000819 return error("Invalid record");
820
821 IsDistinct = Record[0];
822 MetadataList.assignValue(
823 GET_OR_DISTINCT(
Amjad Aboud7faeecc2016-12-25 10:12:09 +0000824 DIFile,
825 (Context, getMDString(Record[1]), getMDString(Record[2]),
826 Record.size() == 3 ? DIFile::CSK_None
827 : static_cast<DIFile::ChecksumKind>(Record[3]),
828 Record.size() == 3 ? nullptr : getMDString(Record[4]))),
Mehdi Amini9f926f72016-12-23 03:59:18 +0000829 NextMetadataNo++);
830 break;
831 }
832 case bitc::METADATA_COMPILE_UNIT: {
833 if (Record.size() < 14 || Record.size() > 17)
834 return error("Invalid record");
835
836 // Ignore Record[0], which indicates whether this compile unit is
837 // distinct. It's always distinct.
838 IsDistinct = true;
839 auto *CU = DICompileUnit::getDistinct(
840 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
841 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
842 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
843 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
844 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
845 Record.size() <= 14 ? 0 : Record[14],
846 Record.size() <= 16 ? true : Record[16]);
847
848 MetadataList.assignValue(CU, NextMetadataNo++);
849
850 // Move the Upgrade the list of subprograms.
851 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
852 CUSubprograms.push_back({CU, SPs});
853 break;
854 }
855 case bitc::METADATA_SUBPROGRAM: {
856 if (Record.size() < 18 || Record.size() > 20)
857 return error("Invalid record");
858
859 IsDistinct =
860 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
861 // Version 1 has a Function as Record[15].
862 // Version 2 has removed Record[15].
863 // Version 3 has the Unit as Record[15].
864 // Version 4 added thisAdjustment.
865 bool HasUnit = Record[0] >= 2;
866 if (HasUnit && Record.size() < 19)
867 return error("Invalid record");
868 Metadata *CUorFn = getMDOrNull(Record[15]);
869 unsigned Offset = Record.size() >= 19 ? 1 : 0;
870 bool HasFn = Offset && !HasUnit;
871 bool HasThisAdj = Record.size() >= 20;
872 DISubprogram *SP = GET_OR_DISTINCT(
873 DISubprogram, (Context,
874 getDITypeRefOrNull(Record[1]), // scope
875 getMDString(Record[2]), // name
876 getMDString(Record[3]), // linkageName
877 getMDOrNull(Record[4]), // file
878 Record[5], // line
879 getMDOrNull(Record[6]), // type
880 Record[7], // isLocal
881 Record[8], // isDefinition
882 Record[9], // scopeLine
883 getDITypeRefOrNull(Record[10]), // containingType
884 Record[11], // virtuality
885 Record[12], // virtualIndex
886 HasThisAdj ? Record[19] : 0, // thisAdjustment
887 static_cast<DINode::DIFlags>(Record[13] // flags
888 ),
889 Record[14], // isOptimized
890 HasUnit ? CUorFn : nullptr, // unit
891 getMDOrNull(Record[15 + Offset]), // templateParams
892 getMDOrNull(Record[16 + Offset]), // declaration
893 getMDOrNull(Record[17 + Offset]) // variables
894 ));
895 MetadataList.assignValue(SP, NextMetadataNo++);
896
897 // Upgrade sp->function mapping to function->sp mapping.
898 if (HasFn) {
899 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
900 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
901 if (F->isMaterializable())
902 // Defer until materialized; unmaterialized functions may not have
903 // metadata.
904 FunctionsWithSPs[F] = SP;
905 else if (!F->empty())
906 F->setSubprogram(SP);
907 }
908 }
909 break;
910 }
911 case bitc::METADATA_LEXICAL_BLOCK: {
912 if (Record.size() != 5)
913 return error("Invalid record");
914
915 IsDistinct = Record[0];
916 MetadataList.assignValue(
917 GET_OR_DISTINCT(DILexicalBlock,
918 (Context, getMDOrNull(Record[1]),
919 getMDOrNull(Record[2]), Record[3], Record[4])),
920 NextMetadataNo++);
921 break;
922 }
923 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
924 if (Record.size() != 4)
925 return error("Invalid record");
926
927 IsDistinct = Record[0];
928 MetadataList.assignValue(
929 GET_OR_DISTINCT(DILexicalBlockFile,
930 (Context, getMDOrNull(Record[1]),
931 getMDOrNull(Record[2]), Record[3])),
932 NextMetadataNo++);
933 break;
934 }
935 case bitc::METADATA_NAMESPACE: {
936 if (Record.size() != 5)
937 return error("Invalid record");
938
939 IsDistinct = Record[0] & 1;
940 bool ExportSymbols = Record[0] & 2;
941 MetadataList.assignValue(
942 GET_OR_DISTINCT(DINamespace,
943 (Context, getMDOrNull(Record[1]),
944 getMDOrNull(Record[2]), getMDString(Record[3]),
945 Record[4], ExportSymbols)),
946 NextMetadataNo++);
947 break;
948 }
949 case bitc::METADATA_MACRO: {
950 if (Record.size() != 5)
951 return error("Invalid record");
952
953 IsDistinct = Record[0];
954 MetadataList.assignValue(
955 GET_OR_DISTINCT(DIMacro,
956 (Context, Record[1], Record[2], getMDString(Record[3]),
957 getMDString(Record[4]))),
958 NextMetadataNo++);
959 break;
960 }
961 case bitc::METADATA_MACRO_FILE: {
962 if (Record.size() != 5)
963 return error("Invalid record");
964
965 IsDistinct = Record[0];
966 MetadataList.assignValue(
967 GET_OR_DISTINCT(DIMacroFile,
968 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
969 getMDOrNull(Record[4]))),
970 NextMetadataNo++);
971 break;
972 }
973 case bitc::METADATA_TEMPLATE_TYPE: {
974 if (Record.size() != 3)
975 return error("Invalid record");
976
977 IsDistinct = Record[0];
978 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
979 (Context, getMDString(Record[1]),
980 getDITypeRefOrNull(Record[2]))),
981 NextMetadataNo++);
982 break;
983 }
984 case bitc::METADATA_TEMPLATE_VALUE: {
985 if (Record.size() != 5)
986 return error("Invalid record");
987
988 IsDistinct = Record[0];
989 MetadataList.assignValue(
990 GET_OR_DISTINCT(DITemplateValueParameter,
991 (Context, Record[1], getMDString(Record[2]),
992 getDITypeRefOrNull(Record[3]),
993 getMDOrNull(Record[4]))),
994 NextMetadataNo++);
995 break;
996 }
997 case bitc::METADATA_GLOBAL_VAR: {
998 if (Record.size() < 11 || Record.size() > 12)
999 return error("Invalid record");
1000
1001 IsDistinct = Record[0] & 1;
1002 unsigned Version = Record[0] >> 1;
1003
1004 if (Version == 1) {
Mehdi Aminief27db82016-12-12 19:34:26 +00001005 MetadataList.assignValue(
Mehdi Amini9f926f72016-12-23 03:59:18 +00001006 GET_OR_DISTINCT(DIGlobalVariable,
Mehdi Aminief27db82016-12-12 19:34:26 +00001007 (Context, getMDOrNull(Record[1]),
1008 getMDString(Record[2]), getMDString(Record[3]),
Mehdi Amini9f926f72016-12-23 03:59:18 +00001009 getMDOrNull(Record[4]), Record[5],
1010 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1011 getMDOrNull(Record[10]), Record[11])),
Mehdi Aminief27db82016-12-12 19:34:26 +00001012 NextMetadataNo++);
Mehdi Amini9f926f72016-12-23 03:59:18 +00001013 } else if (Version == 0) {
1014 // Upgrade old metadata, which stored a global variable reference or a
1015 // ConstantInt here.
1016 Metadata *Expr = getMDOrNull(Record[9]);
Mehdi Aminief27db82016-12-12 19:34:26 +00001017 uint32_t AlignInBits = 0;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001018 if (Record.size() > 11) {
1019 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
Mehdi Aminief27db82016-12-12 19:34:26 +00001020 return error("Alignment value is too large");
Mehdi Amini9f926f72016-12-23 03:59:18 +00001021 AlignInBits = Record[11];
Mehdi Aminief27db82016-12-12 19:34:26 +00001022 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001023 GlobalVariable *Attach = nullptr;
1024 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1025 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1026 Attach = GV;
1027 Expr = nullptr;
1028 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1029 Expr = DIExpression::get(Context,
1030 {dwarf::DW_OP_constu, CI->getZExtValue(),
1031 dwarf::DW_OP_stack_value});
1032 } else {
1033 Expr = nullptr;
1034 }
1035 }
1036 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1037 DIGlobalVariable,
1038 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1039 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1040 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1041 getMDOrNull(Record[10]), AlignInBits));
1042
1043 auto *DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1044 MetadataList.assignValue(DGVE, NextMetadataNo++);
1045 if (Attach)
1046 Attach->addDebugInfo(DGVE);
1047 } else
1048 return error("Invalid record");
1049
1050 break;
1051 }
1052 case bitc::METADATA_LOCAL_VAR: {
1053 // 10th field is for the obseleted 'inlinedAt:' field.
1054 if (Record.size() < 8 || Record.size() > 10)
1055 return error("Invalid record");
1056
1057 IsDistinct = Record[0] & 1;
1058 bool HasAlignment = Record[0] & 2;
1059 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1060 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1061 // this is newer version of record which doesn't have artifical tag.
1062 bool HasTag = !HasAlignment && Record.size() > 8;
1063 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1064 uint32_t AlignInBits = 0;
1065 if (HasAlignment) {
1066 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1067 return error("Alignment value is too large");
1068 AlignInBits = Record[8 + HasTag];
Mehdi Aminief27db82016-12-12 19:34:26 +00001069 }
Mehdi Amini9f926f72016-12-23 03:59:18 +00001070 MetadataList.assignValue(
1071 GET_OR_DISTINCT(DILocalVariable,
1072 (Context, getMDOrNull(Record[1 + HasTag]),
1073 getMDString(Record[2 + HasTag]),
1074 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1075 getDITypeRefOrNull(Record[5 + HasTag]),
1076 Record[6 + HasTag], Flags, AlignInBits)),
1077 NextMetadataNo++);
1078 break;
1079 }
1080 case bitc::METADATA_EXPRESSION: {
1081 if (Record.size() < 1)
1082 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001083
Mehdi Amini9f926f72016-12-23 03:59:18 +00001084 IsDistinct = Record[0] & 1;
1085 bool HasOpFragment = Record[0] & 2;
1086 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1087 if (!HasOpFragment)
1088 if (unsigned N = Elts.size())
1089 if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1090 Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
Mehdi Aminief27db82016-12-12 19:34:26 +00001091
Mehdi Amini9f926f72016-12-23 03:59:18 +00001092 MetadataList.assignValue(
1093 GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
1094 NextMetadataNo++);
1095 break;
1096 }
1097 case bitc::METADATA_GLOBAL_VAR_EXPR: {
1098 if (Record.size() != 3)
1099 return error("Invalid record");
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001100
Mehdi Amini9f926f72016-12-23 03:59:18 +00001101 IsDistinct = Record[0];
1102 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1103 (Context, getMDOrNull(Record[1]),
1104 getMDOrNull(Record[2]))),
1105 NextMetadataNo++);
1106 break;
1107 }
1108 case bitc::METADATA_OBJC_PROPERTY: {
1109 if (Record.size() != 8)
1110 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001111
Mehdi Amini9f926f72016-12-23 03:59:18 +00001112 IsDistinct = Record[0];
1113 MetadataList.assignValue(
1114 GET_OR_DISTINCT(DIObjCProperty,
1115 (Context, getMDString(Record[1]),
1116 getMDOrNull(Record[2]), Record[3],
1117 getMDString(Record[4]), getMDString(Record[5]),
1118 Record[6], getDITypeRefOrNull(Record[7]))),
1119 NextMetadataNo++);
1120 break;
1121 }
1122 case bitc::METADATA_IMPORTED_ENTITY: {
1123 if (Record.size() != 6)
1124 return error("Invalid record");
Mehdi Aminief27db82016-12-12 19:34:26 +00001125
Mehdi Amini9f926f72016-12-23 03:59:18 +00001126 IsDistinct = Record[0];
1127 MetadataList.assignValue(
1128 GET_OR_DISTINCT(DIImportedEntity,
1129 (Context, Record[1], getMDOrNull(Record[2]),
1130 getDITypeRefOrNull(Record[3]), Record[4],
1131 getMDString(Record[5]))),
1132 NextMetadataNo++);
1133 break;
1134 }
1135 case bitc::METADATA_STRING_OLD: {
1136 std::string String(Record.begin(), Record.end());
Mehdi Aminief27db82016-12-12 19:34:26 +00001137
Mehdi Amini9f926f72016-12-23 03:59:18 +00001138 // Test for upgrading !llvm.loop.
1139 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
Mehdi Aminief27db82016-12-12 19:34:26 +00001140
Mehdi Amini9f926f72016-12-23 03:59:18 +00001141 Metadata *MD = MDString::get(Context, String);
1142 MetadataList.assignValue(MD, NextMetadataNo++);
1143 break;
1144 }
1145 case bitc::METADATA_STRINGS:
1146 if (Error Err = parseMetadataStrings(Record, Blob, NextMetadataNo))
1147 return Err;
1148 break;
1149 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1150 if (Record.size() % 2 == 0)
1151 return error("Invalid record");
1152 unsigned ValueID = Record[0];
1153 if (ValueID >= ValueList.size())
1154 return error("Invalid record");
1155 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1156 if (Error Err = parseGlobalObjectAttachment(
1157 *GO, ArrayRef<uint64_t>(Record).slice(1)))
Mehdi Aminief27db82016-12-12 19:34:26 +00001158 return Err;
Mehdi Amini9f926f72016-12-23 03:59:18 +00001159 break;
1160 }
1161 case bitc::METADATA_KIND: {
1162 // Support older bitcode files that had METADATA_KIND records in a
1163 // block with METADATA_BLOCK_ID.
1164 if (Error Err = parseMetadataKindRecord(Record))
1165 return Err;
1166 break;
1167 }
Mehdi Aminief27db82016-12-12 19:34:26 +00001168 }
1169#undef GET_OR_DISTINCT
Mehdi Amini9f926f72016-12-23 03:59:18 +00001170 return Error::success();
Mehdi Aminief27db82016-12-12 19:34:26 +00001171}
1172
1173Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1174 ArrayRef<uint64_t> Record, StringRef Blob, unsigned &NextMetadataNo) {
1175 // All the MDStrings in the block are emitted together in a single
1176 // record. The strings are concatenated and stored in a blob along with
1177 // their sizes.
1178 if (Record.size() != 2)
1179 return error("Invalid record: metadata strings layout");
1180
1181 unsigned NumStrings = Record[0];
1182 unsigned StringsOffset = Record[1];
1183 if (!NumStrings)
1184 return error("Invalid record: metadata strings with no strings");
1185 if (StringsOffset > Blob.size())
1186 return error("Invalid record: metadata strings corrupt offset");
1187
1188 StringRef Lengths = Blob.slice(0, StringsOffset);
1189 SimpleBitstreamCursor R(Lengths);
1190
1191 StringRef Strings = Blob.drop_front(StringsOffset);
1192 do {
1193 if (R.AtEndOfStream())
1194 return error("Invalid record: metadata strings bad length");
1195
1196 unsigned Size = R.ReadVBR(6);
1197 if (Strings.size() < Size)
1198 return error("Invalid record: metadata strings truncated chars");
1199
1200 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
1201 NextMetadataNo++);
1202 Strings = Strings.drop_front(Size);
1203 } while (--NumStrings);
1204
1205 return Error::success();
1206}
1207
1208Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1209 GlobalObject &GO, ArrayRef<uint64_t> Record) {
1210 assert(Record.size() % 2 == 0);
1211 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1212 auto K = MDKindMap.find(Record[I]);
1213 if (K == MDKindMap.end())
1214 return error("Invalid ID");
1215 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1216 if (!MD)
1217 return error("Invalid metadata attachment");
1218 GO.addMetadata(K->second, *MD);
1219 }
1220 return Error::success();
1221}
1222
1223/// Parse metadata attachments.
1224Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1225 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1226 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1227 return error("Invalid record");
1228
1229 SmallVector<uint64_t, 64> Record;
1230
1231 while (true) {
1232 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1233
1234 switch (Entry.Kind) {
1235 case BitstreamEntry::SubBlock: // Handled for us already.
1236 case BitstreamEntry::Error:
1237 return error("Malformed block");
1238 case BitstreamEntry::EndBlock:
1239 return Error::success();
1240 case BitstreamEntry::Record:
1241 // The interesting case.
1242 break;
1243 }
1244
1245 // Read a metadata attachment record.
1246 Record.clear();
1247 switch (Stream.readRecord(Entry.ID, Record)) {
1248 default: // Default behavior: ignore.
1249 break;
1250 case bitc::METADATA_ATTACHMENT: {
1251 unsigned RecordLength = Record.size();
1252 if (Record.empty())
1253 return error("Invalid record");
1254 if (RecordLength % 2 == 0) {
1255 // A function attachment.
1256 if (Error Err = parseGlobalObjectAttachment(F, Record))
1257 return Err;
1258 continue;
1259 }
1260
1261 // An instruction attachment.
1262 Instruction *Inst = InstructionList[Record[0]];
1263 for (unsigned i = 1; i != RecordLength; i = i + 2) {
1264 unsigned Kind = Record[i];
1265 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1266 if (I == MDKindMap.end())
1267 return error("Invalid ID");
Mehdi Amini86623052016-12-16 19:16:29 +00001268 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1269 continue;
1270
Mehdi Aminief27db82016-12-12 19:34:26 +00001271 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
1272 if (isa<LocalAsMetadata>(Node))
1273 // Drop the attachment. This used to be legal, but there's no
1274 // upgrade path.
1275 break;
1276 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1277 if (!MD)
1278 return error("Invalid metadata attachment");
1279
1280 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1281 MD = upgradeInstructionLoopAttachment(*MD);
1282
1283 if (I->second == LLVMContext::MD_tbaa) {
1284 assert(!MD->isTemporary() && "should load MDs before attachments");
1285 MD = UpgradeTBAANode(*MD);
1286 }
1287 Inst->setMetadata(I->second, MD);
1288 }
1289 break;
1290 }
1291 }
1292 }
1293}
1294
1295/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1296Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1297 SmallVectorImpl<uint64_t> &Record) {
1298 if (Record.size() < 2)
1299 return error("Invalid record");
1300
1301 unsigned Kind = Record[0];
1302 SmallString<8> Name(Record.begin() + 1, Record.end());
1303
1304 unsigned NewKind = TheModule.getMDKindID(Name.str());
1305 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1306 return error("Conflicting METADATA_KIND records");
1307 return Error::success();
1308}
1309
1310/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1311Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1312 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1313 return error("Invalid record");
1314
1315 SmallVector<uint64_t, 64> Record;
1316
1317 // Read all the records.
1318 while (true) {
1319 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1320
1321 switch (Entry.Kind) {
1322 case BitstreamEntry::SubBlock: // Handled for us already.
1323 case BitstreamEntry::Error:
1324 return error("Malformed block");
1325 case BitstreamEntry::EndBlock:
1326 return Error::success();
1327 case BitstreamEntry::Record:
1328 // The interesting case.
1329 break;
1330 }
1331
1332 // Read a record.
1333 Record.clear();
1334 unsigned Code = Stream.readRecord(Entry.ID, Record);
1335 switch (Code) {
1336 default: // Default behavior: ignore.
1337 break;
1338 case bitc::METADATA_KIND: {
1339 if (Error Err = parseMetadataKindRecord(Record))
1340 return Err;
1341 break;
1342 }
1343 }
1344 }
1345}
1346
1347MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1348 Pimpl = std::move(RHS.Pimpl);
1349 return *this;
1350}
1351MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001352 : Pimpl(std::move(RHS.Pimpl)) {}
Mehdi Aminief27db82016-12-12 19:34:26 +00001353
1354MetadataLoader::~MetadataLoader() = default;
1355MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1356 BitcodeReaderValueList &ValueList,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00001357 bool IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00001358 std::function<Type *(unsigned)> getTypeByID)
Nico Weberb3901bd2016-12-12 22:46:40 +00001359 : Pimpl(llvm::make_unique<MetadataLoaderImpl>(Stream, TheModule, ValueList,
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001360 getTypeByID, IsImporting)) {}
Mehdi Aminief27db82016-12-12 19:34:26 +00001361
1362Error MetadataLoader::parseMetadata(bool ModuleLevel) {
Mehdi Aminiec68dd42016-12-23 02:20:02 +00001363 return Pimpl->parseMetadata(ModuleLevel);
Mehdi Aminief27db82016-12-12 19:34:26 +00001364}
1365
1366bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1367
1368/// Return the given metadata, creating a replaceable forward reference if
1369/// necessary.
1370Metadata *MetadataLoader::getMetadataFwdRef(unsigned Idx) {
1371 return Pimpl->getMetadataFwdRef(Idx);
1372}
1373
1374MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1375 return Pimpl->getMDNodeFwdRefOrNull(Idx);
1376}
1377
1378DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1379 return Pimpl->lookupSubprogramForFunction(F);
1380}
1381
1382Error MetadataLoader::parseMetadataAttachment(
1383 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1384 return Pimpl->parseMetadataAttachment(F, InstructionList);
1385}
1386
1387Error MetadataLoader::parseMetadataKinds() {
1388 return Pimpl->parseMetadataKinds();
1389}
1390
Mehdi Amini86623052016-12-16 19:16:29 +00001391void MetadataLoader::setStripTBAA(bool StripTBAA) {
1392 return Pimpl->setStripTBAA(StripTBAA);
1393}
1394
1395bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1396
Mehdi Aminief27db82016-12-12 19:34:26 +00001397unsigned MetadataLoader::size() const { return Pimpl->size(); }
1398void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }