1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "MetadataLoader.h"
10 #include "ValueList.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/BitmaskEnum.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLFunctionalExtras.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/Twine.h"
25 #include "llvm/ADT/ilist_iterator.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/BinaryFormat/Dwarf.h"
28 #include "llvm/Bitcode/BitcodeReader.h"
29 #include "llvm/Bitcode/LLVMBitCodes.h"
30 #include "llvm/Bitstream/BitstreamReader.h"
31 #include "llvm/IR/AutoUpgrade.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalObject.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/TrackingMDRef.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/type_traits.h"
60 #include <type_traits>
69 #define DEBUG_TYPE "bitcode-reader"
71 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
72 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
73 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
75 /// Flag whether we need to import full type definitions for ThinLTO.
76 /// Currently needed for Darwin and LLDB.
77 static cl::opt<bool> ImportFullTypeDefinitions(
78 "import-full-type-definitions", cl::init(false), cl::Hidden,
79 cl::desc("Import full type definitions for ThinLTO."));
81 static cl::opt<bool> DisableLazyLoading(
82 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
83 cl::desc("Force disable the lazy-loading on-demand of metadata when "
84 "loading bitcode for importing."));
88 static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
90 class BitcodeReaderMetadataList {
91 /// Array of metadata references.
93 /// Don't use std::vector here. Some versions of libc++ copy (instead of
94 /// move) on resize, and TrackingMDRef is very expensive to copy.
95 SmallVector<TrackingMDRef, 1> MetadataPtrs;
97 /// The set of indices in MetadataPtrs above of forward references that were
99 SmallDenseSet<unsigned, 1> ForwardReference;
101 /// The set of indices in MetadataPtrs above of Metadata that need to be
103 SmallDenseSet<unsigned, 1> UnresolvedNodes;
105 /// Structures for resolving old type refs.
107 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
108 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
109 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
110 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
113 LLVMContext &Context;
115 /// Maximum number of valid references. Forward references exceeding the
116 /// maximum must be invalid.
117 unsigned RefsUpperBound;
120 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
122 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
125 // vector compatibility methods
126 unsigned size() const { return MetadataPtrs.size(); }
127 void resize(unsigned N) { MetadataPtrs.resize(N); }
128 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
129 void clear() { MetadataPtrs.clear(); }
130 Metadata *back() const { return MetadataPtrs.back(); }
131 void pop_back() { MetadataPtrs.pop_back(); }
132 bool empty() const { return MetadataPtrs.empty(); }
134 Metadata *operator[](unsigned i) const {
135 assert(i < MetadataPtrs.size());
136 return MetadataPtrs[i];
139 Metadata *lookup(unsigned I) const {
140 if (I < MetadataPtrs.size())
141 return MetadataPtrs[I];
145 void shrinkTo(unsigned N) {
146 assert(N <= size() && "Invalid shrinkTo request!");
147 assert(ForwardReference.empty() && "Unexpected forward refs");
148 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
149 MetadataPtrs.resize(N);
152 /// Return the given metadata, creating a replaceable forward reference if
154 Metadata *getMetadataFwdRef(unsigned Idx);
156 /// Return the given metadata only if it is fully resolved.
158 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
159 /// would give \c false.
160 Metadata *getMetadataIfResolved(unsigned Idx);
162 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
163 void assignValue(Metadata *MD, unsigned Idx);
164 void tryToResolveCycles();
165 bool hasFwdRefs() const { return !ForwardReference.empty(); }
166 int getNextFwdRef() {
167 assert(hasFwdRefs());
168 return *ForwardReference.begin();
171 /// Upgrade a type that had an MDString reference.
172 void addTypeRef(MDString &UUID, DICompositeType &CT);
174 /// Upgrade a type that had an MDString reference.
175 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
177 /// Upgrade a type ref array that may have MDString references.
178 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
181 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
184 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
185 if (auto *MDN = dyn_cast<MDNode>(MD))
186 if (!MDN->isResolved())
187 UnresolvedNodes.insert(Idx);
197 TrackingMDRef &OldMD = MetadataPtrs[Idx];
203 // If there was a forward reference to this value, replace it.
204 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
205 PrevMD->replaceAllUsesWith(MD);
206 ForwardReference.erase(Idx);
209 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
210 // Bail out for a clearly invalid value.
211 if (Idx >= RefsUpperBound)
217 if (Metadata *MD = MetadataPtrs[Idx])
220 // Track forward refs to be resolved later.
221 ForwardReference.insert(Idx);
223 // Create and return a placeholder, which will later be RAUW'd.
224 ++NumMDNodeTemporary;
225 Metadata *MD = MDNode::getTemporary(Context, None).release();
226 MetadataPtrs[Idx].reset(MD);
230 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
231 Metadata *MD = lookup(Idx);
232 if (auto *N = dyn_cast_or_null<MDNode>(MD))
233 if (!N->isResolved())
238 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
239 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
242 void BitcodeReaderMetadataList::tryToResolveCycles() {
243 if (!ForwardReference.empty())
244 // Still forward references... can't resolve cycles.
247 // Give up on finding a full definition for any forward decls that remain.
248 for (const auto &Ref : OldTypeRefs.FwdDecls)
249 OldTypeRefs.Final.insert(Ref);
250 OldTypeRefs.FwdDecls.clear();
252 // Upgrade from old type ref arrays. In strange cases, this could add to
253 // OldTypeRefs.Unknown.
254 for (const auto &Array : OldTypeRefs.Arrays)
255 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
256 OldTypeRefs.Arrays.clear();
258 // Replace old string-based type refs with the resolved node, if possible.
259 // If we haven't seen the node, leave it to the verifier to complain about
260 // the invalid string reference.
261 for (const auto &Ref : OldTypeRefs.Unknown) {
262 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
263 Ref.second->replaceAllUsesWith(CT);
265 Ref.second->replaceAllUsesWith(Ref.first);
267 OldTypeRefs.Unknown.clear();
269 if (UnresolvedNodes.empty())
273 // Resolve any cycles.
274 for (unsigned I : UnresolvedNodes) {
275 auto &MD = MetadataPtrs[I];
276 auto *N = dyn_cast_or_null<MDNode>(MD);
280 assert(!N->isTemporary() && "Unexpected forward reference");
284 // Make sure we return early again until there's another unresolved ref.
285 UnresolvedNodes.clear();
288 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
289 DICompositeType &CT) {
290 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
291 if (CT.isForwardDecl())
292 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
294 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
297 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
298 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
299 if (LLVM_LIKELY(!UUID))
302 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
305 auto &Ref = OldTypeRefs.Unknown[UUID];
307 Ref = MDNode::getTemporary(Context, None);
311 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
312 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
313 if (!Tuple || Tuple->isDistinct())
316 // Look through the array immediately if possible.
317 if (!Tuple->isTemporary())
318 return resolveTypeRefArray(Tuple);
320 // Create and return a placeholder to use for now. Eventually
321 // resolveTypeRefArrays() will be resolve this forward reference.
322 OldTypeRefs.Arrays.emplace_back(
323 std::piecewise_construct, std::forward_as_tuple(Tuple),
324 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
325 return OldTypeRefs.Arrays.back().second.get();
328 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
329 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
330 if (!Tuple || Tuple->isDistinct())
333 // Look through the DITypeRefArray, upgrading each DIType *.
334 SmallVector<Metadata *, 32> Ops;
335 Ops.reserve(Tuple->getNumOperands());
336 for (Metadata *MD : Tuple->operands())
337 Ops.push_back(upgradeTypeRef(MD));
339 return MDTuple::get(Context, Ops);
344 class PlaceholderQueue {
345 // Placeholders would thrash around when moved, so store in a std::deque
346 // instead of some sort of vector.
347 std::deque<DistinctMDOperandPlaceholder> PHs;
350 ~PlaceholderQueue() {
352 "PlaceholderQueue hasn't been flushed before being destroyed");
354 bool empty() const { return PHs.empty(); }
355 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
356 void flush(BitcodeReaderMetadataList &MetadataList);
358 /// Return the list of temporaries nodes in the queue, these need to be
359 /// loaded before we can flush the queue.
360 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
361 DenseSet<unsigned> &Temporaries) {
362 for (auto &PH : PHs) {
363 auto ID = PH.getID();
364 auto *MD = MetadataList.lookup(ID);
366 Temporaries.insert(ID);
369 auto *N = dyn_cast_or_null<MDNode>(MD);
370 if (N && N->isTemporary())
371 Temporaries.insert(ID);
376 } // end anonymous namespace
378 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
379 PHs.emplace_back(ID);
383 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
384 while (!PHs.empty()) {
385 auto *MD = MetadataList.lookup(PHs.front().getID());
386 assert(MD && "Flushing placeholder on unassigned MD");
388 if (auto *MDN = dyn_cast<MDNode>(MD))
389 assert(MDN->isResolved() &&
390 "Flushing Placeholder while cycles aren't resolved");
392 PHs.front().replaceUseWith(MD);
397 } // anonymous namespace
399 static Error error(const Twine &Message) {
400 return make_error<StringError>(
401 Message, make_error_code(BitcodeError::CorruptedBitcode));
404 class MetadataLoader::MetadataLoaderImpl {
405 BitcodeReaderMetadataList MetadataList;
406 BitcodeReaderValueList &ValueList;
407 BitstreamCursor &Stream;
408 LLVMContext &Context;
410 std::function<Type *(unsigned)> getTypeByID;
412 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
413 /// to keep around the right "context" (Abbrev list) to be able to jump in
414 /// the middle of the metadata block and load any record.
415 BitstreamCursor IndexCursor;
417 /// Index that keeps track of MDString values.
418 std::vector<StringRef> MDStringRef;
420 /// On-demand loading of a single MDString. Requires the index above to be
422 MDString *lazyLoadOneMDString(unsigned Idx);
424 /// Index that keeps track of where to find a metadata record in the stream.
425 std::vector<uint64_t> GlobalMetadataBitPosIndex;
427 /// Cursor position of the start of the global decl attachments, to enable
428 /// loading using the index built for lazy loading, instead of forward
430 uint64_t GlobalDeclAttachmentPos = 0;
433 /// Baisic correctness check that we end up parsing all of the global decl
435 unsigned NumGlobalDeclAttachSkipped = 0;
436 unsigned NumGlobalDeclAttachParsed = 0;
439 /// Load the global decl attachments, using the index built for lazy loading.
440 Expected<bool> loadGlobalDeclAttachments();
442 /// Populate the index above to enable lazily loading of metadata, and load
443 /// the named metadata as well as the transitively referenced global
445 Expected<bool> lazyLoadModuleMetadataBlock();
447 /// On-demand loading of a single metadata. Requires the index above to be
449 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
451 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
452 // point from SP to CU after a block is completly parsed.
453 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
455 /// Functions that need to be matched with subprograms when upgrading old
457 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
459 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
460 DenseMap<unsigned, unsigned> MDKindMap;
462 bool StripTBAA = false;
463 bool HasSeenOldLoopTags = false;
464 bool NeedUpgradeToDIGlobalVariableExpression = false;
465 bool NeedDeclareExpressionUpgrade = false;
467 /// True if metadata is being parsed for a module being ThinLTO imported.
468 bool IsImporting = false;
470 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
471 PlaceholderQueue &Placeholders, StringRef Blob,
472 unsigned &NextMetadataNo);
473 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
474 function_ref<void(StringRef)> CallBack);
475 Error parseGlobalObjectAttachment(GlobalObject &GO,
476 ArrayRef<uint64_t> Record);
477 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
479 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
481 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
482 void upgradeCUSubprograms() {
483 for (auto CU_SP : CUSubprograms)
484 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
485 for (auto &Op : SPs->operands())
486 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
487 SP->replaceUnit(CU_SP.first);
488 CUSubprograms.clear();
491 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
492 void upgradeCUVariables() {
493 if (!NeedUpgradeToDIGlobalVariableExpression)
496 // Upgrade list of variables attached to the CUs.
497 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
498 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
499 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
500 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
501 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
503 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
504 auto *DGVE = DIGlobalVariableExpression::getDistinct(
505 Context, GV, DIExpression::get(Context, {}));
506 GVs->replaceOperandWith(I, DGVE);
510 // Upgrade variables attached to globals.
511 for (auto &GV : TheModule.globals()) {
512 SmallVector<MDNode *, 1> MDs;
513 GV.getMetadata(LLVMContext::MD_dbg, MDs);
514 GV.eraseMetadata(LLVMContext::MD_dbg);
516 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
517 auto *DGVE = DIGlobalVariableExpression::getDistinct(
518 Context, DGV, DIExpression::get(Context, {}));
519 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
521 GV.addMetadata(LLVMContext::MD_dbg, *MD);
525 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
526 /// describes a function argument.
527 void upgradeDeclareExpressions(Function &F) {
528 if (!NeedDeclareExpressionUpgrade)
533 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
534 if (auto *DIExpr = DDI->getExpression())
535 if (DIExpr->startsWithDeref() &&
536 isa_and_nonnull<Argument>(DDI->getAddress())) {
537 SmallVector<uint64_t, 8> Ops;
538 Ops.append(std::next(DIExpr->elements_begin()),
539 DIExpr->elements_end());
540 DDI->setExpression(DIExpression::get(Context, Ops));
544 /// Upgrade the expression from previous versions.
545 Error upgradeDIExpression(uint64_t FromVersion,
546 MutableArrayRef<uint64_t> &Expr,
547 SmallVectorImpl<uint64_t> &Buffer) {
548 auto N = Expr.size();
549 switch (FromVersion) {
551 return error("Invalid record");
553 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
554 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
557 // Move DW_OP_deref to the end.
558 if (N && Expr[0] == dwarf::DW_OP_deref) {
559 auto End = Expr.end();
560 if (Expr.size() >= 3 &&
561 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
562 End = std::prev(End, 3);
563 std::move(std::next(Expr.begin()), End, Expr.begin());
564 *std::prev(End) = dwarf::DW_OP_deref;
566 NeedDeclareExpressionUpgrade = true;
569 // Change DW_OP_plus to DW_OP_plus_uconst.
570 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
571 auto SubExpr = ArrayRef<uint64_t>(Expr);
572 while (!SubExpr.empty()) {
573 // Skip past other operators with their operands
574 // for this version of the IR, obtained from
575 // from historic DIExpression::ExprOperand::getSize().
577 switch (SubExpr.front()) {
581 case dwarf::DW_OP_constu:
582 case dwarf::DW_OP_minus:
583 case dwarf::DW_OP_plus:
586 case dwarf::DW_OP_LLVM_fragment:
591 // If the expression is malformed, make sure we don't
592 // copy more elements than we should.
593 HistoricSize = std::min(SubExpr.size(), HistoricSize);
594 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
596 switch (SubExpr.front()) {
597 case dwarf::DW_OP_plus:
598 Buffer.push_back(dwarf::DW_OP_plus_uconst);
599 Buffer.append(Args.begin(), Args.end());
601 case dwarf::DW_OP_minus:
602 Buffer.push_back(dwarf::DW_OP_constu);
603 Buffer.append(Args.begin(), Args.end());
604 Buffer.push_back(dwarf::DW_OP_minus);
607 Buffer.push_back(*SubExpr.begin());
608 Buffer.append(Args.begin(), Args.end());
612 // Continue with remaining elements.
613 SubExpr = SubExpr.slice(HistoricSize);
615 Expr = MutableArrayRef<uint64_t>(Buffer);
623 return Error::success();
626 void upgradeDebugInfo() {
627 upgradeCUSubprograms();
628 upgradeCUVariables();
632 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
633 BitcodeReaderValueList &ValueList,
634 std::function<Type *(unsigned)> getTypeByID,
636 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
637 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
638 TheModule(TheModule), getTypeByID(std::move(getTypeByID)),
639 IsImporting(IsImporting) {}
641 Error parseMetadata(bool ModuleLevel);
643 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
645 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
646 if (ID < MDStringRef.size())
647 return lazyLoadOneMDString(ID);
648 if (auto *MD = MetadataList.lookup(ID))
650 // If lazy-loading is enabled, we try recursively to load the operand
651 // instead of creating a temporary.
652 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
653 PlaceholderQueue Placeholders;
654 lazyLoadOneMetadata(ID, Placeholders);
655 resolveForwardRefsAndPlaceholders(Placeholders);
656 return MetadataList.lookup(ID);
658 return MetadataList.getMetadataFwdRef(ID);
661 DISubprogram *lookupSubprogramForFunction(Function *F) {
662 return FunctionsWithSPs.lookup(F);
665 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
667 Error parseMetadataAttachment(Function &F,
668 ArrayRef<Instruction *> InstructionList);
670 Error parseMetadataKinds();
672 void setStripTBAA(bool Value) { StripTBAA = Value; }
673 bool isStrippingTBAA() const { return StripTBAA; }
675 unsigned size() const { return MetadataList.size(); }
676 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
677 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
681 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
682 IndexCursor = Stream;
683 SmallVector<uint64_t, 64> Record;
684 GlobalDeclAttachmentPos = 0;
685 // Get the abbrevs, and preload record positions to make them lazy-loadable.
687 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
688 BitstreamEntry Entry;
691 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
695 switch (Entry.Kind) {
696 case BitstreamEntry::SubBlock: // Handled for us already.
697 case BitstreamEntry::Error:
698 return error("Malformed block");
699 case BitstreamEntry::EndBlock: {
702 case BitstreamEntry::Record: {
703 // The interesting case.
705 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
707 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
710 case bitc::METADATA_STRINGS: {
711 // Rewind and parse the strings.
712 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
713 return std::move(Err);
716 if (Expected<unsigned> MaybeRecord =
717 IndexCursor.readRecord(Entry.ID, Record, &Blob))
720 return MaybeRecord.takeError();
721 unsigned NumStrings = Record[0];
722 MDStringRef.reserve(NumStrings);
723 auto IndexNextMDString = [&](StringRef Str) {
724 MDStringRef.push_back(Str);
726 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
727 return std::move(Err);
730 case bitc::METADATA_INDEX_OFFSET: {
731 // This is the offset to the index, when we see this we skip all the
732 // records and load only an index to these.
733 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
734 return std::move(Err);
736 if (Expected<unsigned> MaybeRecord =
737 IndexCursor.readRecord(Entry.ID, Record))
740 return MaybeRecord.takeError();
741 if (Record.size() != 2)
742 return error("Invalid record");
743 auto Offset = Record[0] + (Record[1] << 32);
744 auto BeginPos = IndexCursor.GetCurrentBitNo();
745 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
746 return std::move(Err);
747 Expected<BitstreamEntry> MaybeEntry =
748 IndexCursor.advanceSkippingSubblocks(
749 BitstreamCursor::AF_DontPopBlockAtEnd);
751 return MaybeEntry.takeError();
752 Entry = MaybeEntry.get();
753 assert(Entry.Kind == BitstreamEntry::Record &&
754 "Corrupted bitcode: Expected `Record` when trying to find the "
757 if (Expected<unsigned> MaybeCode =
758 IndexCursor.readRecord(Entry.ID, Record))
759 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
760 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
761 "find the Metadata index");
763 return MaybeCode.takeError();
765 auto CurrentValue = BeginPos;
766 GlobalMetadataBitPosIndex.reserve(Record.size());
767 for (auto &Elt : Record) {
769 GlobalMetadataBitPosIndex.push_back(CurrentValue);
773 case bitc::METADATA_INDEX:
774 // We don't expect to get there, the Index is loaded when we encounter
776 return error("Corrupted Metadata block");
777 case bitc::METADATA_NAME: {
778 // Named metadata need to be materialized now and aren't deferred.
779 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
780 return std::move(Err);
784 if (Expected<unsigned> MaybeCode =
785 IndexCursor.readRecord(Entry.ID, Record)) {
786 Code = MaybeCode.get();
787 assert(Code == bitc::METADATA_NAME);
789 return MaybeCode.takeError();
791 // Read name of the named metadata.
792 SmallString<8> Name(Record.begin(), Record.end());
793 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
794 Code = MaybeCode.get();
796 return MaybeCode.takeError();
798 // Named Metadata comes in two parts, we expect the name to be followed
801 if (Expected<unsigned> MaybeNextBitCode =
802 IndexCursor.readRecord(Code, Record))
803 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
805 return MaybeNextBitCode.takeError();
807 // Read named metadata elements.
808 unsigned Size = Record.size();
809 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
810 for (unsigned i = 0; i != Size; ++i) {
811 // FIXME: We could use a placeholder here, however NamedMDNode are
812 // taking MDNode as operand and not using the Metadata infrastructure.
813 // It is acknowledged by 'TODO: Inherit from Metadata' in the
814 // NamedMDNode class definition.
815 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
816 assert(MD && "Invalid metadata: expect fwd ref to MDNode");
821 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
822 if (!GlobalDeclAttachmentPos)
823 GlobalDeclAttachmentPos = SavedPos;
825 NumGlobalDeclAttachSkipped++;
829 case bitc::METADATA_KIND:
830 case bitc::METADATA_STRING_OLD:
831 case bitc::METADATA_OLD_FN_NODE:
832 case bitc::METADATA_OLD_NODE:
833 case bitc::METADATA_VALUE:
834 case bitc::METADATA_DISTINCT_NODE:
835 case bitc::METADATA_NODE:
836 case bitc::METADATA_LOCATION:
837 case bitc::METADATA_GENERIC_DEBUG:
838 case bitc::METADATA_SUBRANGE:
839 case bitc::METADATA_ENUMERATOR:
840 case bitc::METADATA_BASIC_TYPE:
841 case bitc::METADATA_STRING_TYPE:
842 case bitc::METADATA_DERIVED_TYPE:
843 case bitc::METADATA_COMPOSITE_TYPE:
844 case bitc::METADATA_SUBROUTINE_TYPE:
845 case bitc::METADATA_MODULE:
846 case bitc::METADATA_FILE:
847 case bitc::METADATA_COMPILE_UNIT:
848 case bitc::METADATA_SUBPROGRAM:
849 case bitc::METADATA_LEXICAL_BLOCK:
850 case bitc::METADATA_LEXICAL_BLOCK_FILE:
851 case bitc::METADATA_NAMESPACE:
852 case bitc::METADATA_COMMON_BLOCK:
853 case bitc::METADATA_MACRO:
854 case bitc::METADATA_MACRO_FILE:
855 case bitc::METADATA_TEMPLATE_TYPE:
856 case bitc::METADATA_TEMPLATE_VALUE:
857 case bitc::METADATA_GLOBAL_VAR:
858 case bitc::METADATA_LOCAL_VAR:
859 case bitc::METADATA_LABEL:
860 case bitc::METADATA_EXPRESSION:
861 case bitc::METADATA_OBJC_PROPERTY:
862 case bitc::METADATA_IMPORTED_ENTITY:
863 case bitc::METADATA_GLOBAL_VAR_EXPR:
864 case bitc::METADATA_GENERIC_SUBRANGE:
865 // We don't expect to see any of these, if we see one, give up on
866 // lazy-loading and fallback.
868 GlobalMetadataBitPosIndex.clear();
877 // Load the global decl attachments after building the lazy loading index.
878 // We don't load them "lazily" - all global decl attachments must be
879 // parsed since they aren't materialized on demand. However, by delaying
880 // their parsing until after the index is created, we can use the index
881 // instead of creating temporaries.
882 Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
883 // Nothing to do if we didn't find any of these metadata records.
884 if (!GlobalDeclAttachmentPos)
886 // Use a temporary cursor so that we don't mess up the main Stream cursor or
887 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
888 BitstreamCursor TempCursor = Stream;
889 SmallVector<uint64_t, 64> Record;
890 // Jump to the position before the first global decl attachment, so we can
891 // scan for the first BitstreamEntry record.
892 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
893 return std::move(Err);
895 BitstreamEntry Entry;
898 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
902 switch (Entry.Kind) {
903 case BitstreamEntry::SubBlock: // Handled for us already.
904 case BitstreamEntry::Error:
905 return error("Malformed block");
906 case BitstreamEntry::EndBlock:
907 // Check that we parsed them all.
908 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
910 case BitstreamEntry::Record:
913 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
914 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
916 return MaybeCode.takeError();
917 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
918 // Anything other than a global decl attachment signals the end of
919 // these records. Check that we parsed them all.
920 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
924 NumGlobalDeclAttachParsed++;
926 // FIXME: we need to do this early because we don't materialize global
928 if (Error Err = TempCursor.JumpToBit(CurrentPos))
929 return std::move(Err);
931 if (Expected<unsigned> MaybeRecord =
932 TempCursor.readRecord(Entry.ID, Record))
935 return MaybeRecord.takeError();
936 if (Record.size() % 2 == 0)
937 return error("Invalid record");
938 unsigned ValueID = Record[0];
939 if (ValueID >= ValueList.size())
940 return error("Invalid record");
941 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
942 // Need to save and restore the current position since
943 // parseGlobalObjectAttachment will resolve all forward references which
944 // would require parsing from locations stored in the index.
945 CurrentPos = TempCursor.GetCurrentBitNo();
946 if (Error Err = parseGlobalObjectAttachment(
947 *GO, ArrayRef<uint64_t>(Record).slice(1)))
948 return std::move(Err);
949 if (Error Err = TempCursor.JumpToBit(CurrentPos))
950 return std::move(Err);
955 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
956 /// module level metadata.
957 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
958 if (!ModuleLevel && MetadataList.hasFwdRefs())
959 return error("Invalid metadata: fwd refs into function blocks");
961 // Record the entry position so that we can jump back here and efficiently
962 // skip the whole block in case we lazy-load.
963 auto EntryPos = Stream.GetCurrentBitNo();
965 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
968 SmallVector<uint64_t, 64> Record;
969 PlaceholderQueue Placeholders;
971 // We lazy-load module-level metadata: we build an index for each record, and
972 // then load individual record as needed, starting with the named metadata.
973 if (ModuleLevel && IsImporting && MetadataList.empty() &&
974 !DisableLazyLoading) {
975 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
977 return SuccessOrErr.takeError();
978 if (SuccessOrErr.get()) {
979 // An index was successfully created and we will be able to load metadata
981 MetadataList.resize(MDStringRef.size() +
982 GlobalMetadataBitPosIndex.size());
984 // Now that we have built the index, load the global decl attachments
985 // that were deferred during that process. This avoids creating
987 SuccessOrErr = loadGlobalDeclAttachments();
989 return SuccessOrErr.takeError();
990 assert(SuccessOrErr.get());
992 // Reading the named metadata created forward references and/or
993 // placeholders, that we flush here.
994 resolveForwardRefsAndPlaceholders(Placeholders);
996 // Return at the beginning of the block, since it is easy to skip it
997 // entirely from there.
998 Stream.ReadBlockEnd(); // Pop the abbrev block context.
999 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1001 if (Error Err = Stream.SkipBlock()) {
1002 // FIXME this drops the error on the floor, which
1003 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1004 consumeError(std::move(Err));
1005 return Error::success();
1007 return Error::success();
1009 // Couldn't load an index, fallback to loading all the block "old-style".
1012 unsigned NextMetadataNo = MetadataList.size();
1014 // Read all the records.
1016 BitstreamEntry Entry;
1017 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1020 switch (Entry.Kind) {
1021 case BitstreamEntry::SubBlock: // Handled for us already.
1022 case BitstreamEntry::Error:
1023 return error("Malformed block");
1024 case BitstreamEntry::EndBlock:
1025 resolveForwardRefsAndPlaceholders(Placeholders);
1027 return Error::success();
1028 case BitstreamEntry::Record:
1029 // The interesting case.
1036 ++NumMDRecordLoaded;
1037 if (Expected<unsigned> MaybeCode =
1038 Stream.readRecord(Entry.ID, Record, &Blob)) {
1039 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1040 Blob, NextMetadataNo))
1043 return MaybeCode.takeError();
1047 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1048 ++NumMDStringLoaded;
1049 if (Metadata *MD = MetadataList.lookup(ID))
1050 return cast<MDString>(MD);
1051 auto MDS = MDString::get(Context, MDStringRef[ID]);
1052 MetadataList.assignValue(MDS, ID);
1056 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1057 unsigned ID, PlaceholderQueue &Placeholders) {
1058 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1059 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
1060 // Lookup first if the metadata hasn't already been loaded.
1061 if (auto *MD = MetadataList.lookup(ID)) {
1062 auto *N = cast<MDNode>(MD);
1063 if (!N->isTemporary())
1066 SmallVector<uint64_t, 64> Record;
1068 if (Error Err = IndexCursor.JumpToBit(
1069 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1070 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1071 Twine(toString(std::move(Err))));
1072 BitstreamEntry Entry;
1073 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1074 // FIXME this drops the error on the floor.
1075 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1076 Twine(toString(std::move(E))));
1077 ++NumMDRecordLoaded;
1078 if (Expected<unsigned> MaybeCode =
1079 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1081 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1082 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1083 Twine(toString(std::move(Err))));
1085 report_fatal_error("Can't lazyload MD: " +
1086 Twine(toString(MaybeCode.takeError())));
1089 /// Ensure that all forward-references and placeholders are resolved.
1090 /// Iteratively lazy-loading metadata on-demand if needed.
1091 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1092 PlaceholderQueue &Placeholders) {
1093 DenseSet<unsigned> Temporaries;
1095 // Populate Temporaries with the placeholders that haven't been loaded yet.
1096 Placeholders.getTemporaries(MetadataList, Temporaries);
1098 // If we don't have any temporary, or FwdReference, we're done!
1099 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1102 // First, load all the temporaries. This can add new placeholders or
1103 // forward references.
1104 for (auto ID : Temporaries)
1105 lazyLoadOneMetadata(ID, Placeholders);
1106 Temporaries.clear();
1108 // Second, load the forward-references. This can also add new placeholders
1109 // or forward references.
1110 while (MetadataList.hasFwdRefs())
1111 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1113 // At this point we don't have any forward reference remaining, or temporary
1114 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1116 MetadataList.tryToResolveCycles();
1118 // Finally, everything is in place, we can replace the placeholders operands
1119 // with the final node they refer to.
1120 Placeholders.flush(MetadataList);
1123 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1124 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1125 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1127 bool IsDistinct = false;
1128 auto getMD = [&](unsigned ID) -> Metadata * {
1129 if (ID < MDStringRef.size())
1130 return lazyLoadOneMDString(ID);
1132 if (auto *MD = MetadataList.lookup(ID))
1134 // If lazy-loading is enabled, we try recursively to load the operand
1135 // instead of creating a temporary.
1136 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1137 // Create a temporary for the node that is referencing the operand we
1138 // will lazy-load. It is needed before recursing in case there are
1140 MetadataList.getMetadataFwdRef(NextMetadataNo);
1141 lazyLoadOneMetadata(ID, Placeholders);
1142 return MetadataList.lookup(ID);
1144 // Return a temporary.
1145 return MetadataList.getMetadataFwdRef(ID);
1147 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1149 return &Placeholders.getPlaceholderOp(ID);
1151 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1153 return getMD(ID - 1);
1156 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1158 return MetadataList.getMetadataFwdRef(ID - 1);
1161 auto getMDString = [&](unsigned ID) -> MDString * {
1162 // This requires that the ID is not really a forward reference. In
1163 // particular, the MDString must already have been resolved.
1164 auto MDS = getMDOrNull(ID);
1165 return cast_or_null<MDString>(MDS);
1168 // Support for old type refs.
1169 auto getDITypeRefOrNull = [&](unsigned ID) {
1170 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1173 #define GET_OR_DISTINCT(CLASS, ARGS) \
1174 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1177 default: // Default behavior: ignore.
1179 case bitc::METADATA_NAME: {
1180 // Read name of the named metadata.
1181 SmallString<8> Name(Record.begin(), Record.end());
1183 if (Error E = Stream.ReadCode().moveInto(Code))
1186 ++NumMDRecordLoaded;
1187 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1188 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1189 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1191 return MaybeNextBitCode.takeError();
1193 // Read named metadata elements.
1194 unsigned Size = Record.size();
1195 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1196 for (unsigned i = 0; i != Size; ++i) {
1197 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1199 return error("Invalid named metadata: expect fwd ref to MDNode");
1200 NMD->addOperand(MD);
1204 case bitc::METADATA_OLD_FN_NODE: {
1205 // Deprecated, but still needed to read old bitcode files.
1206 // This is a LocalAsMetadata record, the only type of function-local
1208 if (Record.size() % 2 == 1)
1209 return error("Invalid record");
1211 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1212 // to be legal, but there's no upgrade path.
1213 auto dropRecord = [&] {
1214 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
1217 if (Record.size() != 2) {
1222 unsigned TyID = Record[0];
1223 Type *Ty = getTypeByID(TyID);
1224 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1229 MetadataList.assignValue(
1230 LocalAsMetadata::get(ValueList.getValueFwdRef(
1231 Record[1], Ty, TyID, /*ConstExprInsertBB*/ nullptr)),
1236 case bitc::METADATA_OLD_NODE: {
1237 // Deprecated, but still needed to read old bitcode files.
1238 if (Record.size() % 2 == 1)
1239 return error("Invalid record");
1241 unsigned Size = Record.size();
1242 SmallVector<Metadata *, 8> Elts;
1243 for (unsigned i = 0; i != Size; i += 2) {
1244 unsigned TyID = Record[i];
1245 Type *Ty = getTypeByID(TyID);
1247 return error("Invalid record");
1248 if (Ty->isMetadataTy())
1249 Elts.push_back(getMD(Record[i + 1]));
1250 else if (!Ty->isVoidTy()) {
1251 auto *MD = ValueAsMetadata::get(ValueList.getValueFwdRef(
1252 Record[i + 1], Ty, TyID, /*ConstExprInsertBB*/ nullptr));
1253 assert(isa<ConstantAsMetadata>(MD) &&
1254 "Expected non-function-local metadata");
1257 Elts.push_back(nullptr);
1259 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1263 case bitc::METADATA_VALUE: {
1264 if (Record.size() != 2)
1265 return error("Invalid record");
1267 unsigned TyID = Record[0];
1268 Type *Ty = getTypeByID(TyID);
1269 if (Ty->isMetadataTy() || Ty->isVoidTy())
1270 return error("Invalid record");
1272 MetadataList.assignValue(
1273 ValueAsMetadata::get(ValueList.getValueFwdRef(
1274 Record[1], Ty, TyID, /*ConstExprInsertBB*/ nullptr)),
1279 case bitc::METADATA_DISTINCT_NODE:
1282 case bitc::METADATA_NODE: {
1283 SmallVector<Metadata *, 8> Elts;
1284 Elts.reserve(Record.size());
1285 for (unsigned ID : Record)
1286 Elts.push_back(getMDOrNull(ID));
1287 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1288 : MDNode::get(Context, Elts),
1293 case bitc::METADATA_LOCATION: {
1294 if (Record.size() != 5 && Record.size() != 6)
1295 return error("Invalid record");
1297 IsDistinct = Record[0];
1298 unsigned Line = Record[1];
1299 unsigned Column = Record[2];
1300 Metadata *Scope = getMD(Record[3]);
1301 Metadata *InlinedAt = getMDOrNull(Record[4]);
1302 bool ImplicitCode = Record.size() == 6 && Record[5];
1303 MetadataList.assignValue(
1304 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1310 case bitc::METADATA_GENERIC_DEBUG: {
1311 if (Record.size() < 4)
1312 return error("Invalid record");
1314 IsDistinct = Record[0];
1315 unsigned Tag = Record[1];
1316 unsigned Version = Record[2];
1318 if (Tag >= 1u << 16 || Version != 0)
1319 return error("Invalid record");
1321 auto *Header = getMDString(Record[3]);
1322 SmallVector<Metadata *, 8> DwarfOps;
1323 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1324 DwarfOps.push_back(getMDOrNull(Record[I]));
1325 MetadataList.assignValue(
1326 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1331 case bitc::METADATA_SUBRANGE: {
1332 Metadata *Val = nullptr;
1333 // Operand 'count' is interpreted as:
1334 // - Signed integer (version 0)
1335 // - Metadata node (version 1)
1336 // Operand 'lowerBound' is interpreted as:
1337 // - Signed integer (version 0 and 1)
1338 // - Metadata node (version 2)
1339 // Operands 'upperBound' and 'stride' are interpreted as:
1340 // - Metadata node (version 2)
1341 switch (Record[0] >> 1) {
1343 Val = GET_OR_DISTINCT(DISubrange,
1344 (Context, Record[1], unrotateSign(Record[2])));
1347 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1348 unrotateSign(Record[2])));
1351 Val = GET_OR_DISTINCT(
1352 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1353 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1356 return error("Invalid record: Unsupported version of DISubrange");
1359 MetadataList.assignValue(Val, NextMetadataNo);
1360 IsDistinct = Record[0] & 1;
1364 case bitc::METADATA_GENERIC_SUBRANGE: {
1365 Metadata *Val = nullptr;
1366 Val = GET_OR_DISTINCT(DIGenericSubrange,
1367 (Context, getMDOrNull(Record[1]),
1368 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1369 getMDOrNull(Record[4])));
1371 MetadataList.assignValue(Val, NextMetadataNo);
1372 IsDistinct = Record[0] & 1;
1376 case bitc::METADATA_ENUMERATOR: {
1377 if (Record.size() < 3)
1378 return error("Invalid record");
1380 IsDistinct = Record[0] & 1;
1381 bool IsUnsigned = Record[0] & 2;
1382 bool IsBigInt = Record[0] & 4;
1386 const uint64_t BitWidth = Record[1];
1387 const size_t NumWords = Record.size() - 3;
1388 Value = readWideAPInt(makeArrayRef(&Record[3], NumWords), BitWidth);
1390 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1392 MetadataList.assignValue(
1393 GET_OR_DISTINCT(DIEnumerator,
1394 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1399 case bitc::METADATA_BASIC_TYPE: {
1400 if (Record.size() < 6 || Record.size() > 7)
1401 return error("Invalid record");
1403 IsDistinct = Record[0];
1404 DINode::DIFlags Flags = (Record.size() > 6)
1405 ? static_cast<DINode::DIFlags>(Record[6])
1408 MetadataList.assignValue(
1409 GET_OR_DISTINCT(DIBasicType,
1410 (Context, Record[1], getMDString(Record[2]), Record[3],
1411 Record[4], Record[5], Flags)),
1416 case bitc::METADATA_STRING_TYPE: {
1417 if (Record.size() > 9 || Record.size() < 8)
1418 return error("Invalid record");
1420 IsDistinct = Record[0];
1421 bool SizeIs8 = Record.size() == 8;
1422 // StringLocationExp (i.e. Record[5]) is added at a later time
1423 // than the other fields. The code here enables backward compatibility.
1424 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1425 unsigned Offset = SizeIs8 ? 5 : 6;
1426 MetadataList.assignValue(
1427 GET_OR_DISTINCT(DIStringType,
1428 (Context, Record[1], getMDString(Record[2]),
1429 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1430 StringLocationExp, Record[Offset], Record[Offset + 1],
1431 Record[Offset + 2])),
1436 case bitc::METADATA_DERIVED_TYPE: {
1437 if (Record.size() < 12 || Record.size() > 14)
1438 return error("Invalid record");
1440 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1441 // that there is no DWARF address space associated with DIDerivedType.
1442 Optional<unsigned> DWARFAddressSpace;
1443 if (Record.size() > 12 && Record[12])
1444 DWARFAddressSpace = Record[12] - 1;
1446 Metadata *Annotations = nullptr;
1447 if (Record.size() > 13 && Record[13])
1448 Annotations = getMDOrNull(Record[13]);
1450 IsDistinct = Record[0];
1451 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1452 MetadataList.assignValue(
1453 GET_OR_DISTINCT(DIDerivedType,
1454 (Context, Record[1], getMDString(Record[2]),
1455 getMDOrNull(Record[3]), Record[4],
1456 getDITypeRefOrNull(Record[5]),
1457 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1458 Record[9], DWARFAddressSpace, Flags,
1459 getDITypeRefOrNull(Record[11]), Annotations)),
1464 case bitc::METADATA_COMPOSITE_TYPE: {
1465 if (Record.size() < 16 || Record.size() > 22)
1466 return error("Invalid record");
1468 // If we have a UUID and this is not a forward declaration, lookup the
1470 IsDistinct = Record[0] & 0x1;
1471 bool IsNotUsedInTypeRef = Record[0] >= 2;
1472 unsigned Tag = Record[1];
1473 MDString *Name = getMDString(Record[2]);
1474 Metadata *File = getMDOrNull(Record[3]);
1475 unsigned Line = Record[4];
1476 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1477 Metadata *BaseType = nullptr;
1478 uint64_t SizeInBits = Record[7];
1479 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1480 return error("Alignment value is too large");
1481 uint32_t AlignInBits = Record[8];
1482 uint64_t OffsetInBits = 0;
1483 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1484 Metadata *Elements = nullptr;
1485 unsigned RuntimeLang = Record[12];
1486 Metadata *VTableHolder = nullptr;
1487 Metadata *TemplateParams = nullptr;
1488 Metadata *Discriminator = nullptr;
1489 Metadata *DataLocation = nullptr;
1490 Metadata *Associated = nullptr;
1491 Metadata *Allocated = nullptr;
1492 Metadata *Rank = nullptr;
1493 Metadata *Annotations = nullptr;
1494 auto *Identifier = getMDString(Record[15]);
1495 // If this module is being parsed so that it can be ThinLTO imported
1496 // into another module, composite types only need to be imported
1497 // as type declarations (unless full type definitions requested).
1498 // Create type declarations up front to save memory. Also, buildODRType
1499 // handles the case where this is type ODRed with a definition needed
1500 // by the importing module, in which case the existing definition is
1502 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1503 (Tag == dwarf::DW_TAG_enumeration_type ||
1504 Tag == dwarf::DW_TAG_class_type ||
1505 Tag == dwarf::DW_TAG_structure_type ||
1506 Tag == dwarf::DW_TAG_union_type)) {
1507 Flags = Flags | DINode::FlagFwdDecl;
1509 // This is a hack around preserving template parameters for simplified
1510 // template names - it should probably be replaced with a
1511 // DICompositeType flag specifying whether template parameters are
1512 // required on declarations of this type.
1513 StringRef NameStr = Name->getString();
1514 if (!NameStr.contains('<') || NameStr.startswith("_STN|"))
1515 TemplateParams = getMDOrNull(Record[14]);
1518 BaseType = getDITypeRefOrNull(Record[6]);
1519 OffsetInBits = Record[9];
1520 Elements = getMDOrNull(Record[11]);
1521 VTableHolder = getDITypeRefOrNull(Record[13]);
1522 TemplateParams = getMDOrNull(Record[14]);
1523 if (Record.size() > 16)
1524 Discriminator = getMDOrNull(Record[16]);
1525 if (Record.size() > 17)
1526 DataLocation = getMDOrNull(Record[17]);
1527 if (Record.size() > 19) {
1528 Associated = getMDOrNull(Record[18]);
1529 Allocated = getMDOrNull(Record[19]);
1531 if (Record.size() > 20) {
1532 Rank = getMDOrNull(Record[20]);
1534 if (Record.size() > 21) {
1535 Annotations = getMDOrNull(Record[21]);
1538 DICompositeType *CT = nullptr;
1540 CT = DICompositeType::buildODRType(
1541 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1542 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1543 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1544 Allocated, Rank, Annotations);
1546 // Create a node if we didn't get a lazy ODR type.
1548 CT = GET_OR_DISTINCT(DICompositeType,
1549 (Context, Tag, Name, File, Line, Scope, BaseType,
1550 SizeInBits, AlignInBits, OffsetInBits, Flags,
1551 Elements, RuntimeLang, VTableHolder, TemplateParams,
1552 Identifier, Discriminator, DataLocation, Associated,
1553 Allocated, Rank, Annotations));
1554 if (!IsNotUsedInTypeRef && Identifier)
1555 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1557 MetadataList.assignValue(CT, NextMetadataNo);
1561 case bitc::METADATA_SUBROUTINE_TYPE: {
1562 if (Record.size() < 3 || Record.size() > 4)
1563 return error("Invalid record");
1564 bool IsOldTypeRefArray = Record[0] < 2;
1565 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1567 IsDistinct = Record[0] & 0x1;
1568 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1569 Metadata *Types = getMDOrNull(Record[2]);
1570 if (LLVM_UNLIKELY(IsOldTypeRefArray))
1571 Types = MetadataList.upgradeTypeRefArray(Types);
1573 MetadataList.assignValue(
1574 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1580 case bitc::METADATA_MODULE: {
1581 if (Record.size() < 5 || Record.size() > 9)
1582 return error("Invalid record");
1584 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1585 IsDistinct = Record[0];
1586 MetadataList.assignValue(
1589 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1590 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1591 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1592 getMDString(Record[4 + Offset]),
1593 Record.size() <= 7 ? 0 : Record[7],
1594 Record.size() <= 8 ? false : Record[8])),
1600 case bitc::METADATA_FILE: {
1601 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1602 return error("Invalid record");
1604 IsDistinct = Record[0];
1605 Optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1606 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1607 // is not present. This matches up with the old internal representation,
1608 // and the old encoding for CSK_None in the ChecksumKind. The new
1609 // representation reserves the value 0 in the ChecksumKind to continue to
1610 // encode None in a backwards-compatible way.
1611 if (Record.size() > 4 && Record[3] && Record[4])
1612 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1613 getMDString(Record[4]));
1614 MetadataList.assignValue(
1617 (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum,
1618 Record.size() > 5 ? Optional<MDString *>(getMDString(Record[5]))
1624 case bitc::METADATA_COMPILE_UNIT: {
1625 if (Record.size() < 14 || Record.size() > 22)
1626 return error("Invalid record");
1628 // Ignore Record[0], which indicates whether this compile unit is
1629 // distinct. It's always distinct.
1631 auto *CU = DICompileUnit::getDistinct(
1632 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1633 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1634 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1635 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1636 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1637 Record.size() <= 14 ? 0 : Record[14],
1638 Record.size() <= 16 ? true : Record[16],
1639 Record.size() <= 17 ? false : Record[17],
1640 Record.size() <= 18 ? 0 : Record[18],
1641 Record.size() <= 19 ? false : Record[19],
1642 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1643 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1645 MetadataList.assignValue(CU, NextMetadataNo);
1648 // Move the Upgrade the list of subprograms.
1649 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1650 CUSubprograms.push_back({CU, SPs});
1653 case bitc::METADATA_SUBPROGRAM: {
1654 if (Record.size() < 18 || Record.size() > 21)
1655 return error("Invalid record");
1657 bool HasSPFlags = Record[0] & 4;
1659 DINode::DIFlags Flags;
1660 DISubprogram::DISPFlags SPFlags;
1662 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1664 Flags = static_cast<DINode::DIFlags>(Record[11]);
1665 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1668 // Support for old metadata when
1669 // subprogram specific flags are placed in DIFlags.
1670 const unsigned DIFlagMainSubprogram = 1 << 21;
1671 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
1672 if (HasOldMainSubprogramFlag)
1673 // Remove old DIFlagMainSubprogram from DIFlags.
1674 // Note: This assumes that any future use of bit 21 defaults to it
1676 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1678 if (HasOldMainSubprogramFlag && HasSPFlags)
1679 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1680 else if (!HasSPFlags)
1681 SPFlags = DISubprogram::toSPFlags(
1682 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
1683 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
1684 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
1686 // All definitions should be distinct.
1687 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1688 // Version 1 has a Function as Record[15].
1689 // Version 2 has removed Record[15].
1690 // Version 3 has the Unit as Record[15].
1691 // Version 4 added thisAdjustment.
1692 // Version 5 repacked flags into DISPFlags, changing many element numbers.
1693 bool HasUnit = Record[0] & 2;
1694 if (!HasSPFlags && HasUnit && Record.size() < 19)
1695 return error("Invalid record");
1696 if (HasSPFlags && !HasUnit)
1697 return error("Invalid record");
1698 // Accommodate older formats.
1700 bool HasThisAdj = true;
1701 bool HasThrownTypes = true;
1702 bool HasAnnotations = false;
1703 bool HasTargetFuncName = false;
1704 unsigned OffsetA = 0;
1705 unsigned OffsetB = 0;
1709 if (Record.size() >= 19) {
1713 HasThisAdj = Record.size() >= 20;
1714 HasThrownTypes = Record.size() >= 21;
1716 HasAnnotations = Record.size() >= 19;
1717 HasTargetFuncName = Record.size() >= 20;
1719 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1720 DISubprogram *SP = GET_OR_DISTINCT(
1723 getDITypeRefOrNull(Record[1]), // scope
1724 getMDString(Record[2]), // name
1725 getMDString(Record[3]), // linkageName
1726 getMDOrNull(Record[4]), // file
1728 getMDOrNull(Record[6]), // type
1729 Record[7 + OffsetA], // scopeLine
1730 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
1731 Record[10 + OffsetA], // virtualIndex
1732 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
1735 HasUnit ? CUorFn : nullptr, // unit
1736 getMDOrNull(Record[13 + OffsetB]), // templateParams
1737 getMDOrNull(Record[14 + OffsetB]), // declaration
1738 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
1739 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1740 : nullptr, // thrownTypes
1741 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1742 : nullptr, // annotations
1743 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
1744 : nullptr // targetFuncName
1746 MetadataList.assignValue(SP, NextMetadataNo);
1749 // Upgrade sp->function mapping to function->sp mapping.
1751 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1752 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1753 if (F->isMaterializable())
1754 // Defer until materialized; unmaterialized functions may not have
1756 FunctionsWithSPs[F] = SP;
1757 else if (!F->empty())
1758 F->setSubprogram(SP);
1763 case bitc::METADATA_LEXICAL_BLOCK: {
1764 if (Record.size() != 5)
1765 return error("Invalid record");
1767 IsDistinct = Record[0];
1768 MetadataList.assignValue(
1769 GET_OR_DISTINCT(DILexicalBlock,
1770 (Context, getMDOrNull(Record[1]),
1771 getMDOrNull(Record[2]), Record[3], Record[4])),
1776 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1777 if (Record.size() != 4)
1778 return error("Invalid record");
1780 IsDistinct = Record[0];
1781 MetadataList.assignValue(
1782 GET_OR_DISTINCT(DILexicalBlockFile,
1783 (Context, getMDOrNull(Record[1]),
1784 getMDOrNull(Record[2]), Record[3])),
1789 case bitc::METADATA_COMMON_BLOCK: {
1790 IsDistinct = Record[0] & 1;
1791 MetadataList.assignValue(
1792 GET_OR_DISTINCT(DICommonBlock,
1793 (Context, getMDOrNull(Record[1]),
1794 getMDOrNull(Record[2]), getMDString(Record[3]),
1795 getMDOrNull(Record[4]), Record[5])),
1800 case bitc::METADATA_NAMESPACE: {
1801 // Newer versions of DINamespace dropped file and line.
1803 if (Record.size() == 3)
1804 Name = getMDString(Record[2]);
1805 else if (Record.size() == 5)
1806 Name = getMDString(Record[3]);
1808 return error("Invalid record");
1810 IsDistinct = Record[0] & 1;
1811 bool ExportSymbols = Record[0] & 2;
1812 MetadataList.assignValue(
1813 GET_OR_DISTINCT(DINamespace,
1814 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1819 case bitc::METADATA_MACRO: {
1820 if (Record.size() != 5)
1821 return error("Invalid record");
1823 IsDistinct = Record[0];
1824 MetadataList.assignValue(
1825 GET_OR_DISTINCT(DIMacro,
1826 (Context, Record[1], Record[2], getMDString(Record[3]),
1827 getMDString(Record[4]))),
1832 case bitc::METADATA_MACRO_FILE: {
1833 if (Record.size() != 5)
1834 return error("Invalid record");
1836 IsDistinct = Record[0];
1837 MetadataList.assignValue(
1838 GET_OR_DISTINCT(DIMacroFile,
1839 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1840 getMDOrNull(Record[4]))),
1845 case bitc::METADATA_TEMPLATE_TYPE: {
1846 if (Record.size() < 3 || Record.size() > 4)
1847 return error("Invalid record");
1849 IsDistinct = Record[0];
1850 MetadataList.assignValue(
1851 GET_OR_DISTINCT(DITemplateTypeParameter,
1852 (Context, getMDString(Record[1]),
1853 getDITypeRefOrNull(Record[2]),
1854 (Record.size() == 4) ? getMDOrNull(Record[3])
1855 : getMDOrNull(false))),
1860 case bitc::METADATA_TEMPLATE_VALUE: {
1861 if (Record.size() < 5 || Record.size() > 6)
1862 return error("Invalid record");
1864 IsDistinct = Record[0];
1866 MetadataList.assignValue(
1868 DITemplateValueParameter,
1869 (Context, Record[1], getMDString(Record[2]),
1870 getDITypeRefOrNull(Record[3]),
1871 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
1872 (Record.size() == 6) ? getMDOrNull(Record[5])
1873 : getMDOrNull(Record[4]))),
1878 case bitc::METADATA_GLOBAL_VAR: {
1879 if (Record.size() < 11 || Record.size() > 13)
1880 return error("Invalid record");
1882 IsDistinct = Record[0] & 1;
1883 unsigned Version = Record[0] >> 1;
1886 Metadata *Annotations = nullptr;
1887 if (Record.size() > 12)
1888 Annotations = getMDOrNull(Record[12]);
1890 MetadataList.assignValue(
1891 GET_OR_DISTINCT(DIGlobalVariable,
1892 (Context, getMDOrNull(Record[1]),
1893 getMDString(Record[2]), getMDString(Record[3]),
1894 getMDOrNull(Record[4]), Record[5],
1895 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1896 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1897 Record[11], Annotations)),
1901 } else if (Version == 1) {
1902 // No upgrade necessary. A null field will be introduced to indicate
1903 // that no parameter information is available.
1904 MetadataList.assignValue(
1907 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1908 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1909 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1910 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
1914 } else if (Version == 0) {
1915 // Upgrade old metadata, which stored a global variable reference or a
1916 // ConstantInt here.
1917 NeedUpgradeToDIGlobalVariableExpression = true;
1918 Metadata *Expr = getMDOrNull(Record[9]);
1919 uint32_t AlignInBits = 0;
1920 if (Record.size() > 11) {
1921 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1922 return error("Alignment value is too large");
1923 AlignInBits = Record[11];
1925 GlobalVariable *Attach = nullptr;
1926 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1927 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1930 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1931 Expr = DIExpression::get(Context,
1932 {dwarf::DW_OP_constu, CI->getZExtValue(),
1933 dwarf::DW_OP_stack_value});
1938 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1940 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1941 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1942 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1943 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
1945 DIGlobalVariableExpression *DGVE = nullptr;
1947 DGVE = DIGlobalVariableExpression::getDistinct(
1948 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
1950 Attach->addDebugInfo(DGVE);
1952 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1953 MetadataList.assignValue(MDNode, NextMetadataNo);
1956 return error("Invalid record");
1960 case bitc::METADATA_LOCAL_VAR: {
1961 // 10th field is for the obseleted 'inlinedAt:' field.
1962 if (Record.size() < 8 || Record.size() > 10)
1963 return error("Invalid record");
1965 IsDistinct = Record[0] & 1;
1966 bool HasAlignment = Record[0] & 2;
1967 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1968 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1969 // this is newer version of record which doesn't have artificial tag.
1970 bool HasTag = !HasAlignment && Record.size() > 8;
1971 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1972 uint32_t AlignInBits = 0;
1973 Metadata *Annotations = nullptr;
1975 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1976 return error("Alignment value is too large");
1977 AlignInBits = Record[8];
1978 if (Record.size() > 9)
1979 Annotations = getMDOrNull(Record[9]);
1982 MetadataList.assignValue(
1983 GET_OR_DISTINCT(DILocalVariable,
1984 (Context, getMDOrNull(Record[1 + HasTag]),
1985 getMDString(Record[2 + HasTag]),
1986 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1987 getDITypeRefOrNull(Record[5 + HasTag]),
1988 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
1993 case bitc::METADATA_LABEL: {
1994 if (Record.size() != 5)
1995 return error("Invalid record");
1997 IsDistinct = Record[0] & 1;
1998 MetadataList.assignValue(
1999 GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
2000 getMDString(Record[2]),
2001 getMDOrNull(Record[3]), Record[4])),
2006 case bitc::METADATA_EXPRESSION: {
2007 if (Record.size() < 1)
2008 return error("Invalid record");
2010 IsDistinct = Record[0] & 1;
2011 uint64_t Version = Record[0] >> 1;
2012 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2014 SmallVector<uint64_t, 6> Buffer;
2015 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2018 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2023 case bitc::METADATA_GLOBAL_VAR_EXPR: {
2024 if (Record.size() != 3)
2025 return error("Invalid record");
2027 IsDistinct = Record[0];
2028 Metadata *Expr = getMDOrNull(Record[2]);
2030 Expr = DIExpression::get(Context, {});
2031 MetadataList.assignValue(
2032 GET_OR_DISTINCT(DIGlobalVariableExpression,
2033 (Context, getMDOrNull(Record[1]), Expr)),
2038 case bitc::METADATA_OBJC_PROPERTY: {
2039 if (Record.size() != 8)
2040 return error("Invalid record");
2042 IsDistinct = Record[0];
2043 MetadataList.assignValue(
2044 GET_OR_DISTINCT(DIObjCProperty,
2045 (Context, getMDString(Record[1]),
2046 getMDOrNull(Record[2]), Record[3],
2047 getMDString(Record[4]), getMDString(Record[5]),
2048 Record[6], getDITypeRefOrNull(Record[7]))),
2053 case bitc::METADATA_IMPORTED_ENTITY: {
2054 if (Record.size() < 6 || Record.size() > 8)
2055 return error("Invalid DIImportedEntity record");
2057 IsDistinct = Record[0];
2058 bool HasFile = (Record.size() >= 7);
2059 bool HasElements = (Record.size() >= 8);
2060 MetadataList.assignValue(
2061 GET_OR_DISTINCT(DIImportedEntity,
2062 (Context, Record[1], getMDOrNull(Record[2]),
2063 getDITypeRefOrNull(Record[3]),
2064 HasFile ? getMDOrNull(Record[6]) : nullptr,
2065 HasFile ? Record[4] : 0, getMDString(Record[5]),
2066 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2071 case bitc::METADATA_STRING_OLD: {
2072 std::string String(Record.begin(), Record.end());
2074 // Test for upgrading !llvm.loop.
2075 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2076 ++NumMDStringLoaded;
2077 Metadata *MD = MDString::get(Context, String);
2078 MetadataList.assignValue(MD, NextMetadataNo);
2082 case bitc::METADATA_STRINGS: {
2083 auto CreateNextMDString = [&](StringRef Str) {
2084 ++NumMDStringLoaded;
2085 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2088 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2092 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2093 if (Record.size() % 2 == 0)
2094 return error("Invalid record");
2095 unsigned ValueID = Record[0];
2096 if (ValueID >= ValueList.size())
2097 return error("Invalid record");
2098 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2099 if (Error Err = parseGlobalObjectAttachment(
2100 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2104 case bitc::METADATA_KIND: {
2105 // Support older bitcode files that had METADATA_KIND records in a
2106 // block with METADATA_BLOCK_ID.
2107 if (Error Err = parseMetadataKindRecord(Record))
2111 case bitc::METADATA_ARG_LIST: {
2112 SmallVector<ValueAsMetadata *, 4> Elts;
2113 Elts.reserve(Record.size());
2114 for (uint64_t Elt : Record) {
2115 Metadata *MD = getMD(Elt);
2116 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2118 "Invalid record: DIArgList should not contain forward refs");
2119 if (!isa<ValueAsMetadata>(MD))
2120 return error("Invalid record");
2121 Elts.push_back(cast<ValueAsMetadata>(MD));
2124 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2129 return Error::success();
2130 #undef GET_OR_DISTINCT
2133 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2134 ArrayRef<uint64_t> Record, StringRef Blob,
2135 function_ref<void(StringRef)> CallBack) {
2136 // All the MDStrings in the block are emitted together in a single
2137 // record. The strings are concatenated and stored in a blob along with
2139 if (Record.size() != 2)
2140 return error("Invalid record: metadata strings layout");
2142 unsigned NumStrings = Record[0];
2143 unsigned StringsOffset = Record[1];
2145 return error("Invalid record: metadata strings with no strings");
2146 if (StringsOffset > Blob.size())
2147 return error("Invalid record: metadata strings corrupt offset");
2149 StringRef Lengths = Blob.slice(0, StringsOffset);
2150 SimpleBitstreamCursor R(Lengths);
2152 StringRef Strings = Blob.drop_front(StringsOffset);
2154 if (R.AtEndOfStream())
2155 return error("Invalid record: metadata strings bad length");
2158 if (Error E = R.ReadVBR(6).moveInto(Size))
2160 if (Strings.size() < Size)
2161 return error("Invalid record: metadata strings truncated chars");
2163 CallBack(Strings.slice(0, Size));
2164 Strings = Strings.drop_front(Size);
2165 } while (--NumStrings);
2167 return Error::success();
2170 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2171 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2172 assert(Record.size() % 2 == 0);
2173 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2174 auto K = MDKindMap.find(Record[I]);
2175 if (K == MDKindMap.end())
2176 return error("Invalid ID");
2178 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2180 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2181 GO.addMetadata(K->second, *MD);
2183 return Error::success();
2186 /// Parse metadata attachments.
2187 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2188 Function &F, ArrayRef<Instruction *> InstructionList) {
2189 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2192 SmallVector<uint64_t, 64> Record;
2193 PlaceholderQueue Placeholders;
2196 BitstreamEntry Entry;
2197 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2200 switch (Entry.Kind) {
2201 case BitstreamEntry::SubBlock: // Handled for us already.
2202 case BitstreamEntry::Error:
2203 return error("Malformed block");
2204 case BitstreamEntry::EndBlock:
2205 resolveForwardRefsAndPlaceholders(Placeholders);
2206 return Error::success();
2207 case BitstreamEntry::Record:
2208 // The interesting case.
2212 // Read a metadata attachment record.
2214 ++NumMDRecordLoaded;
2215 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2217 return MaybeRecord.takeError();
2218 switch (MaybeRecord.get()) {
2219 default: // Default behavior: ignore.
2221 case bitc::METADATA_ATTACHMENT: {
2222 unsigned RecordLength = Record.size();
2224 return error("Invalid record");
2225 if (RecordLength % 2 == 0) {
2226 // A function attachment.
2227 if (Error Err = parseGlobalObjectAttachment(F, Record))
2232 // An instruction attachment.
2233 Instruction *Inst = InstructionList[Record[0]];
2234 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2235 unsigned Kind = Record[i];
2236 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2237 if (I == MDKindMap.end())
2238 return error("Invalid ID");
2239 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2242 auto Idx = Record[i + 1];
2243 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2244 !MetadataList.lookup(Idx)) {
2245 // Load the attachment if it is in the lazy-loadable range and hasn't
2247 lazyLoadOneMetadata(Idx, Placeholders);
2248 resolveForwardRefsAndPlaceholders(Placeholders);
2251 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2252 if (isa<LocalAsMetadata>(Node))
2253 // Drop the attachment. This used to be legal, but there's no
2256 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2258 return error("Invalid metadata attachment");
2260 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2261 MD = upgradeInstructionLoopAttachment(*MD);
2263 if (I->second == LLVMContext::MD_tbaa) {
2264 assert(!MD->isTemporary() && "should load MDs before attachments");
2265 MD = UpgradeTBAANode(*MD);
2267 Inst->setMetadata(I->second, MD);
2275 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2276 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2277 SmallVectorImpl<uint64_t> &Record) {
2278 if (Record.size() < 2)
2279 return error("Invalid record");
2281 unsigned Kind = Record[0];
2282 SmallString<8> Name(Record.begin() + 1, Record.end());
2284 unsigned NewKind = TheModule.getMDKindID(Name.str());
2285 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2286 return error("Conflicting METADATA_KIND records");
2287 return Error::success();
2290 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2291 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2292 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2295 SmallVector<uint64_t, 64> Record;
2297 // Read all the records.
2299 BitstreamEntry Entry;
2300 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2303 switch (Entry.Kind) {
2304 case BitstreamEntry::SubBlock: // Handled for us already.
2305 case BitstreamEntry::Error:
2306 return error("Malformed block");
2307 case BitstreamEntry::EndBlock:
2308 return Error::success();
2309 case BitstreamEntry::Record:
2310 // The interesting case.
2316 ++NumMDRecordLoaded;
2317 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2319 return MaybeCode.takeError();
2320 switch (MaybeCode.get()) {
2321 default: // Default behavior: ignore.
2323 case bitc::METADATA_KIND: {
2324 if (Error Err = parseMetadataKindRecord(Record))
2332 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2333 Pimpl = std::move(RHS.Pimpl);
2336 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2337 : Pimpl(std::move(RHS.Pimpl)) {}
2339 MetadataLoader::~MetadataLoader() = default;
2340 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2341 BitcodeReaderValueList &ValueList,
2343 std::function<Type *(unsigned)> getTypeByID)
2344 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2345 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
2347 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2348 return Pimpl->parseMetadata(ModuleLevel);
2351 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2353 /// Return the given metadata, creating a replaceable forward reference if
2355 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
2356 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2359 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2360 return Pimpl->lookupSubprogramForFunction(F);
2363 Error MetadataLoader::parseMetadataAttachment(
2364 Function &F, ArrayRef<Instruction *> InstructionList) {
2365 return Pimpl->parseMetadataAttachment(F, InstructionList);
2368 Error MetadataLoader::parseMetadataKinds() {
2369 return Pimpl->parseMetadataKinds();
2372 void MetadataLoader::setStripTBAA(bool StripTBAA) {
2373 return Pimpl->setStripTBAA(StripTBAA);
2376 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2378 unsigned MetadataLoader::size() const { return Pimpl->size(); }
2379 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2381 void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2382 return Pimpl->upgradeDebugIntrinsics(F);