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/APFloat.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/LLVMBitCodes.h"
25 #include "llvm/Bitstream/BitstreamReader.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Comdat.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/DiagnosticPrinter.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GVMaterializer.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalIFunc.h"
43 #include "llvm/IR/GlobalObject.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/IntrinsicInst.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSummaryIndex.h"
55 #include "llvm/IR/OperandTraits.h"
56 #include "llvm/IR/TrackingMDRef.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/ValueHandle.h"
59 #include "llvm/Support/AtomicOrdering.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/raw_ostream.h"
76 #include <system_error>
83 #define DEBUG_TYPE "bitcode-reader"
85 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
86 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
87 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
89 /// Flag whether we need to import full type definitions for ThinLTO.
90 /// Currently needed for Darwin and LLDB.
91 static cl::opt<bool> ImportFullTypeDefinitions(
92 "import-full-type-definitions", cl::init(false), cl::Hidden,
93 cl::desc("Import full type definitions for ThinLTO."));
95 static cl::opt<bool> DisableLazyLoading(
96 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
97 cl::desc("Force disable the lazy-loading on-demand of metadata when "
98 "loading bitcode for importing."));
102 static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
104 class BitcodeReaderMetadataList {
105 /// Array of metadata references.
107 /// Don't use std::vector here. Some versions of libc++ copy (instead of
108 /// move) on resize, and TrackingMDRef is very expensive to copy.
109 SmallVector<TrackingMDRef, 1> MetadataPtrs;
111 /// The set of indices in MetadataPtrs above of forward references that were
113 SmallDenseSet<unsigned, 1> ForwardReference;
115 /// The set of indices in MetadataPtrs above of Metadata that need to be
117 SmallDenseSet<unsigned, 1> UnresolvedNodes;
119 /// Structures for resolving old type refs.
121 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
122 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
123 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
124 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
127 LLVMContext &Context;
129 /// Maximum number of valid references. Forward references exceeding the
130 /// maximum must be invalid.
131 unsigned RefsUpperBound;
134 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
136 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
139 // vector compatibility methods
140 unsigned size() const { return MetadataPtrs.size(); }
141 void resize(unsigned N) { MetadataPtrs.resize(N); }
142 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
143 void clear() { MetadataPtrs.clear(); }
144 Metadata *back() const { return MetadataPtrs.back(); }
145 void pop_back() { MetadataPtrs.pop_back(); }
146 bool empty() const { return MetadataPtrs.empty(); }
148 Metadata *operator[](unsigned i) const {
149 assert(i < MetadataPtrs.size());
150 return MetadataPtrs[i];
153 Metadata *lookup(unsigned I) const {
154 if (I < MetadataPtrs.size())
155 return MetadataPtrs[I];
159 void shrinkTo(unsigned N) {
160 assert(N <= size() && "Invalid shrinkTo request!");
161 assert(ForwardReference.empty() && "Unexpected forward refs");
162 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
163 MetadataPtrs.resize(N);
166 /// Return the given metadata, creating a replaceable forward reference if
168 Metadata *getMetadataFwdRef(unsigned Idx);
170 /// Return the given metadata only if it is fully resolved.
172 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
173 /// would give \c false.
174 Metadata *getMetadataIfResolved(unsigned Idx);
176 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
177 void assignValue(Metadata *MD, unsigned Idx);
178 void tryToResolveCycles();
179 bool hasFwdRefs() const { return !ForwardReference.empty(); }
180 int getNextFwdRef() {
181 assert(hasFwdRefs());
182 return *ForwardReference.begin();
185 /// Upgrade a type that had an MDString reference.
186 void addTypeRef(MDString &UUID, DICompositeType &CT);
188 /// Upgrade a type that had an MDString reference.
189 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
191 /// Upgrade a type ref array that may have MDString references.
192 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
195 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
198 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
199 if (auto *MDN = dyn_cast<MDNode>(MD))
200 if (!MDN->isResolved())
201 UnresolvedNodes.insert(Idx);
211 TrackingMDRef &OldMD = MetadataPtrs[Idx];
217 // If there was a forward reference to this value, replace it.
218 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
219 PrevMD->replaceAllUsesWith(MD);
220 ForwardReference.erase(Idx);
223 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
224 // Bail out for a clearly invalid value.
225 if (Idx >= RefsUpperBound)
231 if (Metadata *MD = MetadataPtrs[Idx])
234 // Track forward refs to be resolved later.
235 ForwardReference.insert(Idx);
237 // Create and return a placeholder, which will later be RAUW'd.
238 ++NumMDNodeTemporary;
239 Metadata *MD = MDNode::getTemporary(Context, None).release();
240 MetadataPtrs[Idx].reset(MD);
244 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
245 Metadata *MD = lookup(Idx);
246 if (auto *N = dyn_cast_or_null<MDNode>(MD))
247 if (!N->isResolved())
252 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
253 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
256 void BitcodeReaderMetadataList::tryToResolveCycles() {
257 if (!ForwardReference.empty())
258 // Still forward references... can't resolve cycles.
261 // Give up on finding a full definition for any forward decls that remain.
262 for (const auto &Ref : OldTypeRefs.FwdDecls)
263 OldTypeRefs.Final.insert(Ref);
264 OldTypeRefs.FwdDecls.clear();
266 // Upgrade from old type ref arrays. In strange cases, this could add to
267 // OldTypeRefs.Unknown.
268 for (const auto &Array : OldTypeRefs.Arrays)
269 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
270 OldTypeRefs.Arrays.clear();
272 // Replace old string-based type refs with the resolved node, if possible.
273 // If we haven't seen the node, leave it to the verifier to complain about
274 // the invalid string reference.
275 for (const auto &Ref : OldTypeRefs.Unknown) {
276 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
277 Ref.second->replaceAllUsesWith(CT);
279 Ref.second->replaceAllUsesWith(Ref.first);
281 OldTypeRefs.Unknown.clear();
283 if (UnresolvedNodes.empty())
287 // Resolve any cycles.
288 for (unsigned I : UnresolvedNodes) {
289 auto &MD = MetadataPtrs[I];
290 auto *N = dyn_cast_or_null<MDNode>(MD);
294 assert(!N->isTemporary() && "Unexpected forward reference");
298 // Make sure we return early again until there's another unresolved ref.
299 UnresolvedNodes.clear();
302 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
303 DICompositeType &CT) {
304 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
305 if (CT.isForwardDecl())
306 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
308 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
311 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
312 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
313 if (LLVM_LIKELY(!UUID))
316 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
319 auto &Ref = OldTypeRefs.Unknown[UUID];
321 Ref = MDNode::getTemporary(Context, None);
325 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
326 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
327 if (!Tuple || Tuple->isDistinct())
330 // Look through the array immediately if possible.
331 if (!Tuple->isTemporary())
332 return resolveTypeRefArray(Tuple);
334 // Create and return a placeholder to use for now. Eventually
335 // resolveTypeRefArrays() will be resolve this forward reference.
336 OldTypeRefs.Arrays.emplace_back(
337 std::piecewise_construct, std::forward_as_tuple(Tuple),
338 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
339 return OldTypeRefs.Arrays.back().second.get();
342 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
343 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
344 if (!Tuple || Tuple->isDistinct())
347 // Look through the DITypeRefArray, upgrading each DIType *.
348 SmallVector<Metadata *, 32> Ops;
349 Ops.reserve(Tuple->getNumOperands());
350 for (Metadata *MD : Tuple->operands())
351 Ops.push_back(upgradeTypeRef(MD));
353 return MDTuple::get(Context, Ops);
358 class PlaceholderQueue {
359 // Placeholders would thrash around when moved, so store in a std::deque
360 // instead of some sort of vector.
361 std::deque<DistinctMDOperandPlaceholder> PHs;
364 ~PlaceholderQueue() {
366 "PlaceholderQueue hasn't been flushed before being destroyed");
368 bool empty() const { return PHs.empty(); }
369 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
370 void flush(BitcodeReaderMetadataList &MetadataList);
372 /// Return the list of temporaries nodes in the queue, these need to be
373 /// loaded before we can flush the queue.
374 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
375 DenseSet<unsigned> &Temporaries) {
376 for (auto &PH : PHs) {
377 auto ID = PH.getID();
378 auto *MD = MetadataList.lookup(ID);
380 Temporaries.insert(ID);
383 auto *N = dyn_cast_or_null<MDNode>(MD);
384 if (N && N->isTemporary())
385 Temporaries.insert(ID);
390 } // end anonymous namespace
392 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
393 PHs.emplace_back(ID);
397 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
398 while (!PHs.empty()) {
399 auto *MD = MetadataList.lookup(PHs.front().getID());
400 assert(MD && "Flushing placeholder on unassigned MD");
402 if (auto *MDN = dyn_cast<MDNode>(MD))
403 assert(MDN->isResolved() &&
404 "Flushing Placeholder while cycles aren't resolved");
406 PHs.front().replaceUseWith(MD);
411 } // anonymous namespace
413 static Error error(const Twine &Message) {
414 return make_error<StringError>(
415 Message, make_error_code(BitcodeError::CorruptedBitcode));
418 class MetadataLoader::MetadataLoaderImpl {
419 BitcodeReaderMetadataList MetadataList;
420 BitcodeReaderValueList &ValueList;
421 BitstreamCursor &Stream;
422 LLVMContext &Context;
424 std::function<Type *(unsigned)> getTypeByID;
426 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
427 /// to keep around the right "context" (Abbrev list) to be able to jump in
428 /// the middle of the metadata block and load any record.
429 BitstreamCursor IndexCursor;
431 /// Index that keeps track of MDString values.
432 std::vector<StringRef> MDStringRef;
434 /// On-demand loading of a single MDString. Requires the index above to be
436 MDString *lazyLoadOneMDString(unsigned Idx);
438 /// Index that keeps track of where to find a metadata record in the stream.
439 std::vector<uint64_t> GlobalMetadataBitPosIndex;
441 /// Cursor position of the start of the global decl attachments, to enable
442 /// loading using the index built for lazy loading, instead of forward
444 uint64_t GlobalDeclAttachmentPos = 0;
447 /// Baisic correctness check that we end up parsing all of the global decl
449 unsigned NumGlobalDeclAttachSkipped = 0;
450 unsigned NumGlobalDeclAttachParsed = 0;
453 /// Load the global decl attachments, using the index built for lazy loading.
454 Expected<bool> loadGlobalDeclAttachments();
456 /// Populate the index above to enable lazily loading of metadata, and load
457 /// the named metadata as well as the transitively referenced global
459 Expected<bool> lazyLoadModuleMetadataBlock();
461 /// On-demand loading of a single metadata. Requires the index above to be
463 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
465 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
466 // point from SP to CU after a block is completly parsed.
467 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
469 /// Functions that need to be matched with subprograms when upgrading old
471 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
473 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
474 DenseMap<unsigned, unsigned> MDKindMap;
476 bool StripTBAA = false;
477 bool HasSeenOldLoopTags = false;
478 bool NeedUpgradeToDIGlobalVariableExpression = false;
479 bool NeedDeclareExpressionUpgrade = false;
481 /// True if metadata is being parsed for a module being ThinLTO imported.
482 bool IsImporting = false;
484 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
485 PlaceholderQueue &Placeholders, StringRef Blob,
486 unsigned &NextMetadataNo);
487 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
488 function_ref<void(StringRef)> CallBack);
489 Error parseGlobalObjectAttachment(GlobalObject &GO,
490 ArrayRef<uint64_t> Record);
491 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
493 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
495 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
496 void upgradeCUSubprograms() {
497 for (auto CU_SP : CUSubprograms)
498 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
499 for (auto &Op : SPs->operands())
500 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
501 SP->replaceUnit(CU_SP.first);
502 CUSubprograms.clear();
505 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
506 void upgradeCUVariables() {
507 if (!NeedUpgradeToDIGlobalVariableExpression)
510 // Upgrade list of variables attached to the CUs.
511 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
512 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
513 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
514 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
515 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
517 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
518 auto *DGVE = DIGlobalVariableExpression::getDistinct(
519 Context, GV, DIExpression::get(Context, {}));
520 GVs->replaceOperandWith(I, DGVE);
524 // Upgrade variables attached to globals.
525 for (auto &GV : TheModule.globals()) {
526 SmallVector<MDNode *, 1> MDs;
527 GV.getMetadata(LLVMContext::MD_dbg, MDs);
528 GV.eraseMetadata(LLVMContext::MD_dbg);
530 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
531 auto *DGVE = DIGlobalVariableExpression::getDistinct(
532 Context, DGV, DIExpression::get(Context, {}));
533 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
535 GV.addMetadata(LLVMContext::MD_dbg, *MD);
539 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
540 /// describes a function argument.
541 void upgradeDeclareExpressions(Function &F) {
542 if (!NeedDeclareExpressionUpgrade)
547 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
548 if (auto *DIExpr = DDI->getExpression())
549 if (DIExpr->startsWithDeref() &&
550 isa_and_nonnull<Argument>(DDI->getAddress())) {
551 SmallVector<uint64_t, 8> Ops;
552 Ops.append(std::next(DIExpr->elements_begin()),
553 DIExpr->elements_end());
554 DDI->setExpression(DIExpression::get(Context, Ops));
558 /// Upgrade the expression from previous versions.
559 Error upgradeDIExpression(uint64_t FromVersion,
560 MutableArrayRef<uint64_t> &Expr,
561 SmallVectorImpl<uint64_t> &Buffer) {
562 auto N = Expr.size();
563 switch (FromVersion) {
565 return error("Invalid record");
567 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
568 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
571 // Move DW_OP_deref to the end.
572 if (N && Expr[0] == dwarf::DW_OP_deref) {
573 auto End = Expr.end();
574 if (Expr.size() >= 3 &&
575 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
576 End = std::prev(End, 3);
577 std::move(std::next(Expr.begin()), End, Expr.begin());
578 *std::prev(End) = dwarf::DW_OP_deref;
580 NeedDeclareExpressionUpgrade = true;
583 // Change DW_OP_plus to DW_OP_plus_uconst.
584 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
585 auto SubExpr = ArrayRef<uint64_t>(Expr);
586 while (!SubExpr.empty()) {
587 // Skip past other operators with their operands
588 // for this version of the IR, obtained from
589 // from historic DIExpression::ExprOperand::getSize().
591 switch (SubExpr.front()) {
595 case dwarf::DW_OP_constu:
596 case dwarf::DW_OP_minus:
597 case dwarf::DW_OP_plus:
600 case dwarf::DW_OP_LLVM_fragment:
605 // If the expression is malformed, make sure we don't
606 // copy more elements than we should.
607 HistoricSize = std::min(SubExpr.size(), HistoricSize);
608 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
610 switch (SubExpr.front()) {
611 case dwarf::DW_OP_plus:
612 Buffer.push_back(dwarf::DW_OP_plus_uconst);
613 Buffer.append(Args.begin(), Args.end());
615 case dwarf::DW_OP_minus:
616 Buffer.push_back(dwarf::DW_OP_constu);
617 Buffer.append(Args.begin(), Args.end());
618 Buffer.push_back(dwarf::DW_OP_minus);
621 Buffer.push_back(*SubExpr.begin());
622 Buffer.append(Args.begin(), Args.end());
626 // Continue with remaining elements.
627 SubExpr = SubExpr.slice(HistoricSize);
629 Expr = MutableArrayRef<uint64_t>(Buffer);
637 return Error::success();
640 void upgradeDebugInfo() {
641 upgradeCUSubprograms();
642 upgradeCUVariables();
646 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
647 BitcodeReaderValueList &ValueList,
648 std::function<Type *(unsigned)> getTypeByID,
650 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
651 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
652 TheModule(TheModule), getTypeByID(std::move(getTypeByID)),
653 IsImporting(IsImporting) {}
655 Error parseMetadata(bool ModuleLevel);
657 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
659 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
660 if (ID < MDStringRef.size())
661 return lazyLoadOneMDString(ID);
662 if (auto *MD = MetadataList.lookup(ID))
664 // If lazy-loading is enabled, we try recursively to load the operand
665 // instead of creating a temporary.
666 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
667 PlaceholderQueue Placeholders;
668 lazyLoadOneMetadata(ID, Placeholders);
669 resolveForwardRefsAndPlaceholders(Placeholders);
670 return MetadataList.lookup(ID);
672 return MetadataList.getMetadataFwdRef(ID);
675 DISubprogram *lookupSubprogramForFunction(Function *F) {
676 return FunctionsWithSPs.lookup(F);
679 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
681 Error parseMetadataAttachment(
682 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
684 Error parseMetadataKinds();
686 void setStripTBAA(bool Value) { StripTBAA = Value; }
687 bool isStrippingTBAA() const { return StripTBAA; }
689 unsigned size() const { return MetadataList.size(); }
690 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
691 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
695 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
696 IndexCursor = Stream;
697 SmallVector<uint64_t, 64> Record;
698 GlobalDeclAttachmentPos = 0;
699 // Get the abbrevs, and preload record positions to make them lazy-loadable.
701 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
702 BitstreamEntry Entry;
705 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
709 switch (Entry.Kind) {
710 case BitstreamEntry::SubBlock: // Handled for us already.
711 case BitstreamEntry::Error:
712 return error("Malformed block");
713 case BitstreamEntry::EndBlock: {
716 case BitstreamEntry::Record: {
717 // The interesting case.
719 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
721 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
724 case bitc::METADATA_STRINGS: {
725 // Rewind and parse the strings.
726 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
727 return std::move(Err);
730 if (Expected<unsigned> MaybeRecord =
731 IndexCursor.readRecord(Entry.ID, Record, &Blob))
734 return MaybeRecord.takeError();
735 unsigned NumStrings = Record[0];
736 MDStringRef.reserve(NumStrings);
737 auto IndexNextMDString = [&](StringRef Str) {
738 MDStringRef.push_back(Str);
740 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
741 return std::move(Err);
744 case bitc::METADATA_INDEX_OFFSET: {
745 // This is the offset to the index, when we see this we skip all the
746 // records and load only an index to these.
747 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
748 return std::move(Err);
750 if (Expected<unsigned> MaybeRecord =
751 IndexCursor.readRecord(Entry.ID, Record))
754 return MaybeRecord.takeError();
755 if (Record.size() != 2)
756 return error("Invalid record");
757 auto Offset = Record[0] + (Record[1] << 32);
758 auto BeginPos = IndexCursor.GetCurrentBitNo();
759 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
760 return std::move(Err);
761 Expected<BitstreamEntry> MaybeEntry =
762 IndexCursor.advanceSkippingSubblocks(
763 BitstreamCursor::AF_DontPopBlockAtEnd);
765 return MaybeEntry.takeError();
766 Entry = MaybeEntry.get();
767 assert(Entry.Kind == BitstreamEntry::Record &&
768 "Corrupted bitcode: Expected `Record` when trying to find the "
771 if (Expected<unsigned> MaybeCode =
772 IndexCursor.readRecord(Entry.ID, Record))
773 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
774 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
775 "find the Metadata index");
777 return MaybeCode.takeError();
779 auto CurrentValue = BeginPos;
780 GlobalMetadataBitPosIndex.reserve(Record.size());
781 for (auto &Elt : Record) {
783 GlobalMetadataBitPosIndex.push_back(CurrentValue);
787 case bitc::METADATA_INDEX:
788 // We don't expect to get there, the Index is loaded when we encounter
790 return error("Corrupted Metadata block");
791 case bitc::METADATA_NAME: {
792 // Named metadata need to be materialized now and aren't deferred.
793 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
794 return std::move(Err);
798 if (Expected<unsigned> MaybeCode =
799 IndexCursor.readRecord(Entry.ID, Record)) {
800 Code = MaybeCode.get();
801 assert(Code == bitc::METADATA_NAME);
803 return MaybeCode.takeError();
805 // Read name of the named metadata.
806 SmallString<8> Name(Record.begin(), Record.end());
807 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
808 Code = MaybeCode.get();
810 return MaybeCode.takeError();
812 // Named Metadata comes in two parts, we expect the name to be followed
815 if (Expected<unsigned> MaybeNextBitCode =
816 IndexCursor.readRecord(Code, Record))
817 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
819 return MaybeNextBitCode.takeError();
821 // Read named metadata elements.
822 unsigned Size = Record.size();
823 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
824 for (unsigned i = 0; i != Size; ++i) {
825 // FIXME: We could use a placeholder here, however NamedMDNode are
826 // taking MDNode as operand and not using the Metadata infrastructure.
827 // It is acknowledged by 'TODO: Inherit from Metadata' in the
828 // NamedMDNode class definition.
829 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
830 assert(MD && "Invalid metadata: expect fwd ref to MDNode");
835 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
836 if (!GlobalDeclAttachmentPos)
837 GlobalDeclAttachmentPos = SavedPos;
839 NumGlobalDeclAttachSkipped++;
843 case bitc::METADATA_KIND:
844 case bitc::METADATA_STRING_OLD:
845 case bitc::METADATA_OLD_FN_NODE:
846 case bitc::METADATA_OLD_NODE:
847 case bitc::METADATA_VALUE:
848 case bitc::METADATA_DISTINCT_NODE:
849 case bitc::METADATA_NODE:
850 case bitc::METADATA_LOCATION:
851 case bitc::METADATA_GENERIC_DEBUG:
852 case bitc::METADATA_SUBRANGE:
853 case bitc::METADATA_ENUMERATOR:
854 case bitc::METADATA_BASIC_TYPE:
855 case bitc::METADATA_STRING_TYPE:
856 case bitc::METADATA_DERIVED_TYPE:
857 case bitc::METADATA_COMPOSITE_TYPE:
858 case bitc::METADATA_SUBROUTINE_TYPE:
859 case bitc::METADATA_MODULE:
860 case bitc::METADATA_FILE:
861 case bitc::METADATA_COMPILE_UNIT:
862 case bitc::METADATA_SUBPROGRAM:
863 case bitc::METADATA_LEXICAL_BLOCK:
864 case bitc::METADATA_LEXICAL_BLOCK_FILE:
865 case bitc::METADATA_NAMESPACE:
866 case bitc::METADATA_COMMON_BLOCK:
867 case bitc::METADATA_MACRO:
868 case bitc::METADATA_MACRO_FILE:
869 case bitc::METADATA_TEMPLATE_TYPE:
870 case bitc::METADATA_TEMPLATE_VALUE:
871 case bitc::METADATA_GLOBAL_VAR:
872 case bitc::METADATA_LOCAL_VAR:
873 case bitc::METADATA_LABEL:
874 case bitc::METADATA_EXPRESSION:
875 case bitc::METADATA_OBJC_PROPERTY:
876 case bitc::METADATA_IMPORTED_ENTITY:
877 case bitc::METADATA_GLOBAL_VAR_EXPR:
878 case bitc::METADATA_GENERIC_SUBRANGE:
879 // We don't expect to see any of these, if we see one, give up on
880 // lazy-loading and fallback.
882 GlobalMetadataBitPosIndex.clear();
891 // Load the global decl attachments after building the lazy loading index.
892 // We don't load them "lazily" - all global decl attachments must be
893 // parsed since they aren't materialized on demand. However, by delaying
894 // their parsing until after the index is created, we can use the index
895 // instead of creating temporaries.
896 Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
897 // Nothing to do if we didn't find any of these metadata records.
898 if (!GlobalDeclAttachmentPos)
900 // Use a temporary cursor so that we don't mess up the main Stream cursor or
901 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
902 BitstreamCursor TempCursor = Stream;
903 SmallVector<uint64_t, 64> Record;
904 // Jump to the position before the first global decl attachment, so we can
905 // scan for the first BitstreamEntry record.
906 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
907 return std::move(Err);
909 BitstreamEntry Entry;
912 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
916 switch (Entry.Kind) {
917 case BitstreamEntry::SubBlock: // Handled for us already.
918 case BitstreamEntry::Error:
919 return error("Malformed block");
920 case BitstreamEntry::EndBlock:
921 // Check that we parsed them all.
922 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
924 case BitstreamEntry::Record:
927 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
928 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
930 return MaybeCode.takeError();
931 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
932 // Anything other than a global decl attachment signals the end of
933 // these records. Check that we parsed them all.
934 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
938 NumGlobalDeclAttachParsed++;
940 // FIXME: we need to do this early because we don't materialize global
942 if (Error Err = TempCursor.JumpToBit(CurrentPos))
943 return std::move(Err);
945 if (Expected<unsigned> MaybeRecord =
946 TempCursor.readRecord(Entry.ID, Record))
949 return MaybeRecord.takeError();
950 if (Record.size() % 2 == 0)
951 return error("Invalid record");
952 unsigned ValueID = Record[0];
953 if (ValueID >= ValueList.size())
954 return error("Invalid record");
955 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
956 // Need to save and restore the current position since
957 // parseGlobalObjectAttachment will resolve all forward references which
958 // would require parsing from locations stored in the index.
959 CurrentPos = TempCursor.GetCurrentBitNo();
960 if (Error Err = parseGlobalObjectAttachment(
961 *GO, ArrayRef<uint64_t>(Record).slice(1)))
962 return std::move(Err);
963 if (Error Err = TempCursor.JumpToBit(CurrentPos))
964 return std::move(Err);
969 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
970 /// module level metadata.
971 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
972 if (!ModuleLevel && MetadataList.hasFwdRefs())
973 return error("Invalid metadata: fwd refs into function blocks");
975 // Record the entry position so that we can jump back here and efficiently
976 // skip the whole block in case we lazy-load.
977 auto EntryPos = Stream.GetCurrentBitNo();
979 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
982 SmallVector<uint64_t, 64> Record;
983 PlaceholderQueue Placeholders;
985 // We lazy-load module-level metadata: we build an index for each record, and
986 // then load individual record as needed, starting with the named metadata.
987 if (ModuleLevel && IsImporting && MetadataList.empty() &&
988 !DisableLazyLoading) {
989 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
991 return SuccessOrErr.takeError();
992 if (SuccessOrErr.get()) {
993 // An index was successfully created and we will be able to load metadata
995 MetadataList.resize(MDStringRef.size() +
996 GlobalMetadataBitPosIndex.size());
998 // Now that we have built the index, load the global decl attachments
999 // that were deferred during that process. This avoids creating
1001 SuccessOrErr = loadGlobalDeclAttachments();
1003 return SuccessOrErr.takeError();
1004 assert(SuccessOrErr.get());
1006 // Reading the named metadata created forward references and/or
1007 // placeholders, that we flush here.
1008 resolveForwardRefsAndPlaceholders(Placeholders);
1010 // Return at the beginning of the block, since it is easy to skip it
1011 // entirely from there.
1012 Stream.ReadBlockEnd(); // Pop the abbrev block context.
1013 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1015 if (Error Err = Stream.SkipBlock()) {
1016 // FIXME this drops the error on the floor, which
1017 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1018 consumeError(std::move(Err));
1019 return Error::success();
1021 return Error::success();
1023 // Couldn't load an index, fallback to loading all the block "old-style".
1026 unsigned NextMetadataNo = MetadataList.size();
1028 // Read all the records.
1030 BitstreamEntry Entry;
1031 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1034 switch (Entry.Kind) {
1035 case BitstreamEntry::SubBlock: // Handled for us already.
1036 case BitstreamEntry::Error:
1037 return error("Malformed block");
1038 case BitstreamEntry::EndBlock:
1039 resolveForwardRefsAndPlaceholders(Placeholders);
1041 return Error::success();
1042 case BitstreamEntry::Record:
1043 // The interesting case.
1050 ++NumMDRecordLoaded;
1051 if (Expected<unsigned> MaybeCode =
1052 Stream.readRecord(Entry.ID, Record, &Blob)) {
1053 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1054 Blob, NextMetadataNo))
1057 return MaybeCode.takeError();
1061 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1062 ++NumMDStringLoaded;
1063 if (Metadata *MD = MetadataList.lookup(ID))
1064 return cast<MDString>(MD);
1065 auto MDS = MDString::get(Context, MDStringRef[ID]);
1066 MetadataList.assignValue(MDS, ID);
1070 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1071 unsigned ID, PlaceholderQueue &Placeholders) {
1072 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1073 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
1074 // Lookup first if the metadata hasn't already been loaded.
1075 if (auto *MD = MetadataList.lookup(ID)) {
1076 auto *N = cast<MDNode>(MD);
1077 if (!N->isTemporary())
1080 SmallVector<uint64_t, 64> Record;
1082 if (Error Err = IndexCursor.JumpToBit(
1083 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1084 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1085 Twine(toString(std::move(Err))));
1086 BitstreamEntry Entry;
1087 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1088 // FIXME this drops the error on the floor.
1089 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1090 Twine(toString(std::move(E))));
1091 ++NumMDRecordLoaded;
1092 if (Expected<unsigned> MaybeCode =
1093 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1095 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1096 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1097 Twine(toString(std::move(Err))));
1099 report_fatal_error("Can't lazyload MD: " +
1100 Twine(toString(MaybeCode.takeError())));
1103 /// Ensure that all forward-references and placeholders are resolved.
1104 /// Iteratively lazy-loading metadata on-demand if needed.
1105 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1106 PlaceholderQueue &Placeholders) {
1107 DenseSet<unsigned> Temporaries;
1109 // Populate Temporaries with the placeholders that haven't been loaded yet.
1110 Placeholders.getTemporaries(MetadataList, Temporaries);
1112 // If we don't have any temporary, or FwdReference, we're done!
1113 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1116 // First, load all the temporaries. This can add new placeholders or
1117 // forward references.
1118 for (auto ID : Temporaries)
1119 lazyLoadOneMetadata(ID, Placeholders);
1120 Temporaries.clear();
1122 // Second, load the forward-references. This can also add new placeholders
1123 // or forward references.
1124 while (MetadataList.hasFwdRefs())
1125 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1127 // At this point we don't have any forward reference remaining, or temporary
1128 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1130 MetadataList.tryToResolveCycles();
1132 // Finally, everything is in place, we can replace the placeholders operands
1133 // with the final node they refer to.
1134 Placeholders.flush(MetadataList);
1137 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1138 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1139 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1141 bool IsDistinct = false;
1142 auto getMD = [&](unsigned ID) -> Metadata * {
1143 if (ID < MDStringRef.size())
1144 return lazyLoadOneMDString(ID);
1146 if (auto *MD = MetadataList.lookup(ID))
1148 // If lazy-loading is enabled, we try recursively to load the operand
1149 // instead of creating a temporary.
1150 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1151 // Create a temporary for the node that is referencing the operand we
1152 // will lazy-load. It is needed before recursing in case there are
1154 MetadataList.getMetadataFwdRef(NextMetadataNo);
1155 lazyLoadOneMetadata(ID, Placeholders);
1156 return MetadataList.lookup(ID);
1158 // Return a temporary.
1159 return MetadataList.getMetadataFwdRef(ID);
1161 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1163 return &Placeholders.getPlaceholderOp(ID);
1165 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1167 return getMD(ID - 1);
1170 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1172 return MetadataList.getMetadataFwdRef(ID - 1);
1175 auto getMDString = [&](unsigned ID) -> MDString * {
1176 // This requires that the ID is not really a forward reference. In
1177 // particular, the MDString must already have been resolved.
1178 auto MDS = getMDOrNull(ID);
1179 return cast_or_null<MDString>(MDS);
1182 // Support for old type refs.
1183 auto getDITypeRefOrNull = [&](unsigned ID) {
1184 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1187 #define GET_OR_DISTINCT(CLASS, ARGS) \
1188 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1191 default: // Default behavior: ignore.
1193 case bitc::METADATA_NAME: {
1194 // Read name of the named metadata.
1195 SmallString<8> Name(Record.begin(), Record.end());
1197 if (Error E = Stream.ReadCode().moveInto(Code))
1200 ++NumMDRecordLoaded;
1201 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1202 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1203 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1205 return MaybeNextBitCode.takeError();
1207 // Read named metadata elements.
1208 unsigned Size = Record.size();
1209 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1210 for (unsigned i = 0; i != Size; ++i) {
1211 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1213 return error("Invalid named metadata: expect fwd ref to MDNode");
1214 NMD->addOperand(MD);
1218 case bitc::METADATA_OLD_FN_NODE: {
1219 // Deprecated, but still needed to read old bitcode files.
1220 // This is a LocalAsMetadata record, the only type of function-local
1222 if (Record.size() % 2 == 1)
1223 return error("Invalid record");
1225 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1226 // to be legal, but there's no upgrade path.
1227 auto dropRecord = [&] {
1228 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
1231 if (Record.size() != 2) {
1236 Type *Ty = getTypeByID(Record[0]);
1237 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1242 MetadataList.assignValue(
1243 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1248 case bitc::METADATA_OLD_NODE: {
1249 // Deprecated, but still needed to read old bitcode files.
1250 if (Record.size() % 2 == 1)
1251 return error("Invalid record");
1253 unsigned Size = Record.size();
1254 SmallVector<Metadata *, 8> Elts;
1255 for (unsigned i = 0; i != Size; i += 2) {
1256 Type *Ty = getTypeByID(Record[i]);
1258 return error("Invalid record");
1259 if (Ty->isMetadataTy())
1260 Elts.push_back(getMD(Record[i + 1]));
1261 else if (!Ty->isVoidTy()) {
1263 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1264 assert(isa<ConstantAsMetadata>(MD) &&
1265 "Expected non-function-local metadata");
1268 Elts.push_back(nullptr);
1270 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1274 case bitc::METADATA_VALUE: {
1275 if (Record.size() != 2)
1276 return error("Invalid record");
1278 Type *Ty = getTypeByID(Record[0]);
1279 if (Ty->isMetadataTy() || Ty->isVoidTy())
1280 return error("Invalid record");
1282 MetadataList.assignValue(
1283 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1288 case bitc::METADATA_DISTINCT_NODE:
1291 case bitc::METADATA_NODE: {
1292 SmallVector<Metadata *, 8> Elts;
1293 Elts.reserve(Record.size());
1294 for (unsigned ID : Record)
1295 Elts.push_back(getMDOrNull(ID));
1296 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1297 : MDNode::get(Context, Elts),
1302 case bitc::METADATA_LOCATION: {
1303 if (Record.size() != 5 && Record.size() != 6)
1304 return error("Invalid record");
1306 IsDistinct = Record[0];
1307 unsigned Line = Record[1];
1308 unsigned Column = Record[2];
1309 Metadata *Scope = getMD(Record[3]);
1310 Metadata *InlinedAt = getMDOrNull(Record[4]);
1311 bool ImplicitCode = Record.size() == 6 && Record[5];
1312 MetadataList.assignValue(
1313 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1319 case bitc::METADATA_GENERIC_DEBUG: {
1320 if (Record.size() < 4)
1321 return error("Invalid record");
1323 IsDistinct = Record[0];
1324 unsigned Tag = Record[1];
1325 unsigned Version = Record[2];
1327 if (Tag >= 1u << 16 || Version != 0)
1328 return error("Invalid record");
1330 auto *Header = getMDString(Record[3]);
1331 SmallVector<Metadata *, 8> DwarfOps;
1332 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1333 DwarfOps.push_back(getMDOrNull(Record[I]));
1334 MetadataList.assignValue(
1335 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1340 case bitc::METADATA_SUBRANGE: {
1341 Metadata *Val = nullptr;
1342 // Operand 'count' is interpreted as:
1343 // - Signed integer (version 0)
1344 // - Metadata node (version 1)
1345 // Operand 'lowerBound' is interpreted as:
1346 // - Signed integer (version 0 and 1)
1347 // - Metadata node (version 2)
1348 // Operands 'upperBound' and 'stride' are interpreted as:
1349 // - Metadata node (version 2)
1350 switch (Record[0] >> 1) {
1352 Val = GET_OR_DISTINCT(DISubrange,
1353 (Context, Record[1], unrotateSign(Record[2])));
1356 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1357 unrotateSign(Record[2])));
1360 Val = GET_OR_DISTINCT(
1361 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1362 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1365 return error("Invalid record: Unsupported version of DISubrange");
1368 MetadataList.assignValue(Val, NextMetadataNo);
1369 IsDistinct = Record[0] & 1;
1373 case bitc::METADATA_GENERIC_SUBRANGE: {
1374 Metadata *Val = nullptr;
1375 Val = GET_OR_DISTINCT(DIGenericSubrange,
1376 (Context, getMDOrNull(Record[1]),
1377 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1378 getMDOrNull(Record[4])));
1380 MetadataList.assignValue(Val, NextMetadataNo);
1381 IsDistinct = Record[0] & 1;
1385 case bitc::METADATA_ENUMERATOR: {
1386 if (Record.size() < 3)
1387 return error("Invalid record");
1389 IsDistinct = Record[0] & 1;
1390 bool IsUnsigned = Record[0] & 2;
1391 bool IsBigInt = Record[0] & 4;
1395 const uint64_t BitWidth = Record[1];
1396 const size_t NumWords = Record.size() - 3;
1397 Value = readWideAPInt(makeArrayRef(&Record[3], NumWords), BitWidth);
1399 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1401 MetadataList.assignValue(
1402 GET_OR_DISTINCT(DIEnumerator,
1403 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1408 case bitc::METADATA_BASIC_TYPE: {
1409 if (Record.size() < 6 || Record.size() > 7)
1410 return error("Invalid record");
1412 IsDistinct = Record[0];
1413 DINode::DIFlags Flags = (Record.size() > 6)
1414 ? static_cast<DINode::DIFlags>(Record[6])
1417 MetadataList.assignValue(
1418 GET_OR_DISTINCT(DIBasicType,
1419 (Context, Record[1], getMDString(Record[2]), Record[3],
1420 Record[4], Record[5], Flags)),
1425 case bitc::METADATA_STRING_TYPE: {
1426 if (Record.size() > 9 || Record.size() < 8)
1427 return error("Invalid record");
1429 IsDistinct = Record[0];
1430 bool SizeIs8 = Record.size() == 8;
1431 // StringLocationExp (i.e. Record[5]) is added at a later time
1432 // than the other fields. The code here enables backward compatibility.
1433 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1434 unsigned Offset = SizeIs8 ? 5 : 6;
1435 MetadataList.assignValue(
1436 GET_OR_DISTINCT(DIStringType,
1437 (Context, Record[1], getMDString(Record[2]),
1438 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1439 StringLocationExp, Record[Offset], Record[Offset + 1],
1440 Record[Offset + 2])),
1445 case bitc::METADATA_DERIVED_TYPE: {
1446 if (Record.size() < 12 || Record.size() > 14)
1447 return error("Invalid record");
1449 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1450 // that there is no DWARF address space associated with DIDerivedType.
1451 Optional<unsigned> DWARFAddressSpace;
1452 if (Record.size() > 12 && Record[12])
1453 DWARFAddressSpace = Record[12] - 1;
1455 Metadata *Annotations = nullptr;
1456 if (Record.size() > 13 && Record[13])
1457 Annotations = getMDOrNull(Record[13]);
1459 IsDistinct = Record[0];
1460 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1461 MetadataList.assignValue(
1462 GET_OR_DISTINCT(DIDerivedType,
1463 (Context, Record[1], getMDString(Record[2]),
1464 getMDOrNull(Record[3]), Record[4],
1465 getDITypeRefOrNull(Record[5]),
1466 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1467 Record[9], DWARFAddressSpace, Flags,
1468 getDITypeRefOrNull(Record[11]), Annotations)),
1473 case bitc::METADATA_COMPOSITE_TYPE: {
1474 if (Record.size() < 16 || Record.size() > 22)
1475 return error("Invalid record");
1477 // If we have a UUID and this is not a forward declaration, lookup the
1479 IsDistinct = Record[0] & 0x1;
1480 bool IsNotUsedInTypeRef = Record[0] >= 2;
1481 unsigned Tag = Record[1];
1482 MDString *Name = getMDString(Record[2]);
1483 Metadata *File = getMDOrNull(Record[3]);
1484 unsigned Line = Record[4];
1485 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1486 Metadata *BaseType = nullptr;
1487 uint64_t SizeInBits = Record[7];
1488 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1489 return error("Alignment value is too large");
1490 uint32_t AlignInBits = Record[8];
1491 uint64_t OffsetInBits = 0;
1492 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1493 Metadata *Elements = nullptr;
1494 unsigned RuntimeLang = Record[12];
1495 Metadata *VTableHolder = nullptr;
1496 Metadata *TemplateParams = nullptr;
1497 Metadata *Discriminator = nullptr;
1498 Metadata *DataLocation = nullptr;
1499 Metadata *Associated = nullptr;
1500 Metadata *Allocated = nullptr;
1501 Metadata *Rank = nullptr;
1502 Metadata *Annotations = nullptr;
1503 auto *Identifier = getMDString(Record[15]);
1504 // If this module is being parsed so that it can be ThinLTO imported
1505 // into another module, composite types only need to be imported
1506 // as type declarations (unless full type definitions requested).
1507 // Create type declarations up front to save memory. Also, buildODRType
1508 // handles the case where this is type ODRed with a definition needed
1509 // by the importing module, in which case the existing definition is
1511 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1512 (Tag == dwarf::DW_TAG_enumeration_type ||
1513 Tag == dwarf::DW_TAG_class_type ||
1514 Tag == dwarf::DW_TAG_structure_type ||
1515 Tag == dwarf::DW_TAG_union_type)) {
1516 Flags = Flags | DINode::FlagFwdDecl;
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 unsigned OffsetA = 0;
1704 unsigned OffsetB = 0;
1708 if (Record.size() >= 19) {
1712 HasThisAdj = Record.size() >= 20;
1713 HasThrownTypes = Record.size() >= 21;
1715 HasAnnotations = Record.size() >= 19;
1717 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1718 DISubprogram *SP = GET_OR_DISTINCT(
1721 getDITypeRefOrNull(Record[1]), // scope
1722 getMDString(Record[2]), // name
1723 getMDString(Record[3]), // linkageName
1724 getMDOrNull(Record[4]), // file
1726 getMDOrNull(Record[6]), // type
1727 Record[7 + OffsetA], // scopeLine
1728 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
1729 Record[10 + OffsetA], // virtualIndex
1730 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
1733 HasUnit ? CUorFn : nullptr, // unit
1734 getMDOrNull(Record[13 + OffsetB]), // templateParams
1735 getMDOrNull(Record[14 + OffsetB]), // declaration
1736 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
1737 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1738 : nullptr, // thrownTypes
1739 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1740 : nullptr // annotations
1742 MetadataList.assignValue(SP, NextMetadataNo);
1745 // Upgrade sp->function mapping to function->sp mapping.
1747 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1748 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1749 if (F->isMaterializable())
1750 // Defer until materialized; unmaterialized functions may not have
1752 FunctionsWithSPs[F] = SP;
1753 else if (!F->empty())
1754 F->setSubprogram(SP);
1759 case bitc::METADATA_LEXICAL_BLOCK: {
1760 if (Record.size() != 5)
1761 return error("Invalid record");
1763 IsDistinct = Record[0];
1764 MetadataList.assignValue(
1765 GET_OR_DISTINCT(DILexicalBlock,
1766 (Context, getMDOrNull(Record[1]),
1767 getMDOrNull(Record[2]), Record[3], Record[4])),
1772 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1773 if (Record.size() != 4)
1774 return error("Invalid record");
1776 IsDistinct = Record[0];
1777 MetadataList.assignValue(
1778 GET_OR_DISTINCT(DILexicalBlockFile,
1779 (Context, getMDOrNull(Record[1]),
1780 getMDOrNull(Record[2]), Record[3])),
1785 case bitc::METADATA_COMMON_BLOCK: {
1786 IsDistinct = Record[0] & 1;
1787 MetadataList.assignValue(
1788 GET_OR_DISTINCT(DICommonBlock,
1789 (Context, getMDOrNull(Record[1]),
1790 getMDOrNull(Record[2]), getMDString(Record[3]),
1791 getMDOrNull(Record[4]), Record[5])),
1796 case bitc::METADATA_NAMESPACE: {
1797 // Newer versions of DINamespace dropped file and line.
1799 if (Record.size() == 3)
1800 Name = getMDString(Record[2]);
1801 else if (Record.size() == 5)
1802 Name = getMDString(Record[3]);
1804 return error("Invalid record");
1806 IsDistinct = Record[0] & 1;
1807 bool ExportSymbols = Record[0] & 2;
1808 MetadataList.assignValue(
1809 GET_OR_DISTINCT(DINamespace,
1810 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1815 case bitc::METADATA_MACRO: {
1816 if (Record.size() != 5)
1817 return error("Invalid record");
1819 IsDistinct = Record[0];
1820 MetadataList.assignValue(
1821 GET_OR_DISTINCT(DIMacro,
1822 (Context, Record[1], Record[2], getMDString(Record[3]),
1823 getMDString(Record[4]))),
1828 case bitc::METADATA_MACRO_FILE: {
1829 if (Record.size() != 5)
1830 return error("Invalid record");
1832 IsDistinct = Record[0];
1833 MetadataList.assignValue(
1834 GET_OR_DISTINCT(DIMacroFile,
1835 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1836 getMDOrNull(Record[4]))),
1841 case bitc::METADATA_TEMPLATE_TYPE: {
1842 if (Record.size() < 3 || Record.size() > 4)
1843 return error("Invalid record");
1845 IsDistinct = Record[0];
1846 MetadataList.assignValue(
1847 GET_OR_DISTINCT(DITemplateTypeParameter,
1848 (Context, getMDString(Record[1]),
1849 getDITypeRefOrNull(Record[2]),
1850 (Record.size() == 4) ? getMDOrNull(Record[3])
1851 : getMDOrNull(false))),
1856 case bitc::METADATA_TEMPLATE_VALUE: {
1857 if (Record.size() < 5 || Record.size() > 6)
1858 return error("Invalid record");
1860 IsDistinct = Record[0];
1862 MetadataList.assignValue(
1864 DITemplateValueParameter,
1865 (Context, Record[1], getMDString(Record[2]),
1866 getDITypeRefOrNull(Record[3]),
1867 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
1868 (Record.size() == 6) ? getMDOrNull(Record[5])
1869 : getMDOrNull(Record[4]))),
1874 case bitc::METADATA_GLOBAL_VAR: {
1875 if (Record.size() < 11 || Record.size() > 13)
1876 return error("Invalid record");
1878 IsDistinct = Record[0] & 1;
1879 unsigned Version = Record[0] >> 1;
1882 Metadata *Annotations = nullptr;
1883 if (Record.size() > 12)
1884 Annotations = getMDOrNull(Record[12]);
1886 MetadataList.assignValue(
1887 GET_OR_DISTINCT(DIGlobalVariable,
1888 (Context, getMDOrNull(Record[1]),
1889 getMDString(Record[2]), getMDString(Record[3]),
1890 getMDOrNull(Record[4]), Record[5],
1891 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1892 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1893 Record[11], Annotations)),
1897 } else if (Version == 1) {
1898 // No upgrade necessary. A null field will be introduced to indicate
1899 // that no parameter information is available.
1900 MetadataList.assignValue(
1903 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1904 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1905 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1906 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
1910 } else if (Version == 0) {
1911 // Upgrade old metadata, which stored a global variable reference or a
1912 // ConstantInt here.
1913 NeedUpgradeToDIGlobalVariableExpression = true;
1914 Metadata *Expr = getMDOrNull(Record[9]);
1915 uint32_t AlignInBits = 0;
1916 if (Record.size() > 11) {
1917 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1918 return error("Alignment value is too large");
1919 AlignInBits = Record[11];
1921 GlobalVariable *Attach = nullptr;
1922 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1923 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1926 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1927 Expr = DIExpression::get(Context,
1928 {dwarf::DW_OP_constu, CI->getZExtValue(),
1929 dwarf::DW_OP_stack_value});
1934 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1936 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1937 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1938 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1939 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
1941 DIGlobalVariableExpression *DGVE = nullptr;
1943 DGVE = DIGlobalVariableExpression::getDistinct(
1944 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
1946 Attach->addDebugInfo(DGVE);
1948 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1949 MetadataList.assignValue(MDNode, NextMetadataNo);
1952 return error("Invalid record");
1956 case bitc::METADATA_LOCAL_VAR: {
1957 // 10th field is for the obseleted 'inlinedAt:' field.
1958 if (Record.size() < 8 || Record.size() > 10)
1959 return error("Invalid record");
1961 IsDistinct = Record[0] & 1;
1962 bool HasAlignment = Record[0] & 2;
1963 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1964 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1965 // this is newer version of record which doesn't have artificial tag.
1966 bool HasTag = !HasAlignment && Record.size() > 8;
1967 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1968 uint32_t AlignInBits = 0;
1969 Metadata *Annotations = nullptr;
1971 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1972 return error("Alignment value is too large");
1973 AlignInBits = Record[8];
1974 if (Record.size() > 9)
1975 Annotations = getMDOrNull(Record[9]);
1978 MetadataList.assignValue(
1979 GET_OR_DISTINCT(DILocalVariable,
1980 (Context, getMDOrNull(Record[1 + HasTag]),
1981 getMDString(Record[2 + HasTag]),
1982 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1983 getDITypeRefOrNull(Record[5 + HasTag]),
1984 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
1989 case bitc::METADATA_LABEL: {
1990 if (Record.size() != 5)
1991 return error("Invalid record");
1993 IsDistinct = Record[0] & 1;
1994 MetadataList.assignValue(
1995 GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
1996 getMDString(Record[2]),
1997 getMDOrNull(Record[3]), Record[4])),
2002 case bitc::METADATA_EXPRESSION: {
2003 if (Record.size() < 1)
2004 return error("Invalid record");
2006 IsDistinct = Record[0] & 1;
2007 uint64_t Version = Record[0] >> 1;
2008 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2010 SmallVector<uint64_t, 6> Buffer;
2011 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2014 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2019 case bitc::METADATA_GLOBAL_VAR_EXPR: {
2020 if (Record.size() != 3)
2021 return error("Invalid record");
2023 IsDistinct = Record[0];
2024 Metadata *Expr = getMDOrNull(Record[2]);
2026 Expr = DIExpression::get(Context, {});
2027 MetadataList.assignValue(
2028 GET_OR_DISTINCT(DIGlobalVariableExpression,
2029 (Context, getMDOrNull(Record[1]), Expr)),
2034 case bitc::METADATA_OBJC_PROPERTY: {
2035 if (Record.size() != 8)
2036 return error("Invalid record");
2038 IsDistinct = Record[0];
2039 MetadataList.assignValue(
2040 GET_OR_DISTINCT(DIObjCProperty,
2041 (Context, getMDString(Record[1]),
2042 getMDOrNull(Record[2]), Record[3],
2043 getMDString(Record[4]), getMDString(Record[5]),
2044 Record[6], getDITypeRefOrNull(Record[7]))),
2049 case bitc::METADATA_IMPORTED_ENTITY: {
2050 if (Record.size() < 6 && Record.size() > 8)
2051 return error("Invalid record");
2053 IsDistinct = Record[0];
2054 bool HasFile = (Record.size() >= 7);
2055 bool HasElements = (Record.size() >= 8);
2056 MetadataList.assignValue(
2057 GET_OR_DISTINCT(DIImportedEntity,
2058 (Context, Record[1], getMDOrNull(Record[2]),
2059 getDITypeRefOrNull(Record[3]),
2060 HasFile ? getMDOrNull(Record[6]) : nullptr,
2061 HasFile ? Record[4] : 0, getMDString(Record[5]),
2062 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2067 case bitc::METADATA_STRING_OLD: {
2068 std::string String(Record.begin(), Record.end());
2070 // Test for upgrading !llvm.loop.
2071 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2072 ++NumMDStringLoaded;
2073 Metadata *MD = MDString::get(Context, String);
2074 MetadataList.assignValue(MD, NextMetadataNo);
2078 case bitc::METADATA_STRINGS: {
2079 auto CreateNextMDString = [&](StringRef Str) {
2080 ++NumMDStringLoaded;
2081 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2084 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2088 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2089 if (Record.size() % 2 == 0)
2090 return error("Invalid record");
2091 unsigned ValueID = Record[0];
2092 if (ValueID >= ValueList.size())
2093 return error("Invalid record");
2094 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2095 if (Error Err = parseGlobalObjectAttachment(
2096 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2100 case bitc::METADATA_KIND: {
2101 // Support older bitcode files that had METADATA_KIND records in a
2102 // block with METADATA_BLOCK_ID.
2103 if (Error Err = parseMetadataKindRecord(Record))
2107 case bitc::METADATA_ARG_LIST: {
2108 SmallVector<ValueAsMetadata *, 4> Elts;
2109 Elts.reserve(Record.size());
2110 for (uint64_t Elt : Record) {
2111 Metadata *MD = getMD(Elt);
2112 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2114 "Invalid record: DIArgList should not contain forward refs");
2115 if (!isa<ValueAsMetadata>(MD))
2116 return error("Invalid record");
2117 Elts.push_back(cast<ValueAsMetadata>(MD));
2120 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2125 return Error::success();
2126 #undef GET_OR_DISTINCT
2129 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2130 ArrayRef<uint64_t> Record, StringRef Blob,
2131 function_ref<void(StringRef)> CallBack) {
2132 // All the MDStrings in the block are emitted together in a single
2133 // record. The strings are concatenated and stored in a blob along with
2135 if (Record.size() != 2)
2136 return error("Invalid record: metadata strings layout");
2138 unsigned NumStrings = Record[0];
2139 unsigned StringsOffset = Record[1];
2141 return error("Invalid record: metadata strings with no strings");
2142 if (StringsOffset > Blob.size())
2143 return error("Invalid record: metadata strings corrupt offset");
2145 StringRef Lengths = Blob.slice(0, StringsOffset);
2146 SimpleBitstreamCursor R(Lengths);
2148 StringRef Strings = Blob.drop_front(StringsOffset);
2150 if (R.AtEndOfStream())
2151 return error("Invalid record: metadata strings bad length");
2154 if (Error E = R.ReadVBR(6).moveInto(Size))
2156 if (Strings.size() < Size)
2157 return error("Invalid record: metadata strings truncated chars");
2159 CallBack(Strings.slice(0, Size));
2160 Strings = Strings.drop_front(Size);
2161 } while (--NumStrings);
2163 return Error::success();
2166 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2167 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2168 assert(Record.size() % 2 == 0);
2169 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2170 auto K = MDKindMap.find(Record[I]);
2171 if (K == MDKindMap.end())
2172 return error("Invalid ID");
2174 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2176 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2177 GO.addMetadata(K->second, *MD);
2179 return Error::success();
2182 /// Parse metadata attachments.
2183 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2184 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
2185 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2188 SmallVector<uint64_t, 64> Record;
2189 PlaceholderQueue Placeholders;
2192 BitstreamEntry Entry;
2193 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2196 switch (Entry.Kind) {
2197 case BitstreamEntry::SubBlock: // Handled for us already.
2198 case BitstreamEntry::Error:
2199 return error("Malformed block");
2200 case BitstreamEntry::EndBlock:
2201 resolveForwardRefsAndPlaceholders(Placeholders);
2202 return Error::success();
2203 case BitstreamEntry::Record:
2204 // The interesting case.
2208 // Read a metadata attachment record.
2210 ++NumMDRecordLoaded;
2211 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2213 return MaybeRecord.takeError();
2214 switch (MaybeRecord.get()) {
2215 default: // Default behavior: ignore.
2217 case bitc::METADATA_ATTACHMENT: {
2218 unsigned RecordLength = Record.size();
2220 return error("Invalid record");
2221 if (RecordLength % 2 == 0) {
2222 // A function attachment.
2223 if (Error Err = parseGlobalObjectAttachment(F, Record))
2228 // An instruction attachment.
2229 Instruction *Inst = InstructionList[Record[0]];
2230 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2231 unsigned Kind = Record[i];
2232 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2233 if (I == MDKindMap.end())
2234 return error("Invalid ID");
2235 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2238 auto Idx = Record[i + 1];
2239 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2240 !MetadataList.lookup(Idx)) {
2241 // Load the attachment if it is in the lazy-loadable range and hasn't
2243 lazyLoadOneMetadata(Idx, Placeholders);
2244 resolveForwardRefsAndPlaceholders(Placeholders);
2247 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2248 if (isa<LocalAsMetadata>(Node))
2249 // Drop the attachment. This used to be legal, but there's no
2252 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2254 return error("Invalid metadata attachment");
2256 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2257 MD = upgradeInstructionLoopAttachment(*MD);
2259 if (I->second == LLVMContext::MD_tbaa) {
2260 assert(!MD->isTemporary() && "should load MDs before attachments");
2261 MD = UpgradeTBAANode(*MD);
2263 Inst->setMetadata(I->second, MD);
2271 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2272 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2273 SmallVectorImpl<uint64_t> &Record) {
2274 if (Record.size() < 2)
2275 return error("Invalid record");
2277 unsigned Kind = Record[0];
2278 SmallString<8> Name(Record.begin() + 1, Record.end());
2280 unsigned NewKind = TheModule.getMDKindID(Name.str());
2281 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2282 return error("Conflicting METADATA_KIND records");
2283 return Error::success();
2286 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2287 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2288 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2291 SmallVector<uint64_t, 64> Record;
2293 // Read all the records.
2295 BitstreamEntry Entry;
2296 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2299 switch (Entry.Kind) {
2300 case BitstreamEntry::SubBlock: // Handled for us already.
2301 case BitstreamEntry::Error:
2302 return error("Malformed block");
2303 case BitstreamEntry::EndBlock:
2304 return Error::success();
2305 case BitstreamEntry::Record:
2306 // The interesting case.
2312 ++NumMDRecordLoaded;
2313 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2315 return MaybeCode.takeError();
2316 switch (MaybeCode.get()) {
2317 default: // Default behavior: ignore.
2319 case bitc::METADATA_KIND: {
2320 if (Error Err = parseMetadataKindRecord(Record))
2328 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2329 Pimpl = std::move(RHS.Pimpl);
2332 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2333 : Pimpl(std::move(RHS.Pimpl)) {}
2335 MetadataLoader::~MetadataLoader() = default;
2336 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2337 BitcodeReaderValueList &ValueList,
2339 std::function<Type *(unsigned)> getTypeByID)
2340 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2341 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
2343 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2344 return Pimpl->parseMetadata(ModuleLevel);
2347 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2349 /// Return the given metadata, creating a replaceable forward reference if
2351 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
2352 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2355 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2356 return Pimpl->lookupSubprogramForFunction(F);
2359 Error MetadataLoader::parseMetadataAttachment(
2360 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
2361 return Pimpl->parseMetadataAttachment(F, InstructionList);
2364 Error MetadataLoader::parseMetadataKinds() {
2365 return Pimpl->parseMetadataKinds();
2368 void MetadataLoader::setStripTBAA(bool StripTBAA) {
2369 return Pimpl->setStripTBAA(StripTBAA);
2372 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2374 unsigned MetadataLoader::size() const { return Pimpl->size(); }
2375 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2377 void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2378 return Pimpl->upgradeDebugIntrinsics(F);