LLVM 22.0.0git
MetadataLoader.cpp
Go to the documentation of this file.
1//===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include "MetadataLoader.h"
10#include "ValueList.h"
11
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
35#include "llvm/IR/Instruction.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
41#include "llvm/IR/Type.h"
47
48#include <algorithm>
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <deque>
53#include <iterator>
54#include <limits>
55#include <map>
56#include <optional>
57#include <string>
58#include <tuple>
59#include <utility>
60#include <vector>
61namespace llvm {
62class Argument;
63}
64
65using namespace llvm;
66
67#define DEBUG_TYPE "bitcode-reader"
68
69STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
70STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
71STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
72
73/// Flag whether we need to import full type definitions for ThinLTO.
74/// Currently needed for Darwin and LLDB.
76 "import-full-type-definitions", cl::init(false), cl::Hidden,
77 cl::desc("Import full type definitions for ThinLTO."));
78
80 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
81 cl::desc("Force disable the lazy-loading on-demand of metadata when "
82 "loading bitcode for importing."));
83
84namespace {
85
86static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
87
88class BitcodeReaderMetadataList {
89 /// Array of metadata references.
90 ///
91 /// Don't use std::vector here. Some versions of libc++ copy (instead of
92 /// move) on resize, and TrackingMDRef is very expensive to copy.
94
95 /// The set of indices in MetadataPtrs above of forward references that were
96 /// generated.
97 SmallDenseSet<unsigned, 1> ForwardReference;
98
99 /// The set of indices in MetadataPtrs above of Metadata that need to be
100 /// resolved.
101 SmallDenseSet<unsigned, 1> UnresolvedNodes;
102
103 /// Structures for resolving old type refs.
104 struct {
105 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
106 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
107 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
109 } OldTypeRefs;
110
111 LLVMContext &Context;
112
113 /// Maximum number of valid references. Forward references exceeding the
114 /// maximum must be invalid.
115 unsigned RefsUpperBound;
116
117public:
118 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
119 : Context(C),
120 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
121 RefsUpperBound)) {}
122
123 // vector compatibility methods
124 unsigned size() const { return MetadataPtrs.size(); }
125 void resize(unsigned N) { MetadataPtrs.resize(N); }
126 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
127 void clear() { MetadataPtrs.clear(); }
128 Metadata *back() const { return MetadataPtrs.back(); }
129 void pop_back() { MetadataPtrs.pop_back(); }
130 bool empty() const { return MetadataPtrs.empty(); }
131
132 Metadata *operator[](unsigned i) const {
133 assert(i < MetadataPtrs.size());
134 return MetadataPtrs[i];
135 }
136
137 Metadata *lookup(unsigned I) const {
138 if (I < MetadataPtrs.size())
139 return MetadataPtrs[I];
140 return nullptr;
141 }
142
143 void shrinkTo(unsigned N) {
144 assert(N <= size() && "Invalid shrinkTo request!");
145 assert(ForwardReference.empty() && "Unexpected forward refs");
146 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
147 MetadataPtrs.resize(N);
148 }
149
150 /// Return the given metadata, creating a replaceable forward reference if
151 /// necessary.
152 Metadata *getMetadataFwdRef(unsigned Idx);
153
154 /// Return the given metadata only if it is fully resolved.
155 ///
156 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
157 /// would give \c false.
158 Metadata *getMetadataIfResolved(unsigned Idx);
159
160 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
161 void assignValue(Metadata *MD, unsigned Idx);
162 void tryToResolveCycles();
163 bool hasFwdRefs() const { return !ForwardReference.empty(); }
164 int getNextFwdRef() {
165 assert(hasFwdRefs());
166 return *ForwardReference.begin();
167 }
168
169 /// Upgrade a type that had an MDString reference.
170 void addTypeRef(MDString &UUID, DICompositeType &CT);
171
172 /// Upgrade a type that had an MDString reference.
173 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
174
175 /// Upgrade a type ref array that may have MDString references.
176 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
177
178private:
179 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
180};
181
182void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
183 if (auto *MDN = dyn_cast<MDNode>(MD))
184 if (!MDN->isResolved())
185 UnresolvedNodes.insert(Idx);
186
187 if (Idx == size()) {
188 push_back(MD);
189 return;
190 }
191
192 if (Idx >= size())
193 resize(Idx + 1);
194
195 TrackingMDRef &OldMD = MetadataPtrs[Idx];
196 if (!OldMD) {
197 OldMD.reset(MD);
198 return;
199 }
200
201 // If there was a forward reference to this value, replace it.
202 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
203 PrevMD->replaceAllUsesWith(MD);
204 ForwardReference.erase(Idx);
205}
206
207Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
208 // Bail out for a clearly invalid value.
209 if (Idx >= RefsUpperBound)
210 return nullptr;
211
212 if (Idx >= size())
213 resize(Idx + 1);
214
215 if (Metadata *MD = MetadataPtrs[Idx])
216 return MD;
217
218 // Track forward refs to be resolved later.
219 ForwardReference.insert(Idx);
220
221 // Create and return a placeholder, which will later be RAUW'd.
222 ++NumMDNodeTemporary;
224 MetadataPtrs[Idx].reset(MD);
225 return MD;
226}
227
228Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
229 Metadata *MD = lookup(Idx);
230 if (auto *N = dyn_cast_or_null<MDNode>(MD))
231 if (!N->isResolved())
232 return nullptr;
233 return MD;
234}
235
236MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
237 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
238}
239
240void BitcodeReaderMetadataList::tryToResolveCycles() {
241 if (!ForwardReference.empty())
242 // Still forward references... can't resolve cycles.
243 return;
244
245 // Give up on finding a full definition for any forward decls that remain.
246 for (const auto &Ref : OldTypeRefs.FwdDecls)
247 OldTypeRefs.Final.insert(Ref);
248 OldTypeRefs.FwdDecls.clear();
249
250 // Upgrade from old type ref arrays. In strange cases, this could add to
251 // OldTypeRefs.Unknown.
252 for (const auto &Array : OldTypeRefs.Arrays)
253 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
254 OldTypeRefs.Arrays.clear();
255
256 // Replace old string-based type refs with the resolved node, if possible.
257 // If we haven't seen the node, leave it to the verifier to complain about
258 // the invalid string reference.
259 for (const auto &Ref : OldTypeRefs.Unknown) {
260 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
261 Ref.second->replaceAllUsesWith(CT);
262 else
263 Ref.second->replaceAllUsesWith(Ref.first);
264 }
265 OldTypeRefs.Unknown.clear();
266
267 if (UnresolvedNodes.empty())
268 // Nothing to do.
269 return;
270
271 // Resolve any cycles.
272 for (unsigned I : UnresolvedNodes) {
273 auto &MD = MetadataPtrs[I];
274 auto *N = dyn_cast_or_null<MDNode>(MD);
275 if (!N)
276 continue;
277
278 assert(!N->isTemporary() && "Unexpected forward reference");
279 N->resolveCycles();
280 }
281
282 // Make sure we return early again until there's another unresolved ref.
283 UnresolvedNodes.clear();
284}
285
286void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
287 DICompositeType &CT) {
288 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
289 if (CT.isForwardDecl())
290 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
291 else
292 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
293}
294
295Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
296 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
297 if (LLVM_LIKELY(!UUID))
298 return MaybeUUID;
299
300 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
301 return CT;
302
303 auto &Ref = OldTypeRefs.Unknown[UUID];
304 if (!Ref)
306 return Ref.get();
307}
308
309Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
310 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
311 if (!Tuple || Tuple->isDistinct())
312 return MaybeTuple;
313
314 // Look through the array immediately if possible.
315 if (!Tuple->isTemporary())
316 return resolveTypeRefArray(Tuple);
317
318 // Create and return a placeholder to use for now. Eventually
319 // resolveTypeRefArrays() will be resolve this forward reference.
320 OldTypeRefs.Arrays.emplace_back(
321 std::piecewise_construct, std::forward_as_tuple(Tuple),
322 std::forward_as_tuple(MDTuple::getTemporary(Context, {})));
323 return OldTypeRefs.Arrays.back().second.get();
324}
325
326Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
327 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
328 if (!Tuple || Tuple->isDistinct())
329 return MaybeTuple;
330
331 // Look through the DITypeRefArray, upgrading each DIType *.
333 Ops.reserve(Tuple->getNumOperands());
334 for (Metadata *MD : Tuple->operands())
335 Ops.push_back(upgradeTypeRef(MD));
336
337 return MDTuple::get(Context, Ops);
338}
339
340namespace {
341
342class PlaceholderQueue {
343 // Placeholders would thrash around when moved, so store in a std::deque
344 // instead of some sort of vector.
345 std::deque<DistinctMDOperandPlaceholder> PHs;
346
347public:
348 ~PlaceholderQueue() {
349 assert(empty() &&
350 "PlaceholderQueue hasn't been flushed before being destroyed");
351 }
352 bool empty() const { return PHs.empty(); }
353 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
354 void flush(BitcodeReaderMetadataList &MetadataList);
355
356 /// Return the list of temporaries nodes in the queue, these need to be
357 /// loaded before we can flush the queue.
358 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
359 DenseSet<unsigned> &Temporaries) {
360 for (auto &PH : PHs) {
361 auto ID = PH.getID();
362 auto *MD = MetadataList.lookup(ID);
363 if (!MD) {
364 Temporaries.insert(ID);
365 continue;
366 }
367 auto *N = dyn_cast_or_null<MDNode>(MD);
368 if (N && N->isTemporary())
369 Temporaries.insert(ID);
370 }
371 }
372};
373
374} // end anonymous namespace
375
376DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
377 PHs.emplace_back(ID);
378 return PHs.back();
379}
380
381void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
382 while (!PHs.empty()) {
383 auto *MD = MetadataList.lookup(PHs.front().getID());
384 assert(MD && "Flushing placeholder on unassigned MD");
385#ifndef NDEBUG
386 if (auto *MDN = dyn_cast<MDNode>(MD))
387 assert(MDN->isResolved() &&
388 "Flushing Placeholder while cycles aren't resolved");
389#endif
390 PHs.front().replaceUseWith(MD);
391 PHs.pop_front();
392 }
393}
394
395} // anonymous namespace
396
397static Error error(const Twine &Message) {
400}
401
403 BitcodeReaderMetadataList MetadataList;
404 BitcodeReaderValueList &ValueList;
405 BitstreamCursor &Stream;
406 LLVMContext &Context;
407 Module &TheModule;
408 MetadataLoaderCallbacks Callbacks;
409
410 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
411 /// to keep around the right "context" (Abbrev list) to be able to jump in
412 /// the middle of the metadata block and load any record.
413 BitstreamCursor IndexCursor;
414
415 /// Index that keeps track of MDString values.
416 std::vector<StringRef> MDStringRef;
417
418 /// On-demand loading of a single MDString. Requires the index above to be
419 /// populated.
420 MDString *lazyLoadOneMDString(unsigned Idx);
421
422 /// Index that keeps track of where to find a metadata record in the stream.
423 std::vector<uint64_t> GlobalMetadataBitPosIndex;
424
425 /// Cursor position of the start of the global decl attachments, to enable
426 /// loading using the index built for lazy loading, instead of forward
427 /// references.
428 uint64_t GlobalDeclAttachmentPos = 0;
429
430#ifndef NDEBUG
431 /// Baisic correctness check that we end up parsing all of the global decl
432 /// attachments.
433 unsigned NumGlobalDeclAttachSkipped = 0;
434 unsigned NumGlobalDeclAttachParsed = 0;
435#endif
436
437 /// Load the global decl attachments, using the index built for lazy loading.
438 Expected<bool> loadGlobalDeclAttachments();
439
440 /// Populate the index above to enable lazily loading of metadata, and load
441 /// the named metadata as well as the transitively referenced global
442 /// Metadata.
443 Expected<bool> lazyLoadModuleMetadataBlock();
444
445 /// On-demand loading of a single metadata. Requires the index above to be
446 /// populated.
447 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
448
449 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
450 // point from SP to CU after a block is completly parsed.
451 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
452
453 /// Functions that need to be matched with subprograms when upgrading old
454 /// metadata.
456
457 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
459
460 bool StripTBAA = false;
461 bool HasSeenOldLoopTags = false;
462 bool NeedUpgradeToDIGlobalVariableExpression = false;
463 bool NeedDeclareExpressionUpgrade = false;
464
465 /// Map DILocalScope to the enclosing DISubprogram, if any.
467
468 /// True if metadata is being parsed for a module being ThinLTO imported.
469 bool IsImporting = false;
470
471 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
472 PlaceholderQueue &Placeholders, StringRef Blob,
473 unsigned &NextMetadataNo);
474 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
475 function_ref<void(StringRef)> CallBack);
476 Error parseGlobalObjectAttachment(GlobalObject &GO,
478 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
479
480 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
481
482 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
483 void upgradeCUSubprograms() {
484 for (auto CU_SP : CUSubprograms)
485 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
486 for (auto &Op : SPs->operands())
487 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
488 SP->replaceUnit(CU_SP.first);
489 CUSubprograms.clear();
490 }
491
492 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
493 void upgradeCUVariables() {
494 if (!NeedUpgradeToDIGlobalVariableExpression)
495 return;
496
497 // Upgrade list of variables attached to the CUs.
498 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
499 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
500 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
501 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
502 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
503 if (auto *GV =
504 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
506 Context, GV, DIExpression::get(Context, {}));
507 GVs->replaceOperandWith(I, DGVE);
508 }
509 }
510
511 // Upgrade variables attached to globals.
512 for (auto &GV : TheModule.globals()) {
514 GV.getMetadata(LLVMContext::MD_dbg, MDs);
515 GV.eraseMetadata(LLVMContext::MD_dbg);
516 for (auto *MD : MDs)
517 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
519 Context, DGV, DIExpression::get(Context, {}));
520 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
521 } else
522 GV.addMetadata(LLVMContext::MD_dbg, *MD);
523 }
524 }
525
526 DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
527 if (!S)
528 return nullptr;
529 if (auto *SP = ParentSubprogram[S]) {
530 return SP;
531 }
532
533 DILocalScope *InitialScope = S;
535 while (S && !isa<DISubprogram>(S)) {
537 if (!Visited.insert(S).second)
538 break;
539 }
540
541 return ParentSubprogram[InitialScope] =
543 }
544
545 /// Move local imports from DICompileUnit's 'imports' field to
546 /// DISubprogram's retainedNodes.
547 void upgradeCULocals() {
548 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu")) {
549 for (MDNode *N : CUNodes->operands()) {
551 if (!CU)
552 continue;
553
554 if (CU->getRawImportedEntities()) {
555 // Collect a set of imported entities to be moved.
556 SetVector<Metadata *> EntitiesToRemove;
557 for (Metadata *Op : CU->getImportedEntities()->operands()) {
558 auto *IE = cast<DIImportedEntity>(Op);
559 if (isa_and_nonnull<DILocalScope>(IE->getScope())) {
560 EntitiesToRemove.insert(IE);
561 }
562 }
563
564 if (!EntitiesToRemove.empty()) {
565 // Make a new list of CU's 'imports'.
566 SmallVector<Metadata *> NewImports;
567 for (Metadata *Op : CU->getImportedEntities()->operands()) {
568 if (!EntitiesToRemove.contains(cast<DIImportedEntity>(Op))) {
569 NewImports.push_back(Op);
570 }
571 }
572
573 // Find DISubprogram corresponding to each entity.
574 std::map<DISubprogram *, SmallVector<Metadata *>> SPToEntities;
575 for (auto *I : EntitiesToRemove) {
576 auto *Entity = cast<DIImportedEntity>(I);
577 if (auto *SP = findEnclosingSubprogram(
578 cast<DILocalScope>(Entity->getScope()))) {
579 SPToEntities[SP].push_back(Entity);
580 }
581 }
582
583 // Update DISubprograms' retainedNodes.
584 for (auto I = SPToEntities.begin(); I != SPToEntities.end(); ++I) {
585 auto *SP = I->first;
586 auto RetainedNodes = SP->getRetainedNodes();
587 SmallVector<Metadata *> MDs(RetainedNodes.begin(),
588 RetainedNodes.end());
589 MDs.append(I->second);
590 SP->replaceRetainedNodes(MDNode::get(Context, MDs));
591 }
592
593 // Remove entities with local scope from CU.
594 CU->replaceImportedEntities(MDTuple::get(Context, NewImports));
595 }
596 }
597 }
598 }
599
600 ParentSubprogram.clear();
601 }
602
603 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
604 /// describes a function argument.
605 void upgradeDeclareExpressions(Function &F) {
606 if (!NeedDeclareExpressionUpgrade)
607 return;
608
609 auto UpdateDeclareIfNeeded = [&](auto *Declare) {
610 auto *DIExpr = Declare->getExpression();
611 if (!DIExpr || !DIExpr->startsWithDeref() ||
612 !isa_and_nonnull<Argument>(Declare->getAddress()))
613 return;
615 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
616 Declare->setExpression(DIExpression::get(Context, Ops));
617 };
618
619 for (auto &BB : F)
620 for (auto &I : BB) {
621 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
622 if (DVR.isDbgDeclare())
623 UpdateDeclareIfNeeded(&DVR);
624 }
625 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
626 UpdateDeclareIfNeeded(DDI);
627 }
628 }
629
630 /// Upgrade the expression from previous versions.
631 Error upgradeDIExpression(uint64_t FromVersion,
634 auto N = Expr.size();
635 switch (FromVersion) {
636 default:
637 return error("Invalid record");
638 case 0:
639 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
640 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
641 [[fallthrough]];
642 case 1:
643 // Move DW_OP_deref to the end.
644 if (N && Expr[0] == dwarf::DW_OP_deref) {
645 auto End = Expr.end();
646 if (Expr.size() >= 3 &&
647 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
648 End = std::prev(End, 3);
649 std::move(std::next(Expr.begin()), End, Expr.begin());
650 *std::prev(End) = dwarf::DW_OP_deref;
651 }
652 NeedDeclareExpressionUpgrade = true;
653 [[fallthrough]];
654 case 2: {
655 // Change DW_OP_plus to DW_OP_plus_uconst.
656 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
657 auto SubExpr = ArrayRef<uint64_t>(Expr);
658 while (!SubExpr.empty()) {
659 // Skip past other operators with their operands
660 // for this version of the IR, obtained from
661 // from historic DIExpression::ExprOperand::getSize().
662 size_t HistoricSize;
663 switch (SubExpr.front()) {
664 default:
665 HistoricSize = 1;
666 break;
667 case dwarf::DW_OP_constu:
668 case dwarf::DW_OP_minus:
669 case dwarf::DW_OP_plus:
670 HistoricSize = 2;
671 break;
673 HistoricSize = 3;
674 break;
675 }
676
677 // If the expression is malformed, make sure we don't
678 // copy more elements than we should.
679 HistoricSize = std::min(SubExpr.size(), HistoricSize);
680 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
681
682 switch (SubExpr.front()) {
683 case dwarf::DW_OP_plus:
684 Buffer.push_back(dwarf::DW_OP_plus_uconst);
685 Buffer.append(Args.begin(), Args.end());
686 break;
687 case dwarf::DW_OP_minus:
688 Buffer.push_back(dwarf::DW_OP_constu);
689 Buffer.append(Args.begin(), Args.end());
690 Buffer.push_back(dwarf::DW_OP_minus);
691 break;
692 default:
693 Buffer.push_back(*SubExpr.begin());
694 Buffer.append(Args.begin(), Args.end());
695 break;
696 }
697
698 // Continue with remaining elements.
699 SubExpr = SubExpr.slice(HistoricSize);
700 }
701 Expr = MutableArrayRef<uint64_t>(Buffer);
702 [[fallthrough]];
703 }
704 case 3:
705 // Up-to-date!
706 break;
707 }
708
709 return Error::success();
710 }
711
712 void upgradeDebugInfo(bool ModuleLevel) {
713 upgradeCUSubprograms();
714 upgradeCUVariables();
715 if (ModuleLevel)
716 upgradeCULocals();
717 }
718
719 void callMDTypeCallback(Metadata **Val, unsigned TypeID);
720
721public:
723 BitcodeReaderValueList &ValueList,
724 MetadataLoaderCallbacks Callbacks, bool IsImporting)
725 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
726 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
727 TheModule(TheModule), Callbacks(std::move(Callbacks)),
728 IsImporting(IsImporting) {}
729
730 Error parseMetadata(bool ModuleLevel);
731
732 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
733
735 if (ID < MDStringRef.size())
736 return lazyLoadOneMDString(ID);
737 if (auto *MD = MetadataList.lookup(ID))
738 return MD;
739 // If lazy-loading is enabled, we try recursively to load the operand
740 // instead of creating a temporary.
741 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
742 PlaceholderQueue Placeholders;
743 lazyLoadOneMetadata(ID, Placeholders);
744 resolveForwardRefsAndPlaceholders(Placeholders);
745 return MetadataList.lookup(ID);
746 }
747 return MetadataList.getMetadataFwdRef(ID);
748 }
749
751 return FunctionsWithSPs.lookup(F);
752 }
753
754 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
755
757 ArrayRef<Instruction *> InstructionList);
758
760
761 void setStripTBAA(bool Value) { StripTBAA = Value; }
762 bool isStrippingTBAA() const { return StripTBAA; }
763
764 unsigned size() const { return MetadataList.size(); }
765 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
766 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
767};
768
770MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
771 IndexCursor = Stream;
773 GlobalDeclAttachmentPos = 0;
774 // Get the abbrevs, and preload record positions to make them lazy-loadable.
775 while (true) {
776 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
777 BitstreamEntry Entry;
778 if (Error E =
779 IndexCursor
780 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
781 .moveInto(Entry))
782 return std::move(E);
783
784 switch (Entry.Kind) {
785 case BitstreamEntry::SubBlock: // Handled for us already.
787 return error("Malformed block");
789 return true;
790 }
792 // The interesting case.
793 ++NumMDRecordLoaded;
794 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
795 unsigned Code;
796 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
797 return std::move(E);
798 switch (Code) {
800 // Rewind and parse the strings.
801 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
802 return std::move(Err);
803 StringRef Blob;
804 Record.clear();
805 if (Expected<unsigned> MaybeRecord =
806 IndexCursor.readRecord(Entry.ID, Record, &Blob))
807 ;
808 else
809 return MaybeRecord.takeError();
810 unsigned NumStrings = Record[0];
811 MDStringRef.reserve(NumStrings);
812 auto IndexNextMDString = [&](StringRef Str) {
813 MDStringRef.push_back(Str);
814 };
815 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
816 return std::move(Err);
817 break;
818 }
820 // This is the offset to the index, when we see this we skip all the
821 // records and load only an index to these.
822 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
823 return std::move(Err);
824 Record.clear();
825 if (Expected<unsigned> MaybeRecord =
826 IndexCursor.readRecord(Entry.ID, Record))
827 ;
828 else
829 return MaybeRecord.takeError();
830 if (Record.size() != 2)
831 return error("Invalid record");
832 auto Offset = Record[0] + (Record[1] << 32);
833 auto BeginPos = IndexCursor.GetCurrentBitNo();
834 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
835 return std::move(Err);
836 Expected<BitstreamEntry> MaybeEntry =
837 IndexCursor.advanceSkippingSubblocks(
839 if (!MaybeEntry)
840 return MaybeEntry.takeError();
841 Entry = MaybeEntry.get();
843 "Corrupted bitcode: Expected `Record` when trying to find the "
844 "Metadata index");
845 Record.clear();
846 if (Expected<unsigned> MaybeCode =
847 IndexCursor.readRecord(Entry.ID, Record))
848 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
849 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
850 "find the Metadata index");
851 else
852 return MaybeCode.takeError();
853 // Delta unpack
854 auto CurrentValue = BeginPos;
855 GlobalMetadataBitPosIndex.reserve(Record.size());
856 for (auto &Elt : Record) {
857 CurrentValue += Elt;
858 GlobalMetadataBitPosIndex.push_back(CurrentValue);
859 }
860 break;
861 }
863 // We don't expect to get there, the Index is loaded when we encounter
864 // the offset.
865 return error("Corrupted Metadata block");
866 case bitc::METADATA_NAME: {
867 // Named metadata need to be materialized now and aren't deferred.
868 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
869 return std::move(Err);
870 Record.clear();
871
872 unsigned Code;
873 if (Expected<unsigned> MaybeCode =
874 IndexCursor.readRecord(Entry.ID, Record)) {
875 Code = MaybeCode.get();
877 } else
878 return MaybeCode.takeError();
879
880 // Read name of the named metadata.
881 SmallString<8> Name(Record.begin(), Record.end());
882 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
883 Code = MaybeCode.get();
884 else
885 return MaybeCode.takeError();
886
887 // Named Metadata comes in two parts, we expect the name to be followed
888 // by the node
889 Record.clear();
890 if (Expected<unsigned> MaybeNextBitCode =
891 IndexCursor.readRecord(Code, Record))
892 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
893 else
894 return MaybeNextBitCode.takeError();
895
896 // Read named metadata elements.
897 unsigned Size = Record.size();
898 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
899 for (unsigned i = 0; i != Size; ++i) {
900 // FIXME: We could use a placeholder here, however NamedMDNode are
901 // taking MDNode as operand and not using the Metadata infrastructure.
902 // It is acknowledged by 'TODO: Inherit from Metadata' in the
903 // NamedMDNode class definition.
904 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
905 assert(MD && "Invalid metadata: expect fwd ref to MDNode");
906 NMD->addOperand(MD);
907 }
908 break;
909 }
911 if (!GlobalDeclAttachmentPos)
912 GlobalDeclAttachmentPos = SavedPos;
913#ifndef NDEBUG
914 NumGlobalDeclAttachSkipped++;
915#endif
916 break;
917 }
955 // We don't expect to see any of these, if we see one, give up on
956 // lazy-loading and fallback.
957 MDStringRef.clear();
958 GlobalMetadataBitPosIndex.clear();
959 return false;
960 }
961 break;
962 }
963 }
964 }
965}
966
967// Load the global decl attachments after building the lazy loading index.
968// We don't load them "lazily" - all global decl attachments must be
969// parsed since they aren't materialized on demand. However, by delaying
970// their parsing until after the index is created, we can use the index
971// instead of creating temporaries.
972Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
973 // Nothing to do if we didn't find any of these metadata records.
974 if (!GlobalDeclAttachmentPos)
975 return true;
976 // Use a temporary cursor so that we don't mess up the main Stream cursor or
977 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
978 BitstreamCursor TempCursor = Stream;
979 SmallVector<uint64_t, 64> Record;
980 // Jump to the position before the first global decl attachment, so we can
981 // scan for the first BitstreamEntry record.
982 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
983 return std::move(Err);
984 while (true) {
985 BitstreamEntry Entry;
986 if (Error E =
987 TempCursor
988 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
989 .moveInto(Entry))
990 return std::move(E);
991
992 switch (Entry.Kind) {
993 case BitstreamEntry::SubBlock: // Handled for us already.
995 return error("Malformed block");
997 // Check that we parsed them all.
998 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
999 return true;
1001 break;
1002 }
1003 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
1004 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1005 if (!MaybeCode)
1006 return MaybeCode.takeError();
1007 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
1008 // Anything other than a global decl attachment signals the end of
1009 // these records. Check that we parsed them all.
1010 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1011 return true;
1012 }
1013#ifndef NDEBUG
1014 NumGlobalDeclAttachParsed++;
1015#endif
1016 // FIXME: we need to do this early because we don't materialize global
1017 // value explicitly.
1018 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1019 return std::move(Err);
1020 Record.clear();
1021 if (Expected<unsigned> MaybeRecord =
1022 TempCursor.readRecord(Entry.ID, Record))
1023 ;
1024 else
1025 return MaybeRecord.takeError();
1026 if (Record.size() % 2 == 0)
1027 return error("Invalid record");
1028 unsigned ValueID = Record[0];
1029 if (ValueID >= ValueList.size())
1030 return error("Invalid record");
1031 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
1032 // Need to save and restore the current position since
1033 // parseGlobalObjectAttachment will resolve all forward references which
1034 // would require parsing from locations stored in the index.
1035 CurrentPos = TempCursor.GetCurrentBitNo();
1036 if (Error Err = parseGlobalObjectAttachment(
1037 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1038 return std::move(Err);
1039 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1040 return std::move(Err);
1041 }
1042 }
1043}
1044
1045void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1046 unsigned TypeID) {
1047 if (Callbacks.MDType) {
1048 (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1049 Callbacks.GetContainedTypeID);
1050 }
1051}
1052
1053/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1054/// module level metadata.
1056 llvm::TimeTraceScope timeScope("Parse metadata");
1057 if (!ModuleLevel && MetadataList.hasFwdRefs())
1058 return error("Invalid metadata: fwd refs into function blocks");
1059
1060 // Record the entry position so that we can jump back here and efficiently
1061 // skip the whole block in case we lazy-load.
1062 auto EntryPos = Stream.GetCurrentBitNo();
1063
1064 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1065 return Err;
1066
1068 PlaceholderQueue Placeholders;
1069
1070 // We lazy-load module-level metadata: we build an index for each record, and
1071 // then load individual record as needed, starting with the named metadata.
1072 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1074 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1075 if (!SuccessOrErr)
1076 return SuccessOrErr.takeError();
1077 if (SuccessOrErr.get()) {
1078 // An index was successfully created and we will be able to load metadata
1079 // on-demand.
1080 MetadataList.resize(MDStringRef.size() +
1081 GlobalMetadataBitPosIndex.size());
1082
1083 // Now that we have built the index, load the global decl attachments
1084 // that were deferred during that process. This avoids creating
1085 // temporaries.
1086 SuccessOrErr = loadGlobalDeclAttachments();
1087 if (!SuccessOrErr)
1088 return SuccessOrErr.takeError();
1089 assert(SuccessOrErr.get());
1090
1091 // Reading the named metadata created forward references and/or
1092 // placeholders, that we flush here.
1093 resolveForwardRefsAndPlaceholders(Placeholders);
1094 upgradeDebugInfo(ModuleLevel);
1095 // Return at the beginning of the block, since it is easy to skip it
1096 // entirely from there.
1097 Stream.ReadBlockEnd(); // Pop the abbrev block context.
1098 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1099 return Err;
1100 if (Error Err = Stream.SkipBlock()) {
1101 // FIXME this drops the error on the floor, which
1102 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1103 consumeError(std::move(Err));
1104 return Error::success();
1105 }
1106 return Error::success();
1107 }
1108 // Couldn't load an index, fallback to loading all the block "old-style".
1109 }
1110
1111 unsigned NextMetadataNo = MetadataList.size();
1112
1113 // Read all the records.
1114 while (true) {
1115 BitstreamEntry Entry;
1116 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1117 return E;
1118
1119 switch (Entry.Kind) {
1120 case BitstreamEntry::SubBlock: // Handled for us already.
1122 return error("Malformed block");
1124 resolveForwardRefsAndPlaceholders(Placeholders);
1125 upgradeDebugInfo(ModuleLevel);
1126 return Error::success();
1128 // The interesting case.
1129 break;
1130 }
1131
1132 // Read a record.
1133 Record.clear();
1134 StringRef Blob;
1135 ++NumMDRecordLoaded;
1136 if (Expected<unsigned> MaybeCode =
1137 Stream.readRecord(Entry.ID, Record, &Blob)) {
1138 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1139 Blob, NextMetadataNo))
1140 return Err;
1141 } else
1142 return MaybeCode.takeError();
1143 }
1144}
1145
1146MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1147 ++NumMDStringLoaded;
1148 if (Metadata *MD = MetadataList.lookup(ID))
1149 return cast<MDString>(MD);
1150 auto MDS = MDString::get(Context, MDStringRef[ID]);
1151 MetadataList.assignValue(MDS, ID);
1152 return MDS;
1153}
1154
1155void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1156 unsigned ID, PlaceholderQueue &Placeholders) {
1157 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1158 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
1159 // Lookup first if the metadata hasn't already been loaded.
1160 if (auto *MD = MetadataList.lookup(ID)) {
1161 auto *N = dyn_cast<MDNode>(MD);
1162 // If the node is not an MDNode, or if it is not temporary, then
1163 // we're done.
1164 if (!N || !N->isTemporary())
1165 return;
1166 }
1168 StringRef Blob;
1169 if (Error Err = IndexCursor.JumpToBit(
1170 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1171 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1172 Twine(toString(std::move(Err))));
1173 BitstreamEntry Entry;
1174 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1175 // FIXME this drops the error on the floor.
1176 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1177 Twine(toString(std::move(E))));
1178 ++NumMDRecordLoaded;
1179 if (Expected<unsigned> MaybeCode =
1180 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1181 if (Error Err =
1182 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1183 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1184 Twine(toString(std::move(Err))));
1185 } else
1186 report_fatal_error("Can't lazyload MD: " +
1187 Twine(toString(MaybeCode.takeError())));
1188}
1189
1190/// Ensure that all forward-references and placeholders are resolved.
1191/// Iteratively lazy-loading metadata on-demand if needed.
1192void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1193 PlaceholderQueue &Placeholders) {
1194 DenseSet<unsigned> Temporaries;
1195 while (true) {
1196 // Populate Temporaries with the placeholders that haven't been loaded yet.
1197 Placeholders.getTemporaries(MetadataList, Temporaries);
1198
1199 // If we don't have any temporary, or FwdReference, we're done!
1200 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1201 break;
1202
1203 // First, load all the temporaries. This can add new placeholders or
1204 // forward references.
1205 for (auto ID : Temporaries)
1206 lazyLoadOneMetadata(ID, Placeholders);
1207 Temporaries.clear();
1208
1209 // Second, load the forward-references. This can also add new placeholders
1210 // or forward references.
1211 while (MetadataList.hasFwdRefs())
1212 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1213 }
1214 // At this point we don't have any forward reference remaining, or temporary
1215 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1216 // as resolved.
1217 MetadataList.tryToResolveCycles();
1218
1219 // Finally, everything is in place, we can replace the placeholders operands
1220 // with the final node they refer to.
1221 Placeholders.flush(MetadataList);
1222}
1223
1224static Value *getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx,
1225 Type *Ty, unsigned TyID) {
1226 Value *V = ValueList.getValueFwdRef(Idx, Ty, TyID,
1227 /*ConstExprInsertBB*/ nullptr);
1228 if (V)
1229 return V;
1230
1231 // This is a reference to a no longer supported constant expression.
1232 // Pretend that the constant was deleted, which will replace metadata
1233 // references with poison.
1234 // TODO: This is a rather indirect check. It would be more elegant to use
1235 // a separate ErrorInfo for constant materialization failure and thread
1236 // the error reporting through getValueFwdRef().
1237 if (Idx < ValueList.size() && ValueList[Idx] &&
1238 ValueList[Idx]->getType() == Ty)
1239 return PoisonValue::get(Ty);
1240
1241 return nullptr;
1242}
1243
1244Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1245 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1246 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1247
1248 bool IsDistinct = false;
1249 auto getMD = [&](unsigned ID) -> Metadata * {
1250 if (ID < MDStringRef.size())
1251 return lazyLoadOneMDString(ID);
1252 if (!IsDistinct) {
1253 if (auto *MD = MetadataList.lookup(ID))
1254 return MD;
1255 // If lazy-loading is enabled, we try recursively to load the operand
1256 // instead of creating a temporary.
1257 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1258 // Create a temporary for the node that is referencing the operand we
1259 // will lazy-load. It is needed before recursing in case there are
1260 // uniquing cycles.
1261 MetadataList.getMetadataFwdRef(NextMetadataNo);
1262 lazyLoadOneMetadata(ID, Placeholders);
1263 return MetadataList.lookup(ID);
1264 }
1265 // Return a temporary.
1266 return MetadataList.getMetadataFwdRef(ID);
1267 }
1268 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1269 return MD;
1270 return &Placeholders.getPlaceholderOp(ID);
1271 };
1272 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1273 if (ID)
1274 return getMD(ID - 1);
1275 return nullptr;
1276 };
1277 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1278 if (ID)
1279 return MetadataList.getMetadataFwdRef(ID - 1);
1280 return nullptr;
1281 };
1282 auto getMDString = [&](unsigned ID) -> MDString * {
1283 // This requires that the ID is not really a forward reference. In
1284 // particular, the MDString must already have been resolved.
1285 auto MDS = getMDOrNull(ID);
1286 return cast_or_null<MDString>(MDS);
1287 };
1288
1289 // Support for old type refs.
1290 auto getDITypeRefOrNull = [&](unsigned ID) {
1291 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1292 };
1293
1294 auto getMetadataOrConstant = [&](bool IsMetadata,
1295 uint64_t Entry) -> Metadata * {
1296 if (IsMetadata)
1297 return getMDOrNull(Entry);
1299 ConstantInt::get(Type::getInt64Ty(Context), Entry));
1300 };
1301
1302#define GET_OR_DISTINCT(CLASS, ARGS) \
1303 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1304
1305 switch (Code) {
1306 default: // Default behavior: ignore.
1307 break;
1308 case bitc::METADATA_NAME: {
1309 // Read name of the named metadata.
1310 SmallString<8> Name(Record.begin(), Record.end());
1311 Record.clear();
1312 if (Error E = Stream.ReadCode().moveInto(Code))
1313 return E;
1314
1315 ++NumMDRecordLoaded;
1316 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1317 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1318 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1319 } else
1320 return MaybeNextBitCode.takeError();
1321
1322 // Read named metadata elements.
1323 unsigned Size = Record.size();
1324 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1325 for (unsigned i = 0; i != Size; ++i) {
1326 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1327 if (!MD)
1328 return error("Invalid named metadata: expect fwd ref to MDNode");
1329 NMD->addOperand(MD);
1330 }
1331 break;
1332 }
1334 // Deprecated, but still needed to read old bitcode files.
1335 // This is a LocalAsMetadata record, the only type of function-local
1336 // metadata.
1337 if (Record.size() % 2 == 1)
1338 return error("Invalid record");
1339
1340 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1341 // to be legal, but there's no upgrade path.
1342 auto dropRecord = [&] {
1343 MetadataList.assignValue(MDNode::get(Context, {}), NextMetadataNo);
1344 NextMetadataNo++;
1345 };
1346 if (Record.size() != 2) {
1347 dropRecord();
1348 break;
1349 }
1350
1351 unsigned TyID = Record[0];
1352 Type *Ty = Callbacks.GetTypeByID(TyID);
1353 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
1354 dropRecord();
1355 break;
1356 }
1357
1358 Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1359 /*ConstExprInsertBB*/ nullptr);
1360 if (!V)
1361 return error("Invalid value reference from old fn metadata");
1362
1363 MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
1364 NextMetadataNo++;
1365 break;
1366 }
1368 // Deprecated, but still needed to read old bitcode files.
1369 if (Record.size() % 2 == 1)
1370 return error("Invalid record");
1371
1372 unsigned Size = Record.size();
1374 for (unsigned i = 0; i != Size; i += 2) {
1375 unsigned TyID = Record[i];
1376 Type *Ty = Callbacks.GetTypeByID(TyID);
1377 if (!Ty)
1378 return error("Invalid record");
1379 if (Ty->isMetadataTy())
1380 Elts.push_back(getMD(Record[i + 1]));
1381 else if (!Ty->isVoidTy()) {
1382 Value *V = getValueFwdRef(ValueList, Record[i + 1], Ty, TyID);
1383 if (!V)
1384 return error("Invalid value reference from old metadata");
1387 "Expected non-function-local metadata");
1388 callMDTypeCallback(&MD, TyID);
1389 Elts.push_back(MD);
1390 } else
1391 Elts.push_back(nullptr);
1392 }
1393 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1394 NextMetadataNo++;
1395 break;
1396 }
1397 case bitc::METADATA_VALUE: {
1398 if (Record.size() != 2)
1399 return error("Invalid record");
1400
1401 unsigned TyID = Record[0];
1402 Type *Ty = Callbacks.GetTypeByID(TyID);
1403 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
1404 return error("Invalid record");
1405
1406 Value *V = getValueFwdRef(ValueList, Record[1], Ty, TyID);
1407 if (!V)
1408 return error("Invalid value reference from metadata");
1409
1411 callMDTypeCallback(&MD, TyID);
1412 MetadataList.assignValue(MD, NextMetadataNo);
1413 NextMetadataNo++;
1414 break;
1415 }
1417 IsDistinct = true;
1418 [[fallthrough]];
1419 case bitc::METADATA_NODE: {
1421 Elts.reserve(Record.size());
1422 for (unsigned ID : Record)
1423 Elts.push_back(getMDOrNull(ID));
1424 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1425 : MDNode::get(Context, Elts),
1426 NextMetadataNo);
1427 NextMetadataNo++;
1428 break;
1429 }
1431 // 5: inlinedAt, 6: isImplicit, 8: Key Instructions fields.
1432 if (Record.size() != 5 && Record.size() != 6 && Record.size() != 8)
1433 return error("Invalid record");
1434
1435 IsDistinct = Record[0];
1436 unsigned Line = Record[1];
1437 unsigned Column = Record[2];
1438 Metadata *Scope = getMD(Record[3]);
1439 Metadata *InlinedAt = getMDOrNull(Record[4]);
1440 bool ImplicitCode = Record.size() >= 6 && Record[5];
1441 uint64_t AtomGroup = Record.size() == 8 ? Record[6] : 0;
1442 uint8_t AtomRank = Record.size() == 8 ? Record[7] : 0;
1443 MetadataList.assignValue(
1444 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1445 ImplicitCode, AtomGroup, AtomRank)),
1446 NextMetadataNo);
1447 NextMetadataNo++;
1448 break;
1449 }
1451 if (Record.size() < 4)
1452 return error("Invalid record");
1453
1454 IsDistinct = Record[0];
1455 unsigned Tag = Record[1];
1456 unsigned Version = Record[2];
1457
1458 if (Tag >= 1u << 16 || Version != 0)
1459 return error("Invalid record");
1460
1461 auto *Header = getMDString(Record[3]);
1463 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1464 DwarfOps.push_back(getMDOrNull(Record[I]));
1465 MetadataList.assignValue(
1466 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1467 NextMetadataNo);
1468 NextMetadataNo++;
1469 break;
1470 }
1472 Metadata *Val = nullptr;
1473 // Operand 'count' is interpreted as:
1474 // - Signed integer (version 0)
1475 // - Metadata node (version 1)
1476 // Operand 'lowerBound' is interpreted as:
1477 // - Signed integer (version 0 and 1)
1478 // - Metadata node (version 2)
1479 // Operands 'upperBound' and 'stride' are interpreted as:
1480 // - Metadata node (version 2)
1481 switch (Record[0] >> 1) {
1482 case 0:
1483 Val = GET_OR_DISTINCT(DISubrange,
1484 (Context, Record[1], unrotateSign(Record[2])));
1485 break;
1486 case 1:
1487 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1488 unrotateSign(Record[2])));
1489 break;
1490 case 2:
1491 Val = GET_OR_DISTINCT(
1492 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1493 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1494 break;
1495 default:
1496 return error("Invalid record: Unsupported version of DISubrange");
1497 }
1498
1499 MetadataList.assignValue(Val, NextMetadataNo);
1500 IsDistinct = Record[0] & 1;
1501 NextMetadataNo++;
1502 break;
1503 }
1505 Metadata *Val = nullptr;
1506 Val = GET_OR_DISTINCT(DIGenericSubrange,
1507 (Context, getMDOrNull(Record[1]),
1508 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1509 getMDOrNull(Record[4])));
1510
1511 MetadataList.assignValue(Val, NextMetadataNo);
1512 IsDistinct = Record[0] & 1;
1513 NextMetadataNo++;
1514 break;
1515 }
1517 if (Record.size() < 3)
1518 return error("Invalid record");
1519
1520 IsDistinct = Record[0] & 1;
1521 bool IsUnsigned = Record[0] & 2;
1522 bool IsBigInt = Record[0] & 4;
1523 APInt Value;
1524
1525 if (IsBigInt) {
1526 const uint64_t BitWidth = Record[1];
1527 const size_t NumWords = Record.size() - 3;
1528 Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
1529 } else
1530 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1531
1532 MetadataList.assignValue(
1533 GET_OR_DISTINCT(DIEnumerator,
1534 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1535 NextMetadataNo);
1536 NextMetadataNo++;
1537 break;
1538 }
1540 if (Record.size() < 6 || Record.size() > 8)
1541 return error("Invalid record");
1542
1543 IsDistinct = Record[0] & 1;
1544 bool SizeIsMetadata = Record[0] & 2;
1545 DINode::DIFlags Flags = (Record.size() > 6)
1546 ? static_cast<DINode::DIFlags>(Record[6])
1547 : DINode::FlagZero;
1548 uint32_t NumExtraInhabitants = (Record.size() > 7) ? Record[7] : 0;
1549
1550 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1551
1552 MetadataList.assignValue(
1553 GET_OR_DISTINCT(DIBasicType,
1554 (Context, Record[1], getMDString(Record[2]), SizeInBits,
1555 Record[4], Record[5], NumExtraInhabitants, Flags)),
1556 NextMetadataNo);
1557 NextMetadataNo++;
1558 break;
1559 }
1561 if (Record.size() < 11)
1562 return error("Invalid record");
1563
1564 IsDistinct = Record[0] & 1;
1565 bool SizeIsMetadata = Record[0] & 2;
1566 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[6]);
1567
1568 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1569
1570 size_t Offset = 9;
1571
1572 auto ReadWideInt = [&]() {
1573 uint64_t Encoded = Record[Offset++];
1574 unsigned NumWords = Encoded >> 32;
1575 unsigned BitWidth = Encoded & 0xffffffff;
1576 auto Value = readWideAPInt(ArrayRef(&Record[Offset], NumWords), BitWidth);
1577 Offset += NumWords;
1578 return Value;
1579 };
1580
1581 APInt Numerator = ReadWideInt();
1582 APInt Denominator = ReadWideInt();
1583
1584 if (Offset != Record.size())
1585 return error("Invalid record");
1586
1587 MetadataList.assignValue(
1588 GET_OR_DISTINCT(DIFixedPointType,
1589 (Context, Record[1], getMDString(Record[2]), SizeInBits,
1590 Record[4], Record[5], Flags, Record[7], Record[8],
1591 Numerator, Denominator)),
1592 NextMetadataNo);
1593 NextMetadataNo++;
1594 break;
1595 }
1597 if (Record.size() > 9 || Record.size() < 8)
1598 return error("Invalid record");
1599
1600 IsDistinct = Record[0] & 1;
1601 bool SizeIsMetadata = Record[0] & 2;
1602 bool SizeIs8 = Record.size() == 8;
1603 // StringLocationExp (i.e. Record[5]) is added at a later time
1604 // than the other fields. The code here enables backward compatibility.
1605 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1606 unsigned Offset = SizeIs8 ? 5 : 6;
1607 Metadata *SizeInBits =
1608 getMetadataOrConstant(SizeIsMetadata, Record[Offset]);
1609
1610 MetadataList.assignValue(
1611 GET_OR_DISTINCT(DIStringType,
1612 (Context, Record[1], getMDString(Record[2]),
1613 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1614 StringLocationExp, SizeInBits, Record[Offset + 1],
1615 Record[Offset + 2])),
1616 NextMetadataNo);
1617 NextMetadataNo++;
1618 break;
1619 }
1621 if (Record.size() < 12 || Record.size() > 15)
1622 return error("Invalid record");
1623
1624 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1625 // that there is no DWARF address space associated with DIDerivedType.
1626 std::optional<unsigned> DWARFAddressSpace;
1627 if (Record.size() > 12 && Record[12])
1628 DWARFAddressSpace = Record[12] - 1;
1629
1630 Metadata *Annotations = nullptr;
1631 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1632
1633 // Only look for annotations/ptrauth if both are allocated.
1634 // If not, we can't tell which was intended to be embedded, as both ptrauth
1635 // and annotations have been expected at Record[13] at various times.
1636 if (Record.size() > 14) {
1637 if (Record[13])
1638 Annotations = getMDOrNull(Record[13]);
1639 if (Record[14])
1640 PtrAuthData.emplace(Record[14]);
1641 }
1642
1643 IsDistinct = Record[0] & 1;
1644 bool SizeIsMetadata = Record[0] & 2;
1645 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1646
1647 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1648 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1649
1650 MetadataList.assignValue(
1651 GET_OR_DISTINCT(DIDerivedType,
1652 (Context, Record[1], getMDString(Record[2]),
1653 getMDOrNull(Record[3]), Record[4],
1654 getDITypeRefOrNull(Record[5]),
1655 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1656 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1657 getDITypeRefOrNull(Record[11]), Annotations)),
1658 NextMetadataNo);
1659 NextMetadataNo++;
1660 break;
1661 }
1663 if (Record.size() != 13)
1664 return error("Invalid record");
1665
1666 IsDistinct = Record[0] & 1;
1667 bool SizeIsMetadata = Record[0] & 2;
1668 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7]);
1669
1670 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1671
1672 MetadataList.assignValue(
1673 GET_OR_DISTINCT(DISubrangeType,
1674 (Context, getMDString(Record[1]),
1675 getMDOrNull(Record[2]), Record[3],
1676 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1677 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1678 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1679 getMDOrNull(Record[12]))),
1680 NextMetadataNo);
1681 NextMetadataNo++;
1682 break;
1683 }
1685 if (Record.size() < 16 || Record.size() > 26)
1686 return error("Invalid record");
1687
1688 // If we have a UUID and this is not a forward declaration, lookup the
1689 // mapping.
1690 IsDistinct = Record[0] & 0x1;
1691 bool IsNotUsedInTypeRef = Record[0] & 2;
1692 bool SizeIsMetadata = Record[0] & 4;
1693 unsigned Tag = Record[1];
1694 MDString *Name = getMDString(Record[2]);
1695 Metadata *File = getMDOrNull(Record[3]);
1696 unsigned Line = Record[4];
1697 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1698 Metadata *BaseType = nullptr;
1699 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1700 return error("Alignment value is too large");
1701 uint32_t AlignInBits = Record[8];
1702 Metadata *OffsetInBits = nullptr;
1703 uint32_t NumExtraInhabitants = (Record.size() > 22) ? Record[22] : 0;
1704 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1705 Metadata *Elements = nullptr;
1706 unsigned RuntimeLang = Record[12];
1707 std::optional<uint32_t> EnumKind;
1708
1709 Metadata *VTableHolder = nullptr;
1710 Metadata *TemplateParams = nullptr;
1711 Metadata *Discriminator = nullptr;
1712 Metadata *DataLocation = nullptr;
1713 Metadata *Associated = nullptr;
1714 Metadata *Allocated = nullptr;
1715 Metadata *Rank = nullptr;
1716 Metadata *Annotations = nullptr;
1717 Metadata *Specification = nullptr;
1718 Metadata *BitStride = nullptr;
1719 auto *Identifier = getMDString(Record[15]);
1720 // If this module is being parsed so that it can be ThinLTO imported
1721 // into another module, composite types only need to be imported as
1722 // type declarations (unless full type definitions are requested).
1723 // Create type declarations up front to save memory. This is only
1724 // done for types which have an Identifier, and are therefore
1725 // subject to the ODR.
1726 //
1727 // buildODRType handles the case where this is type ODRed with a
1728 // definition needed by the importing module, in which case the
1729 // existing definition is used.
1730 //
1731 // We always import full definitions for anonymous composite types,
1732 // as without a name, debuggers cannot easily resolve a declaration
1733 // to its definition.
1734 if (IsImporting && !ImportFullTypeDefinitions && Identifier && Name &&
1735 (Tag == dwarf::DW_TAG_enumeration_type ||
1736 Tag == dwarf::DW_TAG_class_type ||
1737 Tag == dwarf::DW_TAG_structure_type ||
1738 Tag == dwarf::DW_TAG_union_type)) {
1739 Flags = Flags | DINode::FlagFwdDecl;
1740 // This is a hack around preserving template parameters for simplified
1741 // template names - it should probably be replaced with a
1742 // DICompositeType flag specifying whether template parameters are
1743 // required on declarations of this type.
1744 StringRef NameStr = Name->getString();
1745 if (!NameStr.contains('<') || NameStr.starts_with("_STN|"))
1746 TemplateParams = getMDOrNull(Record[14]);
1747 } else {
1748 BaseType = getDITypeRefOrNull(Record[6]);
1749
1750 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1751
1752 Elements = getMDOrNull(Record[11]);
1753 VTableHolder = getDITypeRefOrNull(Record[13]);
1754 TemplateParams = getMDOrNull(Record[14]);
1755 if (Record.size() > 16)
1756 Discriminator = getMDOrNull(Record[16]);
1757 if (Record.size() > 17)
1758 DataLocation = getMDOrNull(Record[17]);
1759 if (Record.size() > 19) {
1760 Associated = getMDOrNull(Record[18]);
1761 Allocated = getMDOrNull(Record[19]);
1762 }
1763 if (Record.size() > 20) {
1764 Rank = getMDOrNull(Record[20]);
1765 }
1766 if (Record.size() > 21) {
1767 Annotations = getMDOrNull(Record[21]);
1768 }
1769 if (Record.size() > 23) {
1770 Specification = getMDOrNull(Record[23]);
1771 }
1772 if (Record.size() > 25)
1773 BitStride = getMDOrNull(Record[25]);
1774 }
1775
1776 if (Record.size() > 24 && Record[24] != dwarf::DW_APPLE_ENUM_KIND_invalid)
1777 EnumKind = Record[24];
1778
1779 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1780
1781 DICompositeType *CT = nullptr;
1782 if (Identifier)
1784 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1785 SizeInBits, AlignInBits, OffsetInBits, Specification,
1786 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1787 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1788 Allocated, Rank, Annotations, BitStride);
1789
1790 // Create a node if we didn't get a lazy ODR type.
1791 if (!CT)
1792 CT = GET_OR_DISTINCT(
1793 DICompositeType,
1794 (Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1795 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1796 VTableHolder, TemplateParams, Identifier, Discriminator,
1797 DataLocation, Associated, Allocated, Rank, Annotations,
1798 Specification, NumExtraInhabitants, BitStride));
1799 if (!IsNotUsedInTypeRef && Identifier)
1800 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1801
1802 MetadataList.assignValue(CT, NextMetadataNo);
1803 NextMetadataNo++;
1804 break;
1805 }
1807 if (Record.size() < 3 || Record.size() > 4)
1808 return error("Invalid record");
1809 bool IsOldTypeRefArray = Record[0] < 2;
1810 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1811
1812 IsDistinct = Record[0] & 0x1;
1813 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1814 Metadata *Types = getMDOrNull(Record[2]);
1815 if (LLVM_UNLIKELY(IsOldTypeRefArray))
1816 Types = MetadataList.upgradeTypeRefArray(Types);
1817
1818 MetadataList.assignValue(
1819 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1820 NextMetadataNo);
1821 NextMetadataNo++;
1822 break;
1823 }
1824
1825 case bitc::METADATA_MODULE: {
1826 if (Record.size() < 5 || Record.size() > 9)
1827 return error("Invalid record");
1828
1829 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1830 IsDistinct = Record[0];
1831 MetadataList.assignValue(
1833 DIModule,
1834 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1835 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1836 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1837 getMDString(Record[4 + Offset]),
1838 Record.size() <= 7 ? 0 : Record[7],
1839 Record.size() <= 8 ? false : Record[8])),
1840 NextMetadataNo);
1841 NextMetadataNo++;
1842 break;
1843 }
1844
1845 case bitc::METADATA_FILE: {
1846 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1847 return error("Invalid record");
1848
1849 IsDistinct = Record[0];
1850 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1851 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1852 // is not present. This matches up with the old internal representation,
1853 // and the old encoding for CSK_None in the ChecksumKind. The new
1854 // representation reserves the value 0 in the ChecksumKind to continue to
1855 // encode None in a backwards-compatible way.
1856 if (Record.size() > 4 && Record[3] && Record[4])
1857 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1858 getMDString(Record[4]));
1859 MetadataList.assignValue(
1860 GET_OR_DISTINCT(DIFile,
1861 (Context, getMDString(Record[1]),
1862 getMDString(Record[2]), Checksum,
1863 Record.size() > 5 ? getMDString(Record[5]) : nullptr)),
1864 NextMetadataNo);
1865 NextMetadataNo++;
1866 break;
1867 }
1869 if (Record.size() < 14 || Record.size() > 22)
1870 return error("Invalid record");
1871
1872 // Ignore Record[0], which indicates whether this compile unit is
1873 // distinct. It's always distinct.
1874 IsDistinct = true;
1875 auto *CU = DICompileUnit::getDistinct(
1876 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1877 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1878 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1879 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1880 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1881 Record.size() <= 14 ? 0 : Record[14],
1882 Record.size() <= 16 ? true : Record[16],
1883 Record.size() <= 17 ? false : Record[17],
1884 Record.size() <= 18 ? 0 : Record[18],
1885 Record.size() <= 19 ? false : Record[19],
1886 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1887 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1888
1889 MetadataList.assignValue(CU, NextMetadataNo);
1890 NextMetadataNo++;
1891
1892 // Move the Upgrade the list of subprograms.
1893 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1894 CUSubprograms.push_back({CU, SPs});
1895 break;
1896 }
1898 if (Record.size() < 18 || Record.size() > 22)
1899 return error("Invalid record");
1900
1901 bool HasSPFlags = Record[0] & 4;
1902
1905 if (!HasSPFlags)
1906 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1907 else {
1908 Flags = static_cast<DINode::DIFlags>(Record[11]);
1909 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1910 }
1911
1912 // Support for old metadata when
1913 // subprogram specific flags are placed in DIFlags.
1914 const unsigned DIFlagMainSubprogram = 1 << 21;
1915 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
1916 if (HasOldMainSubprogramFlag)
1917 // Remove old DIFlagMainSubprogram from DIFlags.
1918 // Note: This assumes that any future use of bit 21 defaults to it
1919 // being 0.
1920 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1921
1922 if (HasOldMainSubprogramFlag && HasSPFlags)
1923 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1924 else if (!HasSPFlags)
1925 SPFlags = DISubprogram::toSPFlags(
1926 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
1927 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
1928 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
1929
1930 // All definitions should be distinct.
1931 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1932 // Version 1 has a Function as Record[15].
1933 // Version 2 has removed Record[15].
1934 // Version 3 has the Unit as Record[15].
1935 // Version 4 added thisAdjustment.
1936 // Version 5 repacked flags into DISPFlags, changing many element numbers.
1937 bool HasUnit = Record[0] & 2;
1938 if (!HasSPFlags && HasUnit && Record.size() < 19)
1939 return error("Invalid record");
1940 if (HasSPFlags && !HasUnit)
1941 return error("Invalid record");
1942 // Accommodate older formats.
1943 bool HasFn = false;
1944 bool HasThisAdj = true;
1945 bool HasThrownTypes = true;
1946 bool HasAnnotations = false;
1947 bool HasTargetFuncName = false;
1948 unsigned OffsetA = 0;
1949 unsigned OffsetB = 0;
1950 // Key instructions won't be enabled in old-format bitcode, so only
1951 // check it if HasSPFlags is true.
1952 bool UsesKeyInstructions = false;
1953 if (!HasSPFlags) {
1954 OffsetA = 2;
1955 OffsetB = 2;
1956 if (Record.size() >= 19) {
1957 HasFn = !HasUnit;
1958 OffsetB++;
1959 }
1960 HasThisAdj = Record.size() >= 20;
1961 HasThrownTypes = Record.size() >= 21;
1962 } else {
1963 HasAnnotations = Record.size() >= 19;
1964 HasTargetFuncName = Record.size() >= 20;
1965 UsesKeyInstructions = Record.size() >= 21 ? Record[20] : 0;
1966 }
1967
1968 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1969 DISubprogram *SP = GET_OR_DISTINCT(
1970 DISubprogram,
1971 (Context,
1972 getDITypeRefOrNull(Record[1]), // scope
1973 getMDString(Record[2]), // name
1974 getMDString(Record[3]), // linkageName
1975 getMDOrNull(Record[4]), // file
1976 Record[5], // line
1977 getMDOrNull(Record[6]), // type
1978 Record[7 + OffsetA], // scopeLine
1979 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
1980 Record[10 + OffsetA], // virtualIndex
1981 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
1982 Flags, // flags
1983 SPFlags, // SPFlags
1984 HasUnit ? CUorFn : nullptr, // unit
1985 getMDOrNull(Record[13 + OffsetB]), // templateParams
1986 getMDOrNull(Record[14 + OffsetB]), // declaration
1987 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
1988 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1989 : nullptr, // thrownTypes
1990 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1991 : nullptr, // annotations
1992 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
1993 : nullptr, // targetFuncName
1994 UsesKeyInstructions));
1995 MetadataList.assignValue(SP, NextMetadataNo);
1996 NextMetadataNo++;
1997
1998 // Upgrade sp->function mapping to function->sp mapping.
1999 if (HasFn) {
2000 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2001 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2002 if (F->isMaterializable())
2003 // Defer until materialized; unmaterialized functions may not have
2004 // metadata.
2005 FunctionsWithSPs[F] = SP;
2006 else if (!F->empty())
2007 F->setSubprogram(SP);
2008 }
2009 }
2010 break;
2011 }
2013 if (Record.size() != 5)
2014 return error("Invalid record");
2015
2016 IsDistinct = Record[0];
2017 MetadataList.assignValue(
2018 GET_OR_DISTINCT(DILexicalBlock,
2019 (Context, getMDOrNull(Record[1]),
2020 getMDOrNull(Record[2]), Record[3], Record[4])),
2021 NextMetadataNo);
2022 NextMetadataNo++;
2023 break;
2024 }
2026 if (Record.size() != 4)
2027 return error("Invalid record");
2028
2029 IsDistinct = Record[0];
2030 MetadataList.assignValue(
2031 GET_OR_DISTINCT(DILexicalBlockFile,
2032 (Context, getMDOrNull(Record[1]),
2033 getMDOrNull(Record[2]), Record[3])),
2034 NextMetadataNo);
2035 NextMetadataNo++;
2036 break;
2037 }
2039 IsDistinct = Record[0] & 1;
2040 MetadataList.assignValue(
2041 GET_OR_DISTINCT(DICommonBlock,
2042 (Context, getMDOrNull(Record[1]),
2043 getMDOrNull(Record[2]), getMDString(Record[3]),
2044 getMDOrNull(Record[4]), Record[5])),
2045 NextMetadataNo);
2046 NextMetadataNo++;
2047 break;
2048 }
2050 // Newer versions of DINamespace dropped file and line.
2051 MDString *Name;
2052 if (Record.size() == 3)
2053 Name = getMDString(Record[2]);
2054 else if (Record.size() == 5)
2055 Name = getMDString(Record[3]);
2056 else
2057 return error("Invalid record");
2058
2059 IsDistinct = Record[0] & 1;
2060 bool ExportSymbols = Record[0] & 2;
2061 MetadataList.assignValue(
2062 GET_OR_DISTINCT(DINamespace,
2063 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2064 NextMetadataNo);
2065 NextMetadataNo++;
2066 break;
2067 }
2068 case bitc::METADATA_MACRO: {
2069 if (Record.size() != 5)
2070 return error("Invalid record");
2071
2072 IsDistinct = Record[0];
2073 MetadataList.assignValue(
2074 GET_OR_DISTINCT(DIMacro,
2075 (Context, Record[1], Record[2], getMDString(Record[3]),
2076 getMDString(Record[4]))),
2077 NextMetadataNo);
2078 NextMetadataNo++;
2079 break;
2080 }
2082 if (Record.size() != 5)
2083 return error("Invalid record");
2084
2085 IsDistinct = Record[0];
2086 MetadataList.assignValue(
2087 GET_OR_DISTINCT(DIMacroFile,
2088 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
2089 getMDOrNull(Record[4]))),
2090 NextMetadataNo);
2091 NextMetadataNo++;
2092 break;
2093 }
2095 if (Record.size() < 3 || Record.size() > 4)
2096 return error("Invalid record");
2097
2098 IsDistinct = Record[0];
2099 MetadataList.assignValue(
2100 GET_OR_DISTINCT(DITemplateTypeParameter,
2101 (Context, getMDString(Record[1]),
2102 getDITypeRefOrNull(Record[2]),
2103 (Record.size() == 4) ? getMDOrNull(Record[3])
2104 : getMDOrNull(false))),
2105 NextMetadataNo);
2106 NextMetadataNo++;
2107 break;
2108 }
2110 if (Record.size() < 5 || Record.size() > 6)
2111 return error("Invalid record");
2112
2113 IsDistinct = Record[0];
2114
2115 MetadataList.assignValue(
2117 DITemplateValueParameter,
2118 (Context, Record[1], getMDString(Record[2]),
2119 getDITypeRefOrNull(Record[3]),
2120 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
2121 (Record.size() == 6) ? getMDOrNull(Record[5])
2122 : getMDOrNull(Record[4]))),
2123 NextMetadataNo);
2124 NextMetadataNo++;
2125 break;
2126 }
2128 if (Record.size() < 11 || Record.size() > 13)
2129 return error("Invalid record");
2130
2131 IsDistinct = Record[0] & 1;
2132 unsigned Version = Record[0] >> 1;
2133
2134 if (Version == 2) {
2135 Metadata *Annotations = nullptr;
2136 if (Record.size() > 12)
2137 Annotations = getMDOrNull(Record[12]);
2138
2139 MetadataList.assignValue(
2140 GET_OR_DISTINCT(DIGlobalVariable,
2141 (Context, getMDOrNull(Record[1]),
2142 getMDString(Record[2]), getMDString(Record[3]),
2143 getMDOrNull(Record[4]), Record[5],
2144 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2145 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2146 Record[11], Annotations)),
2147 NextMetadataNo);
2148
2149 NextMetadataNo++;
2150 } else if (Version == 1) {
2151 // No upgrade necessary. A null field will be introduced to indicate
2152 // that no parameter information is available.
2153 MetadataList.assignValue(
2155 DIGlobalVariable,
2156 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2157 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2158 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2159 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
2160 NextMetadataNo);
2161
2162 NextMetadataNo++;
2163 } else if (Version == 0) {
2164 // Upgrade old metadata, which stored a global variable reference or a
2165 // ConstantInt here.
2166 NeedUpgradeToDIGlobalVariableExpression = true;
2167 Metadata *Expr = getMDOrNull(Record[9]);
2168 uint32_t AlignInBits = 0;
2169 if (Record.size() > 11) {
2170 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2171 return error("Alignment value is too large");
2172 AlignInBits = Record[11];
2173 }
2174 GlobalVariable *Attach = nullptr;
2175 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2176 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2177 Attach = GV;
2178 Expr = nullptr;
2179 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2181 {dwarf::DW_OP_constu, CI->getZExtValue(),
2182 dwarf::DW_OP_stack_value});
2183 } else {
2184 Expr = nullptr;
2185 }
2186 }
2187 DIGlobalVariable *DGV = GET_OR_DISTINCT(
2188 DIGlobalVariable,
2189 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2190 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2191 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2192 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
2193
2194 DIGlobalVariableExpression *DGVE = nullptr;
2195 if (Attach || Expr)
2197 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
2198 if (Attach)
2199 Attach->addDebugInfo(DGVE);
2200
2201 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
2202 MetadataList.assignValue(MDNode, NextMetadataNo);
2203 NextMetadataNo++;
2204 } else
2205 return error("Invalid record");
2206
2207 break;
2208 }
2210 if (Record.size() != 1)
2211 return error("Invalid DIAssignID record.");
2212
2213 IsDistinct = Record[0] & 1;
2214 if (!IsDistinct)
2215 return error("Invalid DIAssignID record. Must be distinct");
2216
2217 MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2218 NextMetadataNo++;
2219 break;
2220 }
2222 // 10th field is for the obseleted 'inlinedAt:' field.
2223 if (Record.size() < 8 || Record.size() > 10)
2224 return error("Invalid record");
2225
2226 IsDistinct = Record[0] & 1;
2227 bool HasAlignment = Record[0] & 2;
2228 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2229 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
2230 // this is newer version of record which doesn't have artificial tag.
2231 bool HasTag = !HasAlignment && Record.size() > 8;
2232 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
2233 uint32_t AlignInBits = 0;
2234 Metadata *Annotations = nullptr;
2235 if (HasAlignment) {
2236 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2237 return error("Alignment value is too large");
2238 AlignInBits = Record[8];
2239 if (Record.size() > 9)
2240 Annotations = getMDOrNull(Record[9]);
2241 }
2242
2243 MetadataList.assignValue(
2244 GET_OR_DISTINCT(DILocalVariable,
2245 (Context, getMDOrNull(Record[1 + HasTag]),
2246 getMDString(Record[2 + HasTag]),
2247 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2248 getDITypeRefOrNull(Record[5 + HasTag]),
2249 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2250 NextMetadataNo);
2251 NextMetadataNo++;
2252 break;
2253 }
2254 case bitc::METADATA_LABEL: {
2255 if (Record.size() < 5 || Record.size() > 7)
2256 return error("Invalid record");
2257
2258 IsDistinct = Record[0] & 1;
2259 uint64_t Line = Record[4];
2260 uint64_t Column = Record.size() > 5 ? Record[5] : 0;
2261 bool IsArtificial = Record[0] & 2;
2262 std::optional<unsigned> CoroSuspendIdx;
2263 if (Record.size() > 6) {
2264 uint64_t RawSuspendIdx = Record[6];
2265 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2266 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2267 return error("CoroSuspendIdx value is too large");
2268 CoroSuspendIdx = RawSuspendIdx;
2269 }
2270 }
2271
2272 MetadataList.assignValue(
2273 GET_OR_DISTINCT(DILabel,
2274 (Context, getMDOrNull(Record[1]),
2275 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2276 Column, IsArtificial, CoroSuspendIdx)),
2277 NextMetadataNo);
2278 NextMetadataNo++;
2279 break;
2280 }
2282 if (Record.size() < 1)
2283 return error("Invalid record");
2284
2285 IsDistinct = Record[0] & 1;
2286 uint64_t Version = Record[0] >> 1;
2287 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2288
2290 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2291 return Err;
2292
2293 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2294 NextMetadataNo);
2295 NextMetadataNo++;
2296 break;
2297 }
2299 if (Record.size() != 3)
2300 return error("Invalid record");
2301
2302 IsDistinct = Record[0];
2303 Metadata *Expr = getMDOrNull(Record[2]);
2304 if (!Expr)
2305 Expr = DIExpression::get(Context, {});
2306 MetadataList.assignValue(
2307 GET_OR_DISTINCT(DIGlobalVariableExpression,
2308 (Context, getMDOrNull(Record[1]), Expr)),
2309 NextMetadataNo);
2310 NextMetadataNo++;
2311 break;
2312 }
2314 if (Record.size() != 8)
2315 return error("Invalid record");
2316
2317 IsDistinct = Record[0];
2318 MetadataList.assignValue(
2319 GET_OR_DISTINCT(DIObjCProperty,
2320 (Context, getMDString(Record[1]),
2321 getMDOrNull(Record[2]), Record[3],
2322 getMDString(Record[4]), getMDString(Record[5]),
2323 Record[6], getDITypeRefOrNull(Record[7]))),
2324 NextMetadataNo);
2325 NextMetadataNo++;
2326 break;
2327 }
2329 if (Record.size() < 6 || Record.size() > 8)
2330 return error("Invalid DIImportedEntity record");
2331
2332 IsDistinct = Record[0];
2333 bool HasFile = (Record.size() >= 7);
2334 bool HasElements = (Record.size() >= 8);
2335 MetadataList.assignValue(
2336 GET_OR_DISTINCT(DIImportedEntity,
2337 (Context, Record[1], getMDOrNull(Record[2]),
2338 getDITypeRefOrNull(Record[3]),
2339 HasFile ? getMDOrNull(Record[6]) : nullptr,
2340 HasFile ? Record[4] : 0, getMDString(Record[5]),
2341 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2342 NextMetadataNo);
2343 NextMetadataNo++;
2344 break;
2345 }
2347 std::string String(Record.begin(), Record.end());
2348
2349 // Test for upgrading !llvm.loop.
2350 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2351 ++NumMDStringLoaded;
2353 MetadataList.assignValue(MD, NextMetadataNo);
2354 NextMetadataNo++;
2355 break;
2356 }
2358 auto CreateNextMDString = [&](StringRef Str) {
2359 ++NumMDStringLoaded;
2360 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2361 NextMetadataNo++;
2362 };
2363 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2364 return Err;
2365 break;
2366 }
2368 if (Record.size() % 2 == 0)
2369 return error("Invalid record");
2370 unsigned ValueID = Record[0];
2371 if (ValueID >= ValueList.size())
2372 return error("Invalid record");
2373 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2374 if (Error Err = parseGlobalObjectAttachment(
2375 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2376 return Err;
2377 break;
2378 }
2379 case bitc::METADATA_KIND: {
2380 // Support older bitcode files that had METADATA_KIND records in a
2381 // block with METADATA_BLOCK_ID.
2382 if (Error Err = parseMetadataKindRecord(Record))
2383 return Err;
2384 break;
2385 }
2388 Elts.reserve(Record.size());
2389 for (uint64_t Elt : Record) {
2390 Metadata *MD = getMD(Elt);
2391 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2392 return error(
2393 "Invalid record: DIArgList should not contain forward refs");
2394 if (!isa<ValueAsMetadata>(MD))
2395 return error("Invalid record");
2397 }
2398
2399 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2400 NextMetadataNo++;
2401 break;
2402 }
2403 }
2404 return Error::success();
2405#undef GET_OR_DISTINCT
2406}
2407
2408Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2409 ArrayRef<uint64_t> Record, StringRef Blob,
2410 function_ref<void(StringRef)> CallBack) {
2411 // All the MDStrings in the block are emitted together in a single
2412 // record. The strings are concatenated and stored in a blob along with
2413 // their sizes.
2414 if (Record.size() != 2)
2415 return error("Invalid record: metadata strings layout");
2416
2417 unsigned NumStrings = Record[0];
2418 unsigned StringsOffset = Record[1];
2419 if (!NumStrings)
2420 return error("Invalid record: metadata strings with no strings");
2421 if (StringsOffset > Blob.size())
2422 return error("Invalid record: metadata strings corrupt offset");
2423
2424 StringRef Lengths = Blob.slice(0, StringsOffset);
2425 SimpleBitstreamCursor R(Lengths);
2426
2427 StringRef Strings = Blob.drop_front(StringsOffset);
2428 do {
2429 if (R.AtEndOfStream())
2430 return error("Invalid record: metadata strings bad length");
2431
2432 uint32_t Size;
2433 if (Error E = R.ReadVBR(6).moveInto(Size))
2434 return E;
2435 if (Strings.size() < Size)
2436 return error("Invalid record: metadata strings truncated chars");
2437
2438 CallBack(Strings.slice(0, Size));
2439 Strings = Strings.drop_front(Size);
2440 } while (--NumStrings);
2441
2442 return Error::success();
2443}
2444
2445Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2446 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2447 assert(Record.size() % 2 == 0);
2448 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2449 auto K = MDKindMap.find(Record[I]);
2450 if (K == MDKindMap.end())
2451 return error("Invalid ID");
2452 MDNode *MD =
2454 if (!MD)
2455 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2456 GO.addMetadata(K->second, *MD);
2457 }
2458 return Error::success();
2459}
2460
2461/// Parse metadata attachments.
2463 Function &F, ArrayRef<Instruction *> InstructionList) {
2464 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2465 return Err;
2466
2468 PlaceholderQueue Placeholders;
2469
2470 while (true) {
2471 BitstreamEntry Entry;
2472 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2473 return E;
2474
2475 switch (Entry.Kind) {
2476 case BitstreamEntry::SubBlock: // Handled for us already.
2478 return error("Malformed block");
2480 resolveForwardRefsAndPlaceholders(Placeholders);
2481 return Error::success();
2483 // The interesting case.
2484 break;
2485 }
2486
2487 // Read a metadata attachment record.
2488 Record.clear();
2489 ++NumMDRecordLoaded;
2490 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2491 if (!MaybeRecord)
2492 return MaybeRecord.takeError();
2493 switch (MaybeRecord.get()) {
2494 default: // Default behavior: ignore.
2495 break;
2497 unsigned RecordLength = Record.size();
2498 if (Record.empty())
2499 return error("Invalid record");
2500 if (RecordLength % 2 == 0) {
2501 // A function attachment.
2502 if (Error Err = parseGlobalObjectAttachment(F, Record))
2503 return Err;
2504 continue;
2505 }
2506
2507 // An instruction attachment.
2508 Instruction *Inst = InstructionList[Record[0]];
2509 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2510 unsigned Kind = Record[i];
2511 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2512 if (I == MDKindMap.end())
2513 return error("Invalid ID");
2514 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2515 continue;
2516
2517 auto Idx = Record[i + 1];
2518 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2519 !MetadataList.lookup(Idx)) {
2520 // Load the attachment if it is in the lazy-loadable range and hasn't
2521 // been loaded yet.
2522 lazyLoadOneMetadata(Idx, Placeholders);
2523 resolveForwardRefsAndPlaceholders(Placeholders);
2524 }
2525
2526 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2528 // Drop the attachment. This used to be legal, but there's no
2529 // upgrade path.
2530 break;
2532 if (!MD)
2533 return error("Invalid metadata attachment");
2534
2535 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2537
2538 if (I->second == LLVMContext::MD_tbaa) {
2539 assert(!MD->isTemporary() && "should load MDs before attachments");
2540 MD = UpgradeTBAANode(*MD);
2541 }
2542 Inst->setMetadata(I->second, MD);
2543 }
2544 break;
2545 }
2546 }
2547 }
2548}
2549
2550/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2551Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2553 if (Record.size() < 2)
2554 return error("Invalid record");
2555
2556 unsigned Kind = Record[0];
2557 SmallString<8> Name(Record.begin() + 1, Record.end());
2558
2559 unsigned NewKind = TheModule.getMDKindID(Name.str());
2560 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2561 return error("Conflicting METADATA_KIND records");
2562 return Error::success();
2563}
2564
2565/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2567 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2568 return Err;
2569
2571
2572 // Read all the records.
2573 while (true) {
2574 BitstreamEntry Entry;
2575 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2576 return E;
2577
2578 switch (Entry.Kind) {
2579 case BitstreamEntry::SubBlock: // Handled for us already.
2581 return error("Malformed block");
2583 return Error::success();
2585 // The interesting case.
2586 break;
2587 }
2588
2589 // Read a record.
2590 Record.clear();
2591 ++NumMDRecordLoaded;
2592 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2593 if (!MaybeCode)
2594 return MaybeCode.takeError();
2595 switch (MaybeCode.get()) {
2596 default: // Default behavior: ignore.
2597 break;
2598 case bitc::METADATA_KIND: {
2599 if (Error Err = parseMetadataKindRecord(Record))
2600 return Err;
2601 break;
2602 }
2603 }
2604 }
2605}
2606
2608 Pimpl = std::move(RHS.Pimpl);
2609 return *this;
2610}
2612 : Pimpl(std::move(RHS.Pimpl)) {}
2613
2616 BitcodeReaderValueList &ValueList,
2617 bool IsImporting,
2618 MetadataLoaderCallbacks Callbacks)
2619 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2620 Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
2621
2622Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2623 return Pimpl->parseMetadata(ModuleLevel);
2624}
2625
2626bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2627
2628/// Return the given metadata, creating a replaceable forward reference if
2629/// necessary.
2631 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2632}
2633
2635 return Pimpl->lookupSubprogramForFunction(F);
2636}
2637
2639 Function &F, ArrayRef<Instruction *> InstructionList) {
2640 return Pimpl->parseMetadataAttachment(F, InstructionList);
2641}
2642
2644 return Pimpl->parseMetadataKinds();
2645}
2646
2647void MetadataLoader::setStripTBAA(bool StripTBAA) {
2648 return Pimpl->setStripTBAA(StripTBAA);
2649}
2650
2651bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2652
2653unsigned MetadataLoader::size() const { return Pimpl->size(); }
2654void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2655
2657 return Pimpl->upgradeDebugIntrinsics(F);
2658}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
static cl::opt< bool > DisableLazyLoading("disable-ondemand-mds-loading", cl::init(false), cl::Hidden, cl::desc("Force disable the lazy-loading on-demand of metadata when " "loading bitcode for importing."))
static Value * getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx, Type *Ty, unsigned TyID)
static cl::opt< bool > ImportFullTypeDefinitions("import-full-type-definitions", cl::init(false), cl::Hidden, cl::desc("Import full type definitions for ThinLTO."))
Flag whether we need to import full type definitions for ThinLTO.
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:167
#define error(X)
std::pair< llvm::MachO::Target, std::string > UUID
Metadata * getMetadataFwdRefOrLoad(unsigned ID)
Error parseMetadataAttachment(Function &F, ArrayRef< Instruction * > InstructionList)
Parse metadata attachments.
MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule, BitcodeReaderValueList &ValueList, MetadataLoaderCallbacks Callbacks, bool IsImporting)
Error parseMetadataKinds()
Parse the metadata kinds out of the METADATA_KIND_BLOCK.
Error parseMetadata(bool ModuleLevel)
Parse a METADATA_BLOCK.
DISubprogram * lookupSubprogramForFunction(Function *F)
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
Definition ValueList.cpp:50
unsigned size() const
Definition ValueList.h:48
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
@ AF_DontPopBlockAtEnd
If this flag is used, the advance() method does not automatically pop the block scope when the end of...
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:535
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
A scope for locals.
DIFlags
Debug info flags.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
bool isForwardDecl() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:74
Implements a dense probed hash-table based set.
Definition DenseSet.h:269
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static LocalAsMetadata * get(Value *Local)
Definition Metadata.h:561
Metadata node.
Definition Metadata.h:1077
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1573
bool isTemporary() const
Definition Metadata.h:1261
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1577
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
A single uniqued string.
Definition Metadata.h:720
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:607
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1522
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1542
MetadataLoader(BitstreamCursor &Stream, Module &TheModule, BitcodeReaderValueList &ValueList, bool IsImporting, MetadataLoaderCallbacks Callbacks)
Metadata * getMetadataFwdRefOrLoad(unsigned Idx)
Return the given metadata, creating a replaceable forward reference if necessary.
void upgradeDebugIntrinsics(Function &F)
Perform bitcode upgrades on llvm.dbg.* calls.
void shrinkTo(unsigned N)
Error parseMetadataKinds()
Parse a METADATA_KIND block for the current module.
void setStripTBAA(bool StripTBAA=true)
Set the mode to strip TBAA metadata on load.
bool isStrippingTBAA()
Return true if the Loader is stripping TBAA metadata.
Error parseMetadataAttachment(Function &F, ArrayRef< Instruction * > InstructionList)
Parse a METADATA_ATTACHMENT block for a function.
DISubprogram * lookupSubprogramForFunction(Function *F)
Return the DISubprogram metadata for a Function if any, null otherwise.
MetadataLoader & operator=(MetadataLoader &&)
Root of the metadata hierarchy.
Definition Metadata.h:63
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:303
iterator end() const
Definition ArrayRef.h:348
iterator begin() const
Definition ArrayRef.h:347
A tuple of MDNodes.
Definition Metadata.h:1753
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A vector that has set insertion semantics.
Definition SetVector.h:59
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:99
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:168
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
Definition SetVector.h:269
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:269
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:619
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:694
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:154
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:434
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Metadata * get() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:502
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
An efficient, type-erasing, non-owning reference to a callable.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ METADATA_COMMON_BLOCK
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_INDEX_OFFSET
@ METADATA_LEXICAL_BLOCK
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_OBJC_PROPERTY
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPILE_UNIT
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_DERIVED_TYPE
@ METADATA_SUBRANGE_TYPE
@ METADATA_TEMPLATE_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ METADATA_DISTINCT_NODE
@ METADATA_GENERIC_DEBUG
@ METADATA_KIND_BLOCK_ID
@ METADATA_ATTACHMENT_ID
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:143
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:50
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
bool empty() const
Definition BasicBlock.h:101
LLVM_ABI Instruction & back() const
This is an optimization pass for GlobalISel generic memory operations.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
@ Offset
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1665
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto cast_or_null(const Y &Val)
Definition Casting.h:720
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:682
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:759
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:302
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1849
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1083
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
#define N
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...