1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
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/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #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"
84 #include <system_error>
91 #define DEBUG_TYPE "bitcode-reader"
93 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
94 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
95 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
97 /// Flag whether we need to import full type definitions for ThinLTO.
98 /// Currently needed for Darwin and LLDB.
99 static cl::opt<bool> ImportFullTypeDefinitions(
100 "import-full-type-definitions", cl::init(false), cl::Hidden,
101 cl::desc("Import full type definitions for ThinLTO."));
103 static 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."));
110 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
112 class BitcodeReaderMetadataList {
113 /// Array of metadata references.
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;
119 /// The set of indices in MetadataPtrs above of forward references that were
121 SmallDenseSet<unsigned, 1> ForwardReference;
123 /// The set of indices in MetadataPtrs above of Metadata that need to be
125 SmallDenseSet<unsigned, 1> UnresolvedNodes;
127 /// Structures for resolving old type refs.
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;
135 LLVMContext &Context;
138 BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
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(); }
149 Metadata *operator[](unsigned i) const {
150 assert(i < MetadataPtrs.size());
151 return MetadataPtrs[i];
154 Metadata *lookup(unsigned I) const {
155 if (I < MetadataPtrs.size())
156 return MetadataPtrs[I];
160 void shrinkTo(unsigned N) {
161 assert(N <= size() && "Invalid shrinkTo request!");
162 assert(ForwardReference.empty() && "Unexpected forward refs");
163 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
164 MetadataPtrs.resize(N);
167 /// Return the given metadata, creating a replaceable forward reference if
169 Metadata *getMetadataFwdRef(unsigned Idx);
171 /// Return the the given metadata only if it is fully resolved.
173 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
174 /// would give \c false.
175 Metadata *getMetadataIfResolved(unsigned Idx);
177 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
178 void assignValue(Metadata *MD, unsigned Idx);
179 void tryToResolveCycles();
180 bool hasFwdRefs() const { return !ForwardReference.empty(); }
181 int getNextFwdRef() {
182 assert(hasFwdRefs());
183 return *ForwardReference.begin();
186 /// Upgrade a type that had an MDString reference.
187 void addTypeRef(MDString &UUID, DICompositeType &CT);
189 /// Upgrade a type that had an MDString reference.
190 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
192 /// Upgrade a type ref array that may have MDString references.
193 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
196 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
199 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
200 if (auto *MDN = dyn_cast<MDNode>(MD))
201 if (!MDN->isResolved())
202 UnresolvedNodes.insert(Idx);
212 TrackingMDRef &OldMD = MetadataPtrs[Idx];
218 // If there was a forward reference to this value, replace it.
219 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
220 PrevMD->replaceAllUsesWith(MD);
221 ForwardReference.erase(Idx);
224 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
228 if (Metadata *MD = MetadataPtrs[Idx])
231 // Track forward refs to be resolved later.
232 ForwardReference.insert(Idx);
234 // Create and return a placeholder, which will later be RAUW'd.
235 ++NumMDNodeTemporary;
236 Metadata *MD = MDNode::getTemporary(Context, None).release();
237 MetadataPtrs[Idx].reset(MD);
241 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
242 Metadata *MD = lookup(Idx);
243 if (auto *N = dyn_cast_or_null<MDNode>(MD))
244 if (!N->isResolved())
249 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
250 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
253 void BitcodeReaderMetadataList::tryToResolveCycles() {
254 if (!ForwardReference.empty())
255 // Still forward references... can't resolve cycles.
258 // 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();
263 // Upgrade from old type ref arrays. In strange cases, this could add to
264 // OldTypeRefs.Unknown.
265 for (const auto &Array : OldTypeRefs.Arrays)
266 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
267 OldTypeRefs.Arrays.clear();
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) {
273 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
274 Ref.second->replaceAllUsesWith(CT);
276 Ref.second->replaceAllUsesWith(Ref.first);
278 OldTypeRefs.Unknown.clear();
280 if (UnresolvedNodes.empty())
284 // Resolve any cycles.
285 for (unsigned I : UnresolvedNodes) {
286 auto &MD = MetadataPtrs[I];
287 auto *N = dyn_cast_or_null<MDNode>(MD);
291 assert(!N->isTemporary() && "Unexpected forward reference");
295 // Make sure we return early again until there's another unresolved ref.
296 UnresolvedNodes.clear();
299 void 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));
305 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
308 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
309 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
310 if (LLVM_LIKELY(!UUID))
313 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
316 auto &Ref = OldTypeRefs.Unknown[UUID];
318 Ref = MDNode::getTemporary(Context, None);
322 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
323 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
324 if (!Tuple || Tuple->isDistinct())
327 // Look through the array immediately if possible.
328 if (!Tuple->isTemporary())
329 return resolveTypeRefArray(Tuple);
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();
339 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
340 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
341 if (!Tuple || Tuple->isDistinct())
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));
350 return MDTuple::get(Context, Ops);
355 class 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;
361 bool empty() { return PHs.empty(); }
362 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
363 void flush(BitcodeReaderMetadataList &MetadataList);
365 /// Return the list of temporaries nodes in the queue, these need to be
366 /// loaded before we can flush the queue.
367 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
368 DenseSet<unsigned> &Temporaries) {
369 for (auto &PH : PHs) {
370 auto ID = PH.getID();
371 auto *MD = MetadataList.lookup(ID);
373 Temporaries.insert(ID);
376 auto *N = dyn_cast_or_null<MDNode>(MD);
377 if (N && N->isTemporary())
378 Temporaries.insert(ID);
383 } // end anonymous namespace
385 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
386 PHs.emplace_back(ID);
390 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
391 while (!PHs.empty()) {
392 auto *MD = MetadataList.lookup(PHs.front().getID());
393 assert(MD && "Flushing placeholder on unassigned MD");
395 if (auto *MDN = dyn_cast<MDNode>(MD))
396 assert(MDN->isResolved() &&
397 "Flushing Placeholder while cycles aren't resolved");
399 PHs.front().replaceUseWith(MD);
404 } // anonynous namespace
406 class MetadataLoader::MetadataLoaderImpl {
407 BitcodeReaderMetadataList MetadataList;
408 BitcodeReaderValueList &ValueList;
409 BitstreamCursor &Stream;
410 LLVMContext &Context;
412 std::function<Type *(unsigned)> getTypeByID;
414 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
415 /// to keep around the right "context" (Abbrev list) to be able to jump in
416 /// the middle of the metadata block and load any record.
417 BitstreamCursor IndexCursor;
419 /// Index that keeps track of MDString values.
420 std::vector<StringRef> MDStringRef;
422 /// On-demand loading of a single MDString. Requires the index above to be
424 MDString *lazyLoadOneMDString(unsigned Idx);
426 /// Index that keeps track of where to find a metadata record in the stream.
427 std::vector<uint64_t> GlobalMetadataBitPosIndex;
429 /// Populate the index above to enable lazily loading of metadata, and load
430 /// the named metadata as well as the transitively referenced global
432 Expected<bool> lazyLoadModuleMetadataBlock();
434 /// On-demand loading of a single metadata. Requires the index above to be
436 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
438 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
439 // point from SP to CU after a block is completly parsed.
440 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
442 /// Functions that need to be matched with subprograms when upgrading old
444 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
446 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
447 DenseMap<unsigned, unsigned> MDKindMap;
449 bool StripTBAA = false;
450 bool HasSeenOldLoopTags = false;
451 bool NeedUpgradeToDIGlobalVariableExpression = false;
453 /// True if metadata is being parsed for a module being ThinLTO imported.
454 bool IsImporting = false;
456 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
457 PlaceholderQueue &Placeholders, StringRef Blob,
458 unsigned &NextMetadataNo);
459 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
460 std::function<void(StringRef)> CallBack);
461 Error parseGlobalObjectAttachment(GlobalObject &GO,
462 ArrayRef<uint64_t> Record);
463 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
465 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
467 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
468 void upgradeCUSubprograms() {
469 for (auto CU_SP : CUSubprograms)
470 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
471 for (auto &Op : SPs->operands())
472 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
473 SP->replaceOperandWith(7, CU_SP.first);
474 CUSubprograms.clear();
477 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
478 void upgradeCUVariables() {
479 if (!NeedUpgradeToDIGlobalVariableExpression)
482 // Upgrade list of variables attached to the CUs.
483 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
484 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
485 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
486 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
487 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
489 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
491 DIGlobalVariableExpression::getDistinct(Context, GV, nullptr);
492 GVs->replaceOperandWith(I, DGVE);
496 // Upgrade variables attached to globals.
497 for (auto &GV : TheModule.globals()) {
498 SmallVector<MDNode *, 1> MDs, NewMDs;
499 GV.getMetadata(LLVMContext::MD_dbg, MDs);
500 GV.eraseMetadata(LLVMContext::MD_dbg);
502 if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
504 DIGlobalVariableExpression::getDistinct(Context, DGV, nullptr);
505 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
507 GV.addMetadata(LLVMContext::MD_dbg, *MD);
511 void upgradeDebugInfo() {
512 upgradeCUSubprograms();
513 upgradeCUVariables();
517 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
518 BitcodeReaderValueList &ValueList,
519 std::function<Type *(unsigned)> getTypeByID,
521 : MetadataList(TheModule.getContext()), ValueList(ValueList),
522 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
523 getTypeByID(getTypeByID), IsImporting(IsImporting) {}
525 Error parseMetadata(bool ModuleLevel);
527 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
529 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
530 if (ID < MDStringRef.size())
531 return lazyLoadOneMDString(ID);
532 if (auto *MD = MetadataList.lookup(ID))
534 // If lazy-loading is enabled, we try recursively to load the operand
535 // instead of creating a temporary.
536 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
537 PlaceholderQueue Placeholders;
538 lazyLoadOneMetadata(ID, Placeholders);
539 resolveForwardRefsAndPlaceholders(Placeholders);
540 return MetadataList.lookup(ID);
542 return MetadataList.getMetadataFwdRef(ID);
545 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
546 return MetadataList.getMDNodeFwdRefOrNull(Idx);
549 DISubprogram *lookupSubprogramForFunction(Function *F) {
550 return FunctionsWithSPs.lookup(F);
553 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
555 Error parseMetadataAttachment(
556 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
558 Error parseMetadataKinds();
560 void setStripTBAA(bool Value) { StripTBAA = Value; }
561 bool isStrippingTBAA() { return StripTBAA; }
563 unsigned size() const { return MetadataList.size(); }
564 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
567 Error error(const Twine &Message) {
568 return make_error<StringError>(
569 Message, make_error_code(BitcodeError::CorruptedBitcode));
573 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
574 IndexCursor = Stream;
575 SmallVector<uint64_t, 64> Record;
576 // Get the abbrevs, and preload record positions to make them lazy-loadable.
578 BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
579 BitstreamCursor::AF_DontPopBlockAtEnd);
580 switch (Entry.Kind) {
581 case BitstreamEntry::SubBlock: // Handled for us already.
582 case BitstreamEntry::Error:
583 return error("Malformed block");
584 case BitstreamEntry::EndBlock: {
587 case BitstreamEntry::Record: {
588 // The interesting case.
590 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
591 auto Code = IndexCursor.skipRecord(Entry.ID);
593 case bitc::METADATA_STRINGS: {
594 // Rewind and parse the strings.
595 IndexCursor.JumpToBit(CurrentPos);
598 IndexCursor.readRecord(Entry.ID, Record, &Blob);
599 unsigned NumStrings = Record[0];
600 MDStringRef.reserve(NumStrings);
601 auto IndexNextMDString = [&](StringRef Str) {
602 MDStringRef.push_back(Str);
604 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
605 return std::move(Err);
608 case bitc::METADATA_INDEX_OFFSET: {
609 // This is the offset to the index, when we see this we skip all the
610 // records and load only an index to these.
611 IndexCursor.JumpToBit(CurrentPos);
613 IndexCursor.readRecord(Entry.ID, Record);
614 if (Record.size() != 2)
615 return error("Invalid record");
616 auto Offset = Record[0] + (Record[1] << 32);
617 auto BeginPos = IndexCursor.GetCurrentBitNo();
618 IndexCursor.JumpToBit(BeginPos + Offset);
619 Entry = IndexCursor.advanceSkippingSubblocks(
620 BitstreamCursor::AF_DontPopBlockAtEnd);
621 assert(Entry.Kind == BitstreamEntry::Record &&
622 "Corrupted bitcode: Expected `Record` when trying to find the "
625 auto Code = IndexCursor.readRecord(Entry.ID, Record);
627 assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
628 "`METADATA_INDEX` when trying "
629 "to find the Metadata index");
632 auto CurrentValue = BeginPos;
633 GlobalMetadataBitPosIndex.reserve(Record.size());
634 for (auto &Elt : Record) {
636 GlobalMetadataBitPosIndex.push_back(CurrentValue);
640 case bitc::METADATA_INDEX:
641 // We don't expect to get there, the Index is loaded when we encounter
643 return error("Corrupted Metadata block");
644 case bitc::METADATA_NAME: {
645 // Named metadata need to be materialized now and aren't deferred.
646 IndexCursor.JumpToBit(CurrentPos);
648 unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
649 assert(Code == bitc::METADATA_NAME);
651 // Read name of the named metadata.
652 SmallString<8> Name(Record.begin(), Record.end());
653 Code = IndexCursor.ReadCode();
655 // Named Metadata comes in two parts, we expect the name to be followed
658 unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
659 assert(NextBitCode == bitc::METADATA_NAMED_NODE);
662 // Read named metadata elements.
663 unsigned Size = Record.size();
664 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
665 for (unsigned i = 0; i != Size; ++i) {
666 // FIXME: We could use a placeholder here, however NamedMDNode are
667 // taking MDNode as operand and not using the Metadata infrastructure.
668 // It is acknowledged by 'TODO: Inherit from Metadata' in the
669 // NamedMDNode class definition.
670 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
671 assert(MD && "Invalid record");
676 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
677 // FIXME: we need to do this early because we don't materialize global
679 IndexCursor.JumpToBit(CurrentPos);
681 IndexCursor.readRecord(Entry.ID, Record);
682 if (Record.size() % 2 == 0)
683 return error("Invalid record");
684 unsigned ValueID = Record[0];
685 if (ValueID >= ValueList.size())
686 return error("Invalid record");
687 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
688 if (Error Err = parseGlobalObjectAttachment(
689 *GO, ArrayRef<uint64_t>(Record).slice(1)))
690 return std::move(Err);
693 case bitc::METADATA_KIND:
694 case bitc::METADATA_STRING_OLD:
695 case bitc::METADATA_OLD_FN_NODE:
696 case bitc::METADATA_OLD_NODE:
697 case bitc::METADATA_VALUE:
698 case bitc::METADATA_DISTINCT_NODE:
699 case bitc::METADATA_NODE:
700 case bitc::METADATA_LOCATION:
701 case bitc::METADATA_GENERIC_DEBUG:
702 case bitc::METADATA_SUBRANGE:
703 case bitc::METADATA_ENUMERATOR:
704 case bitc::METADATA_BASIC_TYPE:
705 case bitc::METADATA_DERIVED_TYPE:
706 case bitc::METADATA_COMPOSITE_TYPE:
707 case bitc::METADATA_SUBROUTINE_TYPE:
708 case bitc::METADATA_MODULE:
709 case bitc::METADATA_FILE:
710 case bitc::METADATA_COMPILE_UNIT:
711 case bitc::METADATA_SUBPROGRAM:
712 case bitc::METADATA_LEXICAL_BLOCK:
713 case bitc::METADATA_LEXICAL_BLOCK_FILE:
714 case bitc::METADATA_NAMESPACE:
715 case bitc::METADATA_MACRO:
716 case bitc::METADATA_MACRO_FILE:
717 case bitc::METADATA_TEMPLATE_TYPE:
718 case bitc::METADATA_TEMPLATE_VALUE:
719 case bitc::METADATA_GLOBAL_VAR:
720 case bitc::METADATA_LOCAL_VAR:
721 case bitc::METADATA_EXPRESSION:
722 case bitc::METADATA_OBJC_PROPERTY:
723 case bitc::METADATA_IMPORTED_ENTITY:
724 case bitc::METADATA_GLOBAL_VAR_EXPR:
725 // We don't expect to see any of these, if we see one, give up on
726 // lazy-loading and fallback.
728 GlobalMetadataBitPosIndex.clear();
737 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
738 /// module level metadata.
739 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
740 if (!ModuleLevel && MetadataList.hasFwdRefs())
741 return error("Invalid metadata: fwd refs into function blocks");
743 // Record the entry position so that we can jump back here and efficiently
744 // skip the whole block in case we lazy-load.
745 auto EntryPos = Stream.GetCurrentBitNo();
747 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
748 return error("Invalid record");
750 SmallVector<uint64_t, 64> Record;
751 PlaceholderQueue Placeholders;
753 // We lazy-load module-level metadata: we build an index for each record, and
754 // then load individual record as needed, starting with the named metadata.
755 if (ModuleLevel && IsImporting && MetadataList.empty() &&
756 !DisableLazyLoading) {
757 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
759 return SuccessOrErr.takeError();
760 if (SuccessOrErr.get()) {
761 // An index was successfully created and we will be able to load metadata
763 MetadataList.resize(MDStringRef.size() +
764 GlobalMetadataBitPosIndex.size());
766 // Reading the named metadata created forward references and/or
767 // placeholders, that we flush here.
768 resolveForwardRefsAndPlaceholders(Placeholders);
770 // Return at the beginning of the block, since it is easy to skip it
771 // entirely from there.
772 Stream.ReadBlockEnd(); // Pop the abbrev block context.
773 Stream.JumpToBit(EntryPos);
774 if (Stream.SkipBlock())
775 return error("Invalid record");
776 return Error::success();
778 // Couldn't load an index, fallback to loading all the block "old-style".
781 unsigned NextMetadataNo = MetadataList.size();
783 // Read all the records.
785 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
787 switch (Entry.Kind) {
788 case BitstreamEntry::SubBlock: // Handled for us already.
789 case BitstreamEntry::Error:
790 return error("Malformed block");
791 case BitstreamEntry::EndBlock:
792 resolveForwardRefsAndPlaceholders(Placeholders);
794 return Error::success();
795 case BitstreamEntry::Record:
796 // The interesting case.
804 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
806 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
811 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
813 if (Metadata *MD = MetadataList.lookup(ID))
814 return cast<MDString>(MD);
815 auto MDS = MDString::get(Context, MDStringRef[ID]);
816 MetadataList.assignValue(MDS, ID);
820 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
821 unsigned ID, PlaceholderQueue &Placeholders) {
822 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
823 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
824 // Lookup first if the metadata hasn't already been loaded.
825 if (auto *MD = MetadataList.lookup(ID)) {
826 auto *N = dyn_cast_or_null<MDNode>(MD);
827 if (!N->isTemporary())
830 SmallVector<uint64_t, 64> Record;
832 IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
833 auto Entry = IndexCursor.advanceSkippingSubblocks();
835 unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
836 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
837 report_fatal_error("Can't lazyload MD");
840 /// Ensure that all forward-references and placeholders are resolved.
841 /// Iteratively lazy-loading metadata on-demand if needed.
842 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
843 PlaceholderQueue &Placeholders) {
844 DenseSet<unsigned> Temporaries;
846 // Populate Temporaries with the placeholders that haven't been loaded yet.
847 Placeholders.getTemporaries(MetadataList, Temporaries);
849 // If we don't have any temporary, or FwdReference, we're done!
850 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
853 // First, load all the temporaries. This can add new placeholders or
854 // forward references.
855 for (auto ID : Temporaries)
856 lazyLoadOneMetadata(ID, Placeholders);
859 // Second, load the forward-references. This can also add new placeholders
860 // or forward references.
861 while (MetadataList.hasFwdRefs())
862 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
864 // At this point we don't have any forward reference remaining, or temporary
865 // that haven't been loaded. We can safely drop RAUW support and mark cycles
867 MetadataList.tryToResolveCycles();
869 // Finally, everything is in place, we can replace the placeholders operands
870 // with the final node they refer to.
871 Placeholders.flush(MetadataList);
874 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
875 SmallVectorImpl<uint64_t> &Record, unsigned Code,
876 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
878 bool IsDistinct = false;
879 auto getMD = [&](unsigned ID) -> Metadata * {
880 if (ID < MDStringRef.size())
881 return lazyLoadOneMDString(ID);
883 if (auto *MD = MetadataList.lookup(ID))
885 // If lazy-loading is enabled, we try recursively to load the operand
886 // instead of creating a temporary.
887 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
888 // Create a temporary for the node that is referencing the operand we
889 // will lazy-load. It is needed before recursing in case there are
891 MetadataList.getMetadataFwdRef(NextMetadataNo);
892 lazyLoadOneMetadata(ID, Placeholders);
893 return MetadataList.lookup(ID);
895 // Return a temporary.
896 return MetadataList.getMetadataFwdRef(ID);
898 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
900 return &Placeholders.getPlaceholderOp(ID);
902 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
904 return getMD(ID - 1);
907 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
909 return MetadataList.getMetadataFwdRef(ID - 1);
912 auto getMDString = [&](unsigned ID) -> MDString * {
913 // This requires that the ID is not really a forward reference. In
914 // particular, the MDString must already have been resolved.
915 auto MDS = getMDOrNull(ID);
916 return cast_or_null<MDString>(MDS);
919 // Support for old type refs.
920 auto getDITypeRefOrNull = [&](unsigned ID) {
921 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
924 #define GET_OR_DISTINCT(CLASS, ARGS) \
925 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
928 default: // Default behavior: ignore.
930 case bitc::METADATA_NAME: {
931 // Read name of the named metadata.
932 SmallString<8> Name(Record.begin(), Record.end());
934 Code = Stream.ReadCode();
937 unsigned NextBitCode = Stream.readRecord(Code, Record);
938 if (NextBitCode != bitc::METADATA_NAMED_NODE)
939 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
941 // Read named metadata elements.
942 unsigned Size = Record.size();
943 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
944 for (unsigned i = 0; i != Size; ++i) {
945 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
947 return error("Invalid record");
952 case bitc::METADATA_OLD_FN_NODE: {
953 // FIXME: Remove in 4.0.
954 // This is a LocalAsMetadata record, the only type of function-local
956 if (Record.size() % 2 == 1)
957 return error("Invalid record");
959 // If this isn't a LocalAsMetadata record, we're dropping it. This used
960 // to be legal, but there's no upgrade path.
961 auto dropRecord = [&] {
962 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
965 if (Record.size() != 2) {
970 Type *Ty = getTypeByID(Record[0]);
971 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
976 MetadataList.assignValue(
977 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
982 case bitc::METADATA_OLD_NODE: {
983 // FIXME: Remove in 4.0.
984 if (Record.size() % 2 == 1)
985 return error("Invalid record");
987 unsigned Size = Record.size();
988 SmallVector<Metadata *, 8> Elts;
989 for (unsigned i = 0; i != Size; i += 2) {
990 Type *Ty = getTypeByID(Record[i]);
992 return error("Invalid record");
993 if (Ty->isMetadataTy())
994 Elts.push_back(getMD(Record[i + 1]));
995 else if (!Ty->isVoidTy()) {
997 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
998 assert(isa<ConstantAsMetadata>(MD) &&
999 "Expected non-function-local metadata");
1002 Elts.push_back(nullptr);
1004 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1008 case bitc::METADATA_VALUE: {
1009 if (Record.size() != 2)
1010 return error("Invalid record");
1012 Type *Ty = getTypeByID(Record[0]);
1013 if (Ty->isMetadataTy() || Ty->isVoidTy())
1014 return error("Invalid record");
1016 MetadataList.assignValue(
1017 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1022 case bitc::METADATA_DISTINCT_NODE:
1025 case bitc::METADATA_NODE: {
1026 SmallVector<Metadata *, 8> Elts;
1027 Elts.reserve(Record.size());
1028 for (unsigned ID : Record)
1029 Elts.push_back(getMDOrNull(ID));
1030 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1031 : MDNode::get(Context, Elts),
1036 case bitc::METADATA_LOCATION: {
1037 if (Record.size() != 5)
1038 return error("Invalid record");
1040 IsDistinct = Record[0];
1041 unsigned Line = Record[1];
1042 unsigned Column = Record[2];
1043 Metadata *Scope = getMD(Record[3]);
1044 Metadata *InlinedAt = getMDOrNull(Record[4]);
1045 MetadataList.assignValue(
1046 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
1051 case bitc::METADATA_GENERIC_DEBUG: {
1052 if (Record.size() < 4)
1053 return error("Invalid record");
1055 IsDistinct = Record[0];
1056 unsigned Tag = Record[1];
1057 unsigned Version = Record[2];
1059 if (Tag >= 1u << 16 || Version != 0)
1060 return error("Invalid record");
1062 auto *Header = getMDString(Record[3]);
1063 SmallVector<Metadata *, 8> DwarfOps;
1064 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1065 DwarfOps.push_back(getMDOrNull(Record[I]));
1066 MetadataList.assignValue(
1067 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1072 case bitc::METADATA_SUBRANGE: {
1073 if (Record.size() != 3)
1074 return error("Invalid record");
1076 IsDistinct = Record[0];
1077 MetadataList.assignValue(
1078 GET_OR_DISTINCT(DISubrange,
1079 (Context, Record[1], unrotateSign(Record[2]))),
1084 case bitc::METADATA_ENUMERATOR: {
1085 if (Record.size() != 3)
1086 return error("Invalid record");
1088 IsDistinct = Record[0];
1089 MetadataList.assignValue(
1090 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1091 getMDString(Record[2]))),
1096 case bitc::METADATA_BASIC_TYPE: {
1097 if (Record.size() != 6)
1098 return error("Invalid record");
1100 IsDistinct = Record[0];
1101 MetadataList.assignValue(
1102 GET_OR_DISTINCT(DIBasicType,
1103 (Context, Record[1], getMDString(Record[2]), Record[3],
1104 Record[4], Record[5])),
1109 case bitc::METADATA_DERIVED_TYPE: {
1110 if (Record.size() != 12)
1111 return error("Invalid record");
1113 IsDistinct = Record[0];
1114 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1115 MetadataList.assignValue(
1116 GET_OR_DISTINCT(DIDerivedType,
1117 (Context, Record[1], getMDString(Record[2]),
1118 getMDOrNull(Record[3]), Record[4],
1119 getDITypeRefOrNull(Record[5]),
1120 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1121 Record[9], Flags, getDITypeRefOrNull(Record[11]))),
1126 case bitc::METADATA_COMPOSITE_TYPE: {
1127 if (Record.size() != 16)
1128 return error("Invalid record");
1130 // If we have a UUID and this is not a forward declaration, lookup the
1132 IsDistinct = Record[0] & 0x1;
1133 bool IsNotUsedInTypeRef = Record[0] >= 2;
1134 unsigned Tag = Record[1];
1135 MDString *Name = getMDString(Record[2]);
1136 Metadata *File = getMDOrNull(Record[3]);
1137 unsigned Line = Record[4];
1138 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1139 Metadata *BaseType = nullptr;
1140 uint64_t SizeInBits = Record[7];
1141 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1142 return error("Alignment value is too large");
1143 uint32_t AlignInBits = Record[8];
1144 uint64_t OffsetInBits = 0;
1145 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1146 Metadata *Elements = nullptr;
1147 unsigned RuntimeLang = Record[12];
1148 Metadata *VTableHolder = nullptr;
1149 Metadata *TemplateParams = nullptr;
1150 auto *Identifier = getMDString(Record[15]);
1151 // If this module is being parsed so that it can be ThinLTO imported
1152 // into another module, composite types only need to be imported
1153 // as type declarations (unless full type definitions requested).
1154 // Create type declarations up front to save memory. Also, buildODRType
1155 // handles the case where this is type ODRed with a definition needed
1156 // by the importing module, in which case the existing definition is
1158 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1159 (Tag == dwarf::DW_TAG_enumeration_type ||
1160 Tag == dwarf::DW_TAG_class_type ||
1161 Tag == dwarf::DW_TAG_structure_type ||
1162 Tag == dwarf::DW_TAG_union_type)) {
1163 Flags = Flags | DINode::FlagFwdDecl;
1165 BaseType = getDITypeRefOrNull(Record[6]);
1166 OffsetInBits = Record[9];
1167 Elements = getMDOrNull(Record[11]);
1168 VTableHolder = getDITypeRefOrNull(Record[13]);
1169 TemplateParams = getMDOrNull(Record[14]);
1171 DICompositeType *CT = nullptr;
1173 CT = DICompositeType::buildODRType(
1174 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1175 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1176 VTableHolder, TemplateParams);
1178 // Create a node if we didn't get a lazy ODR type.
1180 CT = GET_OR_DISTINCT(DICompositeType,
1181 (Context, Tag, Name, File, Line, Scope, BaseType,
1182 SizeInBits, AlignInBits, OffsetInBits, Flags,
1183 Elements, RuntimeLang, VTableHolder, TemplateParams,
1185 if (!IsNotUsedInTypeRef && Identifier)
1186 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1188 MetadataList.assignValue(CT, NextMetadataNo);
1192 case bitc::METADATA_SUBROUTINE_TYPE: {
1193 if (Record.size() < 3 || Record.size() > 4)
1194 return error("Invalid record");
1195 bool IsOldTypeRefArray = Record[0] < 2;
1196 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1198 IsDistinct = Record[0] & 0x1;
1199 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1200 Metadata *Types = getMDOrNull(Record[2]);
1201 if (LLVM_UNLIKELY(IsOldTypeRefArray))
1202 Types = MetadataList.upgradeTypeRefArray(Types);
1204 MetadataList.assignValue(
1205 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1211 case bitc::METADATA_MODULE: {
1212 if (Record.size() != 6)
1213 return error("Invalid record");
1215 IsDistinct = Record[0];
1216 MetadataList.assignValue(
1217 GET_OR_DISTINCT(DIModule,
1218 (Context, getMDOrNull(Record[1]),
1219 getMDString(Record[2]), getMDString(Record[3]),
1220 getMDString(Record[4]), getMDString(Record[5]))),
1226 case bitc::METADATA_FILE: {
1227 if (Record.size() != 3 && Record.size() != 5)
1228 return error("Invalid record");
1230 IsDistinct = Record[0];
1231 MetadataList.assignValue(
1234 (Context, getMDString(Record[1]), getMDString(Record[2]),
1235 Record.size() == 3 ? DIFile::CSK_None
1236 : static_cast<DIFile::ChecksumKind>(Record[3]),
1237 Record.size() == 3 ? nullptr : getMDString(Record[4]))),
1242 case bitc::METADATA_COMPILE_UNIT: {
1243 if (Record.size() < 14 || Record.size() > 17)
1244 return error("Invalid record");
1246 // Ignore Record[0], which indicates whether this compile unit is
1247 // distinct. It's always distinct.
1249 auto *CU = DICompileUnit::getDistinct(
1250 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1251 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1252 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1253 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1254 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1255 Record.size() <= 14 ? 0 : Record[14],
1256 Record.size() <= 16 ? true : Record[16]);
1258 MetadataList.assignValue(CU, NextMetadataNo);
1261 // Move the Upgrade the list of subprograms.
1262 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1263 CUSubprograms.push_back({CU, SPs});
1266 case bitc::METADATA_SUBPROGRAM: {
1267 if (Record.size() < 18 || Record.size() > 20)
1268 return error("Invalid record");
1271 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1272 // Version 1 has a Function as Record[15].
1273 // Version 2 has removed Record[15].
1274 // Version 3 has the Unit as Record[15].
1275 // Version 4 added thisAdjustment.
1276 bool HasUnit = Record[0] >= 2;
1277 if (HasUnit && Record.size() < 19)
1278 return error("Invalid record");
1279 Metadata *CUorFn = getMDOrNull(Record[15]);
1280 unsigned Offset = Record.size() >= 19 ? 1 : 0;
1281 bool HasFn = Offset && !HasUnit;
1282 bool HasThisAdj = Record.size() >= 20;
1283 DISubprogram *SP = GET_OR_DISTINCT(
1284 DISubprogram, (Context,
1285 getDITypeRefOrNull(Record[1]), // scope
1286 getMDString(Record[2]), // name
1287 getMDString(Record[3]), // linkageName
1288 getMDOrNull(Record[4]), // file
1290 getMDOrNull(Record[6]), // type
1291 Record[7], // isLocal
1292 Record[8], // isDefinition
1293 Record[9], // scopeLine
1294 getDITypeRefOrNull(Record[10]), // containingType
1295 Record[11], // virtuality
1296 Record[12], // virtualIndex
1297 HasThisAdj ? Record[19] : 0, // thisAdjustment
1298 static_cast<DINode::DIFlags>(Record[13] // flags
1300 Record[14], // isOptimized
1301 HasUnit ? CUorFn : nullptr, // unit
1302 getMDOrNull(Record[15 + Offset]), // templateParams
1303 getMDOrNull(Record[16 + Offset]), // declaration
1304 getMDOrNull(Record[17 + Offset]) // variables
1306 MetadataList.assignValue(SP, NextMetadataNo);
1309 // Upgrade sp->function mapping to function->sp mapping.
1311 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1312 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1313 if (F->isMaterializable())
1314 // Defer until materialized; unmaterialized functions may not have
1316 FunctionsWithSPs[F] = SP;
1317 else if (!F->empty())
1318 F->setSubprogram(SP);
1323 case bitc::METADATA_LEXICAL_BLOCK: {
1324 if (Record.size() != 5)
1325 return error("Invalid record");
1327 IsDistinct = Record[0];
1328 MetadataList.assignValue(
1329 GET_OR_DISTINCT(DILexicalBlock,
1330 (Context, getMDOrNull(Record[1]),
1331 getMDOrNull(Record[2]), Record[3], Record[4])),
1336 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1337 if (Record.size() != 4)
1338 return error("Invalid record");
1340 IsDistinct = Record[0];
1341 MetadataList.assignValue(
1342 GET_OR_DISTINCT(DILexicalBlockFile,
1343 (Context, getMDOrNull(Record[1]),
1344 getMDOrNull(Record[2]), Record[3])),
1349 case bitc::METADATA_NAMESPACE: {
1350 if (Record.size() != 5)
1351 return error("Invalid record");
1353 IsDistinct = Record[0] & 1;
1354 bool ExportSymbols = Record[0] & 2;
1355 MetadataList.assignValue(
1356 GET_OR_DISTINCT(DINamespace,
1357 (Context, getMDOrNull(Record[1]),
1358 getMDOrNull(Record[2]), getMDString(Record[3]),
1359 Record[4], ExportSymbols)),
1364 case bitc::METADATA_MACRO: {
1365 if (Record.size() != 5)
1366 return error("Invalid record");
1368 IsDistinct = Record[0];
1369 MetadataList.assignValue(
1370 GET_OR_DISTINCT(DIMacro,
1371 (Context, Record[1], Record[2], getMDString(Record[3]),
1372 getMDString(Record[4]))),
1377 case bitc::METADATA_MACRO_FILE: {
1378 if (Record.size() != 5)
1379 return error("Invalid record");
1381 IsDistinct = Record[0];
1382 MetadataList.assignValue(
1383 GET_OR_DISTINCT(DIMacroFile,
1384 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1385 getMDOrNull(Record[4]))),
1390 case bitc::METADATA_TEMPLATE_TYPE: {
1391 if (Record.size() != 3)
1392 return error("Invalid record");
1394 IsDistinct = Record[0];
1395 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1396 (Context, getMDString(Record[1]),
1397 getDITypeRefOrNull(Record[2]))),
1402 case bitc::METADATA_TEMPLATE_VALUE: {
1403 if (Record.size() != 5)
1404 return error("Invalid record");
1406 IsDistinct = Record[0];
1407 MetadataList.assignValue(
1408 GET_OR_DISTINCT(DITemplateValueParameter,
1409 (Context, Record[1], getMDString(Record[2]),
1410 getDITypeRefOrNull(Record[3]),
1411 getMDOrNull(Record[4]))),
1416 case bitc::METADATA_GLOBAL_VAR: {
1417 if (Record.size() < 11 || Record.size() > 12)
1418 return error("Invalid record");
1420 IsDistinct = Record[0] & 1;
1421 unsigned Version = Record[0] >> 1;
1424 MetadataList.assignValue(
1425 GET_OR_DISTINCT(DIGlobalVariable,
1426 (Context, getMDOrNull(Record[1]),
1427 getMDString(Record[2]), getMDString(Record[3]),
1428 getMDOrNull(Record[4]), Record[5],
1429 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1430 getMDOrNull(Record[10]), Record[11])),
1433 } else if (Version == 0) {
1434 // Upgrade old metadata, which stored a global variable reference or a
1435 // ConstantInt here.
1436 Metadata *Expr = getMDOrNull(Record[9]);
1437 uint32_t AlignInBits = 0;
1438 if (Record.size() > 11) {
1439 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1440 return error("Alignment value is too large");
1441 AlignInBits = Record[11];
1443 GlobalVariable *Attach = nullptr;
1444 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1445 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1448 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1449 Expr = DIExpression::get(Context,
1450 {dwarf::DW_OP_constu, CI->getZExtValue(),
1451 dwarf::DW_OP_stack_value});
1456 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1458 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1459 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1460 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1461 getMDOrNull(Record[10]), AlignInBits));
1463 DIGlobalVariableExpression *DGVE = nullptr;
1465 DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1467 NeedUpgradeToDIGlobalVariableExpression = true;
1469 Attach->addDebugInfo(DGVE);
1471 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1472 MetadataList.assignValue(MDNode, NextMetadataNo);
1475 return error("Invalid record");
1479 case bitc::METADATA_LOCAL_VAR: {
1480 // 10th field is for the obseleted 'inlinedAt:' field.
1481 if (Record.size() < 8 || Record.size() > 10)
1482 return error("Invalid record");
1484 IsDistinct = Record[0] & 1;
1485 bool HasAlignment = Record[0] & 2;
1486 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1487 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1488 // this is newer version of record which doesn't have artifical tag.
1489 bool HasTag = !HasAlignment && Record.size() > 8;
1490 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1491 uint32_t AlignInBits = 0;
1493 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1494 return error("Alignment value is too large");
1495 AlignInBits = Record[8 + HasTag];
1497 MetadataList.assignValue(
1498 GET_OR_DISTINCT(DILocalVariable,
1499 (Context, getMDOrNull(Record[1 + HasTag]),
1500 getMDString(Record[2 + HasTag]),
1501 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1502 getDITypeRefOrNull(Record[5 + HasTag]),
1503 Record[6 + HasTag], Flags, AlignInBits)),
1508 case bitc::METADATA_EXPRESSION: {
1509 if (Record.size() < 1)
1510 return error("Invalid record");
1512 IsDistinct = Record[0] & 1;
1513 bool HasOpFragment = Record[0] & 2;
1514 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1516 if (unsigned N = Elts.size())
1517 if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1518 Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
1520 MetadataList.assignValue(
1521 GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
1526 case bitc::METADATA_GLOBAL_VAR_EXPR: {
1527 if (Record.size() != 3)
1528 return error("Invalid record");
1530 IsDistinct = Record[0];
1531 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1532 (Context, getMDOrNull(Record[1]),
1533 getMDOrNull(Record[2]))),
1538 case bitc::METADATA_OBJC_PROPERTY: {
1539 if (Record.size() != 8)
1540 return error("Invalid record");
1542 IsDistinct = Record[0];
1543 MetadataList.assignValue(
1544 GET_OR_DISTINCT(DIObjCProperty,
1545 (Context, getMDString(Record[1]),
1546 getMDOrNull(Record[2]), Record[3],
1547 getMDString(Record[4]), getMDString(Record[5]),
1548 Record[6], getDITypeRefOrNull(Record[7]))),
1553 case bitc::METADATA_IMPORTED_ENTITY: {
1554 if (Record.size() != 6)
1555 return error("Invalid record");
1557 IsDistinct = Record[0];
1558 MetadataList.assignValue(
1559 GET_OR_DISTINCT(DIImportedEntity,
1560 (Context, Record[1], getMDOrNull(Record[2]),
1561 getDITypeRefOrNull(Record[3]), Record[4],
1562 getMDString(Record[5]))),
1567 case bitc::METADATA_STRING_OLD: {
1568 std::string String(Record.begin(), Record.end());
1570 // Test for upgrading !llvm.loop.
1571 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
1572 ++NumMDStringLoaded;
1573 Metadata *MD = MDString::get(Context, String);
1574 MetadataList.assignValue(MD, NextMetadataNo);
1578 case bitc::METADATA_STRINGS: {
1579 auto CreateNextMDString = [&](StringRef Str) {
1580 ++NumMDStringLoaded;
1581 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
1584 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1588 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1589 if (Record.size() % 2 == 0)
1590 return error("Invalid record");
1591 unsigned ValueID = Record[0];
1592 if (ValueID >= ValueList.size())
1593 return error("Invalid record");
1594 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1595 if (Error Err = parseGlobalObjectAttachment(
1596 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1600 case bitc::METADATA_KIND: {
1601 // Support older bitcode files that had METADATA_KIND records in a
1602 // block with METADATA_BLOCK_ID.
1603 if (Error Err = parseMetadataKindRecord(Record))
1608 return Error::success();
1609 #undef GET_OR_DISTINCT
1612 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1613 ArrayRef<uint64_t> Record, StringRef Blob,
1614 std::function<void(StringRef)> CallBack) {
1615 // All the MDStrings in the block are emitted together in a single
1616 // record. The strings are concatenated and stored in a blob along with
1618 if (Record.size() != 2)
1619 return error("Invalid record: metadata strings layout");
1621 unsigned NumStrings = Record[0];
1622 unsigned StringsOffset = Record[1];
1624 return error("Invalid record: metadata strings with no strings");
1625 if (StringsOffset > Blob.size())
1626 return error("Invalid record: metadata strings corrupt offset");
1628 StringRef Lengths = Blob.slice(0, StringsOffset);
1629 SimpleBitstreamCursor R(Lengths);
1631 StringRef Strings = Blob.drop_front(StringsOffset);
1633 if (R.AtEndOfStream())
1634 return error("Invalid record: metadata strings bad length");
1636 unsigned Size = R.ReadVBR(6);
1637 if (Strings.size() < Size)
1638 return error("Invalid record: metadata strings truncated chars");
1640 CallBack(Strings.slice(0, Size));
1641 Strings = Strings.drop_front(Size);
1642 } while (--NumStrings);
1644 return Error::success();
1647 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1648 GlobalObject &GO, ArrayRef<uint64_t> Record) {
1649 assert(Record.size() % 2 == 0);
1650 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1651 auto K = MDKindMap.find(Record[I]);
1652 if (K == MDKindMap.end())
1653 return error("Invalid ID");
1654 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1656 return error("Invalid metadata attachment");
1657 GO.addMetadata(K->second, *MD);
1659 return Error::success();
1662 /// Parse metadata attachments.
1663 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1664 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1665 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1666 return error("Invalid record");
1668 SmallVector<uint64_t, 64> Record;
1669 PlaceholderQueue Placeholders;
1672 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1674 switch (Entry.Kind) {
1675 case BitstreamEntry::SubBlock: // Handled for us already.
1676 case BitstreamEntry::Error:
1677 return error("Malformed block");
1678 case BitstreamEntry::EndBlock:
1679 resolveForwardRefsAndPlaceholders(Placeholders);
1680 return Error::success();
1681 case BitstreamEntry::Record:
1682 // The interesting case.
1686 // Read a metadata attachment record.
1688 ++NumMDRecordLoaded;
1689 switch (Stream.readRecord(Entry.ID, Record)) {
1690 default: // Default behavior: ignore.
1692 case bitc::METADATA_ATTACHMENT: {
1693 unsigned RecordLength = Record.size();
1695 return error("Invalid record");
1696 if (RecordLength % 2 == 0) {
1697 // A function attachment.
1698 if (Error Err = parseGlobalObjectAttachment(F, Record))
1703 // An instruction attachment.
1704 Instruction *Inst = InstructionList[Record[0]];
1705 for (unsigned i = 1; i != RecordLength; i = i + 2) {
1706 unsigned Kind = Record[i];
1707 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1708 if (I == MDKindMap.end())
1709 return error("Invalid ID");
1710 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1713 auto Idx = Record[i + 1];
1714 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1715 !MetadataList.lookup(Idx)) {
1716 // Load the attachment if it is in the lazy-loadable range and hasn't
1718 lazyLoadOneMetadata(Idx, Placeholders);
1719 resolveForwardRefsAndPlaceholders(Placeholders);
1722 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1723 if (isa<LocalAsMetadata>(Node))
1724 // Drop the attachment. This used to be legal, but there's no
1727 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1729 return error("Invalid metadata attachment");
1731 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1732 MD = upgradeInstructionLoopAttachment(*MD);
1734 if (I->second == LLVMContext::MD_tbaa) {
1735 assert(!MD->isTemporary() && "should load MDs before attachments");
1736 MD = UpgradeTBAANode(*MD);
1738 Inst->setMetadata(I->second, MD);
1746 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1747 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1748 SmallVectorImpl<uint64_t> &Record) {
1749 if (Record.size() < 2)
1750 return error("Invalid record");
1752 unsigned Kind = Record[0];
1753 SmallString<8> Name(Record.begin() + 1, Record.end());
1755 unsigned NewKind = TheModule.getMDKindID(Name.str());
1756 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1757 return error("Conflicting METADATA_KIND records");
1758 return Error::success();
1761 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1762 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1763 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1764 return error("Invalid record");
1766 SmallVector<uint64_t, 64> Record;
1768 // Read all the records.
1770 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1772 switch (Entry.Kind) {
1773 case BitstreamEntry::SubBlock: // Handled for us already.
1774 case BitstreamEntry::Error:
1775 return error("Malformed block");
1776 case BitstreamEntry::EndBlock:
1777 return Error::success();
1778 case BitstreamEntry::Record:
1779 // The interesting case.
1785 ++NumMDRecordLoaded;
1786 unsigned Code = Stream.readRecord(Entry.ID, Record);
1788 default: // Default behavior: ignore.
1790 case bitc::METADATA_KIND: {
1791 if (Error Err = parseMetadataKindRecord(Record))
1799 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1800 Pimpl = std::move(RHS.Pimpl);
1803 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
1804 : Pimpl(std::move(RHS.Pimpl)) {}
1806 MetadataLoader::~MetadataLoader() = default;
1807 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1808 BitcodeReaderValueList &ValueList,
1810 std::function<Type *(unsigned)> getTypeByID)
1811 : Pimpl(llvm::make_unique<MetadataLoaderImpl>(Stream, TheModule, ValueList,
1812 getTypeByID, IsImporting)) {}
1814 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
1815 return Pimpl->parseMetadata(ModuleLevel);
1818 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1820 /// Return the given metadata, creating a replaceable forward reference if
1822 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1823 return Pimpl->getMetadataFwdRefOrLoad(Idx);
1826 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1827 return Pimpl->getMDNodeFwdRefOrNull(Idx);
1830 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1831 return Pimpl->lookupSubprogramForFunction(F);
1834 Error MetadataLoader::parseMetadataAttachment(
1835 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1836 return Pimpl->parseMetadataAttachment(F, InstructionList);
1839 Error MetadataLoader::parseMetadataKinds() {
1840 return Pimpl->parseMetadataKinds();
1843 void MetadataLoader::setStripTBAA(bool StripTBAA) {
1844 return Pimpl->setStripTBAA(StripTBAA);
1847 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1849 unsigned MetadataLoader::size() const { return Pimpl->size(); }
1850 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }